From b1d17ec9ffc992f2d0df37900969731c58577dd8 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Tue, 3 Nov 2026 18:57:38 +0100 Subject: [PATCH 01/71] fix: restore retail sv.numPlayersNeededToStart The getter returned a fixed 2 ahead of its own logic, and the console setter raised every value below 2 to 2 in release builds, so a server could never start a round with a single player: the client kept showing "The game will start when 1 more player(s) join" even with sv.numPlayersNeededToStart 1 and bots on the map. Retail does neither. The bf2 ELF getter (080BC1F0) returns 6, or 8 from 33 slots up, on ranked servers and the configured value otherwise; the console SET is a raw field write. Both functions now match that. Validated on the Windows x86 dedicated server with the retail 1.50 client: with sv.numPlayersNeededToStart 1 the round starts on the first human spawn and the bots join the round. Co-Authored-By: Claude Opus 5.5 --- Code/BF2/Game/GameServer/ServerSettings.cpp | 8 ++++---- Code/BF2/Game/GameServer/ServerSettingsConsole.cpp | 11 +++-------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/Code/BF2/Game/GameServer/ServerSettings.cpp b/Code/BF2/Game/GameServer/ServerSettings.cpp index b611b1fa3..fce88ce2c 100644 --- a/Code/BF2/Game/GameServer/ServerSettings.cpp +++ b/Code/BF2/Game/GameServer/ServerSettings.cpp @@ -330,12 +330,12 @@ float ServerSettings::getManDownTime() const return m_manDownTime; // +0x6C } -// [CHOSEN, not recovered] getNumPlayersNeededToStart currently returns 2 before -// its original ranked/configured logic. The following getters retain fixed ranked -// overrides for unlocks, coop settings, and team ratio. +// Number of players the round waits for: ranked servers use 6, or 8 from 33 slots up; every +// other server uses the configured sv.numPlayersNeededToStart, so a value of 1 starts the round +// with the first player. The following getters retain fixed ranked overrides for unlocks, coop +// settings, and team ratio. int ServerSettings::getNumPlayersNeededToStart() const { - return 2; if (m_ranked) // +0xF5 return (getMaxPlayers() >= 33 ? 1 : 0) * 2 + 6; return m_playersNeededToStart; // +0x58 diff --git a/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp b/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp index 5ab32fe97..9136b3948 100644 --- a/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp +++ b/Code/BF2/Game/GameServer/ServerSettingsConsole.cpp @@ -68,15 +68,10 @@ std::string svNumReservedSlotsSet(int value) return svReceiver()->setNumReservedSlots(value); } -// [CHOSEN, not recovered] Release configurations floor the requested player count -// at two; development configurations retain the raw setter for single-player tests. -// The getter supplies the effective value. +// Stores the requested player count unchanged, as retail does; the getter applies the ranked +// override. void svNumPlayersNeededToStartSet(int value) { -#if defined(NDEBUG) - if (value < 2) - value = 2; -#endif svReceiver()->m_playersNeededToStart = value; } @@ -354,7 +349,7 @@ BF2_CONSOLE_GETSET_1(numReservedSlots, int, svReceiver() != 0, svReceiver()->m_n // numPlayersNeededToStart: ConsoleClass668, PE slot 0x82ACB4 -> ctor 0x4D0AF0 / exec 0x4D0C40; // ELF registration 0x87B109A / executor 0x87C22A0. Retail SET is a raw field write; GET uses -// the effective ranked getter. The pre-existing chosen release-build floor remains in its helper. +// the effective ranked getter. The helper keeps that raw write. BF2_CONSOLE_PROPERTY_FN(numPlayersNeededToStart, int, svReceiver() != 0, svReceiver()->getNumPlayersNeededToStart(), svNumPlayersNeededToStartSet, kSvConsoleTag) From fad6b3a5f7118628890e99cc97e3f1c8b8fad070 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Tue, 3 Nov 2026 19:02:06 +0100 Subject: [PATCH 02/71] AI: engine-side support for the AI reconstruction Math, Core, IO, Scene, Physics and Platform units the AI library needs, plus the GameLogic/GameEvents AI call sites (collision-handler and radio-courier reports, CombatArea AI queries, PortalEvent, DropVehicleEvent producer). Minimal hunks only; Polynom.h keeps its libstdc++ licence notice. goUpInPath restores the leading slash it strips, as the ELF does; on Windows only when the path had one, because isPathAbsolute also accepts drive paths there. The Linux plugin loader calls deinitDll before dlclose so a map reload cannot reuse stale AI singletons ([CHOSEN, not recovered], a native-port design). The RendDX9 and bf2_runtime_pair manifests link the units the recovered Math code now needs. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: OpenAI Codex --- CMakeLists.txt | 2 + Code/BF2/Core/ConsoleObjectBase.cpp | 4 + Code/BF2/Core/ConsoleObjects.cpp | 3 + Code/BF2/Core/DllStlAllocator.cpp | 22 + Code/BF2/Core/DllStlAllocator.h | 16 + Code/BF2/Core/Globals.cpp | 4 +- Code/BF2/Core/PluginDll.cpp | 16 +- Code/BF2/Core/PluginDll.h | 7 + Code/BF2/Core/Random.cpp | 16 +- Code/BF2/Core/Random.h | 3 + Code/BF2/Core/SpHandlePool.h | 1 + Code/BF2/Core/StringUtil.cpp | 305 ++++++-- Code/BF2/Core/StringUtil.h | 24 +- Code/BF2/Game/GameEvents/DropVehicleEvent.cpp | 5 +- Code/BF2/Game/GameEvents/DropVehicleEvent.h | 4 +- Code/BF2/Game/GameLogic/CombatArea.cpp | 12 + Code/BF2/Game/GameLogic/CombatArea.h | 3 + Code/BF2/Game/GameLogic/CombatAreaManager.cpp | 54 ++ Code/BF2/Game/GameLogic/CombatAreaManager.h | 7 + .../BF2/Game/GameLogic/GameLogicCollision.cpp | 33 +- Code/BF2/Game/GameLogic/GameLogicDamage.cpp | 4 +- .../BF2/Game/GameLogic/GameLogicExplosion.cpp | 21 +- Code/BF2/Game/GameLogic/Player.cpp | 9 +- Code/BF2/Game/GameLogic/Player.h | 16 +- .../BF2/Game/GameLogic/SquadManager/Squad.cpp | 6 +- .../GameLogic/SquadManager/SquadManager.cpp | 14 +- Code/BF2/Game/GameServer/GameServer.cpp | 47 +- Code/BF2/Game/GameServer/GameServer.h | 2 +- .../Game/Objects/Base/SimpleObjectTemplate.h | 5 +- Code/BF2/Game/Objects/Game/ArtilleryHandler.h | 3 + Code/BF2/Game/Objects/Game/Soldier.cpp | 73 +- Code/BF2/Game/Objects/Game/Triggerable.h | 5 + .../Objects/Projectiles/GenericProjectile.cpp | 13 +- .../Weapons/FireComponents/MultiFireComp.cpp | 11 +- .../Game/Objects/Weapons/GenericFireArm.cpp | 29 +- Code/BF2/IO/File/File.cpp | 45 +- Code/BF2/IO/File/File.h | 5 +- Code/BF2/IO/Input/InputMapStream.cpp | 19 +- Code/BF2/IO/Stream/BoundingBox.cpp | 179 +++++ Code/BF2/IO/Stream/MemStream.cpp | 4 + Code/BF2/Math/BoundingBox.h | 38 + Code/BF2/Math/DoubleVec3.cpp | 81 ++ Code/BF2/Math/DoubleVec3.h | 19 + Code/BF2/Math/Frustum.cpp | 111 ++- Code/BF2/Math/Frustum.h | 13 +- Code/BF2/Math/Intersect.cpp | 52 +- Code/BF2/Math/Intersect.h | 11 + Code/BF2/Math/LocalBoundingBox.cpp | 99 ++- Code/BF2/Math/LocalBoundingBox.h | 31 +- Code/BF2/Math/Mat3.cpp | 77 ++ Code/BF2/Math/Mat3.h | 30 + Code/BF2/Math/Mat4.cpp | 124 +++ Code/BF2/Math/Mat4.h | 17 + Code/BF2/Math/Mat4Inverse.cpp | 30 +- Code/BF2/Math/Math.cpp | 16 +- Code/BF2/Math/Plane3.cpp | 24 +- Code/BF2/Math/Plane3.h | 6 +- Code/BF2/Math/Polynom.h | 286 +++++++ Code/BF2/Math/PortableX87.h | 272 +++++++ Code/BF2/Math/Vec3.cpp | 733 +++++++++++++++++- Code/BF2/Math/Vec3.h | 95 ++- Code/BF2/Physics/SoldierResponse.h | 5 + Code/BF2/Platform/X87Compat.h | 93 +++ .../WorldObjTemplPortal/PortalEvent.cpp | 18 + .../Object/WorldObjTemplPortal/PortalEvent.h | 29 + .../WorldObjTemplPortal/PortalManager.cpp | 28 +- Code/Build/renddx9.cmd | 2 + 67 files changed, 3073 insertions(+), 318 deletions(-) create mode 100644 Code/BF2/Core/DllStlAllocator.cpp create mode 100644 Code/BF2/Core/DllStlAllocator.h create mode 100644 Code/BF2/IO/Stream/BoundingBox.cpp create mode 100644 Code/BF2/Math/BoundingBox.h create mode 100644 Code/BF2/Math/DoubleVec3.cpp create mode 100644 Code/BF2/Math/DoubleVec3.h create mode 100644 Code/BF2/Math/Mat3.cpp create mode 100644 Code/BF2/Math/Mat3.h create mode 100644 Code/BF2/Math/Polynom.h create mode 100644 Code/BF2/Math/PortableX87.h create mode 100644 Code/BF2/Platform/X87Compat.h create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.cpp create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.h diff --git a/CMakeLists.txt b/CMakeLists.txt index dd83553e6..87b445db0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1841,6 +1841,8 @@ if(BUILD_TESTING AND MSVC) "${BF2_ROOT}/Physics/StaticResponsePhysics.cpp" "${BF2_ROOT}/IO/Network/INetworkable.cpp" "${BF2_ROOT}/Math/LocalBoundingBox.cpp" + "${BF2_ROOT}/Math/Intersect.cpp" + "${BF2_ROOT}/IO/Stream/BoundingBox.cpp" "${BF2_ROOT}/Math/Frustum.cpp" "${BF2_ROOT}/Math/Mat4.cpp" "${BF2_ROOT}/Math/Plane3.cpp" diff --git a/Code/BF2/Core/ConsoleObjectBase.cpp b/Code/BF2/Core/ConsoleObjectBase.cpp index a9df93be6..4bca74059 100644 --- a/Code/BF2/Core/ConsoleObjectBase.cpp +++ b/Code/BF2/Core/ConsoleObjectBase.cpp @@ -1,6 +1,9 @@ // Path: [INFERRED] - see ConsoleObjectBase.h header block. // Contents: recovered from bf2.i64 (ELF, symbolised), 0x83be630 - 0x83beab6. +// static init: ELF 0x4863B0 (__tcf_0 0x486410, _GLOBAL__I 0x486440): 's Init object only. +#include + #include "ConsoleObjectBase.h" #include "ConsoleObjectMacro.h" // consoleBindingList / the three default accessors #include @@ -13,6 +16,7 @@ namespace hfe { // Converts typed arguments or stores raw string pointers, executes the binding and formats its result. // setArgFromString uses one-based indices; argument storage belongs to the generated binding. +// ELF 0x486320; engine 0x83BE630. Slots +0x68, +0x7C, +0x60, +0x64 are attested in both images. std::string ConsoleObjectBaseImpl::execute(std::string* args, int argCount) { // [TEMP] [CHOSEN, not recovered] BF2_TRACE_CONSOLE logs each invoked binding. diff --git a/Code/BF2/Core/ConsoleObjects.cpp b/Code/BF2/Core/ConsoleObjects.cpp index 904eb9b63..9c7ac76b0 100644 --- a/Code/BF2/Core/ConsoleObjects.cpp +++ b/Code/BF2/Core/ConsoleObjects.cpp @@ -1,5 +1,8 @@ // Console binding registration and lookup. [INFERRED] Source placement. +// static init: ELF 0x4872D0 (__tcf_0 0x487330, _GLOBAL__I 0x487360): 's Init object only. +#include + #include "ConsoleObjects.h" #include // strncasecmp / _strnicmp - see prefixMatchesNoCase below diff --git a/Code/BF2/Core/DllStlAllocator.cpp b/Code/BF2/Core/DllStlAllocator.cpp new file mode 100644 index 000000000..f32372c11 --- /dev/null +++ b/Code/BF2/Core/DllStlAllocator.cpp @@ -0,0 +1,22 @@ +// DllStlAllocator.cpp is an original ELF FILE symbol. Function placement [INFERRED] +// from its position between DllModule.cpp and Random.cpp. +#include "DllStlAllocator.h" + +namespace dice { +namespace hfe { + +// ELF 0x48A7F0; engine 0x83C3420. +void* HeapAlloc(unsigned long size) +{ + return new char[size]; +} + +// ELF 0x48A820; engine 0x83C3430. +void HeapFree(void* storage) +{ + if (storage) + delete[] static_cast(storage); +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Core/DllStlAllocator.h b/Code/BF2/Core/DllStlAllocator.h new file mode 100644 index 000000000..3fe3bf060 --- /dev/null +++ b/Code/BF2/Core/DllStlAllocator.h @@ -0,0 +1,16 @@ +// Allocation pair shared by the engine and side DLLs. Header placement [INFERRED]. +#ifndef CORE_DLLSTLALLOCATOR_H +#define CORE_DLLSTLALLOCATOR_H + +namespace dice { +namespace hfe { + +// Allocates uninitialized array storage; allocation failure follows operator new[]. +void* HeapAlloc(unsigned long size); +// Releases storage from HeapAlloc; a null pointer has no effect. +void HeapFree(void* storage); + +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/Core/Globals.cpp b/Code/BF2/Core/Globals.cpp index 2da7cb944..c867bb428 100644 --- a/Code/BF2/Core/Globals.cpp +++ b/Code/BF2/Core/Globals.cpp @@ -111,8 +111,8 @@ namespace ai { IBase* g_aiConnection = 0; // ds:0x8B29AE0 _ZN4dice3hfe2ai14g_aiConnectionE // [CHOSEN] AI-instance singleton name. Its bots-game query controls whether loading includes .ai files. IBase* g_aiInstance = 0; // ds:0x8AC37F8 [CHOSEN name] -// [CHOSEN] AI collision-handler singleton name. Null without an AI DLL; consumers report damage and firing here. -IBase* g_bfCollisionHandler = 0; // ds:0x8AC35E4 [CHOSEN name] +// ds:0x8AC35E4 is CommonSingletonServer::m_iBFCollisionHandler (AIDLL/AI/Main), not a separate +// global: the engine's fire, timeout, collision, explosion and damage reports read it there. } namespace world { diff --git a/Code/BF2/Core/PluginDll.cpp b/Code/BF2/Core/PluginDll.cpp index 074eebcd4..4f16a7b6d 100644 --- a/Code/BF2/Core/PluginDll.cpp +++ b/Code/BF2/Core/PluginDll.cpp @@ -1,5 +1,5 @@ // Loads engine plugins for client and dedicated images; source path [INFERRED]. -// Windows unload calls optional deinitDll and reports exceptions. ELF unload only closes the library. +// Windows unload calls optional deinitDll and reports exceptions. Linux also deinitializes before close. #include "PluginDll.h" @@ -113,9 +113,19 @@ bool FreeLibraryBf(void* handle, const char* diagnosticName) return false; } #else - // : the bare wrapper call. No deinitDll lookup, no diagnostic, and the - // second argument is never read. (void)diagnosticName; +#if defined(__linux__) + // [CHOSEN, not recovered] Native-port design, not retail: unregister AI/console singletons before dlclose + // so a map reload cannot reuse stale objects. Retail ELF 0x83C3400 only closes the library; + // Win32 BF2.exe 0x446CE0 calls deinitDll first. AIModule::close (ELF 0x3EECB0) + // unregisters the AI singleton; preserve that teardown before unmapping native libaidll.so. + if (handle) + { + DeinitDllFn deinitDll = reinterpret_cast(::GetProcAddress(handle, "deinitDll")); + if (deinitDll) + deinitDll(); + } +#endif return ::FreeLibrary(handle); #endif } diff --git a/Code/BF2/Core/PluginDll.h b/Code/BF2/Core/PluginDll.h index a50248cd9..e15291fd1 100644 --- a/Code/BF2/Core/PluginDll.h +++ b/Code/BF2/Core/PluginDll.h @@ -3,6 +3,13 @@ #ifndef CORE_PLUGINDLL_H #define CORE_PLUGINDLL_H +#if !defined(_WIN32) +// [PLATFORM] ELF wrappers over dlopen/dlsym/dlclose, defined in PluginDll.cpp. +void* LoadLibrary(const char* name); +void* GetProcAddress(void* handle, const char* name); +bool FreeLibrary(void* handle); +#endif + namespace dice { namespace hfe { diff --git a/Code/BF2/Core/Random.cpp b/Code/BF2/Core/Random.cpp index d73d31190..70552a64b 100644 --- a/Code/BF2/Core/Random.cpp +++ b/Code/BF2/Core/Random.cpp @@ -1,4 +1,9 @@ -// Stream serialization for shared random-distribution types. [INFERRED] Source placement. +// Random state and distribution serialization. [INFERRED] Core placement; AI FILE symbol: Random.cpp. + +#if defined(BF2_IMAGE_AIDLL) +// static init: ELF 0x48A850 (__tcf_0 0x48A8D0, _GLOBAL__I 0x48A900): iostream Init, then Rand. +#include +#endif #include "Random.h" @@ -10,6 +15,13 @@ namespace dice { namespace hfe { +#if defined(BF2_IMAGE_AIDLL) +// ELF BSS 0x4DD454; the initializer's store at 0x48A8BA is Random's default seed. +Random Rand; +#else +// [CHOSEN, not recovered] Image partition: these distribution codecs belong to the engine; +// the original AI Random.cpp contributes its independent state and initialization only. + // ELF 0x83CFC50 (87 B), PE 0x5C10D0 (91 B). The default arm covers CRD_NONE and every invalid // selector; do not print an unknown integer numerically. std::ostream& operator<<(std::ostream& stream, ContRandDist distribution) @@ -93,5 +105,7 @@ std::istream& operator>>(std::istream& stream, RandomDistribution& distribution) return stream; } +#endif + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Core/Random.h b/Code/BF2/Core/Random.h index 7dc9d5931..e9181663a 100644 --- a/Code/BF2/Core/Random.h +++ b/Code/BF2/Core/Random.h @@ -62,6 +62,9 @@ static_assert(sizeof(RandomDistribution) == 0x14, extern Random g_random; // ELF ds:0x8ABBCB0 [CHOSEN symbol name] +// The AI DLL's independent random instance (ia-32 BSS 0x4DD454, Random.cpp initializer). +extern Random Rand; + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Core/SpHandlePool.h b/Code/BF2/Core/SpHandlePool.h index 5ca45b06e..b7b60c849 100644 --- a/Code/BF2/Core/SpHandlePool.h +++ b/Code/BF2/Core/SpHandlePool.h @@ -25,6 +25,7 @@ class SpHandlePool }; // Initializes empty records with generation zero and links every slot into the free list. + // libaidll.so: the SpHandlePool instantiation is ELF 0x36D580 (weak). SpHandlePool() { for (int i = 0; i < N; ++i) diff --git a/Code/BF2/Core/StringUtil.cpp b/Code/BF2/Core/StringUtil.cpp index 79aed2d31..085535a4e 100644 --- a/Code/BF2/Core/StringUtil.cpp +++ b/Code/BF2/Core/StringUtil.cpp @@ -17,16 +17,114 @@ # include #endif +namespace { + +// ELF 0x48BE30 (string), 0x48C420 (wstring); engine ELF 0x83D1510/0x83D1A40. +template +String extractFileExt_internal(const String& path) +{ + typedef typename String::value_type Char; + const int dot = static_cast(path.rfind(static_cast('.'))); + if (dot == -1 || (dot > 1 && path[dot - 1] == static_cast('.'))) + return String(); + return path.substr(dot + 1); +} + +// ELF 0x48BEF0 (string), 0x48C4E0 (wstring); engine ELF 0x83D15B0/0x83D1AE0. +template +String extractFileName_internal(const String& path) +{ + typedef typename String::value_type Char; + int last = static_cast(path.rfind(static_cast('\\'))); + const int slash = static_cast(path.rfind(static_cast('/'))); + if (slash > last) last = slash; + return last == -1 ? path : path.substr(last + 1); +} + +// ELF 0x48BFB0 (string), 0x48C5A0 (wstring); engine ELF 0x83D1660/0x83D1B90. +template +String extractFilePath_internal(const String& path, Char delimiter) +{ + int last = static_cast(path.rfind(static_cast('\\'))); + const int slash = static_cast(path.rfind(static_cast('/'))); + if (slash > last) last = slash; + if (last == -1) return String(); + return path.substr(0, last) + delimiter; +} + +// ELF 0x48C0A0 (string), 0x48C690 (wstring); engine ELF 0x83D1740/0x83D1C70. +template +String extractFileNameWithoutExt_internal(const String& path) +{ + const String name = dice::hfe::extractFileName(path); + const int dot = static_cast(name.rfind(static_cast('.'))); + return dot == -1 ? name : name.substr(0, dot); +} + +// ELF 0x48C160 (string), 0x48C750 (wstring); engine ELF 0x83D17F0/0x83D1D20. +template +String extractEverythingExceptExt_internal(const String& path) +{ + typedef typename String::value_type Char; + const String normalized = dice::hfe::getFixPathDelimiters(path, static_cast('/')); + const int dot = static_cast(normalized.rfind(static_cast('.'))); + return dot == -1 ? normalized : normalized.substr(0, dot); +} + +// ELF 0x48C230 (string), 0x48C820 (wstring); engine ELF 0x83D18A0/0x83D1DD0. +template +void fixPath_internal(String& path, Char delimiter) +{ + if (!path.empty()) + { + dice::hfe::fixPathDelimiters(path, delimiter); + if (path[path.length() - 1] != delimiter) + path.append(1, delimiter); + } +} + +// ELF 0x48C2D0 (string), 0x48C8A0 (wstring); engine ELF 0x83D1920/0x83D1E50. +template +void fixPathDelimiters_internal(String& path, Char delimiter) +{ + const typename String::size_type length = path.length(); + for (typename String::size_type i = 0; i < length; ++i) + if (path[i] == static_cast('/') || path[i] == static_cast('\\')) + path[i] = delimiter; +} + +// ELF 0x48C380 (string), 0x48C950 (wstring); engine ELF 0x83D19C0/0x83D1EF0. +template +String getFixPath_internal(const String& path, Char delimiter) +{ + String result(path); + dice::hfe::fixPath(result, delimiter); + return result; +} + +// ELF 0x48C3D0 (string), 0x48C9A0 (wstring); engine ELF 0x83D1A00/0x83D1F30. +template +String getFixPathDelimiters_internal(const String& path, Char delimiter) +{ + String result(path); + dice::hfe::fixPathDelimiters(result, delimiter); + return result; +} + +} // anonymous namespace + namespace dice { namespace hfe { +// ELF 0x48A920. +// static init: ELF 0x48BDE0 (getEmptyString's local static teardown). const std::string& getEmptyString() { static const std::string empty; return empty; } -// Converts wide text using the active C locale. The existing error check tests count + 1, +// ELF 0x48BA40. Converts wide text using the active C locale. The existing error check tests count + 1, // so callers must not rely on it to reject every invalid conversion. std::string makeNarrow(const std::wstring& source) { @@ -42,7 +140,7 @@ std::string makeNarrow(const std::wstring& source) return std::string(buffer.data(), converted); } -// Converts multibyte text to wide characters using the active C locale. +// ELF 0x48BCA0. Converts multibyte text to wide characters using the active C locale. std::wstring makeWide(const std::string& source) { const std::size_t capacity = std::mbstowcs(0, source.c_str(), 0) + 1; @@ -57,7 +155,7 @@ std::wstring makeWide(const std::string& source) return result; } -// Formats into a shared 4-KB buffer and returns a string copy; not reentrant or thread-safe. +// ELF 0x48A990. Formats into a shared 4-KB buffer and returns a string copy; not reentrant or thread-safe. // A negative vsnprintf result replaces the message with a warning. Successful formatting writes // the terminator at the reported length. Preserve the original runtime-dependent overflow behavior. std::string formatString(const char* fmt, ...) @@ -79,6 +177,25 @@ std::string formatString(const char* fmt, ...) return std::string(s_buffer); } +// ELF 0x48AA30; engine ELF 0x83D0440. +std::wstring formatWstring(const wchar_t* fmt, ...) +{ + static wchar_t buffer[4096]; + va_list args; + va_start(args, fmt); + const int count = std::vswprintf(buffer, 0xFFF, fmt, args); + va_end(args); + if (count == -1) + { + // shipped defect: POSIX %s reads the wide warning as narrow bytes, producing only "W". + std::swprintf(buffer, 0x1000, L"%s", + L"WARNING: The original message was too long for formatString(). \n"); + } + else + buffer[count] = 0; + return std::wstring(buffer); +} + #if !DEDICATED // Client PE 431130, all 29 instructions read. Buffer 99C158 is shared, and // _vsnwprintf's -1 result replaces the whole message with the shipped warning. @@ -98,38 +215,76 @@ std::wstring formatString(const wchar_t* fmt, ...) } #endif -// Compares null-terminated strings without case. String overloads delegate through c_str(). +// ELF 0x48AB30. Compares null-terminated strings without case. String overloads delegate through c_str(). int compareIgnoreCase(const char* a, const char* b) { return strcasecmp(a, b); } +// ELF 0x48ABD0. int compareIgnoreCase(const char* a, const char* b, int n) { + if (n == 0) + return 0; return strncasecmp(a, b, n); } +// ELF 0x48AAD0. int compareIgnoreCase(const std::string& a, const std::string& b) { return compareIgnoreCase(a.c_str(), b.c_str()); } +// ELF 0x48AB60. int compareIgnoreCase(const std::string& a, const std::string& b, int n) { return compareIgnoreCase(a.c_str(), b.c_str(), n); } +// ELF 0x48AC10. bool equalsIgnoreCase(const std::string& a, const std::string& b) { return compareIgnoreCase(a, b) == 0; } +// ELF 0x48AC50. bool equalsIgnoreCase(const std::string& a, const std::string& b, int n) { return compareIgnoreCase(a, b, n) == 0; } -// Returns the engine's case-insensitive hash using ASCII-only uppercase folding. +// ELF 0x48AC90; engine ELF 0x83D0600. amd-64 preserves the full size_type return. +std::string::size_type lowerCaseFind(const std::string& text, const std::string& pattern) +{ + std::string loweredText(text); + std::string loweredPattern(pattern); + setLowerCase(loweredText); + setLowerCase(loweredPattern); + return loweredText.find(loweredPattern); +} + +// ELF 0x48AD60; engine ELF 0x83D06B0. +void eraseSubString(std::string& text, const std::string& pattern) +{ + const std::string::size_type at = text.find(pattern); + if (at != std::string::npos) + text.erase(at, pattern.length()); +} + +// ELF 0x48B9A0; engine ELF 0x83D10F0. Both images explicitly return the input pointer. +std::string* replaceAll(std::string* text, const std::string& pattern, const std::string& replacement) +{ + std::string::size_type at = 0; + while ((at = text->find(pattern, at)) != std::string::npos) + { + text->replace(at, pattern.length(), replacement); + // Read the replacement length after the mutation too, preserving argument aliasing. + at += replacement.length(); + } + return text; +} + +// ELF 0x487AF0. Returns the engine's case-insensitive hash using ASCII-only uppercase folding. // Preserve its constants and shifts because bucket order affects duplicate selection. unsigned int calcStringHashValueNoCase(const std::string& s) { @@ -157,7 +312,7 @@ unsigned int calcStringHashValueNoCase(const std::string& s) return (hash >> 16) + hash; // hiword(hash) + hash } -// Reports whether the virtual-filesystem path is absolute under the selected platform rules. +// ELF 0x48B910. Reports whether the virtual-filesystem path is absolute under the selected platform rules. // [PLATFORM] POSIX requires a leading slash; Windows searches for :\ or :/ anywhere in the string. // Leading slash alone is relative on Windows, allowing engine search-path resolution. bool isPathAbsolute(const std::string& s) @@ -171,39 +326,38 @@ bool isPathAbsolute(const std::string& s) // Normalizes both slash forms to c. fixPath additionally ensures a trailing separator; // both preserve an empty string as empty. +// ELF 0x48B3E0. void fixPathDelimiters(std::string& s, char c) { - for (std::string::size_type i = 0; i < s.size(); ++i) - if (s[i] == '/' || s[i] == '\\') - s[i] = c; + fixPathDelimiters_internal(s, c); } +// ELF 0x48B3B0. void fixPath(std::string& s, char c) { - if (s.empty()) - return; // guarded - "" stays "" - - fixPathDelimiters(s, c); - - if (s[s.size() - 1] != c) - s.append(1, c); // guarantee the trailing separator + fixPath_internal(s, c); } +// ELF 0x48B460. std::string getFixPathDelimiters(const std::string& s, char c) { - std::string out(s); - fixPathDelimiters(out, c); - return out; + return getFixPathDelimiters_internal(s, c); } +// ELF 0x48B410. std::string getFixPath(const std::string& s, char c) { - std::string out(s); - fixPath(out, c); - return out; + return getFixPath_internal(s, c); } -// Wide-character helper counterparts remain [UNRESOLVED]; the narrow implementations follow below. +// ELF 0x48B600; engine ELF 0x83D0DF0. +void fixPath(std::wstring& s, wchar_t c) { fixPath_internal(s, c); } +// ELF 0x48B630; engine ELF 0x83D0E00. +void fixPathDelimiters(std::wstring& s, wchar_t c) { fixPathDelimiters_internal(s, c); } +// ELF 0x48B660; engine ELF 0x83D0E10. +std::wstring getFixPath(const std::wstring& s, wchar_t c) { return getFixPath_internal(s, c); } +// ELF 0x48B6B0; engine ELF 0x83D0E40. +std::wstring getFixPathDelimiters(const std::wstring& s, wchar_t c) { return getFixPathDelimiters_internal(s, c); } // Changes case using explicit Latin-1 pairs for Ã¥/Ã…, ä/Ä, ö/Ö, ü/Ü and é/É before CRT fallback. // Keep these mappings independent of the active locale; archive and content lookup depend on them. @@ -227,7 +381,7 @@ const unsigned int kLatin1CasePairCount = sizeof(kLatin1CasePairs) / sizeof(kLat } // anonymous namespace -// Uppercases text in place, handling the explicit extended-character pairs before toupper. +// ELF 0x48AE00. Uppercases text in place, handling the explicit extended-character pairs before toupper. void setUpperCase(std::string& s) { for (std::string::size_type i = 0; i < s.size(); ++i) @@ -249,7 +403,7 @@ void setUpperCase(std::string& s) } } -// The exact mirror - same five pairs, tested upper-first. +// ELF 0x48AFF0. The exact mirror - same five pairs, tested upper-first. void setLowerCase(std::string& s) { for (std::string::size_type i = 0; i < s.size(); ++i) @@ -277,6 +431,7 @@ void setLowerCase(std::string& s) // settles it in the opposite direction. Here the body constructs into the hidden sret pointer // (`std::string::string(this, a2)` where `this` is the return slot) and hands that back. A // reference-returning function has nothing to construct. +// ELF 0x48B1E0. std::string getUpperCase(const std::string& s) { std::string result(s); @@ -284,6 +439,7 @@ std::string getUpperCase(const std::string& s) return result; } +// ELF 0x48B220. std::string getLowerCase(const std::string& s) { std::string result(s); @@ -291,64 +447,46 @@ std::string getLowerCase(const std::string& s) return result; } -// Returns the directory through the last slash of either kind, using delimiter for the trailing separator. +// ELF 0x48B2E0. Returns the directory through the last slash of either kind, using delimiter for the trailing separator. // Returns an empty string when no separator exists. std::string extractFilePath(const std::string& path, char delimiter) { - std::string::size_type last = path.rfind('\\'); - const std::string::size_type slash = path.rfind('/'); - if (slash != std::string::npos && (last == std::string::npos || slash > last)) - last = slash; - if (last == std::string::npos) - return std::string(); - - std::string out = path.substr(0, last); - out.append(1, delimiter); - return out; + return extractFilePath_internal(path, delimiter); } -// Returns text after the last dot, or empty for no dot/trailing dot. +// ELF 0x48B260. Returns text after the last dot, or empty for no dot/trailing dot. // A preceding dot suppresses extensions only when the last dot is at index 2 or later: // ..x yields x, while a..x yields empty. std::string extractFileExt(const std::string& path) { - const std::string::size_type dot = path.rfind('.'); - if (dot == std::string::npos) - return std::string(); - - if (dot > 1 && path[dot - 1] == '.') - return std::string(); - - return path.substr(dot + 1); + return extractFileExt_internal(path); } -// Normalizes repeated separators, strips a leading slash and recursively collapses /../ segments. -// Traversal beyond the beginning is absorbed rather than rejected; this is not a containment check. -// [CHOSEN, not recovered] removeDoubleSlashes still requires direct binary verification, including -// backslash and leading-double-slash behavior. +// ELF 0x48B870; engine ELF 0x83D0FD0. void removeDoubleSlashes(std::string& path) { - std::string::size_type at = path.find("//"); - while (at != std::string::npos) + const std::string::size_type at = path.find("//"); + if (at != std::string::npos) { path.erase(at, 1); - at = path.find("//", at); + removeDoubleSlashes(path); } } -void goUpInPath(std::string& path) +namespace { +// ELF 0x48B700; engine ELF 0x83D0E70. +void goUpInPath_worker(std::string& path) { removeDoubleSlashes(path); if (!path.empty() && path[0] == '/') - path.erase(0, 1); // absolute becomes relative - see above + path.erase(0, 1); const std::string::size_type found = path.find("/../"); if (found == std::string::npos) return; - std::string::size_type start = (found == 0) ? std::string::npos - : path.rfind('/', found - 1); + std::string::size_type start = path.rfind("/", found - 1); if (start == std::string::npos) start = 0; @@ -358,32 +496,51 @@ void goUpInPath(std::string& path) path.erase(start, count); - goUpInPath(path); // recurse until no "/../" remains + goUpInPath_worker(path); +} +} // anonymous namespace + +// ELF 0x48B930; engine ELF 0x83D1090. +void goUpInPath(std::string& path) +{ + // The worker strips a leading '/'; the ELF restores it for an absolute path, and on ELF an + // absolute path is exactly one with a leading '/'. + // [PLATFORM] isPathAbsolute also accepts drive paths (C:/...) on Windows, which never had a + // leading '/'; restoring one there yields "/C:/..." and breaks every file lookup. Windows + // restores the slash only when the path started with one. [INFERRED] PE body not compared. +#if defined(_WIN32) + const bool absolute = !path.empty() && path[0] == '/'; +#else + const bool absolute = isPathAbsolute(path); +#endif + goUpInPath_worker(path); + if (absolute) + path.insert(0, "/"); } -// Returns the final path component without its last extension. Names without a dot remain unchanged. +// ELF 0x48B330. Returns the final path component without its last extension. Names without a dot remain unchanged. std::string extractFileNameWithoutExt(const std::string& path) { - const std::string name = extractFileName(path); - const std::string::size_type dot = name.rfind('.'); - if (dot == std::string::npos) - return name; - return name.substr(0, dot); + return extractFileNameWithoutExt_internal(path); } -// Returns the component after the last slash of either kind. A trailing slash produces an empty name. +// ELF 0x48B2A0. Returns the component after the last slash of either kind. A trailing slash produces an empty name. std::string extractFileName(const std::string& path) { - const std::string::size_type backslash = path.rfind('\\'); - const std::string::size_type slash = path.rfind('/'); - - std::string::size_type last = backslash; - if (slash != std::string::npos && (last == std::string::npos || slash > last)) - last = slash; - - if (last == std::string::npos) - return path; - return path.substr(last + 1); + return extractFileName_internal(path); } + +// ELF 0x48B370; engine ELF 0x83D0C30. +std::string extractEverythingExceptExt(const std::string& path) { return extractEverythingExceptExt_internal(path); } +// ELF 0x48B4B0; engine ELF 0x83D0D00. +std::wstring extractFileExt(const std::wstring& path) { return extractFileExt_internal(path); } +// ELF 0x48B4F0; engine ELF 0x83D0D30. +std::wstring extractFileName(const std::wstring& path) { return extractFileName_internal(path); } +// ELF 0x48B530; engine ELF 0x83D0D60. +std::wstring extractFilePath(const std::wstring& path, wchar_t c) { return extractFilePath_internal(path, c); } +// ELF 0x48B580; engine ELF 0x83D0D90. +std::wstring extractFileNameWithoutExt(const std::wstring& path) { return extractFileNameWithoutExt_internal(path); } +// ELF 0x48B5C0; engine ELF 0x83D0DC0. +std::wstring extractEverythingExceptExt(const std::wstring& path) { return extractEverythingExceptExt_internal(path); } // Converts multibyte text to wide characters; failed conversion returns an empty string. std::wstring toWideString(const std::string& s) { diff --git a/Code/BF2/Core/StringUtil.h b/Code/BF2/Core/StringUtil.h index ca578fc99..b29a1c2db 100644 --- a/Code/BF2/Core/StringUtil.h +++ b/Code/BF2/Core/StringUtil.h @@ -1,5 +1,4 @@ // Engine string/path helpers from the attested Core/StringUtil.cpp translation unit. -// This header declares narrow-string helpers; the original also instantiates wide counterparts. #ifndef CORE_STRINGUTIL_H // [INFERRED] guard style #define CORE_STRINGUTIL_H @@ -9,8 +8,9 @@ namespace dice { namespace hfe { -// Formats printf-style arguments into a string. [UNRESOLVED] Original return type beyond observed string consumers. +// Formats printf-style arguments in a shared buffer and returns a copy; not thread-safe. std::string formatString(const char* fmt, ...); +std::wstring formatWstring(const wchar_t* fmt, ...); #if !DEDICATED // Client PE 431130: wide overload, including the shared buffer and overflow warning. // [INFERRED] overload spelling; the dedicated ELF has no HUD caller for it. @@ -30,6 +30,12 @@ int compareIgnoreCase(const std::string& a, const std::string& b, int n); bool equalsIgnoreCase(const std::string& a, const std::string& b); bool equalsIgnoreCase(const std::string& a, const std::string& b, int n); +std::string::size_type lowerCaseFind(const std::string& text, const std::string& pattern); +// Removes only the first occurrence, if any. +void eraseSubString(std::string& text, const std::string& pattern); +// Replaces matches in place and returns text; text must be non-null. +// An empty pattern has no terminating case. +std::string* replaceAll(std::string* text, const std::string& pattern, const std::string& replacement); // Case conversion // The set* forms are 479 bytes each - they go through the locale, not a naive toupper loop. @@ -53,11 +59,16 @@ void fixPathDelimiters(std::string&, char); void fixPath(std::string&, char); std::string getFixPathDelimiters(const std::string&, char); std::string getFixPath(const std::string&, char); +void fixPathDelimiters(std::wstring&, wchar_t); +void fixPath(std::wstring&, wchar_t); +std::wstring getFixPathDelimiters(const std::wstring&, wchar_t); +std::wstring getFixPath(const std::wstring&, wchar_t); bool isPathAbsolute(const std::string&); -// Normalizes repeated path separators before parent traversal. -// [CHOSEN, not recovered] The helper body still needs direct binary verification. +// Recursively removes doubled forward slashes; backslashes are unchanged. void removeDoubleSlashes(std::string&); +// Collapses /../ segments and repeated forward slashes, preserving an absolute leading slash. +// Traversal beyond the beginning is absorbed; this is not a containment check. void goUpInPath(std::string&); std::string extractFilePath(const std::string&, char); @@ -65,6 +76,11 @@ std::string extractFileName(const std::string&); std::string extractFileNameWithoutExt(const std::string&); std::string extractFileExt(const std::string&); std::string extractEverythingExceptExt(const std::string&); // internal 0x83d17f0 +std::wstring extractFilePath(const std::wstring&, wchar_t); +std::wstring extractFileName(const std::wstring&); +std::wstring extractFileNameWithoutExt(const std::wstring&); +std::wstring extractFileExt(const std::wstring&); +std::wstring extractEverythingExceptExt(const std::wstring&); // Misc // Returns a shared empty std::string. Used as a sentinel return by FileManager::fileExistsEx and diff --git a/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp b/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp index 482a1d558..eab6620f7 100644 --- a/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp +++ b/Code/BF2/Game/GameEvents/DropVehicleEvent.cpp @@ -43,16 +43,15 @@ DropVehicleEvent::DropVehicleEvent(float positionX, float positionZ, int team, b { } -#if !DEDICATED // PE7B2460, all16 instructions read. Do not delegate to the default ctor: -// the retail client does not initialize m_field15, even though serialize reads it. +// ELF 0x840F690 inlines the same producer in BFCommander::dropVehicle. +// shipped defect: m_field15 is not initialized, even though serialize reads it. DropVehicleEvent::DropVehicleEvent(int team, Vec2 position) : GameEvent() { m_positionX = position.x; m_positionZ = position.y; m_team = static_cast(team); } -#endif int DropVehicleEvent::getType() const { diff --git a/Code/BF2/Game/GameEvents/DropVehicleEvent.h b/Code/BF2/Game/GameEvents/DropVehicleEvent.h index 6da8a087a..6759a3594 100644 --- a/Code/BF2/Game/GameEvents/DropVehicleEvent.h +++ b/Code/BF2/Game/GameEvents/DropVehicleEvent.h @@ -16,10 +16,8 @@ class DropVehicleEvent : public GameEvent // 0x18 public: // [INFERRED] argument order - no ELF constructor exists. DropVehicleEvent(float positionX, float positionZ, int team, bool field15); -#if !DEDICATED - // Client PE7B2460 leaves the serialized byte+15 untouched. + // The commander producer leaves the trailing serialized byte untouched. DropVehicleEvent(int team, Vec2 position); -#endif DropVehicleEvent() : m_positionX(0.0f), m_positionZ(0.0f), m_team(0), m_field15(false) {} virtual ~DropVehicleEvent() {} diff --git a/Code/BF2/Game/GameLogic/CombatArea.cpp b/Code/BF2/Game/GameLogic/CombatArea.cpp index df099cccf..61563f5f3 100644 --- a/Code/BF2/Game/GameLogic/CombatArea.cpp +++ b/Code/BF2/Game/GameLogic/CombatArea.cpp @@ -85,5 +85,17 @@ bool CombatArea::checkPositionPolygon(const Vec3& position) const return inside; } +// ELF 0x81245E0. The first edge's left-hand normal offsets its midpoint. +bool CombatArea::isClockwise() const +{ + const float dx = m_points[1].x - m_points[0].x; + const float dz = m_points[1].y - m_points[0].y; + Vec3 position; + position.x = -dz + (m_points[1].x + m_points[0].x) * 0.5f; + position.y = 0.0f; + position.z = dx + (m_points[1].y + m_points[0].y) * 0.5f; + return !checkPositionPolygon(position); +} + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Game/GameLogic/CombatArea.h b/Code/BF2/Game/GameLogic/CombatArea.h index 62e56d55e..4a4f4bda7 100644 --- a/Code/BF2/Game/GameLogic/CombatArea.h +++ b/Code/BF2/Game/GameLogic/CombatArea.h @@ -26,6 +26,9 @@ class CombatArea // Test the XZ position against the inclusive rectangle. bool checkPositionRect(const Vec3& position) const; + // Test the left side of the first polygon edge; requires at least two vertices. + bool isClockwise() const; + // Offsets describe the original 32-bit layout; STL-bearing layouts depend on the compiler. /* +0x00 */ int m_isPolygon; // 0 = rectangle, non-0 = polygon /* +0x04 */ float m_minX; diff --git a/Code/BF2/Game/GameLogic/CombatAreaManager.cpp b/Code/BF2/Game/GameLogic/CombatAreaManager.cpp index cac969aed..58332913d 100644 --- a/Code/BF2/Game/GameLogic/CombatAreaManager.cpp +++ b/Code/BF2/Game/GameLogic/CombatAreaManager.cpp @@ -295,5 +295,59 @@ void CombatAreaManager::addVehicleTimer(int vehicleCategory, float seconds) entry->second = seconds; } +// ELF 0x8125A00. The caller owns clearing the output vector. +bool CombatAreaManager::getAiCombatAreas(std::vector& areas) const +{ + for (unsigned int i = 0; i < m_areas.size(); ++i) + if (m_areas[i]->m_usedByPathFinding) + areas.push_back(m_areas[i]); + return areas.size() == 1; +} + +// ELF 0x8125890. The manager's player/team and enable filters do not apply here. +bool CombatAreaManager::isAiPositionInside(const Vec3& position, + const std::vector& areas) const +{ + bool anyInclusion = false; + bool inside = false; + for (unsigned int i = 0; i < areas.size(); ++i) + if (!areas[i]->m_isExclusion) + anyInclusion = true; + + if (!anyInclusion) + { + world::IHeightmap* heightmap = + static_cast(world::heightmapCluster)->getPrimaryHeightmap(); + int sizeX, sizeZ; + heightmap->getSize(sizeX, sizeZ); + // shipped defect: the dimensions are queried but never used to test the position. + inside = true; + } + + for (unsigned int i = 0; i < areas.size(); ++i) + { + CombatArea* area = areas[i]; + if (!area->m_isExclusion) + { + const bool hit = static_cast(area->m_isPolygon) + ? area->checkPositionPolygon(position) : area->checkPositionRect(position); + if (hit) + inside = true; + } + } + for (unsigned int i = 0; i < areas.size(); ++i) + { + CombatArea* area = areas[i]; + if (area->m_isExclusion) + { + const bool hit = static_cast(area->m_isPolygon) + ? area->checkPositionPolygon(position) : area->checkPositionRect(position); + if (hit) + inside = false; + } + } + return inside; +} + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Game/GameLogic/CombatAreaManager.h b/Code/BF2/Game/GameLogic/CombatAreaManager.h index 665479747..99181f1cb 100644 --- a/Code/BF2/Game/GameLogic/CombatAreaManager.h +++ b/Code/BF2/Game/GameLogic/CombatAreaManager.h @@ -5,6 +5,7 @@ #include #include #include +#include "../../Math/Vec3.h" namespace dice { namespace hfe { @@ -24,6 +25,12 @@ class CombatAreaManager // Null players and players without a controllable vehicle return false. bool isPlayerInside(world::IPlayer* player); + // Append pathfinding-enabled areas; return true only when the resulting list has one area. + bool getAiCombatAreas(std::vector& areas) const; + + // Apply inclusions and then exclusions from a borrowed AI area list. + bool isAiPositionInside(const Vec3& position, const std::vector& areas) const; + // Return the category grace period in seconds. Null objects, ladders, and absent entries // use the default. A non-null object must have a valid template. float getTimeAllowedOutside(world::IObject* object); diff --git a/Code/BF2/Game/GameLogic/GameLogicCollision.cpp b/Code/BF2/Game/GameLogic/GameLogicCollision.cpp index 659a28827..b6c933448 100644 --- a/Code/BF2/Game/GameLogic/GameLogicCollision.cpp +++ b/Code/BF2/Game/GameLogic/GameLogicCollision.cpp @@ -30,6 +30,8 @@ #include "../Objects/ISoldier.h" // the man-down retraction's getOccupingPlayer #include "../Objects/Projectiles/GenericProjectile.h" // the sole IProjectileObject implementor #include "../../Core/System.h" // WorldPref::getTickCount +#include "../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" // the AI collision courier +#include "../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler #if !DEDICATED // The client bodies of doImpact / playCollisionEffect (BF2.exe 0x5CADF0 / 0x5CA9C0 / 0x5CA910). #include "../Main/Game.h" // isDedicated() - BF2.exe 0x440510 @@ -46,8 +48,6 @@ namespace dice { namespace hfe { namespace world { extern IBase* materialManager; } // ds:0x8AD2820 - Core/Globals.cpp -namespace ai { extern IBase* g_bfCollisionHandler; } // ds:0x8AC35E4 - Core/Globals.cpp, and - // declared the same way in GenericProjectile.cpp namespace world { @@ -121,18 +121,6 @@ void normaliseIfNeeded(Vec3& v) } inline MaterialManager* materials() { return static_cast(materialManager); } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Stops at the opaque AI collision -// courier: object-hit and terrain-hit argument lists are unresolved. -// Reachable when g_bfCollisionHandler is populated. -// [RETIRE-WHEN: bfcollisionhandler-iface] Recover the complete typed interface, -// including projectile removal, before replacing this boundary. -[[noreturn]] void bfCollisionHandlerFrontier(const char* what) -{ - std::fprintf(stderr, - "[FRONTIER] dice::hfe::world::GameLogicCollision AI collision courier: %s\n", what); - std::fflush(stderr); - std::abort(); -} #if !DEDICATED // Builds a plane from normal and point, preserving (z + y) + x dot-product order. @@ -844,8 +832,10 @@ bool GameLogicCollision::serverHandleCollisionForProjectile(IObject* projectile, proj, projectile, hitObject, armor, damaged, faceB); } - if (ai::g_bfCollisionHandler) - bfCollisionHandlerFrontier("object hit (IBFCollisionHandler +0x0C)"); + // ELF 0x80DD04A: the AI collision handler hears the object hit (+0x0C) at the contact. + if (ai::IBFCollisionHandler* const collision = static_cast( + ai::CommonSingletonServer::m_iBFCollisionHandler)) + collision->handleCollision(projectile, hitObject, contact); } else { @@ -860,8 +850,15 @@ bool GameLogicCollision::serverHandleCollisionForProjectile(IObject* projectile, proj, projectile, 0, 0, false, faceB); } - if (ai::g_bfCollisionHandler) - bfCollisionHandlerFrontier("terrain hit (IBFCollisionHandler +0x30)"); + // ELF 0x80DD468: a terrain hit is a miss (+0x30): the owner's id (-1 without one), the + // round and its object id, the contact. + if (ai::IBFCollisionHandler* const collision = static_cast( + ai::CommonSingletonServer::m_iBFCollisionHandler)) + { + IPlayer* const owner = gp->getPlayer(); // +0x54 + collision->handleProjectileMiss(owner ? owner->getId() : -1, projectile, + projectile->getObjectId(), contact); + } } // ricochet / penetrate diff --git a/Code/BF2/Game/GameLogic/GameLogicDamage.cpp b/Code/BF2/Game/GameLogic/GameLogicDamage.cpp index 5d1095def..bdabbed78 100644 --- a/Code/BF2/Game/GameLogic/GameLogicDamage.cpp +++ b/Code/BF2/Game/GameLogic/GameLogicDamage.cpp @@ -427,8 +427,8 @@ void GameLogicDamage::serverGiveDamage(IObject* object, float damage, IPlayer* a { Vec3 pos = position; const unsigned int weaponId = weapon->getObjectId(); // +0x10 - // ..539 / PE 58763F..684: registered IBFCollisionHandler, - // not the independent chosen g_bfCollisionHandler storage. Vec3 is + // ..539 / bf2_w32ded.exe 0x58763F..684: the registered IBFCollisionHandler, the same + // variable (w32ded 0x8B7030, BF2.exe 0xA38688) every other engine report reads. Vec3 is // BY value (mangling and PE's twelve stack bytes); GCC passes its copy // indirectly. The typed call preserves the native compiler's ABI. collisionHandler->handleProjectileDamage(owner, damage, seatPlayer->getId(), weaponId, pos); diff --git a/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp b/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp index 9c78e9159..77d15ef2c 100644 --- a/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp +++ b/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp @@ -37,12 +37,12 @@ #include "../../Scene/Object/PlayerManager.h" #include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" #include "../../Sound/BfSound.h" +#include "../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler namespace dice { namespace hfe { -namespace ai { extern IBase* g_bfCollisionHandler; } - namespace world { extern IBase* materialManager; @@ -166,15 +166,6 @@ class FlagIgnoreWaterPredicator : public ObjectFlagPredicator } }; -// IBFCollisionHandler remains an AI-only interface frontier. -[[noreturn]] void bfCollisionHandlerFrontier() -{ - std::fprintf(stderr, - "[FRONTIER] dice::hfe::world::GameLogicExplosion AI explosion courier reached\n"); - std::fflush(stderr); - std::abort(); -} - GenericProjectile* projectileFromObject(IObject* object) { if (!object) @@ -443,8 +434,12 @@ bool GameLogicExplosion::serverHandleExplosionOnObject( return false; IPlayerControlObject* const pco = findPco(root); - if (player && ai::g_bfCollisionHandler && weapon) - bfCollisionHandlerFrontier(); + // ELF 0x80E375E: the AI hears the queued damage (+0x20), the explosion position by value. + ai::IBFCollisionHandler* const collision = + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler); + if (player && collision && weapon) + collision->handleExplosionDamage(object, calculatedDamage, player->getId(), + weapon->getObjectId(), explosionPosition); if (!pco) return false; diff --git a/Code/BF2/Game/GameLogic/Player.cpp b/Code/BF2/Game/GameLogic/Player.cpp index d958a4b00..f2e2087e2 100644 --- a/Code/BF2/Game/GameLogic/Player.cpp +++ b/Code/BF2/Game/GameLogic/Player.cpp @@ -230,9 +230,7 @@ Player::Player(int index, world::CPersistentExplosionEffectManager* explosionEff , m_profileId(0) , m_field2E0(1.0f) , m_field2E4(0.0f) - , m_field2E8(0) - , m_field2EC(0) - , m_field2F0(0) + , m_tearGasPosition() , m_field2F4(0.0f) , m_field2F8(1.0f) , m_gasDamage(0.0f) @@ -2192,10 +2190,7 @@ void Player::setBlurryVision(float fadeTime, float holdTime, float damage) if (vehicle) { const Vec3& position = vehicle->getAbsolutePosition(); - // These existing three dword carriers hold float bits, not numeric integers. - std::memcpy(&m_field2E8, &position.x, sizeof(float)); - std::memcpy(&m_field2EC, &position.y, sizeof(float)); - std::memcpy(&m_field2F0, &position.z, sizeof(float)); + m_tearGasPosition = position; } } m_field2E4 = damage; diff --git a/Code/BF2/Game/GameLogic/Player.h b/Code/BF2/Game/GameLogic/Player.h index 75f2c3ab4..dcc598d25 100644 --- a/Code/BF2/Game/GameLogic/Player.h +++ b/Code/BF2/Game/GameLogic/Player.h @@ -360,6 +360,14 @@ class Player : public world::IPlayer, public io::IConsoleSaveable, public io::Ne // Applies decoded remote weapon ammunition state to the player's live weapons. void forceSetRemoteClientAmmo(unsigned int firedMask); + // The position captured when a tear-gas exposure starts (see m_tearGasPosition). + // [CHOSEN, not recovered] Neither image has this accessor: the retail AI image reads the three + // floats at raw x86 offsets +0x2E8/+0x2EC/+0x2F0 of the world::IPlayer it gets from + // IAIPlayer::getPlayer (BBPAvoidCollisionInfantery::createPlan, libaidll 0x22E304..0x22E310, + // three `flds`). The inline accessor gives the native AI image the same field without copying + // x86 offsets. + const Vec3& getTearGasPosition() const { return m_tearGasPosition; } + private: // Non-vtable Player helpers, all attested by their ELF manglings and direct callers. Keeping // these private avoids inventing a wider gameplay API for implementation details. @@ -564,9 +572,11 @@ class Player : public world::IPlayer, public io::IConsoleSaveable, public io::Ne /* +0x2D8 */ int m_profileId; // 0 /* +0x2E0 */ float m_field2E0; // 1.0f NOT 0 /* +0x2E4 */ float m_field2E4; // 0; gas damage per second [UNRESOLVED name] - /* +0x2E8 */ int m_field2E8; // 0 - /* +0x2EC */ int m_field2EC; // 0 - /* +0x2F0 */ int m_field2F0; // 0 + // +0x2E8..+0x2F0: one Vec3, zeroed by the constructor; setBlurryVision (bf2 0x80F6890, + // 0x80F691D..0x80F693A) copies the three words of the default vehicle's getAbsolutePosition + // (+0x6C) through a base register at +0x2E8 when a gas exposure starts; the AI image reads + // them as floats. No other writer in the bf2 image. [INFERRED] name. + /* +0x2E8 */ Vec3 m_tearGasPosition; // (0, 0, 0) /* +0x2F4 */ float m_field2F4; // 0; blur fade countdown [UNRESOLVED name] /* +0x2F8 */ float m_field2F8; // 1.0f NOT 0 /* +0x2FC */ float m_gasDamage; // 0 diff --git a/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp b/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp index 7e7f36681..df38b37b4 100644 --- a/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp +++ b/Code/BF2/Game/GameLogic/SquadManager/Squad.cpp @@ -435,12 +435,10 @@ bool Squad::removeFromSquad(int playerId, bool skipScriptEvent, bool kicked) if (ai::g_aiInstance && ai::aiInstance()->isInitialized()) { - const int teamId = player->getTeam(); // player unchecked - (void)teamId; // / PE 0x45F844 reads the team before the courier call with // (playerId, current m_squadId, teamId), ELF +0x90 / PE +0x8C. - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::Squad::removeFromSquad (AIEventCourier::event_removedFromSquad)"); + const int teamId = player->getTeam(); // player unchecked + ai::BFSingletonServer::m_iaiEventCourier->event_removedFromSquad(playerId, m_squadId, teamId); } if (m_members.empty()) // +0x144 diff --git a/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp b/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp index 387d4859f..1adaf7138 100644 --- a/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp +++ b/Code/BF2/Game/GameLogic/SquadManager/SquadManager.cpp @@ -549,8 +549,10 @@ void SquadManager::issueSquadOrder(int teamId, int squadId, SquadOrder& order, } } -// Broadcasts the order before commander and member HUD notifications. Preserve -// repeated ID lookups. [UNRESOLVED] The optional AI courier branch remains omitted. +// issueCommanderOrder - ELF 0x811D800. Broadcasts the order before commander and member HUD +// notifications. Preserve repeated ID lookups. The AI singleton (ds:0x8AC37F8) is loaded once +// before the member loop; while it is non-null and initialized (IAIInstance +0x1C), every member +// first gets ecai 8 `(playerId, orderId)` (eventManager +0x14) and then its HUD 26, AI or not. void SquadManager::issueCommanderOrder(int teamId, int squadId, SquadOrder& order, bool suppressEvent) { @@ -578,6 +580,7 @@ void SquadManager::issueCommanderOrder(int teamId, int squadId, SquadOrder& orde new PostRemoteEvent(ECHud, 27, false, &squadId, 4, 0.0f)); } + IBase* const aiSingleton = ai::g_aiInstance; // 0x811D939: read once, before the loop for (std::set::iterator it = squad->m_members.begin(); it != squad->m_members.end(); ++it) { @@ -585,7 +588,12 @@ void SquadManager::issueCommanderOrder(int teamId, int squadId, SquadOrder& orde if (!player) continue; - // [UNRESOLVED] ecai 8 notification behind ds:0x8AC37F8 / PE dword_8B25B0. + // 0x811D98E..0x811DAA3: the AI courier's commander-order notification. + if (aiSingleton && reinterpret_cast(aiSingleton)->isInitialized()) + { + int aiPayload[2] = { *it, order.orderId }; + eventManager->postEvent(ECAI, 8, aiPayload, 0.0f); + } if (player->getId() == 255) { eventManager->postEvent(ECHud, 26, &squadId, 0.0f); diff --git a/Code/BF2/Game/GameServer/GameServer.cpp b/Code/BF2/Game/GameServer/GameServer.cpp index 1ff718b7e..b869c638a 100644 --- a/Code/BF2/Game/GameServer/GameServer.cpp +++ b/Code/BF2/Game/GameServer/GameServer.cpp @@ -121,6 +121,7 @@ #include // srand / rand - the challenge ordinal #include // the empty-maplist refusal writes to std::cout #include +#include "../../Scene/Object/WorldObjTemplPortal/PortalManager.h" // IPortalManager::update, +0x40 namespace dice { namespace hfe { @@ -2339,16 +2340,6 @@ extern IBase* portalManager; // ds:0x8B1ED80 - ditto } // namespace world namespace { -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Bot portal updates diagnose and abort at this seam. -void portalManagerUpdate(IBase* manager, float dt); // world::PortalManager::update(float) - vtable +0x40 (0x88CABE0 slot 16) - -void portalManagerUpdate(IBase* /*manager*/, float /*dt*/) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::(anon)::portalManagerUpdate" - " (world::PortalManager::update, vtable +0x40) reached (bots game)\n"); - std::fflush(stderr); - std::abort(); -} // Typed bridge from the shared connection interface to packet processing. inline bool clientConnectionProcessReceivedPacket(IClientConnection* c, io::BitStream* stream) { @@ -3513,7 +3504,7 @@ void GameServer::simulatePlayersCollisions(float dt) void GameServer::updatePortals(float dt) { if (ai::g_aiInstance && ai::aiInstance()->isBotsGame()) - portalManagerUpdate(world::portalManager, dt); // [FRONTIER] + reinterpret_cast(world::portalManager)->update(dt); // +0x40 } // Marks an acknowledged object ghostable for one connection. Missing connection @@ -3900,16 +3891,32 @@ void GameServer::handleRadioMessageReceivedEvent(RadioMessageReceivedEvent* even event->m_connectionId = connectionId; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: gameserver-radio-ai-courier] -// The no-bot production path above never enters this arm. Keeping a fail-loud callable boundary -// prevents a bots-enabled server from silently dropping radio commands while the 309-byte courier -// body and its AI-event payload remain unrecovered. -void GameServer::sendRadioMessageToAI(IEventWrapper&, int) +// sendRadioMessageToAI - ELF 0x080B5A80, 304 B. The sender is the wrapper's sender id (-1: the +// local human player); an alive sender's message is posted once per alive AI player that +// filterMessage lets hear it, as ECAI event 10 {messageId, sender id, receiver id} (the +// AIEventListener radio arm, which forwards it to the courier). +void GameServer::sendRadioMessageToAI(IEventWrapper& wrapper, int messageId) { - std::fprintf(stderr, - "[FRONTIER] dice::hfe::GameServer::sendRadioMessageToAI reached\n"); - std::fflush(stderr); - std::abort(); + world::IPlayer* sender = wrapper.getSenderId() == -1 // +0x08 + ? world::playerManager->getLocalHumanPlayer() // +0x30 + : world::playerManager->getPlayerFromId(wrapper.getSenderId()); // +0x20 + if (!sender || !sender->getIsAlive()) // +0x6C + return; + const std::list& players = world::playerManager->getPlayers(); // +0x3C + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + world::IPlayer* const receiver = *it; + if (!receiver || !receiver->getIsAlive() || !receiver->getIsAIPlayer()) // +0x6C, +0x64 + continue; + if (!filterMessage(wrapper, sender, receiver)) // 0x080ADD00 + continue; + struct { int messageId; int senderId; int receiverId; } payload; // ebp-0x28..-0x20 + const int senderId = sender->getId(); // +0x54, called first + payload.receiverId = receiver->getId(); + payload.messageId = messageId; + payload.senderId = senderId; + eventManager->postEvent(ECAI, 10, &payload, 0.0f); // +0x14 + } } // Forwards chat to player/admin and server-console listeners, temporarily hiding diff --git a/Code/BF2/Game/GameServer/GameServer.h b/Code/BF2/Game/GameServer/GameServer.h index c8066a798..563f4b1f1 100644 --- a/Code/BF2/Game/GameServer/GameServer.h +++ b/Code/BF2/Game/GameServer/GameServer.h @@ -175,7 +175,7 @@ class GameServer : public Game, public IGameServer, public IEventListener bool filterTeamTail(IEventWrapper& wrapper, world::IPlayer* sender, world::IPlayer* receiver); bool filterLocalTail(IEventWrapper& wrapper, world::IPlayer* sender, world::IPlayer* receiver); void handleRadioMessageReceivedEvent(RadioMessageReceivedEvent*, void*); - void sendRadioMessageToAI(IEventWrapper&, int); // [FRONTIER] + void sendRadioMessageToAI(IEventWrapper&, int); // ELF 0x080B5A80 // : `if (m_isWaitingForClients) ++m_clientAckedEndOfRoundGuard` - void clientAckedEndOfRoundGuard(int connectionId); virtual bool changePlayerName(int, const std::string&); // +0x168 diff --git a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h index e3e7e3082..e788a4d6d 100644 --- a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h +++ b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.h @@ -14,7 +14,7 @@ namespace dice { namespace hfe { -namespace ai { class AIObjectUnit; class WeaponObject; } // field readers, friended below +namespace ai { class AIObjectUnit; class WeaponObject; class BFCollisionHandler; class BFObjectEnvironment; } // field readers, friended below namespace world { class ArtilleryHandler; @@ -153,8 +153,11 @@ class SimpleObjectTemplate : public ObjectTemplate, public ISimpleObjectTemplate protected: friend struct BaseTemplateConsoleAccess; // recovered direct-field console executors friend class SimpleObject; + friend class ai::BFObjectEnvironment; // the spawner query reads m_aiTemplate directly friend class ai::AIObjectUnit; // m_aiTemplate (+296) of a soldier's KIT - the // AIObjectUnit reads the kit template directly. + friend class ai::BFCollisionHandler; // m_aiTemplate (+296) - handleProjectileDamage's + // AI weapon template lookup friend class ai::WeaponObject; // a projectile's m_drag (+64), m_mass (+92) and // WeaponObject reads gravity configuration directly. friend class GenericFireArm; // m_aiTemplate (+296) - GenericFireArm::init diff --git a/Code/BF2/Game/Objects/Game/ArtilleryHandler.h b/Code/BF2/Game/Objects/Game/ArtilleryHandler.h index ed23a26f7..a0b50603f 100644 --- a/Code/BF2/Game/Objects/Game/ArtilleryHandler.h +++ b/Code/BF2/Game/Objects/Game/ArtilleryHandler.h @@ -37,6 +37,9 @@ class ArtilleryHandler void failedFire(); void doFire(); bool haveAnyArtillery(); + // [INFERRED] name: inlined into BFCommander::gameHasArtillery (bf2 0x840FCE0), which tests + // the list header at +4 against its first node. + bool hasArtilleryPieces() const { return !m_artillery.empty(); } private: void findHelperObjects(ArtilleryObjectStruct& artillery); diff --git a/Code/BF2/Game/Objects/Game/Soldier.cpp b/Code/BF2/Game/Objects/Game/Soldier.cpp index 44c73e324..f06d415ab 100644 --- a/Code/BF2/Game/Objects/Game/Soldier.cpp +++ b/Code/BF2/Game/Objects/Game/Soldier.cpp @@ -383,13 +383,28 @@ inline bool aiConnectionIsUp() return ai::g_aiInstance != 0 && ai::aiInstance()->isBotsGame(); } -// Object +0x34, read raw. It is the handle the AI event carries for this body, and this tree -// has not yet named the base-class field it lives in - so it is a documented offset rather than -// an invented member. [UNRESOLVED] name. -inline int objectAiHandle(const void* object) -{ - return *reinterpret_cast(static_cast(object) + 0x34); -} +// The ECAI 1/2 (entered/exited vehicle) payload this body posts for itself: retail stores five +// dwords - this soldier's AI object (Object +0x34, IObject::m_aiObject), a null second AI object, +// team, id and a zero trailing word. PlayerControlObject's AiEnterNote/AiExitNote give the same +// events this shape; the pointer members keep it whole on native x64. The x86 layout is retail's. +struct SoldierAiSeatPayload +{ + void* aiObject; // +0x00 this soldier's AI object + void* otherAiObject; // +0x04 always null here + int team; // +0x08 + int id; // +0x0C + int trailing; // +0x10 the trailing flag byte, stored as a whole dword +}; +// The ECAI 6/7 (man down / revived) payload: this soldier's AI object, then the player id. +struct SoldierAiPlayerPayload +{ + void* aiObject; // +0x00 Object +0x34 + int playerId; // +0x04 +}; +#if defined(_M_IX86) +static_assert(sizeof(SoldierAiSeatPayload) == 20, "retail five-dword ECAI 1/2 payload"); +static_assert(sizeof(SoldierAiPlayerPayload) == 8, "retail two-dword ECAI 6/7 payload"); +#endif // Retail Object +0x3C, read directly by handleMessage and enter. LayoutAccess names the same // cached armor component without depending on the shipped pointer width. @@ -752,13 +767,13 @@ void Soldier::exit() if (aiConnectionIsUp() && getOccupingPlayer()) { - int payload[5]; - payload[0] = objectAiHandle(this); // +0x34 - payload[1] = 0; - payload[2] = getOccupingPlayer()->getTeam(); // +0xE8 - payload[3] = getOccupingPlayer()->getId(); // +0x54 - payload[4] = 0; // the trailing byte - eventManager->postEvent(ECAI, 2, payload, 0.0f); // +0x14 + SoldierAiSeatPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.otherAiObject = 0; + payload.team = getOccupingPlayer()->getTeam(); // +0xE8 + payload.id = getOccupingPlayer()->getId(); // +0x54 + payload.trailing = 0; // the trailing byte + eventManager->postEvent(ECAI, 2, &payload, 0.0f); // +0x14 } if (getOccupingPlayer()) @@ -3052,13 +3067,13 @@ bool Soldier::enter(IPlayer* player) // 7. tell the AI, if there is one listening. if (aiConnectionIsUp() && getOccupingPlayer()) { - int payload[5]; - payload[0] = objectAiHandle(this); - payload[1] = 0; - payload[2] = getOccupingPlayer()->getTeam(); - payload[3] = getOccupingPlayer()->getId(); - payload[4] = 0; // a trailing byte in the ELF - eventManager->postEvent(static_cast(3), 1, payload, 0.0f); + SoldierAiSeatPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.otherAiObject = 0; + payload.team = getOccupingPlayer()->getTeam(); + payload.id = getOccupingPlayer()->getId(); + payload.trailing = 0; // a trailing byte in the ELF + eventManager->postEvent(static_cast(3), 1, &payload, 0.0f); } // 8. reset the per-body input latches. Backwards, 1 then 0 - dice's. @@ -3129,10 +3144,10 @@ void Soldier::handleMessage(TemplateMessage message, IPlayer* player, bool remot + WorldPref::getTickCount())); if (aiConnectionIsUp()) { - int payload[2]; - payload[0] = objectAiHandle(this); - payload[1] = getOccupingPlayer()->getId(); - eventManager->postEvent(static_cast(3), 6, payload, 0.0f); + SoldierAiPlayerPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.playerId = getOccupingPlayer()->getId(); + eventManager->postEvent(static_cast(3), 6, &payload, 0.0f); } } @@ -3175,10 +3190,10 @@ void Soldier::handleMessage(TemplateMessage message, IPlayer* player, bool remot if (getOccupingPlayer() && aiConnectionIsUp()) { - int payload[2]; - payload[0] = objectAiHandle(this); - payload[1] = getOccupingPlayer()->getId(); - eventManager->postEvent(static_cast(3), 7, payload, 0.0f); + SoldierAiPlayerPayload payload; + payload.aiObject = object_detail::LayoutAccess::aiObject(this); // +0x34 + payload.playerId = getOccupingPlayer()->getId(); + eventManager->postEvent(static_cast(3), 7, &payload, 0.0f); } } break; diff --git a/Code/BF2/Game/Objects/Game/Triggerable.h b/Code/BF2/Game/Objects/Game/Triggerable.h index c5351458a..3498c1414 100644 --- a/Code/BF2/Game/Objects/Game/Triggerable.h +++ b/Code/BF2/Game/Objects/Game/Triggerable.h @@ -13,6 +13,7 @@ namespace dice { namespace hfe { class ISound; class TriggerableTargetNetworkable; +namespace ai { class BAPConTriggerableActive; class BBPTriggerable; } namespace world { class TriggerableTemplate; class TriggerableTargetTemplate; @@ -51,6 +52,10 @@ class Triggerable : public Bundle, public ISoundNode private: friend class TriggerableManager; // Retail reads the cached template and toggles +16C directly. friend class TriggerableTarget; + // [INFERRED] friendship: the AI condition reads +16C inline (libaidll ELF 0x1EAF50). + friend class ai::BAPConTriggerableActive; + // [INFERRED] friendship: the pattern reads the cached template inline (libaidll ELF 0x2A6F56). + friend class ai::BBPTriggerable; int m_refCount; // +140 const TriggerableTemplate* m_template; // +144 int m_id; // +148 diff --git a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp index f17f1ed69..89689c6ea 100644 --- a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp +++ b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp @@ -25,6 +25,7 @@ #include "../IWeaponObject.h" #include "../Networkables/Networkables.h" #include "../../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler #include "../../../Core/Ids.h" #include "../../../Core/Debug.h" // getStickTransformation's retail error arm #include "../../../Core/Random.h" // g_random - retail distribution sampler @@ -49,10 +50,6 @@ namespace dice { namespace hfe { -namespace ai { -// Stored as an erased pointer; IBFCollisionHandler does not derive from IBase. -extern IBase* g_bfCollisionHandler; -} namespace world { extern IBase* materialManager; // ds:0x8AD2820, defined in Core/Globals.cpp @@ -511,8 +508,8 @@ void GenericProjectile::resetProjectile(bool a2) gameLogic->removeProjectile(this); // . Drop this projectile from the AI's collision tracking before the trail goes. - if (ai::g_bfCollisionHandler) - reinterpret_cast(ai::g_bfCollisionHandler) + if (ai::CommonSingletonServer::m_iBFCollisionHandler) + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler) ->handleProjectileTimeout(static_cast(this), this); destroyTrailEffect(); @@ -1052,8 +1049,8 @@ void GenericProjectile::detonate(bool forced) objectManager->postMessage(this, static_cast(32), destroyDelay); // . The same removal resetProjectile does, and the last thing detonate does. - if (ai::g_bfCollisionHandler) - reinterpret_cast(ai::g_bfCollisionHandler) + if (ai::CommonSingletonServer::m_iBFCollisionHandler) + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler) ->handleProjectileTimeout(static_cast(this), this); } diff --git a/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp b/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp index 282a72e97..e948f4108 100644 --- a/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/FireComponents/MultiFireComp.cpp @@ -26,15 +26,10 @@ #include "../../../../IO/Stream/IStream.h" #include "../../../../Physics/IPhysicsNode.h" #include "../../../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler namespace dice { namespace hfe { -namespace ai { - -// Stored as an erased pointer; IBFCollisionHandler does not derive from IBase. -extern IBase* g_bfCollisionHandler; - -} // namespace ai namespace world { namespace { @@ -371,8 +366,8 @@ bool MultiFireComp::launchProjectile(int index) { IProjectileObject* const projectile = static_cast( object->queryInterface(IID_IProjectileObject)); - if (ai::g_bfCollisionHandler) - reinterpret_cast(ai::g_bfCollisionHandler) + if (ai::CommonSingletonServer::m_iBFCollisionHandler) + static_cast(ai::CommonSingletonServer::m_iBFCollisionHandler) ->handleProjectileFire(projectile, object); } } diff --git a/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp b/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp index 015ae1ad5..f5ebb0b2d 100644 --- a/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp +++ b/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp @@ -54,15 +54,12 @@ #include #include +#include "../../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AI/AIDLL/AI/Main/CommonSingletonServer.h" + namespace dice { namespace hfe { -namespace ai { -// This singleton is null in the production no-bot server. Its concrete IBFCollisionHandler -// interface is aidll-owned and intentionally not fabricated in the engine reconstruction. -extern IBase* g_bfCollisionHandler; -} - namespace world { // ds:0x8ABAF24 (ELF) / dword_899500 (PE), published by Core/Globals.cpp. @@ -70,15 +67,6 @@ extern IBase* heightmapCluster; namespace { -// [TEMP] [CHOSEN, not recovered] - the agents.md frontier stop: name the method on stderr, -// flush, and never return. It never fabricates a default and lets execution continue. -[[noreturn]] void gfaFrontier(const char* method) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::world::GenericFireArm::%s reached\n", method); - std::fflush(stderr); - std::abort(); -} - const float kTicksPerSecond = 30.0f; // flt_888B174 - the fixed timestep const float kRedeployInterval = 2.0f; // flt_888FFE4 - enableItem's deploy retry gap, in seconds // ds:0x8AAC680. Like the two other recovered readers, no writer exists in the dedicated server. @@ -1518,8 +1506,15 @@ void GenericFireArm::postFire(FireState requestedState, m_targetComp->postFire(event); if (m_zoomComp) m_zoomComp->postFire(event); - if (ai::g_bfCollisionHandler && projectileObject) - gfaFrontier("postFire (AIDLL IBFCollisionHandler fire report)"); + // ELF 0x8251867: every real round is reported to the AI collision handler + // (+0x18). The IProjectileObject query is repeated, as compiled. + ai::IBFCollisionHandler* const collision = static_cast( + ai::CommonSingletonServer::m_iBFCollisionHandler); + if (collision && projectileObject) + collision->handleProjectileFire( + static_cast( + projectileObject->queryInterface(IID_IProjectileObject)), + projectileObject); } } diff --git a/Code/BF2/IO/File/File.cpp b/Code/BF2/IO/File/File.cpp index daa4a9a7c..986e7cc71 100644 --- a/Code/BF2/IO/File/File.cpp +++ b/Code/BF2/IO/File/File.cpp @@ -4,25 +4,32 @@ #include "FileManager.h" // io::fileManager - open() goes through the virtual filesystem #include "../../Math/Vec3.h" +#include namespace dice { namespace hfe { namespace io { +// static init: ELF 0x48D4F0 (__tcf_0 0x48D550, _GLOBAL__I 0x48D580): iostream only. + // Owns one stream reference and releases it on destruction. +// ELF 0x48CA20, 0x48CA30. File::File() : m_file(0) { } -// Opens path with the requested mode, access and flags. -// [UNRESOLVED] Whether the original constructor forwards flags or always passes zero. +// Opens path with the requested mode and access. +// ELF 0x48CA40, 0x48CA90; engine 0x8435080, 0x84350C0. File::File(const std::string& path, IFileSystem::FileMode mode, IFileSystem::FileAccess access, unsigned int flags) : m_file(0) { - open(path, mode, access, flags); + // shipped defect: the constructor discards flags. + (void)flags; + open(path, mode, access, 0); } +// ELF 0x48CAE0, 0x48CB00. File::~File() { if (m_file) @@ -97,8 +104,32 @@ bool File::read(float& v) { return read(&v, sizeof(v)) == sizeof(v); } bool File::read(double& v) { return read(&v, sizeof(v)) == sizeof(v); } bool File::read(bool& v) { return read(&v, sizeof(v)) == sizeof(v); } +// ELF 0x48CCF0; engine 0x84352F0. +unsigned int File::write(std::ostringstream& s) +{ + const std::string text = s.str(); + return write(text.c_str(), static_cast(text.length())); +} + +// Reads through delimiter, consuming it. Empty input leaves out unchanged and returns false. +// Embedded NUL truncates out; the 4096-character buffer is unchecked. +// ELF 0x48CF90; engine 0x8435580. +bool File::read(std::string& out, char delimiter) +{ + char buffer[4096]; + unsigned int count = 0; + while (m_file->read(buffer + count, 1) == 1 && buffer[count] != delimiter) + ++count; + buffer[count] = 0; + if (count == 0) + return false; + out = buffer; + return true; +} + // Reads wide characters through delimiter, consuming it and returning true even on EOF or short read. // Embedded NUL truncates out. Input must fit the unchecked 4096-character buffer. +// ELF 0x48D050; engine 0x8435620 use sizeof(wchar_t) disk units. bool File::read(std::wstring& out, wchar_t delimiter) { wchar_t buffer[4096]; @@ -127,6 +158,14 @@ bool File::write(const std::string& v) return write(v.c_str(), static_cast(v.size())) == v.size(); } +// Writes native wide-character bytes, without a length prefix or trailing NUL. +// ELF 0x48D400; engine 0x84359B0. This is not a UTF-16 encoder on POSIX. +bool File::write(const std::wstring& v) +{ + const unsigned int bytes = static_cast(v.length() * sizeof(wchar_t)); + return write(v.c_str(), bytes) == bytes; +} + // Reads or writes vector components as raw structure bytes, without endian conversion. bool File::read(Vec2& v) { return read(&v, sizeof(v)) == sizeof(v); } bool File::read(Vec3& v) { return read(&v, sizeof(v)) == sizeof(v); } diff --git a/Code/BF2/IO/File/File.h b/Code/BF2/IO/File/File.h index 681594bef..f4d262093 100644 --- a/Code/BF2/IO/File/File.h +++ b/Code/BF2/IO/File/File.h @@ -77,10 +77,13 @@ class File bool write(const Vec3& v); bool write(const Vec4& v); - // String reads stop at the supplied delimiter; narrow writes emit raw bytes without length or terminator. + // Reads consume the delimiter. Narrow reads return false without assigning on empty input; + // wide reads assign even empty input and return true. Both have an unchecked 4096-unit limit. + // Native engine wide reads use the UTF-16 port adaptation; the AI DLL uses native wchar_t. bool read(std::string& out, char delimiter); bool read(std::wstring& out, wchar_t delimiter); bool write(const std::string& v); + // Writes native character bytes without a length or terminator (not a POSIX UTF-16 encoder). bool write(const std::wstring& v); unsigned int write(std::ostringstream& s); diff --git a/Code/BF2/IO/Input/InputMapStream.cpp b/Code/BF2/IO/Input/InputMapStream.cpp index 2789bf14a..7a04514c3 100644 --- a/Code/BF2/IO/Input/InputMapStream.cpp +++ b/Code/BF2/IO/Input/InputMapStream.cpp @@ -48,10 +48,12 @@ const PlayerInputName kPlayerInputNames[] = { { PISayAll, "PISayAll" }, { PISayTeam, "PISayTeam" }, { PINextItem, "PINextItem" }, { PIPrevItem, "PIPrevItem" }, { PICommunication, "PICommunication" }, { PIShowScoreBoard, "PIShowScoreBoard" }, - { PINone, "PINone" }, + // Reader-only aliases precede PINone in the shipped comparison chain. + { PINone, "PINumInput" }, { PINone, "PINotInUse" }, { PINone, "PINone" }, }; const int kPlayerInputNameCount = sizeof(kPlayerInputNames) / sizeof(kPlayerInputNames[0]); +#if !defined(BF2_IMAGE_AIDLL) struct GameInputName { GameInputMap value; const char* name; }; const GameInputName kGameInputNames[] = { { GIMenu, "GIMenu" }, @@ -130,21 +132,26 @@ const GameInputName kGameInputNames[] = { { GILeader, "GILeader" }, { GINone, "GINone" }, }; +#endif } // namespace // the switch-to-literal writer. +// ELF 0x48D5A0; engine 0x84A18C0. Values 0..64 print; all others leave the stream untouched. std::ostream& operator<<(std::ostream& stream, PlayerInputMap value) { - for (int i = 0; i < kPlayerInputNameCount; ++i) + for (int i = 0; i < kPlayerInputNameCount - 3; ++i) { if (kPlayerInputNames[i].value == value) return stream << kPlayerInputNames[i].name; } + if (value == PINone) + return stream << "PINone"; return stream; // out-of-range writes nothing } +#if !defined(BF2_IMAGE_AIDLL) std::ostream& operator<<(std::ostream& stream, GameInputMap value) { for (const auto& row : kGameInputNames) @@ -154,6 +161,7 @@ std::ostream& operator<<(std::ostream& stream, GameInputMap value) } return stream; } +#endif namespace { // Source-level factoring of the identical unrolled comparison chains. Preserve @@ -183,6 +191,8 @@ void parseInputName(const std::string& token, Enum& value, } } +// ELF 0x48D8A0; engine 0x84A1B60. Numeric tokens of at most two characters pass through +// the enum writer, then the same ordered comparisons; sscanf accepts a numeric prefix. std::istream& operator>>(std::istream& stream, PlayerInputMap& value) { std::string token; @@ -191,6 +201,7 @@ std::istream& operator>>(std::istream& stream, PlayerInputMap& value) return stream; } +#if !defined(BF2_IMAGE_AIDLL) std::istream& operator>>(std::istream& stream, GameInputMap& value) { std::string token; @@ -198,7 +209,9 @@ std::istream& operator>>(std::istream& stream, GameInputMap& value) parseInputName(token, value, kGameInputNames, GINone); return stream; } +#endif +// ELF 0x490240; engine 0x84A4240. Conversion to narrow text precedes numeric parsing. std::wistream& operator>>(std::wistream& stream, PlayerInputMap& value) { std::wstring token; @@ -207,6 +220,7 @@ std::wistream& operator>>(std::wistream& stream, PlayerInputMap& value) return stream; } +#if !defined(BF2_IMAGE_AIDLL) std::wistream& operator>>(std::wistream& stream, GameInputMap& value) { std::wstring token; @@ -214,6 +228,7 @@ std::wistream& operator>>(std::wistream& stream, GameInputMap& value) parseInputName(hfe::makeNarrow(token), value, kGameInputNames, GINone); return stream; } +#endif } // namespace io } // namespace hfe diff --git a/Code/BF2/IO/Stream/BoundingBox.cpp b/Code/BF2/IO/Stream/BoundingBox.cpp new file mode 100644 index 000000000..9a0702765 --- /dev/null +++ b/Code/BF2/IO/Stream/BoundingBox.cpp @@ -0,0 +1,179 @@ +// Eight-corner bounds. [INFERRED] Source directory; the ELF FILE symbol attests BoundingBox.cpp. +#include "../../Math/BoundingBox.h" +#include "../../Math/LocalBoundingBox.h" +#include "../../Math/Frustum.h" + +#include +// static init: ELF 0x493F20, 0x493F80, 0x493FB0 (std::__ioinit). +#include + +namespace dice { +namespace hfe { + +// ELF 0x492BF0; engine ELF 0x83AF780. +void BoundingBox::initWithLocalBoundingBox(const LocalBoundingBox& box) +{ + for (int i = 0; i < 8; ++i) + { + const Vec3 point = {(i & 4) ? box.m_max.x : box.m_min.x, + (i & 2) ? box.m_max.y : box.m_min.y, + (i & 1) ? box.m_max.z : box.m_min.z}; + m_corners[i] = point; + } +} + +// ELF 0x492CF0; engine ELF 0x83AF840. +void BoundingBox::transform(const Mat4& matrix) +{ + for (int i = 0; i < 8; ++i) + { + const float x = m_corners[i].x, y = m_corners[i].y, z = m_corners[i].z; + const float tx = matrix.m[0] * x + matrix.m[4] * y + matrix.m[8] * z + matrix.m[12]; + const float ty = matrix.m[1] * x + matrix.m[5] * y + matrix.m[9] * z + matrix.m[13]; + const float tz = matrix.m[2] * x + matrix.m[6] * y + matrix.m[10] * z + matrix.m[14]; + m_corners[i].x = tx; + m_corners[i].y = ty; + m_corners[i].z = tz; + } +} + +// ELF 0x492D80; engine ELF 0x83AF8D0. +bool BoundingBox::outside(const Frustum& frustum) const +{ + return !inside(frustum); +} + +// ELF 0x492DC0; engine ELF 0x83AF900. +bool BoundingBox::inside(const Frustum& frustum) const +{ + for (int i = 0; i < 6; ++i) + { + const Plane3& plane = frustum.m_planes[i]; + int outsideCount = 0; + for (int j = 0; j < 8; ++j) + { + const Vec3& point = m_corners[j]; + if (plane.normal.x * point.x + plane.normal.y * point.y + + plane.normal.z * point.z + plane.d > 0.0f) + ++outsideCount; + } + if (outsideCount == 8) + return false; + } + return true; +} + +// ELF 0x492E70; engine ELF 0x83AF990. +Vec3 BoundingBox::getMax() const +{ + Vec3 result = m_corners[0]; + for (int i = 1; i < 8; ++i) + { + if (m_corners[i].x > result.x) result.x = m_corners[i].x; + if (m_corners[i].y > result.y) result.y = m_corners[i].y; + if (m_corners[i].z > result.z) result.z = m_corners[i].z; + } + return result; +} + +// ELF 0x492EC0; engine ELF 0x83AF9E0. +Vec3 BoundingBox::getMin() const +{ + Vec3 result = m_corners[0]; + for (int i = 1; i < 8; ++i) + { + if (result.x > m_corners[i].x) result.x = m_corners[i].x; + if (result.y > m_corners[i].y) result.y = m_corners[i].y; + if (result.z > m_corners[i].z) result.z = m_corners[i].z; + } + return result; +} + +// ELF 0x492F20; engine ELF 0x83AFA40. +Vec3 BoundingBox::getCentre() const +{ + return {(m_corners[7].x + m_corners[0].x) * 0.5f, + (m_corners[7].y + m_corners[0].y) * 0.5f, + (m_corners[7].z + m_corners[0].z) * 0.5f}; +} + +// ELF 0x492F80; engine ELF 0x83AFA90. +bool BoundingBox::intersect(const BoundingBox& other) const +{ + Vec3 a[3], b[3]; + const int cornerIndices[3] = {4, 2, 1}; + for (int i = 0; i < 3; ++i) + { + const Vec3& corner = m_corners[cornerIndices[i]]; + a[i] = {(corner.x - m_corners[0].x) * 0.5f, + (corner.y - m_corners[0].y) * 0.5f, + (corner.z - m_corners[0].z) * 0.5f}; + } + float ah[3], bh[3]; + for (int i = 0; i < 3; ++i) + ah[i] = std::sqrt(a[i].x * a[i].x + a[i].y * a[i].y + a[i].z * a[i].z); + for (int i = 0; i < 3; ++i) + { + const float inverse = 1.0f / ah[i]; + a[i].x *= inverse; a[i].y *= inverse; a[i].z *= inverse; + } + for (int i = 0; i < 3; ++i) + { + const Vec3& corner = other.m_corners[cornerIndices[i]]; + b[i] = {(corner.x - other.m_corners[0].x) * 0.5f, + (corner.y - other.m_corners[0].y) * 0.5f, + (corner.z - other.m_corners[0].z) * 0.5f}; + } + for (int i = 0; i < 3; ++i) + bh[i] = std::sqrt(b[i].x * b[i].x + b[i].y * b[i].y + b[i].z * b[i].z); + for (int i = 0; i < 3; ++i) + { + const float inverse = 1.0f / bh[i]; + b[i].x *= inverse; b[i].y *= inverse; b[i].z *= inverse; + } + const Vec3 otherCentre = other.getCentre(); + const Vec3 centre = getCentre(); + const Vec3 delta = {otherCentre.x - centre.x, otherCentre.y - centre.y, + otherCentre.z - centre.z}; + float r[3][3], absolute[3][3], t[3]; + for (int i = 0; i < 3; ++i) + { + for (int j = 0; j < 3; ++j) + { + r[i][j] = a[i].x * b[j].x + a[i].y * b[j].y + a[i].z * b[j].z; + absolute[i][j] = std::fabs(r[i][j]); + } + t[i] = a[i].x * delta.x + a[i].y * delta.y + a[i].z * delta.z; + if (std::fabs(t[i]) > bh[0] * absolute[i][0] + bh[1] * absolute[i][1] + + bh[2] * absolute[i][2] + ah[i]) + return false; + } + for (int j = 0; j < 3; ++j) + { + if (std::fabs(b[j].x * delta.x + b[j].y * delta.y + b[j].z * delta.z) + > ah[0] * absolute[0][j] + ah[1] * absolute[1][j] + + ah[2] * absolute[2][j] + bh[j]) + return false; + } + for (int i = 0; i < 3; ++i) + { + const int next = (i + 1) % 3, last = (i + 2) % 3; + const int firstA = i == 0 ? 1 : 0; + const int secondA = i == 2 ? 1 : 2; + for (int j = 0; j < 3; ++j) + { + const int firstB = j == 0 ? 1 : 0; + const int secondB = j == 2 ? 1 : 2; + const float distance = std::fabs(r[next][j] * t[last] - t[next] * r[last][j]); + const float radiusA = ah[firstA] * absolute[secondA][j] + ah[secondA] * absolute[firstA][j]; + const float radiusB = bh[firstB] * absolute[i][secondB] + bh[secondB] * absolute[i][firstB]; + // Shipped ia-32 comparisons accept unordered values, including on the final axis. + if (distance > radiusA + radiusB) + return false; + } + } + return true; +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/IO/Stream/MemStream.cpp b/Code/BF2/IO/Stream/MemStream.cpp index fa94edf20..eb6db67b8 100644 --- a/Code/BF2/IO/Stream/MemStream.cpp +++ b/Code/BF2/IO/Stream/MemStream.cpp @@ -3,6 +3,10 @@ #include "MemStream.h" #include // memcpy +#include + +// static init: ELF 0x492B40 (__tcf_0 0x492BA0, _GLOBAL__I 0x492BD0): iostream only. +// Engine 0x84388A0/0x84388F0/0x8438900 has the same initialization and teardown. namespace dice { namespace hfe { diff --git a/Code/BF2/Math/BoundingBox.h b/Code/BF2/Math/BoundingBox.h new file mode 100644 index 000000000..6b0e75a91 --- /dev/null +++ b/Code/BF2/Math/BoundingBox.h @@ -0,0 +1,38 @@ +// Eight-corner bounding volume. Header placement and member spelling are [INFERRED]. +#ifndef MATH_BOUNDINGBOX_H +#define MATH_BOUNDINGBOX_H + +#include "Vec3.h" + +namespace dice { +namespace hfe { + +struct LocalBoundingBox; +struct Mat4; +class Frustum; + +class BoundingBox +{ +public: + // Writes corners in binary x/y/z order, with z changing fastest. + void initWithLocalBoundingBox(const LocalBoundingBox& box); + void transform(const Mat4& matrix); + // Plane overlap tests; inside does not require full containment. + bool outside(const Frustum& frustum) const; + bool inside(const Frustum& frustum) const; + Vec3 getMax() const; + Vec3 getMin() const; + // Midpoint of corners zero and seven. + Vec3 getCentre() const; + // Separating-axis test for orthogonal boxes; degenerate axes are not guarded. + bool intersect(const BoundingBox& other) const; + + Vec3 m_corners[8]; // +0x00, stride 0x0C +}; + +static_assert(sizeof(BoundingBox) == 0x60, "BoundingBox layout drift"); + +} // namespace hfe +} // namespace dice + +#endif // MATH_BOUNDINGBOX_H diff --git a/Code/BF2/Math/DoubleVec3.cpp b/Code/BF2/Math/DoubleVec3.cpp new file mode 100644 index 000000000..4173f4bfa --- /dev/null +++ b/Code/BF2/Math/DoubleVec3.cpp @@ -0,0 +1,81 @@ +// ELF FILE symbol DoubleVec3.cpp. [INFERRED] Math directory placement. +#include "DoubleVec3.h" +#include +// ELF static init 0x2F22E0, __tcf_0 0x2F2340, _GLOBAL__I 0x2F2370: iostream initialization. +#include + +namespace dice { namespace hfe { +namespace { + +// [INFERRED] Helper names for the inlined operations in ELF 0x2F1D80. +bool normalizeDoubleBasis(DoubleVec3& vector) +{ + const double squared = vector.x * vector.x + vector.y * vector.y + vector.z * vector.z; + const double epsilon = 1.1920928955078125e-7f; + if (std::fabs(squared - 1.0) < epsilon) + return true; + if (std::fabs(squared) < epsilon) + return false; + const double inverse = 1.0 / std::sqrt(squared); + vector.x *= inverse; + vector.y *= inverse; + vector.z *= inverse; + return true; +} + +void zeroDoubleBasis(DoubleVec3& vector) +{ + vector.x = 0; + vector.y = 0; + vector.z = 0; +} + +void crossDoubleBasis(DoubleVec3& output, const DoubleVec3& a, const DoubleVec3& b) +{ + output.x = a.y * b.z - a.z * b.y; + output.y = b.x * a.z - b.z * a.x; + output.z = b.y * a.x - b.x * a.y; +} + +void snapDoubleBasis(DoubleVec3& vector) +{ + const double epsilon = 1.1920928955078125e-7f; + if (std::fabs(vector.x) < epsilon) vector.x = 0; + if (std::fabs(vector.y) < epsilon) vector.y = 0; + if (std::fabs(vector.z) < epsilon) vector.z = 0; +} + +} // namespace + +// ELF 0x2F1D80. The up-vector reconstruction alone continues after a degenerate result. +int DoubleVec3::makeOrthonormalBasis(DoubleVec3& forward, DoubleVec3& up) +{ + if (!normalizeDoubleBasis(forward)) { zeroDoubleBasis(forward); return -20003; } + if (!normalizeDoubleBasis(up)) { zeroDoubleBasis(up); return -20003; } + crossDoubleBasis(*this, forward, up); + if (!normalizeDoubleBasis(*this)) { zeroDoubleBasis(*this); return -20003; } + crossDoubleBasis(up, *this, forward); + if (!normalizeDoubleBasis(up)) zeroDoubleBasis(up); + crossDoubleBasis(forward, up, *this); + if (!normalizeDoubleBasis(forward)) { zeroDoubleBasis(forward); return -20003; } + snapDoubleBasis(*this); + snapDoubleBasis(forward); + snapDoubleBasis(up); + return 0; +} + +// ELF 0x2F2260. +const DoubleVec3& DoubleVec3::getZero() +{ + static DoubleVec3 DoubleVec3zero = {0, 0, 0}; + return DoubleVec3zero; +} + +// ELF 0x2F22A0. +const DoubleVec3& DoubleVec3::getIdentity() +{ + static DoubleVec3 DoubleVec3identity = {1, 1, 1}; + return DoubleVec3identity; +} + +} } diff --git a/Code/BF2/Math/DoubleVec3.h b/Code/BF2/Math/DoubleVec3.h new file mode 100644 index 000000000..88e6cecb8 --- /dev/null +++ b/Code/BF2/Math/DoubleVec3.h @@ -0,0 +1,19 @@ +// Double-precision vectors used by navigation mesh generation. +// [INFERRED] Header placement; the ELF FILE symbol attests DoubleVec3.cpp. +#ifndef MATH_DOUBLEVEC3_H +#define MATH_DOUBLEVEC3_H + +namespace dice { namespace hfe { + +struct DoubleVec3 +{ + double x, y, z; + int makeOrthonormalBasis(DoubleVec3& forward, DoubleVec3& up); + static const DoubleVec3& getZero(); + static const DoubleVec3& getIdentity(); +}; + +typedef char DoubleVec3IsTheFileRecord[sizeof(DoubleVec3) == 24 ? 1 : -1]; + +} } +#endif diff --git a/Code/BF2/Math/Frustum.cpp b/Code/BF2/Math/Frustum.cpp index 26aca4d66..509e30a3b 100644 --- a/Code/BF2/Math/Frustum.cpp +++ b/Code/BF2/Math/Frustum.cpp @@ -1,9 +1,13 @@ // Frustum setup and intersection queries. #include "Frustum.h" +#include "../Core/Debug.h" +#include #include #include +// static init: ELF 0x495CF0, 0x495D50, 0x495D80 (std::__ioinit). +#include namespace dice { namespace hfe { @@ -29,6 +33,7 @@ inline void normalizePlaneNormal(Vec3& n) } } // namespace +// ELF 0x1A0D00. // Initializes plane normals, corners, bounds, centre, and identity transform; marks derived data dirty. // Leaves plane distances, outcodes, radii, and projection scalars untouched. Frustum::Frustum() @@ -54,7 +59,7 @@ Frustum::Frustum() m_type = 2; // +0x1E4 } -// Copies setup parameters and transformation, then rebuilds derived planes and corners. +// ELF 0x494130. Copies setup parameters and transformation, then rebuilds derived planes and corners. Frustum& Frustum::operator=(const Frustum& other) { m_fov = other.m_fov; @@ -69,6 +74,7 @@ Frustum& Frustum::operator=(const Frustum& other) return *this; } +// ELF 0x494270. void Frustum::setPerspective(float fov, float aspect, float nearDist, float farDist, const Mat4& m) { m_fov = fov; // +0x1CC @@ -122,7 +128,7 @@ void Frustum::setPerspective(float fov, float aspect, float nearDist, float farD updateSecondarySizes(); } -// ELF83B1500 / client PE6DD4C0 / renderer PE1007A7F0. Width/height and distance +// ELF 0x494A20; engine ELF 0x83B1500 / client PE6DD4C0 / renderer PE1007A7F0. Width/height and distance // stores, six axial planes, native plane transform/sign masks, matrix and centre, // then the same secondary-size recompute as perspective. FOV/aspect stay untouched. void Frustum::setOrtho(float width, float height, float nearDist, float farDist, const Mat4& m) @@ -133,17 +139,17 @@ void Frustum::setOrtho(float width, float height, float nearDist, float farDist, m_dword1D8 = height; m_type = 1; m_planes[0].normal = {-1.0f, 0.0f, 0.0f}; - m_planes[0].d = -(width * -0.5f * -1.0f); + m_planes[0].d = -((-width * 0.5f) * -1.0f + 0.0f + 0.0f); m_planes[1].normal = {1.0f, 0.0f, 0.0f}; - m_planes[1].d = -(width * 0.5f); + m_planes[1].d = -(width * 0.5f + 0.0f + 0.0f); m_planes[3].normal = {0.0f, -1.0f, 0.0f}; - m_planes[3].d = -(height * -0.5f * -1.0f); + m_planes[3].d = -(0.0f + (-height * 0.5f) * -1.0f + 0.0f); m_planes[2].normal = {0.0f, 1.0f, 0.0f}; - m_planes[2].d = -(height * 0.5f); + m_planes[2].d = -(0.0f + height * 0.5f + 0.0f); m_planes[4].normal = {0.0f, 0.0f, -1.0f}; - m_planes[4].d = -(nearDist * -1.0f); + m_planes[4].d = -(0.0f + nearDist * -1.0f); m_planes[5].normal = {0.0f, 0.0f, 1.0f}; - m_planes[5].d = -farDist; + m_planes[5].d = -(0.0f + farDist); for (int i = 0; i < 6; ++i) { m_planes[i] = Plane3::transform(m_planes[i], m); unsigned int bits[3]; @@ -223,7 +229,43 @@ void Frustum::setOrtho(float width, float height, float nearDist, float farDist, updateSecondarySizes(); } -// ELF83B1EA0 / PE6DD730: unknown type values intentionally do nothing. +// ELF 0x494F20; engine ELF 0x83B1960. +void Frustum::expandToEncapsulate(const Frustum& other) +{ + for (int i = 0; i < 6; ++i) + { + Plane3& plane = m_planes[i]; + float maximum = -FLT_MAX; + float minimum = FLT_MAX; + for (int j = 0; j < 8; ++j) + { + const Vec3& corner = other.m_corners[j]; + const float projection = plane.normal.x * corner.x + plane.normal.y * corner.y + + plane.normal.z * corner.z; + maximum = maximum > projection ? maximum : projection; + minimum = minimum > projection ? projection : minimum; + } + // Shipped behavior replaces the distance, without negating the chosen projection. + plane.d = plane.d > 0.0f ? maximum : minimum; + } + const auto pairLength = [this](int a, int b) { + const Plane3& p = m_planes[a]; + const Plane3& q = m_planes[b]; + const float x = p.d * p.normal.x + q.d * q.normal.x; + const float y = p.d * p.normal.y + q.d * q.normal.y; + const float z = p.d * p.normal.z + q.d * q.normal.z; + return std::sqrt(x * x + y * y + z * z); + }; + m_dword1D4 = pairLength(0, 1); + m_dword1D8 = pairLength(2, 3); + m_farDist = pairLength(5, 4); + m_transformation.m[12] -= m_planes[4].d * m_planes[4].normal.x; + m_transformation.m[13] -= m_planes[4].d * m_planes[4].normal.y; + m_transformation.m[14] -= m_planes[4].d * m_planes[4].normal.z; + reSetup(); +} + +// ELF 0x4954B0; engine ELF 0x83B1EA0 / PE6DD730: unknown type values intentionally do nothing. void Frustum::reSetup() { if (m_type == 0) @@ -232,28 +274,63 @@ void Frustum::reSetup() setOrtho(m_dword1D4, m_dword1D8, m_nearDist, m_farDist, m_transformation); } -// a store followed by the existing setup path. +// ELF 0x495630. A store followed by the existing setup path. void Frustum::setFov(float fov) { m_fov = fov; reSetup(); } -// replace, rather than compose, the entire transformation. +// ELF 0x495560. Replace, rather than compose, the entire transformation. void Frustum::transform(const Mat4& transformation) { m_transformation = transformation; reSetup(); } -// ELF83B2050 / PE6DD7F0: unconditional store followed by reSetup. +// ELF 0x4956B0; engine ELF 0x83B2050 / PE6DD7F0: unconditional store followed by reSetup. void Frustum::setFarDist(float distance) { m_farDist = distance; reSetup(); } -// Returns whether the point is inside the frustum. +// ELF 0x495670; engine ELF 0x83B2020. +void Frustum::setNearDist(float distance) +{ + m_nearDist = distance; + reSetup(); +} + +// ELF 0x4956E0; engine ELF 0x83B2070. +const Vec3& Frustum::getCornerForPlane(unsigned int corner, FrustumPlane plane) const +{ + static const unsigned int corners[6][4] = { + {5, 4, 0, 1}, {3, 2, 6, 7}, {0, 4, 6, 2}, + {5, 7, 3, 1}, {1, 0, 2, 3}, {7, 6, 4, 5} + }; + if (static_cast(plane) < 6 && corner < 4) + return m_corners[corners[static_cast(plane)][corner]]; + Debug(DebugTypeError, "Math/Frustum.cpp", 430, "") << "Invalid corner or plane."; + return m_corners[1]; +} + +// ELF 0x498760; engine ELF 0x83B4EE0. This inline was emitted in LocalBoundingBox.cpp. +unsigned int Frustum::getOutcode(const Vec3& p) const +{ + unsigned int result = 0; + const int order[6] = {5, 4, 1, 0, 2, 3}; + for (int i = 0; i < 6; ++i) + { + const int index = order[i]; + const Plane3& plane = m_planes[index]; + if (plane.normal.x * p.x + plane.normal.y * p.y + plane.normal.z * p.z + plane.d > 0.0f) + result |= 1u << index; + } + return result; +} + +// ELF 0x495920. Returns whether the point is inside the frustum. bool Frustum::inside(const Vec3& p) const { const Plane3& p5 = m_planes[5]; @@ -276,7 +353,7 @@ bool Frustum::inside(const Vec3& p) const } -// Tests far, near, right, left, top, bottom in that order; reject when n.p + d exceeds radius. +// ELF 0x495A30. Tests far, near, right, left, top, bottom in that order; reject when n.p + d exceeds radius. // Preserve early-return order for NaNs and floating-point exceptions. bool Frustum::inside(const Vec3& p, float radius) const { @@ -300,7 +377,7 @@ bool Frustum::inside(const Vec3& p, float radius) const } -// Tests a sphere and, on success, writes whether it lies fully inside the frustum. +// ELF 0x495B30. Tests a sphere and, on success, writes whether it lies fully inside the frustum. // fullyInside is unchanged on false. Its sign-bit test includes negative zero; preserve plane evaluation order. bool Frustum::inside(const Vec3& p, float radius, bool& fullyInside) const @@ -349,7 +426,7 @@ bool Frustum::inside(const Vec3& p, float radius, bool& fullyInside) const return true; } -// the corners, the bounding radius (max |corner - centre|), the corners copied +// ELF 0x494D80. The corners, the bounding radius (max |corner - centre|), the corners copied // to the second set, the dirty flag cleared. void Frustum::updateSecondarySizes() { @@ -374,7 +451,7 @@ void Frustum::updateSecondarySizes() m_cornersDirty = false; // byte +0x1C8 } -// the eight three-plane intersections, then the box from corners 0 and 1, +// ELF 0x495220. The eight three-plane intersections, then the box from corners 0 and 1, // expanded by 2..7 (LocalBoundingBox::expand - dirty set). void Frustum::recalcCorners() { diff --git a/Code/BF2/Math/Frustum.h b/Code/BF2/Math/Frustum.h index 8f465d03b..5119cae5b 100644 --- a/Code/BF2/Math/Frustum.h +++ b/Code/BF2/Math/Frustum.h @@ -2,7 +2,6 @@ // [INFERRED] header placement. Perspective FOV is in radians. // Preserve the plane/corner order used by culling. Private field names are [CHOSEN]; // M_prevCorners is a [CHOSEN name] for the cached previous corners. -// Unimplemented operations remain explicit [FRONTIER] declarations. #ifndef MATH_FRUSTUM_H // [INFERRED] guard style #define MATH_FRUSTUM_H @@ -20,7 +19,7 @@ class Frustum { public: Frustum(); - Frustum& operator=(const Frustum& other); // [FRONTIER] + Frustum& operator=(const Frustum& other); void setPerspective(float fov, float aspect, float nearDist, float farDist, const Mat4& m); void setOrtho(float, float, float, float, const Mat4& m); @@ -29,20 +28,22 @@ class Frustum void getPerspProjection(Mat4&) const {} // empty void getOrthoProjection(Mat4&) const {} // empty void getViewMatrix(Mat4&) const {} // empty - void expandToEncapsulate(const Frustum& other); // [FRONTIER] + void expandToEncapsulate(const Frustum& other); void reSetup(); void transform(const Mat4& m); float getFov() { return m_fov; } void setFov(float fov); float getNearDist() const { return m_nearDist; } - void setNearDist(float d); // [FRONTIER] + void setNearDist(float d); float getFarDist() const { return m_farDist; } void setFarDist(float d); - const Vec3& getCornerForPlane(unsigned int corner, FrustumPlane plane) const; // [FRONTIER] + // Returns one of four corners for a plane; invalid input emits an error. + const Vec3& getCornerForPlane(unsigned int corner, FrustumPlane plane) const; bool inside(const Vec3& p) const; bool inside(const Vec3& p, float radius) const; bool inside(const Vec3& p, float radius, bool& fullyInside) const; - unsigned int getOutcode(const Vec3& p) const; // [FRONTIER] + // Six outside-plane bits, in the same order as m_planes. + unsigned int getOutcode(const Vec3& p) const; /* +0x000 */ Plane3 m_planes[6]; /* +0x060 */ Vec3 m_corners[8]; diff --git a/Code/BF2/Math/Intersect.cpp b/Code/BF2/Math/Intersect.cpp index 0e31734e8..d3147d14d 100644 --- a/Code/BF2/Math/Intersect.cpp +++ b/Code/BF2/Math/Intersect.cpp @@ -1,11 +1,58 @@ // Sphere, ray, and box intersection helpers. #include "Intersect.h" +#include "Frustum.h" +#include "Ray3.h" + +#include +#include +// static init: ELF 0x4963C0, 0x496420, 0x496450 (std::__ioinit). +#include namespace dice { namespace hfe { -// Per axis: below the box -> (c - min)^2, above it -> (c - max)^2, inside -> 0. +// ELF 0x495E20; engine ELF 0x83B26D0. +bool findIntersection(const Plane3& plane, const Ray3& ray, Vec3& position) +{ + const float denominator = plane.normal.x * ray.direction.x + + plane.normal.y * ray.direction.y + + plane.normal.z * ray.direction.z; + // The ia-32 images proceed for an unordered denominator too. + if (std::fabs(denominator) < FLT_EPSILON) + return false; + const float amount = -(plane.normal.x * ray.origin.x + plane.normal.y * ray.origin.y + + plane.normal.z * ray.origin.z + plane.d) / denominator; + Vec3 result; + result.x = ray.origin.x + ray.direction.x * amount; + result.y = ray.origin.y + ray.direction.y * amount; + result.z = ray.origin.z + ray.direction.z * amount; + position = result; + return true; +} + +// ELF 0x495F20; engine ELF 0x83B27C0. +bool intersect(const Frustum& frustum, const LocalBoundingBox& box) +{ + for (int i = 0; i < 6; ++i) + { + Vec3 point = {}; + const unsigned int mask = static_cast(frustum.m_planeOutcodes[i]); + if (mask <= 7) + { + point.x = (mask & 1) ? box.m_max.x : box.m_min.x; + point.y = (mask & 2) ? box.m_max.y : box.m_min.y; + point.z = (mask & 4) ? box.m_max.z : box.m_min.z; + } + const Plane3& plane = frustum.m_planes[i]; + if (point.x * plane.normal.x + point.y * plane.normal.y + + point.z * plane.normal.z + plane.d > 0.0f) + return false; + } + return true; +} + +// ELF 0x496180. Per axis: below the box -> (c - min)^2, above it -> (c - max)^2, inside -> 0. bool sphereIntersectsAABB(const Vec3& centre, float radius, const Vec3& boxMin, const Vec3& boxMax) { const float* c = ¢re.x; @@ -64,13 +111,14 @@ inline bool slabTest(const Vec3& origin, const Vec3& dir, const float* lo, const } // namespace +// ELF 0x496010. bool rayIntersectsAABB(const Vec3& origin, const Vec3& dir, const Vec3& boxMin, const Vec3& boxMax, float& tMin, float& tMax) { return slabTest(origin, dir, &boxMin.x, &boxMax.x, tMin, tMax); } -// the box grown by `radius` on all six sides first. +// ELF 0x4961F0. The box grown by `radius` on all six sides first. bool rayRadiusIntersectsAABB(const Vec3& origin, const Vec3& dir, float radius, const Vec3& boxMin, const Vec3& boxMax, float& tMin, float& tMax) { diff --git a/Code/BF2/Math/Intersect.h b/Code/BF2/Math/Intersect.h index 35e10ffe3..12d00246b 100644 --- a/Code/BF2/Math/Intersect.h +++ b/Code/BF2/Math/Intersect.h @@ -8,6 +8,17 @@ namespace dice { namespace hfe { +struct Plane3; +struct Ray3; +class Frustum; +struct LocalBoundingBox; + +// Intersects the infinite ray line with a plane. Near-parallel lines leave position unchanged. +// Negative ray parameters are accepted. +bool findIntersection(const Plane3& plane, const Ray3& ray, Vec3& position); +// Tests the box against the frustum's six planes using its cached normal sign masks. +bool intersect(const Frustum& frustum, const LocalBoundingBox& box); + // Sum of squared per-axis distances from the centre to the box <= radius^2. (`>=` on r*r, as // shipped - a sphere exactly touching counts.) bool sphereIntersectsAABB(const Vec3& centre, float radius, const Vec3& boxMin, const Vec3& boxMax); diff --git a/Code/BF2/Math/LocalBoundingBox.cpp b/Code/BF2/Math/LocalBoundingBox.cpp index a21eb262a..dd2744ec0 100644 --- a/Code/BF2/Math/LocalBoundingBox.cpp +++ b/Code/BF2/Math/LocalBoundingBox.cpp @@ -3,25 +3,24 @@ #include "LocalBoundingBox.h" #include "Ray3.h" +#include "BoundingBox.h" +#include "Frustum.h" +#include "Intersect.h" #include #include +// static init: ELF 0x4986B0, 0x498710, 0x498740 (std::__ioinit). +#include namespace dice { namespace hfe { namespace { -struct Plane3 -{ - Vec3 normal; - float distance; -}; - float planeDistance(const Plane3& plane, const Vec3& point) { return plane.normal.x * point.x + plane.normal.y * point.y - + plane.normal.z * point.z + plane.distance; + + plane.normal.z * point.z + plane.d; } float dot(const Vec3& a, const Vec3& b) @@ -49,31 +48,75 @@ Vec3 transformPoint(const Mat4& transform, const Vec3& point) return result; } -// dice::hfe::findIntersection(Plane3 const&, Ray3 const&, Vec3&) - ; -// Kept TU-local because Plane3 is not otherwise needed by the recovered tree. -bool findIntersection(const Plane3& plane, const Ray3& ray, Vec3& position) +} // anonymous namespace + +// ELF 0x496470; engine ELF 0x83B2CA0. +void LocalBoundingBox::expand(const BoundingBox& box) { - const float denominator = dot(plane.normal, ray.direction); - if (!(FLT_EPSILON <= std::fabs(denominator))) - return false; + expand(box.getMin()); + expand(box.getMax()); +} - const float t = -planeDistance(plane, ray.origin) / denominator; - position.x = ray.origin.x + ray.direction.x * t; - position.y = ray.origin.y + ray.direction.y * t; - position.z = ray.origin.z + ray.direction.z * t; - return true; +// ELF 0x4964E0; engine ELF 0x83B2D00. +bool LocalBoundingBox::inside(const Frustum* frustum, const Mat4* transform, unsigned char mask) const +{ + unsigned char common = mask; + for (int i = 0; i < 8; ++i) + { + const Vec3 corner = {(i & 4) ? m_max.x : m_min.x, + (i & 2) ? m_max.y : m_min.y, + (i & 1) ? m_max.z : m_min.z}; + const Vec3 point = transformPoint(*transform, corner); + common &= static_cast(frustum->getOutcode(point)) & mask; + if (common == 0) + return true; + } + return false; } -} // anonymous namespace +// ELF 0x4969F0; engine ELF 0x83B31F0. +int LocalBoundingBox::getMajorAxis() const +{ + if (m_derivedDataDirty) + const_cast(this)->calcRadius(); + if (m_size.y > m_size.x) + return m_size.z > m_size.y ? 2 : 1; + return m_size.z > m_size.x ? 2 : 0; +} + +// ELF 0x497560; engine ELF 0x83B3CE0. +bool LocalBoundingBox::inside(const Frustum& frustum) const +{ + return intersect(frustum, *this); +} + +// ELF 0x4981F0; engine ELF 0x83B49B0. +bool LocalBoundingBox::isInside(const Vec3& point, const Vec3& ownerPosition, + const Mat4& ownerInverse) const +{ + const float dx = point.x - ownerPosition.x; + const float dy = point.y - ownerPosition.y; + const float dz = point.z - ownerPosition.z; + const float* const m = ownerInverse.m; + const float lx = m[4] * dy + m[0] * dx + m[8] * dz; + const float ly = m[9] * dz + (m[5] * dy + m[1] * dx); + const float lz = dz * m[10] + dy * m[6] + dx * m[2]; + if (!(lx >= m_min.x)) return false; + if (!(m_max.x >= lx)) return false; + if (!(ly >= m_min.y)) return false; + if (!(m_max.y >= ly)) return false; + if (!(lz >= m_min.z)) return false; + return m_max.z >= lz; +} -// ; The source overload is only an identity-transform +// ELF 0x496A70. The source overload is only an identity-transform // forwarding wrapper in both ports. bool LocalBoundingBox::intersectRay(const Ray3& ray, Vec3& position, Vec3* normal) const { return intersectRay(ray, Mat4::getIdentity(), position, normal); } -// Tests the ray against this box under transform and writes intersection data when found. +// ELF 0x496AC0. Tests the ray against this box under transform and writes intersection data when found. bool LocalBoundingBox::intersectRay(const Ray3& ray, const Mat4& transform, Vec3& position, Vec3* normal) const { @@ -85,29 +128,29 @@ bool LocalBoundingBox::intersectRay(const Ray3& ray, const Mat4& transform, planes[0].normal.x = transform.m[8]; planes[0].normal.y = transform.m[9]; planes[0].normal.z = transform.m[10]; - planes[0].distance = -dot(planes[0].normal, worldMax); + planes[0].d = -dot(planes[0].normal, worldMax); planes[1].normal.x = -transform.m[8]; planes[1].normal.y = -transform.m[9]; planes[1].normal.z = -transform.m[10]; - planes[1].distance = -dot(planes[1].normal, worldMin); + planes[1].d = -dot(planes[1].normal, worldMin); planes[2].normal.x = transform.m[4]; planes[2].normal.y = transform.m[5]; planes[2].normal.z = transform.m[6]; - planes[2].distance = -dot(planes[2].normal, worldMax); + planes[2].d = -dot(planes[2].normal, worldMax); planes[3].normal.x = -transform.m[4]; planes[3].normal.y = -transform.m[5]; planes[3].normal.z = -transform.m[6]; - planes[3].distance = -dot(planes[3].normal, worldMin); + planes[3].d = -dot(planes[3].normal, worldMin); planes[4].normal.x = transform.m[0]; planes[4].normal.y = transform.m[1]; planes[4].normal.z = transform.m[2]; - planes[4].distance = -dot(planes[4].normal, worldMax); + planes[4].d = -dot(planes[4].normal, worldMax); planes[5].normal.x = -transform.m[0]; planes[5].normal.y = -transform.m[1]; planes[5].normal.z = -transform.m[2]; - planes[5].distance = -dot(planes[5].normal, worldMin); + planes[5].d = -dot(planes[5].normal, worldMin); Vec3 entryPoint = {}; Vec3 farPoint = {}; @@ -200,7 +243,7 @@ bool LocalBoundingBox::intersectRay(const Ray3& ray, const Mat4& transform, return true; } -// Tests two oriented bounding boxes using their separating axes. +// ELF 0x497600. Tests two oriented bounding boxes using their separating axes. bool LocalBoundingBox::testIntersectWithOBB(const Mat4& thisTransform, const LocalBoundingBox& other, const Mat4& otherTransform, diff --git a/Code/BF2/Math/LocalBoundingBox.h b/Code/BF2/Math/LocalBoundingBox.h index 9cddb3422..b9ff537f8 100644 --- a/Code/BF2/Math/LocalBoundingBox.h +++ b/Code/BF2/Math/LocalBoundingBox.h @@ -16,6 +16,8 @@ namespace dice { namespace hfe { struct Ray3; +class Frustum; +class BoundingBox; struct LocalBoundingBox { @@ -30,7 +32,7 @@ struct LocalBoundingBox m_centre.x = m_centre.y = m_centre.z = 0.0f; } - // Recomputes center, size and corner-derived radii, then clears the dirty flag. + // ELF 0x4983E0. Recomputes center, size and corner-derived radii, then clears the dirty flag. void calcRadius() { float maxOrigin = 0.0f; @@ -62,7 +64,7 @@ struct LocalBoundingBox m_derivedDataDirty = false; } - // Tests squared point-to-box distance against squared radius, visiting z, y, then x. + // ELF 0x497590. Tests squared point-to-box distance against squared radius, visiting x, y, then z. bool intersectSphere(const Vec3& centre, float radius) const { float d2 = 0.0f; @@ -79,7 +81,7 @@ struct LocalBoundingBox return radius * radius >= d2; } - // Expands max before min on each axis, then marks derived bounds dirty. + // ELF 0x495DA0. Expands max before min on each axis, then marks derived bounds dirty. void expand(const Vec3& p) { if (p.x > m_max.x) m_max.x = p.x; @@ -101,6 +103,15 @@ struct LocalBoundingBox m_derivedDataDirty = true; } + void expand(const BoundingBox& box); + // Tests transformed corners against selected planes; both pointers must be valid even with mask zero. + bool inside(const Frustum* frustum, const Mat4* transform, unsigned char mask) const; + bool inside(const Frustum& frustum) const; + // Returns the largest cached size's axis (x=0, y=1, z=2), recalculating when dirty. + // Ties favor the earlier axis. + int getMajorAxis() const; + bool isInside(const Vec3& point, const Vec3& ownerPosition, const Mat4& ownerInverse) const; + // Returns size, recalculating derived bounds when dirty. const Vec3& getSize() { @@ -109,6 +120,7 @@ struct LocalBoundingBox return m_size; } + // ELF 0x4982E0; engine ELF 0x83B4AA0. // Tests the world-space sphere center against this box expanded by radius in the owner's local frame. bool isInside(const Vec3& centre, float radius, const Vec3& ownerPosition, const Mat4& ownerInverse) const @@ -120,13 +132,12 @@ struct LocalBoundingBox const float lx = m[4] * dy + m[0] * dx + m[8] * dz; const float ly = m[9] * dz + (m[5] * dy + m[1] * dx); const float lz = dz * m[10] + dy * m[6] + dx * m[2]; - if (lx < m_min.x - radius) return false; - if (m_max.x + radius < lx) return false; - if (ly < m_min.y - radius) return false; - if (m_max.y + radius < ly) return false; - if (lz < m_min.z - radius) return false; - if (radius + m_max.z < lz) return false; - return true; + if (!(lx >= m_min.x - radius)) return false; + if (!(m_max.x + radius >= lx)) return false; + if (!(ly >= m_min.y - radius)) return false; + if (!(m_max.y + radius >= ly)) return false; + if (!(lz >= m_min.z - radius)) return false; + return radius + m_max.z >= lz; } // Separating-axis test under the supplied transforms; refreshes dirty bounds. diff --git a/Code/BF2/Math/Mat3.cpp b/Code/BF2/Math/Mat3.cpp new file mode 100644 index 000000000..a06c5ee74 --- /dev/null +++ b/Code/BF2/Math/Mat3.cpp @@ -0,0 +1,77 @@ +// FILE symbol: Mat3.cpp; Math directory placement is [INFERRED]. +#include "Mat3.h" + +// static init: ELF 0x498CA0 (__tcf_0 0x498D00, _GLOBAL__I 0x498D30): iostream Init only. +#include + +namespace dice { +namespace hfe { + +// ELF 0x498870; bf2 0x83B4FE0. Both images retain the intermediate rotation values. +Mat3& Mat3::setInverse(const Mat3& source) +{ + const float r00 = source.m[0]; + m[0] = r00; + const float r10 = source.m[3]; + m[1] = r10; + const float r01 = source.m[1]; + m[3] = r01; + const float r11 = source.m[4]; + m[4] = r11; + m[6] = -(r00 * source.m[6] + r01 * source.m[7]); + const float ty = -(r10 * source.m[6] + r11 * source.m[7]); + m[5] = m[2] = 0.0f; + m[7] = ty; + // shipped defect: m[8] is never initialized here. + return *this; +} + +// ELF 0x4988E0; bf2 0x83B5040. +Mat3& Mat3::mult(const Mat3& lhs, const Mat3& rhs) +{ + m[0] = rhs.m[0] * lhs.m[0] + rhs.m[3] * lhs.m[1]; + m[3] = rhs.m[0] * lhs.m[3] + rhs.m[3] * lhs.m[4]; + m[6] = rhs.m[0] * lhs.m[6] + rhs.m[3] * lhs.m[7] + rhs.m[6]; + m[1] = rhs.m[1] * lhs.m[0] + rhs.m[4] * lhs.m[1]; + m[4] = rhs.m[1] * lhs.m[3] + rhs.m[4] * lhs.m[4]; + m[7] = rhs.m[1] * lhs.m[6] + rhs.m[4] * lhs.m[7] + rhs.m[7]; + m[2] = m[5] = 0.0f; + m[8] = 1.0f; + return *this; +} + +// ELF 0x498990; bf2 0x83B50E0. +Mat3& Mat3::fullMult(const Mat3& lhs, const Mat3& rhs) +{ + for (int column = 0; column < 3; ++column) + for (int row = 0; row < 3; ++row) + m[row * 3 + column] = rhs.m[column] * lhs.m[row * 3] + + rhs.m[3 + column] * lhs.m[row * 3 + 1] + + rhs.m[6 + column] * lhs.m[row * 3 + 2]; + return *this; +} + +// ELF 0x498A90; bf2 0x83B51E0. +Mat3& Mat3::rotMult(const Mat3& lhs, const Mat3& rhs) +{ + m[0] = rhs.m[0] * lhs.m[0] + rhs.m[3] * lhs.m[1]; + m[3] = rhs.m[0] * lhs.m[3] + rhs.m[3] * lhs.m[4]; + m[1] = rhs.m[1] * lhs.m[0] + rhs.m[4] * lhs.m[1]; + m[4] = rhs.m[1] * lhs.m[3] + rhs.m[4] * lhs.m[4]; + return *this; +} + +// ELF 0x498AF0; bf2 0x83B5240. A full product returned by value. +Mat3 Mat3::operator*(const Mat3& rhs) const +{ + Mat3 result = {}; + for (int row = 0; row < 3; ++row) + for (int column = 0; column < 3; ++column) + result.m[row * 3 + column] = rhs.m[column] * m[row * 3] + + rhs.m[3 + column] * m[row * 3 + 1] + + rhs.m[6 + column] * m[row * 3 + 2]; + return result; +} + +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Math/Mat3.h b/Code/BF2/Math/Mat3.h new file mode 100644 index 000000000..1905efe45 --- /dev/null +++ b/Code/BF2/Math/Mat3.h @@ -0,0 +1,30 @@ +// Three-by-three matrices; member spelling is [INFERRED]. +#ifndef MATH_MAT3_H +#define MATH_MAT3_H + +namespace dice { +namespace hfe { + +struct Mat3 +{ + float m[9]; + + // Inverts an orthonormal 2D affine transform, preserving m[8]. + // Input/output aliasing retains the shipped sequential overwrite behavior. + Mat3& setInverse(const Mat3& source); + // Affine product; writes the final column as (0, 0, 1). + // The destination must be distinct from the operands for an ordinary matrix product. + Mat3& mult(const Mat3& lhs, const Mat3& rhs); + // Full product, with sequential column writes; operands must not alias the destination. + Mat3& fullMult(const Mat3& lhs, const Mat3& rhs); + // Writes only the upper-left 2x2 product, preserving all other elements. + Mat3& rotMult(const Mat3& lhs, const Mat3& rhs); + Mat3 operator*(const Mat3& rhs) const; +}; + +static_assert(sizeof(Mat3) == 0x24, "Mat3 layout drift"); + +} // namespace hfe +} // namespace dice + +#endif // MATH_MAT3_H diff --git a/Code/BF2/Math/Mat4.cpp b/Code/BF2/Math/Mat4.cpp index 35ec55c18..2ec60168e 100644 --- a/Code/BF2/Math/Mat4.cpp +++ b/Code/BF2/Math/Mat4.cpp @@ -1,5 +1,8 @@ // Matrix transforms, affine inversion, rotations, and text serialization. +// static init: ELF 0x49B9F0 (__tcf_0 0x49BA50, _GLOBAL__I 0x49BA80): 's Init object only. +#include + #include "Mat4.h" #include @@ -10,6 +13,7 @@ namespace dice { namespace hfe { +// ELF 0x499440. const Mat4& Mat4::getZero() { static const Mat4 zero = {{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, @@ -17,6 +21,7 @@ const Mat4& Mat4::getZero() return zero; } +// ELF 0x499300. const Mat4& Mat4::getIdentity() { static const Mat4 identity = {{ @@ -28,6 +33,7 @@ const Mat4& Mat4::getIdentity() return identity; } +// ELF 0x498D50. Mat4 Mat4::operator*(const Mat4& rhs) const { Mat4 result; @@ -46,6 +52,7 @@ Mat4 Mat4::operator*(const Mat4& rhs) const } // Writes the full row-major product of lhs and rhs. Output must not alias either input. +// ELF 0x4996D0. void Mat4::fullMult(const Mat4& lhs, const Mat4& rhs) { for (int column = 0; column < 4; ++column) @@ -61,6 +68,7 @@ void Mat4::fullMult(const Mat4& lhs, const Mat4& rhs) } } +// ELF 0x499910. void Mat4::mult(const Mat4& lhs, const Mat4& rhs) { // Unlike operator*, this is the engine's affine fast path: the final column is restored to @@ -84,6 +92,7 @@ void Mat4::mult(const Mat4& lhs, const Mat4& rhs) m[15] = 1.0f; } +// ELF 0x499220. void Mat4::setInverse(const Mat4& source) { // BF2's ordinary transform inverse assumes an orthonormal 3x3 rotation. A separate @@ -112,6 +121,113 @@ void Mat4::setInverse(const Mat4& source) m[15] = 1.0f; } +// ELF 0x4990D0; bf2 0x83B57B0. Reload factors for each sequential store, including aliases. +Mat4& Mat4::scale(const Vec3& factors) +{ + m[0] = factors.x * m[0]; + m[4] = factors.x * m[4]; + m[8] = factors.x * m[8]; + m[12] = factors.x * m[12]; + m[1] = factors.y * m[1]; + m[5] = factors.y * m[5]; + m[9] = factors.y * m[9]; + m[13] = factors.y * m[13]; + m[2] = factors.z * m[2]; + m[6] = factors.z * m[6]; + m[10] = factors.z * m[10]; + m[14] = factors.z * m[14]; + return *this; +} + +// ELF 0x499150; bf2 0x83B5830. +Mat4& Mat4::rotScale(const Vec3& factors) +{ + m[0] = factors.x * m[0]; + m[4] = factors.x * m[4]; + m[8] = factors.x * m[8]; + m[1] = factors.y * m[1]; + m[5] = factors.y * m[5]; + m[9] = factors.y * m[9]; + m[2] = factors.z * m[2]; + m[6] = factors.z * m[6]; + m[10] = factors.z * m[10]; + return *this; +} + +// ELF 0x4991B0; bf2 0x83B5890. +Mat4& Mat4::setTranspose(const Mat4& source) +{ + for (int row = 0; row < 4; ++row) + for (int column = 0; column < 4; ++column) + m[row * 4 + column] = source.m[column * 4 + row]; + return *this; +} + +// ELF 0x499580; bf2 0x83B5C30. +const Mat4& Mat4::getTexScaleBias() +{ + static const Mat4 scalebias = {{ + 0.5f, 0.0f, 0.0f, 0.0f, + 0.0f, -0.5f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.0f, 1.0f + }}; + return scalebias; +} + +// ELF 0x49AA60; bf2 0x83B6FB0. +int calcProjectionMatrix(Mat4& m, float fov, float aspectScale, + float nearDistance, float farDistance) +{ + const float distance = farDistance - nearDistance; + if (distance < FLT_EPSILON) + return -20000; + + const float halfAngle = fov * 0.5f; + const float sine = sinf(halfAngle); + const float cosine = cosf(halfAngle); + const float cotangent = cosine / sine; + const float depth = farDistance / distance; + const float x = cotangent * aspectScale; + if (depth == 1.0f) + { + m = Mat4{{x, 0.0f, 0.0f, 0.0f, + 0.0f, cotangent, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 1.0f, + 0.0f, 0.0f, -nearDistance, 0.0f}}; + } + else + { + m = Mat4{{x, 0.0f, 0.0f, 0.0f, + 0.0f, cotangent, 0.0f, 0.0f, + 0.0f, 0.0f, depth, 1.0f, + 0.0f, 0.0f, -depth * nearDistance, 0.0f}}; + } + return 0; +} + +// ELF 0x49AC20; bf2 0x83B7160. +Mat4& calcRotationMatrixFromAllVectors(Mat4& m, const Vec3& forward, const Vec3& up, + const Vec3& right, const Vec3& eye) +{ + m.m[0] = right.x; + m.m[4] = right.y; + m.m[8] = right.z; + m.m[12] = -(eye.x * right.x + eye.y * right.y + eye.z * right.z); + m.m[1] = up.x; + m.m[5] = up.y; + m.m[9] = up.z; + m.m[13] = -(eye.x * up.x + eye.y * up.y + eye.z * up.z); + m.m[2] = forward.x; + m.m[6] = forward.y; + m.m[10] = forward.z; + const float z = -(eye.x * forward.x + eye.y * forward.y + eye.z * forward.z); + m.m[3] = m.m[7] = m.m[11] = 0.0f; + m.m[15] = 1.0f; + m.m[14] = z; + return m; +} + namespace { const float s_degreesToRadians = 0.0174532924f; // in both shipped builds @@ -164,6 +280,7 @@ float clampUnit(float value) } // unnamed namespace +// ELF 0x499CA0. void setRotationZXY(Mat4& matrix, float zDegrees, float xDegrees, float yDegrees) { Rotation3 rotateZ = identityRotation(); @@ -231,6 +348,7 @@ void setRotationZXY(Mat4& matrix, float zDegrees, float xDegrees, float yDegrees matrix.m[10] = rotation.m[8]; } +// ELF 0x49A380. void getRotationZXY(const Mat4& matrix, float& zDegrees, float& xDegrees, float& yDegrees) { const float sineX = matrix.m[9]; @@ -267,6 +385,7 @@ void getRotationZXY(const Mat4& matrix, float& zDegrees, float& xDegrees, float& // Overwrites m with an X-axis rotation in degrees, including identity translation. +// ELF 0x499A90. void setRotateXDeg(Mat4& m, float degrees) { m = Mat4::getIdentity(); @@ -284,6 +403,7 @@ void setRotateXDeg(Mat4& m, float degrees) // Overwrites m with a Y-axis rotation in degrees, including identity translation. +// ELF 0x499B40. void setRotateYDeg(Mat4& m, float degrees) { m = Mat4::getIdentity(); @@ -299,6 +419,7 @@ void setRotateYDeg(Mat4& m, float degrees) } // The Z twin of the above, same "identity first, then the four terms" shape. +// ELF 0x499BF0. void setRotateZDeg(Mat4& m, float degrees) { m = Mat4::getIdentity(); @@ -315,6 +436,7 @@ void setRotateZDeg(Mat4& m, float degrees) // lhs * rhs, but only the nine rotation elements are computed and stored - the // translation row and the fourth column of `this` keep whatever they held. See the header. +// ELF 0x49B0D0. void Mat4::rotMult(const Mat4& lhs, const Mat4& rhs) { for (int row = 0; row < 3; ++row) @@ -330,6 +452,7 @@ void Mat4::rotMult(const Mat4& lhs, const Mat4& rhs) // The change-of-basis rotation about an arbitrary line - see the header for the // four steps and for the up-hint's degenerate case. +// ELF 0x49A650. void setRotateAboutLine(Mat4& m, float degrees, const Vec3& axis) { Vec3 up; @@ -398,6 +521,7 @@ std::ostream& operator<<(std::ostream& out, const Mat4& m) } +// ELF 0x49AD00. void calcLookAtMatrix(Mat4& m, const Vec3& eye, const Vec3& target, const Vec3& up) { float* f = m.m; diff --git a/Code/BF2/Math/Mat4.h b/Code/BF2/Math/Mat4.h index 43b3918c8..f7fb88e15 100644 --- a/Code/BF2/Math/Mat4.h +++ b/Code/BF2/Math/Mat4.h @@ -21,6 +21,7 @@ struct Mat4 static const Mat4& getIdentity(); static const Mat4& getZero(); // dice::hfe::Mat4::getZero - ArmorGLComp::setUseDestroyedLodRecursive // hands it to the geometry to hide a part + static const Mat4& getTexScaleBias(); Mat4 operator*(const Mat4& rhs) const; void mult(const Mat4& lhs, const Mat4& rhs); @@ -29,6 +30,13 @@ struct Mat4 void setInverse(const Mat4& source); + // Scales x/y/z components, including translation for scale and excluding it for rotScale. + // Both return this matrix and preserve the fourth column. + Mat4& scale(const Vec3& factors); + Mat4& rotScale(const Vec3& factors); + // Sequential transpose; source must be distinct for a correct transpose. + Mat4& setTranspose(const Mat4& source); + // Writes only the 3x3 rotation product, preserving translation and the fourth column. void rotMult(const Mat4& lhs, const Mat4& rhs); }; @@ -65,6 +73,15 @@ void setRotateAboutLine(Mat4& m, float degrees, const Vec3& axis); void calcLookAtMatrix(Mat4& m, const Vec3& eye, const Vec3& target, const Vec3& up); +// Perspective projection in radians. Returns -20000 without writing m when far-near < FLT_EPSILON. +// Otherwise returns zero; aspectScale multiplies the horizontal cotangent. +int calcProjectionMatrix(Mat4& m, float fov, float aspectScale, float nearDistance, float farDistance); + +// Writes the basis columns in right/up/forward order and translation as negative eye dot each axis. +// Returns the destination matrix. +Mat4& calcRotationMatrixFromAllVectors(Mat4& m, const Vec3& forward, const Vec3& up, + const Vec3& right, const Vec3& eye); + // General 4x4 inverse. Supports input/output aliasing; no singular-determinant guard. // [INFERRED] Void return. void fullInvert(const Mat4& source, Mat4& destination); diff --git a/Code/BF2/Math/Mat4Inverse.cpp b/Code/BF2/Math/Mat4Inverse.cpp index 0ade7d680..e19b4f2ae 100644 --- a/Code/BF2/Math/Mat4Inverse.cpp +++ b/Code/BF2/Math/Mat4Inverse.cpp @@ -1,7 +1,11 @@ -// Full 4x4 inverse for client and supported aidll builds. -// The dedicated implementation has different rounding and remains declaration-only. +// Full 4x4 inverse for client and aidll builds. +// AIDLL.dll 0x10123490 is instruction-identical to RendDX9.dll 0x10078270. +// The dedicated engine implementation has different rounding and remains declaration-only. #include "Mat4.h" -#if !DEDICATED || (defined(BF2_IMAGE_AIDLL) && defined(_MSC_VER) && defined(_M_IX86)) +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "PortableX87.h" +#endif +#if !DEDICATED || defined(BF2_IMAGE_AIDLL) namespace dice { namespace hfe { namespace { // Explicit x87 arithmetic keeps the caller's precision/rounding control and @@ -10,27 +14,38 @@ namespace { float roundedPairProduct(float left, float right) { float value; +#if defined(_MSC_VER) && defined(_M_IX86) __asm { fld left fmul right fstp value } +#else + // [CHOSEN, not recovered] Preserve x87 product float store. + value = bf2x87::store(bf2x87::mul(bf2x87::wide(left), bf2x87::wide(right))); +#endif return value; } double pairProduct(float left, float right) { double value; +#if defined(_MSC_VER) && defined(_M_IX86) __asm { fld left fmul right fstp value } +#else + // [CHOSEN, not recovered] Preserve x87 product double store. + value = bf2x87::storeDouble(bf2x87::mul(bf2x87::wide(left), bf2x87::wide(right))); +#endif return value; } void cofactor(float& output, double a0, double b0, double a1, double b1, double a2, double b2, double a3, double b3, double a4, double b4, double a5, double b5) { +#if defined(_MSC_VER) && defined(_M_IX86) __asm { mov edx, output fld a0 @@ -53,12 +68,17 @@ void cofactor(float& output, double a0, double b0, double a1, double b1, fsubr dword ptr [edx] fstp dword ptr [edx] } +#else + // [CHOSEN, not recovered] Preserve x87 staged cofactor float stores. + bf2x87::cofactor(output, a0, b0, a1, b1, a2, b2, a3, b3, a4, b4, a5, b5); +#endif } void divideByDeterminant(const float* input, float* output) { const float one = 1.0f; // Retain the reciprocal on the x87 stack throughout all16 scaled stores. // No zero/NaN/infinity test exists in either shipped image. +#if defined(_MSC_VER) && defined(_M_IX86) __asm { mov ecx, input mov edx, output @@ -84,6 +104,10 @@ void divideByDeterminant(const float* input, float* output) jnz scaleElement fstp st } +#else + // [CHOSEN, not recovered] Preserve x87 retained determinant reciprocal for all stores. + bf2x87::divideByDeterminant(input, output); +#endif } } void fullInvert(const Mat4& source, Mat4& destination) diff --git a/Code/BF2/Math/Math.cpp b/Code/BF2/Math/Math.cpp index 08db09bca..581e9814e 100644 --- a/Code/BF2/Math/Math.cpp +++ b/Code/BF2/Math/Math.cpp @@ -1,5 +1,7 @@ // Math initialization and proportional control. +// static init: ELF 0x49BCF0 (__tcf_0 0x49BD50, _GLOBAL__I 0x49BD80): iostream Init only. +#include #include "Math.h" @@ -10,7 +12,7 @@ namespace hfe { // Initialization succeeds without allocating resources. - +// ELF 0x49BAA0; bf2 0x83B7EF0. bool initMath() { return true; @@ -18,15 +20,17 @@ bool initMath() // No resources require shutdown. - +// ELF 0x49BAB0; bf2 0x83B7F00. void closeMath() { } +// ELF 0x49BAC0 / 0x49BB00; bf2 0x83B7F10 / 0x83B7F40. PController::PController() { init(0, 0.0f); } +// ELF 0x49BB40 / 0x49BB80; bf2 0x83B7F70 / 0x83B7F80. PController::PController(const float* target, float rate) { init(target, rate); } -// ELF 83B7F90 / PE 68D2E0. The constructors inline or forward this same initialization. +// ELF 0x49BBC0; bf2 0x83B7F90 / PE 0x68D2E0. Constructors forward this initialization. void PController::init(const float* target, float rate) { m_target = target; @@ -36,6 +40,8 @@ void PController::init(const float* target, float rate) // Does nothing without a target. Thresholds are strict; the negative clamp selects error for NaN. // Negative steps and rates are accepted. +// ELF 0x49BC00; bf2 0x83B7FC0. [PLATFORM] The two x87 builds spill different intermediate +// values around fabs; native float arithmetic follows their shared source-level operations. void PController::update(int steps) { if (!m_target) @@ -71,7 +77,8 @@ void PController::update(int steps) m_value = 0.0f; } -// see the header. +// bf2 ELF 0x83B9710; this helper has no symbol in libaidll. +#if !defined(BF2_IMAGE_AIDLL) float smooth_in_out(float current, float target, float* velocity, float smoothTime, float dt) { const float omega = 2.0f / smoothTime; @@ -86,6 +93,7 @@ float smooth_in_out(float current, float target, float* velocity, float smoothTi *velocity = 0.0f; return target + (change + temp) * exp; } +#endif } // namespace hfe } // namespace dice diff --git a/Code/BF2/Math/Plane3.cpp b/Code/BF2/Math/Plane3.cpp index fff114b53..a04299221 100644 --- a/Code/BF2/Math/Plane3.cpp +++ b/Code/BF2/Math/Plane3.cpp @@ -3,9 +3,13 @@ #include "Plane3.h" #include "Mat4.h" +// static init: ELF 0x49C1D0, 0x49C230, 0x49C260 (std::__ioinit). +#include + namespace dice { namespace hfe { +// ELF 0x49BDA0; engine ELF 0x83B8110. // n' = R * n (the 3x3, row-vector form: n'.x = m0*nx + m4*ny + m8*nz ...); // the plane's point p = -n * d goes through the full affine (R * p + t, t = m12..m14) and // d' = -(n' . p'). @@ -23,7 +27,23 @@ Plane3 Plane3::transform(const Plane3& plane, const Mat4& m) return r; } -// aidll / The body constructs one point on the plane as +// ELF 0x49BEE0; engine ELF 0x83B8240. +void Plane3::projectVector(const Vec3& v, Vec3& out) +{ + const float nx = normal.x, ny = normal.y, nz = normal.z; + const float xx = nx * nx, yy = ny * ny, zz = nz * nz; + const float xy = -nx * ny, xz = -nx * nz, yz = -ny * nz; + const float vx = v.x, vy = v.y, vz = v.z; + // No normalization: the projection is scaled by the squared normal length. + const float x = vx * (yy + zz) + vy * xy + vz * xz; + const float y = xy * vx + vy * (zz + xx) + vz * yz; + const float z = xz * vx + vy * yz + vz * (xx + yy); + out.x = x; + out.y = y; + out.z = z; +} + +// ELF 0x49C020; engine ELF 0x83B8360. The body constructs one point on the plane as // `-normal * d`, intersects the infinite line, records whether the parameter lies in [0, 1], and // returns true for every non-parallel line. The range flag does not control the return value. // On a parallel line neither output is written. @@ -51,7 +71,7 @@ bool Plane3::intersectLine(const Vec3& a, const Vec3& b, Vec3& out, bool& inside return true; } -// transcribed term for term (a2 = p1, a3 = p2, a4 = p3 in the decompile). +// ELF 0x493FD0; engine ELF 0x83B0B50. Originally emitted in Frustum.cpp. Vec3 intersect(const Plane3& p1, const Plane3& p2, const Plane3& p3) { const float n1x = p1.normal.x, n1y = p1.normal.y, n1z = p1.normal.z; diff --git a/Code/BF2/Math/Plane3.h b/Code/BF2/Math/Plane3.h index b79c06489..bd3b6b19b 100644 --- a/Code/BF2/Math/Plane3.h +++ b/Code/BF2/Math/Plane3.h @@ -18,9 +18,11 @@ struct Plane3 // static, by value. static Plane3 transform(const Plane3& plane, const Mat4& m); - // projectVector: engine [FRONTIER]. - // intersectLine: aidll / - written. + // Projects onto the plane through the origin, scaled by normal's squared length. + // The input may alias the output; d does not participate. void projectVector(const Vec3& v, Vec3& out); + // Intersects an infinite line; parallel lines leave both outputs unchanged. + // The range flag reports whether the intersection lies on the segment. bool intersectLine(const Vec3& a, const Vec3& b, Vec3& out, bool& insideSegment); }; diff --git a/Code/BF2/Math/Polynom.h b/Code/BF2/Math/Polynom.h new file mode 100644 index 000000000..ff31f2609 --- /dev/null +++ b/Code/BF2/Math/Polynom.h @@ -0,0 +1,286 @@ +// Real polynomial in one variable: a std::vector of coefficients, lowest power first. +// Header-only, as shipped: every member is a weak inline in both images (Math/Polynom.h is the +// __FILE__ of findRoots' degree error). Recovered from libaidll.so (Linux 1.5.3153, ia-32, +// symbols); bf2 carries the same weak bodies (findRoots 0x83ADDE0, evaluate 0x83AEFE0, +// operator+= 0x83AF030, operator*= 0x83AF180). The constructors, the copy and the two products +// have no symbol of their own; their shape is the one findRoots and Aimer::getNearestImpactPoint +// inline ([INFERRED] spelling). +// [PLATFORM] precision: the x87 build evaluates and sums in extended precision. + +// The complex helpers below adapt GCC 3 libstdc++ std_complex.h. +// Upstream: https://github.com/gcc-mirror/gcc/blob/releases/gcc-3.3.6/libstdc++-v3/include/std/std_complex.h +// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002 +// Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 2, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING. If not, write to the Free +// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, +// USA. + +// As a special exception, you may use this file as part of a free software +// library without restriction. Specifically, if other files instantiate +// templates or use macros or inline functions from this file, or you compile +// this file and link it with other files to produce an executable, this +// file does not by itself cause the resulting executable to be covered by +// the GNU General Public License. This exception does not however +// invalidate any other reasons why the executable file might be covered by +// the GNU General Public License. + +// +// ISO C++ 14882: 26.2 Complex Numbers +// Note: this is not a conforming implementation. +// Initially implemented by Ulrich Drepper +// Improved by Gabriel Dos Reis +// + +#ifndef MATH_POLYNOM_H +#define MATH_POLYNOM_H + +#include +#include +#include + +#include "../Core/Debug.h" + +namespace dice { +namespace hfe { + +namespace polynom_detail { + +// The image's own std::sqrt(const complex&) (libaidll 0x1CA770) and +// std::pow(const complex&, const float&) (0x1CAA80): GCC 3 libstdc++ instantiations, +// transcribed so that the native library cannot change the roots. [CHOSEN, not recovered] +// packaging; the algorithms are upstream libstdc++'s. Other libraries differ materially here: +// a sqrt of a negative real with a tiny nonzero real part flips Cardano's sign test below. +inline float complexAbs(const std::complex& z) +{ + const float x = std::fabs(z.real()); + const float y = std::fabs(z.imag()); + const float s = y <= x ? x : y; + if (s == 0.0f) + return s; + const float xs = z.real() / s; + const float ys = z.imag() / s; + return s * std::sqrt(ys * ys + xs * xs); +} + +inline std::complex complexSqrt(const std::complex& z) +{ + const float x = z.real(); + const float y = z.imag(); + if (x == 0.0f) + { + const float t = std::sqrt(std::fabs(y) * 0.5f); + return std::complex(t, y < 0.0f ? -t : t); + } + const float a = complexAbs(z); + const float t = std::sqrt(std::fabs(x) + a + std::fabs(x) + a); + const float u = t * 0.5f; + if (x <= 0.0f) + return std::complex(std::fabs(y) / t, y < 0.0f ? -u : u); + return std::complex(u, y / t); +} + +inline std::complex complexPow(const std::complex& z, const float& y) +{ + if (z.imag() == 0.0f) + return std::complex(std::pow(z.real(), y), 0.0f); + const float logAbs = std::log(complexAbs(z)); + const float angle = std::atan2(z.imag(), z.real()); + const float r = std::exp(logAbs * y); + return std::complex(r * std::cos(y * angle), std::sin(y * angle) * r); +} + +} // namespace polynom_detail + +class Polynom; +Polynom operator*(float factor, const Polynom& polynom); +Polynom operator*(const Polynom& lhs, const Polynom& rhs); + +class Polynom : public std::vector +{ +public: + Polynom() {} + + // `degree + 1` zero coefficients (the image fills them and zeroes them once more). + explicit Polynom(unsigned int size) + : std::vector(size, 0.0f) + { + for (unsigned int i = 0; i < size; ++i) + (*this)[i] = 0.0f; + } + + // The image copies by default construction and assignment (vector::operator=). + Polynom(const Polynom& other) + : std::vector() + { + std::vector::operator=(other); + } + + // Horner's scheme; an empty polynomial is 0. ELF 0x1CA310. + float evaluate(float x) const + { + const unsigned int n = size(); + float result = 0.0f; + if (n >= 2) + { + result = (*this)[n - 1]; + for (unsigned int i = n - 2; i < n; --i) + result = result * x + (*this)[i]; + } + else if (n == 1) + { + result = (*this)[0]; + } + return result; + } + + // ELF 0x1CA370. Grows to the longer operand. + Polynom& operator+=(const Polynom& other) + { + const unsigned int n = size(); + const unsigned int m = other.size(); + if (n < m) + { + resize(m, 0.0f); + unsigned int i = 0; + for (; i < n; ++i) + (*this)[i] = other[i] + (*this)[i]; + for (; i < m; ++i) + (*this)[i] = other[i]; + } + else + { + for (unsigned int i = 0; i < m; ++i) + (*this)[i] = other[i] + (*this)[i]; + } + return *this; + } + + // ELF 0x1CA4D0. The product has size() + other.size() - 1 coefficients. + Polynom& operator*=(const Polynom& other) + { + Polynom product(size() - 1 + other.size()); + for (unsigned int i = 0; i < size(); ++i) + for (unsigned int j = 0; j < other.size(); ++j) + product[i + j] = other[j] * (*this)[i] + product[i + j]; + std::vector::operator=(product); + return *this; + } + + // Appends the real roots of a polynomial of degree 1 to 3 (trailing zero coefficients are + // dropped first) to `roots`. A negative quadratic discriminant adds none, one below 1e-5 a + // double root once. The cubic is depressed by x = t - c2 / (3 c3) and solved by Cardano: one + // real root for a discriminant above 1e-10, else the real parts of the three complex roots. + // Degree 0 adds nothing; a higher degree is reported (an Error-type Debug, which aborts in + // this tree). ELF 0x1C8F50. + void findRoots(std::vector& roots) const + { + unsigned int degree = size() - 1; + while (degree != 0 && (*this)[degree] == 0.0f) + --degree; + + switch (degree) + { + case 0: + return; + case 1: + roots.push_back(-(*this)[0] / (*this)[1]); + return; + case 2: + { + const float b = (*this)[1]; + const float discriminant = b * b - (*this)[2] * 4.0f * (*this)[0]; + if (!(discriminant >= 0.0f)) + return; + if (discriminant < 1e-05f) + { + roots.push_back(-b / ((*this)[2] + (*this)[2])); + return; + } + const float root = std::sqrt(discriminant); + roots.push_back((-b - root) / ((*this)[2] + (*this)[2])); + roots.push_back((root - (*this)[1]) / ((*this)[2] + (*this)[2])); + return; + } + case 3: + break; + default: + Debug(DebugTypeError, "Math/Polynom.h", 0x100, "") << "Polynom::findRoots() unhandled polynom degree"; + return; + } + + const float c3 = (*this)[3]; + Polynom shift(2); // x = t + shift[0] + shift[0] = -(*this)[2] / (c3 * 3.0f); + shift[1] = 1.0f; + Polynom depressed(1); + depressed[0] = (*this)[0]; + depressed += (*this)[1] * shift; + depressed += (*this)[2] * shift * shift; + depressed += c3 * shift * shift * shift; + Polynom scale(1); + scale[0] = 1.0f / c3; + depressed *= scale; // t^3 + p t + q + + const float p3 = depressed[1] / 3.0f; + const float q = depressed[0]; + const float discriminant = p3 * p3 * p3 + q * 0.5f * (q * 0.5f); + if (discriminant > 1e-10f) + { + const float root = std::sqrt(discriminant); + float a = -q * 0.5f + root; + float b = -q * 0.5f - root; + const float u = a < 0.0f ? -std::pow(-a, 0.33333334f) : std::pow(a, 0.33333334f); + const float v = b < 0.0f ? -std::pow(-b, 0.33333334f) : std::pow(b, 0.33333334f); + roots.push_back(shift.evaluate(v + u)); + return; + } + + typedef std::complex Complex; + const Complex half(-q * 0.5f, 0.0f); + const Complex root = polynom_detail::complexSqrt(Complex(discriminant, 0.0f)); + const Complex a = half + root; + const Complex b = half - root; + const float third = 0.33333334f; + const Complex u = a.real() < 0.0f ? -polynom_detail::complexPow(-a, third) : polynom_detail::complexPow(a, third); + const Complex v = b.real() < 0.0f ? -polynom_detail::complexPow(-b, third) : polynom_detail::complexPow(b, third); + const Complex sum = u + v; + const Complex mid = -(sum / 2.0f); + const Complex offset = (u - v) / 2.0f * Complex(0.0f, 1.7320508f); + roots.push_back(shift.evaluate(sum.real())); + roots.push_back(shift.evaluate((mid - offset).real())); + roots.push_back(shift.evaluate((mid + offset).real())); + } +}; + +// The products findRoots inlines: a scaled copy, and a copy multiplied in place. +inline Polynom operator*(float factor, const Polynom& polynom) +{ + Polynom result(polynom.size()); + for (unsigned int i = 0; i < polynom.size(); ++i) + result[i] = factor * polynom[i]; + return result; +} + +inline Polynom operator*(const Polynom& lhs, const Polynom& rhs) +{ + Polynom result(lhs); + return result *= rhs; +} + +} // namespace hfe +} // namespace dice + +#endif // MATH_POLYNOM_H diff --git a/Code/BF2/Math/PortableX87.h b/Code/BF2/Math/PortableX87.h new file mode 100644 index 000000000..a77f36be6 --- /dev/null +++ b/Code/BF2/Math/PortableX87.h @@ -0,0 +1,272 @@ +// [CHOSEN, not recovered] Native C++ arms for the MSVC x86 expression blocks. +#ifndef BF2_MATH_PORTABLEX87_H +#define BF2_MATH_PORTABLEX87_H + +#include "../Platform/X87Compat.h" +#include +#include +#include +#include +#include +#include +#include + +namespace bf2x87 { + +// x87 leaves an out-of-range finite trig operand unchanged (C2=1). +// Native libm supplies the transcendental approximation inside that range. +inline Real sine(Real a) { return isFinite(a) && abs(a) >= std::ldexp(1.0L,63) ? a : sinValue(a); } +inline Real cosine(Real a) { return isFinite(a) && abs(a) >= std::ldexp(1.0L,63) ? a : cosValue(a); } +inline void trig(float angle, float& sineOut, float& cosineOut) +{ + if (isFinite(angle) && abs(wide(angle)) >= std::ldexp(1.0L,63)) { + // FSINCOS did not push a cosine. The second FSTP underflows the stack. + cosineOut = angle; + const std::uint32_t indefinite = 0xffc00000U; + std::memcpy(&sineOut, &indefinite, 4); + std::feraiseexcept(FE_INVALID); + return; + } + cosineOut = store(cosine(wide(angle))); + sineOut = store(sine(wide(angle))); +} + +inline float multiply(float a, float b) +{ + // FLD quiets a signaling source before FMUL chooses the larger NaN payload. + std::uint32_t aa, bb; + std::memcpy(&aa, &a, 4); std::memcpy(&bb, &b, 4); + const bool an = (aa & 0x7fffffffU) > 0x7f800000U; + const bool bn = (bb & 0x7fffffffU) > 0x7f800000U; + if ((an && !(aa & 0x400000U)) || (bn && !(bb & 0x400000U))) + std::feraiseexcept(FE_INVALID); + if (an) aa |= 0x400000U; + if (an && bn) { + if (bb & 0x400000U) { + if ((bb & 0x7fffffffU) > (aa & 0x7fffffffU) || + ((bb & 0x7fffffffU) == (aa & 0x7fffffffU) && bb < aa)) aa = bb; + } + std::memcpy(&a, &aa, 4); + return a; + } + return store(mul(wide(a), wide(b))); +} +inline float offset(float value, float start, float origin) +{ return store(add(sub(wide(value), wide(start)), wide(origin))); } +inline float center(float origin, float dimension) +{ return store(sub(wide(origin), mul(wide(dimension), 0.5L))); } +inline float multiplyAdd(float value, float factor, float translation) +{ return store(add(mul(wide(value), wide(factor)), wide(translation))); } +inline Real decoded(float value) +{ const Real loaded = wide(value); return less(loaded,0) ? -add(loaded, 1.0L) : loaded; } +inline bool sumNotLess(float a, float b, float limit) +{ return notLess(add(wide(a), wide(b)), wide(limit)); } +inline void fadeInPlace(float& current, float delta, float duration, bool increase) +{ + const Real step = div(wide(delta), wide(duration)); + const Real next = increase ? add(step, wide(current)) : sub(wide(current), step); + current = store(next); + if (increase) { if (greater(next,1)) current = 1.0f; } + else if (less(next,0)) current = 0.0f; +} +inline float fade(float current, float delta, float duration, bool increase) +{ fadeInPlace(current,delta,duration,increase); return current; } +inline bool chooseValue(float current, float target, float delta, float speed, + float braking, bool eased, float& value) +{ + const Real loadedCurrent=wide(current), loadedTarget=wide(target); + if (!less(loadedCurrent,loadedTarget) && !greater(loadedCurrent,loadedTarget)) return false; + const bool increasing = less(loadedCurrent,loadedTarget); + const Real distance = increasing ? sub(wide(target), wide(current)) : sub(wide(current), wide(target)); + Real step; + if (eased && less(distance,wide(braking))) { + const Real angle = wide(1.57075f); + step = mul(mul(cosine(sub(angle, mul(div(distance, wide(braking)), angle))), wide(speed)), wide(delta)); + } else step = mul(wide(delta), wide(speed)); + const Real next = increasing ? add(step, wide(current)) : sub(wide(current), step); + const float rounded = store(next); + value = (increasing ? greater(next,wide(target)) : less(next,wide(target))) ? target : rounded; + return true; +} +inline void fractionalDigits(double magnitude, int integral, int digits, char*& cursor) +{ + Real remainder = sub(wide(magnitude), wide(integral)); + // The original is a do/while, including its caller precondition digits > 0. + do { + remainder = mul(remainder, 10.0L); + const int digit = integer(remainder); + *cursor++ = static_cast(static_cast(digit) + 0x30U); + remainder = sub(remainder, wide(digit)); + } while (--digits != 0); +} +inline bool waitRemaining(double last, double cooldown, double now, double& remaining) +{ + const Real next = sub(wide(cooldown), mul(sub(wide(now), wide(last)), wide(1.0 / 60.0))); + if (!greaterOrUnordered(next, 0)) return false; + remaining = storeDouble(next); + return true; +} +inline bool abilityPosition(float x, float y) +{ return greaterOrUnordered(add(abs(sub(wide(y), -4000.0L)), abs(sub(wide(x), -4000.0L))), wide(std::numeric_limits::epsilon())); } +inline void beginCooldown(double now, const float& duration, float& remaining, + bool& reloading, float& deadline, bool supply) +{ + const Real next = add(wide(now), wide(duration)); + remaining = duration; + if (supply) reloading = true; + deadline = store(next); + if (!supply) reloading = true; +} +inline void movePointer(float* position, float x, float y, int sensitivity, + bool absolute, float width, float height) +{ + if (absolute) { + position[0] = store(mul(mul(wide(x), wide(width)), 0.5L)); + position[1] = store(mul(mul(wide(y), wide(height)), 0.5L)); + } else { + position[0] = store(add(mul(wide(x), wide(sensitivity)), wide(position[0]))); + position[1] = store(add(mul(wide(sensitivity), wide(y)), wide(position[1]))); + } +} +inline void clampCoordinate(float& value, float origin, float extent) +{ + if (less(wide(value),wide(origin))) value = origin; + else { + const Real upper = add(wide(extent), wide(origin)); + if (less(upper,wide(value))) value = store(upper); + } +} +inline float affine(float a, float ma, float b, float mb, float c, float mc, float translation) +{ return store(add(add(add(mul(wide(a), wide(ma)), mul(wide(b), wide(mb))), mul(wide(c), wide(mc))), wide(translation))); } +inline void project(float x, float y, float z, float height, float halfWidth, + float& outputX, float& outputY, float& outputZ) +{ + const Real halfHeight = mul(wide(height), 0.5L); + const Real inverse = div(1.0L, wide(z)); + outputX = store(mul(mul(wide(x), inverse), wide(halfWidth))); + outputY = store(mul(mul(-halfHeight, wide(y)), inverse)); + outputZ = store(inverse); +} +inline float distanceWithX(Real x, float fromY, float fromZ, float toY, + float toZ, float scale) +{ + const Real z = sub(wide(toZ), wide(fromZ)); + const Real y = sub(wide(toY), wide(fromY)); + return store(mul(squareRoot(add(add(mul(z,z),mul(x,x)),mul(y,y))),wide(scale))); +} +inline float distance(float fromX, float fromY, float fromZ, float toX, float toY, + float toZ, float scale) +{ + const Real z = sub(wide(toZ), wide(fromZ)); + const Real x = sub(wide(toX), wide(fromX)); + const Real y = sub(wide(toY), wide(fromY)); + return store(mul(squareRoot(add(add(mul(z,z),mul(x,x)),mul(y,y))),wide(scale))); +} +inline void pullPoint(float hx, float hy, float hz, float ox, float oy, float oz, float* output) +{ + const Real z = sub(wide(hz), wide(oz)); const float dz = store(z); + const Real y = sub(wide(hy), wide(oy)); const float dy = store(y); + const Real x = sub(wide(hx), wide(ox)); + const Real length = squareRoot(add(add(mul(z,z),mul(y,y)),mul(x,x))); + const float magnitude = store(length); + if (!greater(length,wide(0.2f))) return; + const float scale = store(div(wide(0.2f), wide(magnitude))); + const float offsetX = store(mul(x,wide(scale))); + output[0] = store(sub(wide(hx),wide(offsetX))); + output[1] = store(sub(wide(hy),mul(wide(dy),wide(scale)))); + output[2] = store(sub(wide(hz),mul(wide(dz),wide(scale)))); +} +inline bool subtractTimer(float& timer, float delta, bool inclusive) +{ + const Real next = sub(wide(timer), wide(delta)); timer = store(next); + return inclusive ? lessEqual(next,0) : less(next,0); +} +inline bool addDemoTimer(float& timer, float delta) +{ + const Real next = add(wide(delta),wide(timer)); timer = store(next); + return lessEqual(10,next); +} +inline float mapCoordinate(float world, float camera, float scale, bool alive) +{ + Real next = mul(wide(world), 0.5L); + if (alive) next = add(next,wide(camera)); + return store(mul(next,wide(scale))); +} +inline float heading(float x, float z) +{ return store(atanValue(wide(x),wide(z))); } +inline float armorRatio(float points, float maximum, float previous, bool blend) +{ + Real ratio = div(wide(points),wide(maximum)); + if (blend) ratio = mul(add(ratio,wide(previous)),0.5L); + return store(ratio); +} +inline float ammoRatio(int status, float previous, bool blend) +{ + Real ratio = mul(wide(status),wide(0.06666667014360428f)); + if (blend) ratio = mul(add(ratio,wide(previous)),0.5L); + return store(ratio); +} +inline void cooldown(float deadline, double now, float duration, float& remaining, float& fraction) +{ + const Real next = sub(wide(deadline),wide(now)); + remaining = store(next); fraction = store(div(next,wide(duration))); +} +inline float glyphWidth(float third, float second, float first, float width) +{ return store(add(add(add(wide(third),wide(second)),wide(first)),wide(width))); } +inline void cofactor(float& output, double a0, double b0, double a1, double b1, + double a2, double b2, double a3, double b3, double a4, double b4, + double a5, double b5) +{ + output = store(add(add(mul(wide(a0),wide(b0)),mul(wide(a1),wide(b1))),mul(wide(a2),wide(b2)))); + output = store(sub(wide(output), add(add(mul(wide(a3),wide(b3)),mul(wide(a4),wide(b4))),mul(wide(a5),wide(b5))))); +} +inline void divideByDeterminant(const float* input, float* output) +{ + Real determinant = add(mul(wide(input[4]),wide(output[1])),mul(wide(input[0]),wide(output[0]))); + determinant = add(determinant,mul(wide(input[8]),wide(output[2]))); + determinant = add(determinant,mul(wide(input[12]),wide(output[3]))); + const Real inverse = div(1.0L,determinant); + for (int i=0;i<16;++i) output[i] = store(mul(inverse,wide(output[i]))); +} +inline void lod(float lodScale, float view, float nearRatio, float farRatio, + float& base, float& nearDistance, float& inverseNear, float& farDistance, float& inverseFar) +{ + const Real product = mul(wide(lodScale),wide(view)); base = store(product); + const Real near = mul(product,wide(nearRatio)); nearDistance = store(near); + inverseNear = store(div(1.0L,sub(wide(base),near))); + const Real far = mul(wide(farRatio),wide(base)); farDistance = store(far); + inverseFar = store(div(1.0L,sub(wide(base),far))); +} +inline float effectiveDistance(float renderer, float global, float factor) +{ + const Real next = mul(mul(wide(renderer),wide(global)),wide(factor)); + return greater(next,200) ? store(next) : 200.0f; +} +inline void packedRotation(float angle, short& sineOut, short& cosineOut) +{ + sineOut = lowShort(integer(mul(sine(wide(angle)),32767.0L))); + cosineOut = lowShort(integer(mul(cosine(wide(angle)),32767.0L))); +} +inline void tableRotation(unsigned index, short& sineOut, short& cosineOut) +{ + // FILD dword is signed even though the C++ parameter is unsigned. + const Real angle = mul(wide(lowWord(index)),wide(0.0015339808305725455284f)); + sineOut = integer(mul(sine(angle),32767.0L)); + cosineOut = integer(mul(cosine(angle),32767.0L)); +} +inline void zoom(float radians, float halfScale, float reference, float& zoomOut, float& inverseOut) +{ + const Real angle = mul(wide(radians),wide(halfScale)); + const float ref = store(mul(wide(reference),wide(halfScale))); + const Real ratio = div(div(cosine(angle),sine(angle)),div(cosine(wide(ref)),sine(wide(ref)))); + zoomOut = store(ratio); + inverseOut = ratio == 0 ? 0.0f : store(div(1.0L,ratio)); +} +inline float consoleFloat(const float* input, bool* returnFlag) +{ + const Real loaded = wide(*input); + *returnFlag = true; + return store(loaded); +} +} // namespace bf2x87 +#endif diff --git a/Code/BF2/Math/Vec3.cpp b/Code/BF2/Math/Vec3.cpp index ebc422caa..9f4a97b5e 100644 --- a/Code/BF2/Math/Vec3.cpp +++ b/Code/BF2/Math/Vec3.cpp @@ -4,9 +4,21 @@ #include // makeOrthonormalBasis #include // the console Vec3 text form below #include +#include namespace dice { namespace hfe { + +namespace { +// [CHOSEN, not recovered] Explicit Init objects package the three original TUs in this merged file. +// static init: ELF 0x367450 / 0x3674B0 / 0x3674E0; engine 0x83F8170 / 0x83F81C0 / 0x83F81D0. +std::ios_base::Init boxStreamInit; +// static init: ELF 0x36C860 / 0x36C8C0 / 0x36C8F0; engine 0x83FB9E0 / 0x83FBA30 / 0x83FBA40. +std::ios_base::Init coordinateStreamInit; +// static init: ELF 0x49C8D0 / 0x49C930 / 0x49C960; engine 0x83B9DD0 / 0x83B9E20 / 0x83B9E30. +std::ios_base::Init basisStreamInit; +} + namespace Math { @@ -172,12 +184,242 @@ void vec2ToVec3XZ(const Vec2& in, Vec3& out) out.z = in.y; } -// Squared XZ distance; keep differences and products in double precision. +// ELF libaidll 0x36AE40 (bf2 0x83FA260). +void vec3ToVec2XY(const Vec3& in, Vec2& out) +{ + out.x = in.x; + out.y = in.y; +} + +// ELF libaidll 0x36AE60 (bf2 0x83FA280): z cleared last. +void vec2ToVec3XY(const Vec2& in, Vec3& out) +{ + out.x = in.x; + out.y = in.y; + out.z = 0.0f; +} + +// ELF libaidll 0x36AEE0 (bf2 0x83FA2E0). +void vec3ToVec2YZ(const Vec3& in, Vec2& out) +{ + out.x = in.y; + out.y = in.z; +} + +// ELF libaidll 0x36AF00 (bf2 0x83FA300): x cleared first. +void vec2ToVec3YZ(const Vec2& in, Vec3& out) +{ + out.x = 0.0f; + out.y = in.x; + out.z = in.y; +} + +// ELF libaidll 0x36AFB0 (bf2 0x83FA380). +void addVec3ToVec2XZ(const Vec3& in, Vec2& out) +{ + out.x = in.x + out.x; + out.y = in.z + out.y; +} + +// ELF libaidll 0x36AFD0. +void subVec3ToVec2XZ(const Vec3& in, Vec2& out) +{ + out.x = out.x - in.x; + out.y = out.y - in.z; +} + +// ELF libaidll 0x36AFF0 (bf2 0x83FA3C0). +void addVec2ToVec3XZ(const Vec2& in, Vec3& out) +{ + out.x = in.x + out.x; + out.z = in.y + out.z; +} + +// ELF libaidll 0x36B010 (bf2 0x83FA3E0). +void subVec2ToVec3XZ(const Vec2& in, Vec3& out) +{ + out.x = out.x - in.x; + out.z = out.z - in.y; +} + +// ELF libaidll 0x36C1E0: out.y is cleared first; x' = x cos - z sin, z' = sin x + cos z. +void rotateXZ(const Vec3& in, Vec3& out, float radians) +{ + out.y = 0.0f; + const float c = std::cos(radians); + const float s = std::sin(radians); + out.x = in.x * c - in.z * s; + out.z = s * in.x + c * in.z; +} + +// ELF 0x36BF10; engine ELF 0x83FB1D0. Float arithmetic is explicit in the amd-64 SSE body. float distXZSqr(const Vec3& a, const Vec3& b) { - const double dx = static_cast(a.x) - b.x; - const double dz = static_cast(a.z) - b.z; - return static_cast(dx * dx + dz * dz); + const float dx = a.x - b.x; + const float dz = a.z - b.z; + return dx * dx + dz * dz; +} + +// libaidll.so 0x36AF30 (the engine's Math TU, beside vec3ToVec2XZ). +void getNormal(const Vec2& in, Vec2& out) +{ + const float x = in.x; + const float y = in.y; + out.x = y; + out.y = -x; +} + +// libaidll.so 0x36AF70 (FireObject::isWithinRadius's caller): `mov 8(in),out.x`, then in.x with +// the sign bit flipped (`xor $0x80000000`) to out.y. +void getVec2NormalFromVec3XZ(const Vec3& in, Vec2& out) +{ + out.x = in.z; + out.y = -in.x; +} + +// libaidll.so 0x36C2E0. +bool lineIntersect(const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, float& t, float& s) +{ + const float denominator = (b.x - a.x) * (d.y - c.y) - (b.y - a.y) * (d.x - c.x); + if (denominator == 0.0f) + return false; + t = ((a.y - c.y) * (d.x - c.x) - (d.y - c.y) * (a.x - c.x)) / denominator; + s = ((a.y - c.y) * (b.x - a.x) - (a.x - c.x) * (b.y - a.y)) / denominator; + return true; +} + +// ELF libaidll 0x36B0F0; engine bf2 0x83FA4C0. The temporary output is stored before the +// origin is reread, so output aliasing a retains the shipped double-add behavior. +bool lineIntersect(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d, Vec3& output) +{ + const Vec3 first = {b.x - a.x, b.y - a.y, b.z - a.z}; + Vec3 firstUnit = first; + if (!Math::normaliseIfNeeded(firstUnit)) + Math::zero(firstUnit); + const Vec3 second = {d.x - c.x, d.y - c.y, d.z - c.z}; + Vec3 secondUnit = second; + if (!Math::normaliseIfNeeded(secondUnit)) + Math::zero(secondUnit); + const float dot = firstUnit.x * secondUnit.x + firstUnit.y * secondUnit.y + + firstUnit.z * secondUnit.z; + if (std::fabs(std::fabs(dot) - 1.0f) < 0.001f) + return false; + const Vec3 offset = {c.x - a.x, c.y - a.y, c.z - a.z}; + Vec3 cross; + Math::cross(cross, first, second); + Vec3 offsetCross; + Math::cross(offsetCross, offset, second); + const float denominator = cross.x * cross.x + cross.y * cross.y + cross.z * cross.z; + if (denominator == 0.0f) + { + if (offsetCross.x * offsetCross.x + offsetCross.y * offsetCross.y + + offsetCross.z * offsetCross.z != 0.0f) + return false; + output = a; + return true; + } + const float parameter = (cross.x * offsetCross.x + cross.y * offsetCross.y + + cross.z * offsetCross.z) / denominator; + output.x = first.x * parameter; + output.y = first.y * parameter; + output.z = first.z * parameter; + output.x += a.x; + output.y += a.y; + output.z += a.z; + return true; +} + +// ELF libaidll 0x36B6C0; engine bf2 0x83FAA20. +bool linePointOnSegment(const Vec3& point, const Vec3& a, const Vec3& b) +{ + const Vec3 direction = {b.x - a.x, b.y - a.y, b.z - a.z}; + const Vec3 offset = {point.x - a.x, point.y - a.y, point.z - a.z}; + Vec3 unitDirection = direction; + if (!Math::normaliseIfNeeded(unitDirection)) + Math::zero(unitDirection); + Vec3 unitOffset = offset; + if (!Math::normaliseIfNeeded(unitOffset)) + Math::zero(unitOffset); + if (std::fabs(std::sqrt(offset.x * offset.x + offset.y * offset.y + offset.z * offset.z)) < + 0.001f) + return true; + const float dot = unitOffset.x * unitDirection.x + unitOffset.y * unitDirection.y + + unitOffset.z * unitDirection.z; + if (std::fabs(dot - 1.0f) > 0.001f) + return false; + const float segmentLength = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + const float offsetLength = std::sqrt(offset.x * offset.x + offset.y * offset.y + + offset.z * offset.z); + const float difference = segmentLength - offsetLength; + if (std::fabs(difference) > 0.001f && difference < 0.0f) + return false; + const float scale = segmentLength / offsetLength; + const Vec3 projected = {offset.x * scale, offset.y * scale, offset.z * scale}; + const Vec3 error = {projected.x - direction.x, projected.y - direction.y, + projected.z - direction.z}; + return std::fabs(error.x * error.x + error.y * error.y + error.z * error.z) < 0.001f; +} + +// ELF libaidll 0x36B610; engine bf2 0x83FA980. +bool lineSegmentIntersect(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d, Vec3& output) +{ + // shipped defect: a failed line calculation still tests the unchanged output. + lineIntersect(a, b, c, d, output); + return linePointOnSegment(output, a, b) && linePointOnSegment(output, c, d); +} + +// ELF libaidll 0x36B5B0; engine bf2 0x83FA930. +bool lineSegmentIntersect(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d) +{ + Vec3 output = {}; + return lineSegmentIntersect(a, b, c, d, output); +} + +// libaidll.so 0x36C650. Each pass projects the edge's endpoints and the point (three +// vec3ToVec2XZ calls, point last), takes getNormal of the edge inline, and rejects on +// `0 > dot` (ja: an unordered dot does not reject). An empty polygon is inside. +bool pointWithinPolygon2d(const Vec3& point, Vec3* polygon, int count) +{ + for (int i = 0; i < count;) + { + Vec2 a = { 0.0f, 0.0f }; + vec3ToVec2XZ(polygon[i], a); + ++i; + Vec2 b = { 0.0f, 0.0f }; + vec3ToVec2XZ(polygon[i % count], b); + Vec2 edge; + edge.x = b.x - a.x; + edge.y = b.y - a.y; + Vec2 normal; + getNormal(edge, normal); + Vec2 p = { 0.0f, 0.0f }; + vec3ToVec2XZ(point, p); + const float dot = (p.x - a.x) * normal.x + (p.y - a.y) * normal.y; + if (0.0f > dot) + return false; + } + return true; +} + +// libaidll.so 0x36C790. The same test on 2D vertices; the point is read once. +bool pointWithinPolygon2d(const Vec2& point, Vec2* polygon, int count) +{ + for (int i = 0; i < count;) + { + const Vec2& a = polygon[i]; + ++i; + const Vec2& b = polygon[i % count]; + Vec2 edge; + edge.x = b.x - a.x; + edge.y = b.y - a.y; + Vec2 normal; + getNormal(edge, normal); + const float dot = (point.x - a.x) * normal.x + (point.y - a.y) * normal.y; + if (0.0f > dot) + return false; + } + return true; } // Computes (centre - minimum) + centre in double precision before each float store. @@ -189,5 +431,488 @@ Vec2& getBoxMaxCorner(const Vec2& minimum, const Vec2& centre, Vec2& output) return output; } +// The four `ja` tests: unordered comparisons do not reject. +bool insideCentreBox(const Vec2& point, const Vec2& minimum, const Vec2& centre) +{ + if (minimum.x > point.x || minimum.y > point.y) + return false; + Vec2 maximum; + maximum.x = 0.0f; + maximum.y = 0.0f; + getBoxMaxCorner(minimum, centre, maximum); + return !(point.x > maximum.x) && !(point.y > maximum.y); +} + +// libaidll.so 0x366D30. The four `ja` tests: unordered comparisons do not reject. +bool insideCornerBox(const Vec2& point, const Vec2& minimum, const Vec2& maximum) +{ + if (minimum.x > point.x || minimum.y > point.y || point.x > maximum.x) + return false; + return !(point.y > maximum.y); +} + +// libaidll.so 0x366DB0. +void getBoxCentre(const Vec2& minimum, Vec2& centre, const Vec2& maximum) +{ + centre.x = (maximum.x + minimum.x) * 0.5f; + centre.y = (maximum.y + minimum.y) * 0.5f; +} + +// ELF 0x366F60 (libaidll.so), engine ELF 0x83F7CC0: preserve the early axis collapses. +bool getBoxIntersections(const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, + Vec2& outMinimum, Vec2& outMaximum) +{ + float minimum; + float maximum; + float collapsed = 0.0f; + bool collapse = false; + if (d.x > b.x) + { + if (c.x > b.x) + return false; + maximum = b.x; + if (b.x == c.x || c.x > a.x) + minimum = c.x; + else + { + minimum = a.x; + collapse = true; + collapsed = b.y > d.y ? d.y : c.y; + } + } + else if (b.x == d.x) + { + minimum = c.x > a.x ? c.x : a.x; + maximum = d.x; + } + else + { + if (a.x > d.x) + return false; + maximum = d.x; + if (a.x == d.x || !(c.x > a.x)) + minimum = a.x; + else + { + minimum = c.x; + collapse = true; + collapsed = d.y > b.y ? b.y : a.y; + } + } + outMinimum.x = minimum; + outMaximum.x = maximum; + if (collapse) + { + outMinimum.y = collapsed; + outMaximum.y = collapsed; + return true; + } + + if (d.y > b.y) + { + if (c.y > b.y) + return false; + maximum = b.y; + if (b.y == c.y || c.y > a.y) + minimum = c.y; + else + { + minimum = a.y; + collapse = true; + collapsed = b.x > d.x ? d.x : c.x; + } + } + else if (b.y == d.y) + { + minimum = c.y > a.y ? c.y : a.y; + maximum = d.y; + } + else + { + if (a.y > d.y) + return false; + maximum = d.y; + if (a.y == d.y || !(c.y > a.y)) + minimum = a.y; + else + { + minimum = c.y; + collapse = true; + collapsed = d.x > b.x ? b.x : a.x; + } + } + outMinimum.y = minimum; + outMaximum.y = maximum; + if (collapse) + { + outMinimum.x = collapsed; + outMaximum.x = collapsed; + } + return true; +} + +// libaidll.so 0x3671E0. The line is direction . q + offset = 0 with direction = (normal.y, +// -normal.x); atMinimum / atMaximum are its values at the two corners. Each range test is written +// so that a NaN parameter fails it, as the image's `jb` tests do. +void getIntersection(const Vec2& minimum, const Vec2& maximum, const Vec2& normal, + const Vec2& point, Vec2& out) +{ + const float width = maximum.x - minimum.x; + const float height = maximum.y - minimum.y; + if (width == 0.0f || height == 0.0f) + { + out = point; + return; + } + Vec2 direction; + direction.x = normal.y; + direction.y = -normal.x; + const float offset = -(direction.x * point.x + direction.y * point.y); + const float atMinimum = direction.y * minimum.y + minimum.x * direction.x + offset; + const float atMaximum = maximum.x * direction.x + direction.y * maximum.y + offset; + if (normal.y > 0.0f) + { + const float t = atMaximum / (normal.y * width); + if (t >= 0.0f && t <= 1.0f) + { + out.y = maximum.y; + out.x = maximum.x - t * width; + return; + } + } + else if (normal.y < 0.0f) + { + const float t = -atMinimum / (normal.y * width); + if (t >= 0.0f && t <= 1.0f) + { + out.y = minimum.y; + out.x = t * width + minimum.x; + return; + } + } + if (normal.x < 0.0f) + { + const float t = -atMinimum / (height * direction.y); + if (!(t >= 0.0f && t <= 1.0f)) + return; + out.x = minimum.x; + out.y = minimum.y + t * height; + } + else if (normal.x > 0.0f) + { + const float t = atMaximum / (height * direction.y); + if (!(t >= 0.0f && t <= 1.0f)) + return; + out.x = maximum.x; + out.y = maximum.y - t * height; + } +} + +// libaidll.so 0x36C470 (recovered by ai-w1-b-entries for the mouse-turret entries). The cosine is +// clamped twice in the image (same value); the angle to the left normal gives the magnitude, and +// a negative dot product folds it onto the far half circle. +float getSignedDiffAngleToDir(const Vec2& a, const Vec2& b) +{ + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + getNormal(a, normal); + float c = b.x * normal.x + b.y * normal.y; + if (!(-1.0f <= c)) + c = -1.0f; + else if (1.0f < c) + c = 1.0f; + float angle = 1.57079637f - std::acos(c); + if (b.x * a.x + b.y * a.y < 0.0f) + { + float sign = 1.0f; + if (angle <= 0.0f) + sign = (angle < 0.0f) ? -1.0f : 0.0f; + angle = sign * 3.14159274f - angle; + } + return angle; +} + +// libaidll.so 0x36C570 (listing). As getSignedDiffAngleToDir with `normal` supplied; the dot product +// is clamped only when it is ordered and outside [-1, 1], and the flip applies unless b.a >= 0. +float getSignedDiffAngleToDirWithNormal(const Vec2& a, const Vec2& normal, const Vec2& b) +{ + float c = b.y * normal.y + b.x * normal.x; + if (-1.0f > c) + c = -1.0f; + else if (c > 1.0f) + c = 1.0f; + float angle = 1.57079637f - std::acos(c); + if (!(b.y * a.y + b.x * a.x >= 0.0f)) + { + float sign = 1.0f; + if (!(angle > 0.0f)) + sign = (0.0f > angle) ? -1.0f : 0.0f; + angle = sign * 3.14159274f - angle; + } + return angle; +} + +// libaidll.so 0x36C3B0 +float getSignedDiffAngleToDirXZ(const Vec3& a, const Vec3& b) +{ + Vec2 a2; + a2.x = a.x; + a2.y = a.z; + Vec2 b2; + b2.x = b.x; + b2.y = b.z; + return getSignedDiffAngleToDir(a2, b2); +} + +// libaidll.so 0x36C410 +float getSignedDiffAngleToDirYZ(const Vec3& a, const Vec3& b) +{ + Vec2 a2; + a2.x = a.y; + a2.y = a.z; + Vec2 b2; + b2.x = b.y; + b2.y = b.z; + return getSignedDiffAngleToDir(a2, b2); +} + +// ELF 0x36B030; engine ELF 0x83FA400. +void addVec2ToPos3XZ(const Vec2& in, Vec3& out) +{ + out.x = in.x + out.x; + out.z = in.y + out.z; +} + +// ELF 0x36B050; engine ELF 0x83FA420. +void subVec2ToPos3XZ(const Vec2& in, Vec3& out) +{ + out.x = out.x - in.x; + out.z = out.z - in.y; +} + +// ELF 0x36B070; engine ELF 0x83FA440. +void getVectorToXZ(const Vec3& from, const Vec3& to, Vec2& out) +{ + out.x = to.x - from.x; + out.y = to.z - from.z; +} + +// ELF 0x36B090; engine ELF 0x83FA460. +void getVectorToXY(const Vec3& from, const Vec3& to, Vec2& out) +{ + out.x = to.x - from.x; + out.y = to.y - from.y; +} + +// ELF 0x36B0B0; engine ELF 0x83FA480. +void getVectorToYZ(const Vec3& from, const Vec3& to, Vec2& out) +{ + out.x = to.y - from.y; + out.y = to.z - from.z; +} + +// ELF 0x36B0D0; engine ELF 0x83FA4A0. +void flipVec3XZ(Vec3& value) +{ + const float x = value.x; + const float z = value.z; + value.z = x; + value.x = z; +} + +// ELF 0x36BEC0; engine ELF 0x83FB190. +float distXZ(const Vec3& a, const Vec3& b) +{ + return std::sqrt(distXZSqr(a, b)); +} + +// ELF 0x36BF40; engine ELF 0x83FB200. +float distXY(const Vec3& a, const Vec3& b) +{ + return std::sqrt(distXYSqr(a, b)); +} + +// ELF 0x36BF90; engine ELF 0x83FB240. +float distXYSqr(const Vec3& a, const Vec3& b) +{ + const float x = a.x - b.x; + const float y = a.y - b.y; + return x * x + y * y; +} + +// ELF 0x36BFC0; engine ELF 0x83FB270. +float distYZ(const Vec3& a, const Vec3& b) +{ + return std::sqrt(distYZSqr(a, b)); +} + +// ELF 0x36C010; engine ELF 0x83FB2B0. +float distYZSqr(const Vec3& a, const Vec3& b) +{ + const float y = a.y - b.y; + const float z = a.z - b.z; + return y * y + z * z; +} + +// ELF 0x36C040; engine ELF 0x83FB2E0. +float magnitudeXY(const Vec3& value) +{ + return std::sqrt(magnitudeXYSqr(value)); +} + +// ELF 0x36C080; engine ELF 0x83FB310. +float magnitudeXYSqr(const Vec3& value) +{ + return value.x * value.x + value.y * value.y; +} + +// ELF 0x36C0A0; engine ELF 0x83FB330. +float magnitudeXZ(const Vec3& value) +{ + return std::sqrt(magnitudeXZSqr(value)); +} + +// ELF 0x36C0E0; engine ELF 0x83FB360. +float magnitudeXZSqr(const Vec3& value) +{ + return value.x * value.x + value.z * value.z; +} + +// ELF 0x36C100; engine ELF 0x83FB380. +float magnitudeYZ(const Vec3& value) +{ + return std::sqrt(magnitudeYZSqr(value)); +} + +// ELF 0x36C140; engine ELF 0x83FB3B0. +float magnitudeYZSqr(const Vec3& value) +{ + return value.y * value.y + value.z * value.z; +} + +// ELF 0x36C160; engine ELF 0x83FB3D0. +void rotateXY(const Vec3& in, Vec3& out, float radians) +{ + out.z = 0.0f; + const float c = std::cos(radians); + const float s = std::sin(radians); + out.x = in.x * c - in.y * s; + out.y = s * in.x + c * in.y; +} + +// ELF 0x36C260; engine ELF 0x83FB4B0. +void rotateYZ(const Vec3& in, Vec3& out, float radians) +{ + out.x = 0.0f; + const float c = std::cos(radians); + const float s = std::sin(radians); + out.y = in.y * c - in.z * s; + out.z = s * in.y + c * in.z; +} + +namespace { + +// [INFERRED] Packaging for Vec2's inlined component access; both components are attested floats. +float& boxComponent(Vec2& value, int axis) +{ + return *reinterpret_cast(reinterpret_cast(&value) + axis * sizeof(float)); +} + +const float& boxComponent(const Vec2& value, int axis) +{ + return *reinterpret_cast(reinterpret_cast(&value) + axis * sizeof(float)); +} + +// [INFERRED] Packaging of the inlined Vec3 normalization, dot product and subtraction. +void normaliseGeometry(Vec3& value) +{ + if (!Math::normaliseIfNeeded(value)) + Math::zero(value); +} + +float geometryDot(const Vec3& a, const Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +Vec3 geometryDifference(const Vec3& to, const Vec3& from) +{ + Vec3 result = { to.x - from.x, to.y - from.y, to.z - from.z }; + return result; +} + +} // anonymous namespace + +// ELF 0x366DF0; engine ELF 0x83F7B50. +// [INFERRED] int return follows the full-width zero/one materialization in both images. +int getLineIntersections(const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, + Vec2& outFirst, Vec2& outSecond, bool& overlap, int firstAxis, int secondAxis) +{ + if (firstAxis != secondAxis) + { + const float coordinate = boxComponent(a, secondAxis); + if (!(coordinate >= boxComponent(c, secondAxis))) + return false; + if (!(boxComponent(d, secondAxis) >= coordinate)) + return false; + const float other = boxComponent(c, firstAxis); + if (!(other >= boxComponent(a, firstAxis))) + return false; + if (!(boxComponent(b, firstAxis) >= other)) + return false; + boxComponent(outFirst, firstAxis) = other; + boxComponent(outFirst, secondAxis) = boxComponent(a, secondAxis); + overlap = false; + return true; + } + + const int otherAxis = (firstAxis + 1) % 2; + if (boxComponent(d, otherAxis) != boxComponent(c, otherAxis)) + return false; + const float firstMinimum = boxComponent(a, firstAxis); + const float secondMaximum = boxComponent(d, firstAxis); + if (!(secondMaximum > firstMinimum)) + return false; + const float secondMinimum = boxComponent(c, firstAxis); + const float firstMaximum = boxComponent(b, firstAxis); + if (secondMinimum > firstMaximum) + return false; + + const Vec2& left = !(secondMinimum > firstMinimum) ? a : c; + const Vec2& right = !(secondMaximum > firstMaximum) ? d : b; + const float leftX = left.x; + const float leftY = left.y; + outFirst.y = leftY; + outFirst.x = leftX; + const float rightX = right.x; + const float rightY = right.y; + outSecond.x = rightX; + outSecond.y = rightY; + overlap = true; + return true; +} + +// ELF 0x36BB10; engine ELF 0x83FAE30. +bool allPointsOnSameLine(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d) +{ + Vec3 first = geometryDifference(b, a); + normaliseGeometry(first); + Vec3 current = geometryDifference(c, a); + normaliseGeometry(current); + for (int i = 0; i < 2; ++i) + { + const float error = std::fabs(geometryDot(first, current)) - 1.0f; + if (geometryDot(first, first) > 0.001f && geometryDot(current, current) > 0.001f + && std::fabs(error) > 0.001f) + return false; + // The final iteration repeats this construction and normalization before returning. + current = geometryDifference(d, a); + normaliseGeometry(current); + } + return true; +} + + } // namespace hfe } // namespace dice diff --git a/Code/BF2/Math/Vec3.h b/Code/BF2/Math/Vec3.h index 00e194a4a..c578c3a5f 100644 --- a/Code/BF2/Math/Vec3.h +++ b/Code/BF2/Math/Vec3.h @@ -72,13 +72,104 @@ typedef Math::Vec4 Vec4; void vec3ToVec2XZ(const Vec3& in, Vec2& out); void vec2ToVec3XZ(const Vec2& in, Vec3& out); -// Squared distance in the XZ plane; ignores y. [INFERRED] Float return. -// Native return rounds once; original x87 callers could compare the unrounded value. +// The XY and YZ planes the same way: libaidll 0x36AE40 / 0x36AE60 / 0x36AEE0 / 0x36AF00 +// (bf2 0x83FA260 / 0x83FA280 / 0x83FA2E0 / 0x83FA300). The restoring direction clears the +// dropped component. +void vec3ToVec2XY(const Vec3& in, Vec2& out); +void vec2ToVec3XY(const Vec2& in, Vec3& out); +void vec3ToVec2YZ(const Vec3& in, Vec2& out); +void vec2ToVec3YZ(const Vec2& in, Vec3& out); +// libaidll 0x36AFB0 / bf2 0x83FA380: out.x += in.x, out.y += in.z. +void addVec3ToVec2XZ(const Vec3& in, Vec2& out); +// libaidll 0x36AFD0: out.x -= in.x, out.y -= in.z. +void subVec3ToVec2XZ(const Vec3& in, Vec2& out); +// libaidll 0x36AFF0 / bf2 0x83FA3C0: out.x += in.x, out.z += in.y; y untouched. +void addVec2ToVec3XZ(const Vec2& in, Vec3& out); +// libaidll 0x36B010 / bf2 0x83FA3E0: out.x -= in.x, out.z -= in.y; y untouched. +void subVec2ToVec3XZ(const Vec2& in, Vec3& out); +// The position variants update the same XZ components and leave height untouched. +void addVec2ToPos3XZ(const Vec2& in, Vec3& out); +void subVec2ToPos3XZ(const Vec2& in, Vec3& out); +// Writes the indicated projection of to - from; inputs and output may alias. +void getVectorToXZ(const Vec3& from, const Vec3& to, Vec2& out); +void getVectorToXY(const Vec3& from, const Vec3& to, Vec2& out); +void getVectorToYZ(const Vec3& from, const Vec3& to, Vec2& out); +void flipVec3XZ(Vec3& value); +// Rotates a projected vector, clearing the omitted component before reading the input. +// In-place rotation retains the shipped sequential-write behavior. +void rotateXY(const Vec3& in, Vec3& out, float radians); +void rotateYZ(const Vec3& in, Vec3& out, float radians); +// ELF libaidll 0x36C1E0 (added by ai-bot): `in` turned by `radians` about Y into `out` (y = 0). +void rotateXZ(const Vec3& in, Vec3& out, float radians); +// Squared distance in the XZ plane; ignores y. The x87 image can retain excess precision. float distXZSqr(const Vec3& a, const Vec3& b); +float distXZ(const Vec3& a, const Vec3& b); +float distXY(const Vec3& a, const Vec3& b); +float distXYSqr(const Vec3& a, const Vec3& b); +float distYZ(const Vec3& a, const Vec3& b); +float distYZSqr(const Vec3& a, const Vec3& b); +float magnitudeXY(const Vec3& value); +float magnitudeXYSqr(const Vec3& value); +float magnitudeXZ(const Vec3& value); +float magnitudeXZSqr(const Vec3& value); +float magnitudeYZ(const Vec3& value); +float magnitudeYZSqr(const Vec3& value); +// The left-hand normal of a 2D vector: (y, -x). Reads both components before writing. +void getNormal(const Vec2& in, Vec2& out); +// The XZ projection's left-hand normal in one step: (z, -x). libaidll.so 0x36AF70. +void getVec2NormalFromVec3XZ(const Vec3& in, Vec2& out); +// Intersects the infinite lines a-b and c-d. False only when they are parallel (zero +// denominator); otherwise t and s are the parameters along a-b and c-d. +bool lineIntersect(const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, float& t, float& s); +// Finds the point on a-b selected by the cross-product construction for the two infinite lines. +// Near-parallel normalized directions are refused; failure leaves output untouched. +bool lineIntersect(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d, Vec3& output); +// Tests whether the point lies along a-b, with the shipped direction and distance tolerances. +bool linePointOnSegment(const Vec3& point, const Vec3& a, const Vec3& b); +// Intersects segments using the shipped unchecked infinite-line result. The output overload +// retains its previous output when that calculation refuses the lines. +bool lineSegmentIntersect(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d); +bool lineSegmentIntersect(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d, Vec3& output); +// True when c and d lie on the line through a and b (the shipped direction tolerance). +bool allPointsOnSameLine(const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& d); +// True when `point` (XZ) lies on the inner side of every edge of the polygon (XZ), i.e. no +// edge normal (getNormal of b - a) has a negative dot product with point - a. libaidll.so +// 0x36C650 (Vec3) and 0x36C790 (Vec2). +bool pointWithinPolygon2d(const Vec3& point, Vec3* polygon, int count); +bool pointWithinPolygon2d(const Vec2& point, Vec2* polygon, int count); // Computes (centre - minimum) + centre, storing x before reading y. // Output may alias either input. [INFERRED] Reference return. Vec2& getBoxMaxCorner(const Vec2& minimum, const Vec2& centre, Vec2& output); +// AI image 0x366CA0: point within [minimum, getBoxMaxCorner(minimum, centre)], bounds inclusive. +bool insideCentreBox(const Vec2& point, const Vec2& minimum, const Vec2& centre); +// libaidll.so 0x366D30: point within [minimum, maximum], bounds inclusive; NaN does not reject. +bool insideCornerBox(const Vec2& point, const Vec2& minimum, const Vec2& maximum); +// libaidll.so 0x366DB0: the centre of the box minimum..maximum. Note the argument order. +void getBoxCentre(const Vec2& minimum, Vec2& centre, const Vec2& maximum); +// Intersects ordered axis-aligned line segments. Axis indices must be 0 or 1. +// Writes the first point and sets overlap false for a crossing; a collinear overlap writes both. +// Failure leaves the outputs untouched. +int getLineIntersections(const Vec2& a, const Vec2& b, const Vec2& c, const Vec2& d, + Vec2& outFirst, Vec2& outSecond, bool& overlap, int firstAxis, int secondAxis); +// Finds the shipped box-overlap segment. May collapse the other axis and return early; +// a false result can leave the output X coordinates already written. +bool getBoxIntersections(const Vec2& firstMinimum, const Vec2& firstMaximum, + const Vec2& secondMinimum, const Vec2& secondMaximum, + Vec2& outMinimum, Vec2& outMaximum); +// libaidll.so 0x3671E0: where the line through `point` along (normal.y, -normal.x) meets an edge +// of the box minimum..maximum (y edges first). A flat box yields `point`; `out` is left untouched +// when no edge qualifies. Not the same body as ai::getIntersection (ControlFunctions). +void getIntersection(const Vec2& minimum, const Vec2& maximum, const Vec2& normal, + const Vec2& point, Vec2& out); +// libaidll.so 0x36C470: signed angle (radians, -pi..pi) from direction a to direction b, both unit. +float getSignedDiffAngleToDir(const Vec2& a, const Vec2& b); +// libaidll.so 0x36C570 (bf2 0x83FB750): the same angle with the caller's left-hand normal of `a` +// (getNormal); the clamp passes NaN through. +float getSignedDiffAngleToDirWithNormal(const Vec2& a, const Vec2& normal, const Vec2& b); +// libaidll.so 0x36C3B0 / 0x36C410: the same for the XZ and YZ projections of two Vec3. +float getSignedDiffAngleToDirXZ(const Vec3& a, const Vec3& b); +float getSignedDiffAngleToDirYZ(const Vec3& a, const Vec3& b); } // namespace hfe } // namespace dice diff --git a/Code/BF2/Physics/SoldierResponse.h b/Code/BF2/Physics/SoldierResponse.h index 30746ef3b..043bce772 100644 --- a/Code/BF2/Physics/SoldierResponse.h +++ b/Code/BF2/Physics/SoldierResponse.h @@ -14,6 +14,8 @@ namespace hfe { class SoldierNetworkable; // the wire wrapper - a friend below; see Networkables.h class SoldierSound; // reads the retail ground-contact byte in its movement-sound tick +namespace ai { class AIObjectPhysical; } // isInAir reads the ground-contact byte (+0xFA) + namespace world { class SoldierResponsePhysics : public PointResponsePhysics @@ -79,6 +81,9 @@ class SoldierResponsePhysics : public PointResponsePhysics // (ELF 0x8254940 / PE 0x5847C0). Narrow friend preserves that raw response-physics gate. friend class GenericFireArm; + // ai::AIObjectPhysical::isInAir (bf2 0x841A0C0) reads the ground-contact byte. + friend class dice::hfe::ai::AIObjectPhysical; + // Layout 0x90..0xFB, every default from the 241-byte ctor. /* +0x90 */ int m_refCount; // 1 // The tinfo's names for +0x94 / +0xA0 / +0xB8 are kept so the IDB and this header still read diff --git a/Code/BF2/Platform/X87Compat.h b/Code/BF2/Platform/X87Compat.h new file mode 100644 index 000000000..d02ccb84f --- /dev/null +++ b/Code/BF2/Platform/X87Compat.h @@ -0,0 +1,93 @@ +// [CHOSEN, not recovered] Shared numeric policy for native x87 expression arms. +#ifndef BF2_PLATFORM_X87COMPAT_H +#define BF2_PLATFORM_X87COMPAT_H +#include +#include +#include +#include +#include +#include +#include +namespace bf2x87 { +using Real = long double; +inline bool isNaN(Real value) { return std::isnan(value); } +inline bool isFinite(Real value) { return (std::isfinite)(value); } // (): tu_math.h defines an isfinite macro +inline Real abs(Real value) { return std::fabs(value); } +inline Real squareRoot(Real value) { return std::sqrt(value); } +inline Real sinValue(Real value) { return std::sin(value); } +inline Real cosValue(Real value) { return std::cos(value); } +inline Real atanValue(Real a, Real b) { return std::atan2(a,b); } +// Load exactly, round after each arithmetic operation, and narrow only at stores. +template inline Real wide(T value) +{ + // [RETIRE-WHEN: native-x87-extended] Binary64 long-double ports still need + // validated extended arithmetic before entering the portable inverse helpers. + if (std::numeric_limits::digits < 64) { + std::fprintf(stderr, "[FRONTIER] bf2x87::wide requires x87 extended precision\n"); + std::fflush(stderr); + std::abort(); + } + return Real(value); +} +inline Real add(Real a, Real b) { volatile Real r = a + b; return r; } +inline Real sub(Real a, Real b) { volatile Real r = a - b; return r; } +inline Real mul(Real a, Real b) { volatile Real r = a * b; return r; } +inline Real div(Real a, Real b) { volatile Real r = a / b; return r; } +inline float store(Real value) { volatile float r = static_cast(value); return r; } +inline double storeDouble(Real value) { volatile double r = static_cast(value); return r; } + +// FCOM/FTST signal invalid for quiet NaNs too; the status is unordered. +inline bool unordered(Real a, Real b) { return isNaN(a) || isNaN(b); } +inline bool ordered(Real a, Real b) { return !unordered(a,b); } +inline void compare(Real a, Real b) { if (unordered(a,b)) std::feraiseexcept(FE_INVALID); } +inline bool less(Real a, Real b) { compare(a,b); return a < b; } +inline bool lessEqual(Real a, Real b) { compare(a,b); return a <= b; } +inline bool greater(Real a, Real b) { compare(a,b); return a > b; } +inline bool greaterEqual(Real a, Real b) { compare(a,b); return a >= b; } +inline bool notLess(Real a, Real b) { return !less(a,b); } +inline bool greaterOrUnordered(Real a, Real b) { return !lessEqual(a,b); } + +// FISTP integer indefinite on masked invalid. Check the rounded result before +// converting; a C++ out-of-range float-to-int cast has undefined behaviour. +// toIntRound follows the active rounding direction (nearest uses ties to even). +// Explicit truncation leaves the caller's rounding mode unchanged. +template inline T integer(Real value, bool truncate = true) +{ + static_assert(std::numeric_limits::is_signed && std::numeric_limits::is_integer, + "signed FIST destination required"); + const Real rounded = truncate ? std::trunc(value) : std::rint(value); + const Real bound = std::ldexp(1.0L, std::numeric_limits::digits); + if (!(rounded >= -bound && rounded < bound)) { + std::feraiseexcept(FE_INVALID); + return std::numeric_limits::min(); + } + return static_cast(rounded); +} +inline std::int32_t toIntTruncate(Real value) { return integer(value); } +inline std::int32_t toIntRound(Real value) { return integer(value, false); } +inline std::int64_t toInt64Truncate(Real value) { return integer(value); } +inline std::int32_t lowWord(std::int64_t value) +{ + const std::uint32_t bits = static_cast(value); + std::int32_t result; + std::memcpy(&result, &bits, sizeof(result)); + return result; +} +// [CHOSEN, not recovered] An unsigned 32-bit cast of a floating value: the PE (_ftol2, a +// 64-bit FISTP) and x86-64 code (64-bit CVTTSD2SI) keep the low 32 bits, so a negative value +// wraps (-1.0 -> 0xFFFFFFFF). arm64 FCVTZU saturates it to 0 instead; use this where a +// negative or out-of-range value can reach the cast. +inline std::uint32_t lowUInt32(Real value) +{ + return static_cast(toInt64Truncate(value)); +} +inline short lowShort(std::int64_t value) +{ + const std::uint16_t bits = static_cast(value); + short result; + std::memcpy(&result, &bits, sizeof(result)); + return result; +} + +} // namespace bf2x87 +#endif diff --git a/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.cpp b/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.cpp new file mode 100644 index 000000000..dd82b9c23 --- /dev/null +++ b/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.cpp @@ -0,0 +1,18 @@ +// ELF FILE symbol attests PortalEvent.cpp; directory placement is [INFERRED]. +#include "PortalEvent.h" + +namespace dice { namespace hfe { namespace world { + +// ELF 0x8325D30. +PortalEventType PortalEvent::getType() const +{ + return m_type; +} + +// ELF 0x8325D60. +unsigned int PortalEvent::getPortalId() const +{ + return m_portalId; +} + +} } } diff --git a/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.h b/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.h new file mode 100644 index 000000000..813c25c7d --- /dev/null +++ b/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalEvent.h @@ -0,0 +1,29 @@ +// Portal transition payload. Header placement beside PortalManager is [INFERRED]. +#ifndef SCENE_OBJECT_WORLDOBJTEMPLPORTAL_PORTALEVENT_H +#define SCENE_OBJECT_WORLDOBJTEMPLPORTAL_PORTALEVENT_H + +#include "PortalManager.h" + +namespace dice { namespace hfe { namespace world { + +class PortalEvent +{ +public: + // Declaration-only construction/destruction; the AI callback only borrows events. + PortalEvent(PortalEventType type, IObject* passingObject, IObject* portalObject, + unsigned int portalId); + virtual ~PortalEvent(); + + PortalEventType getType() const; + unsigned int getPortalId() const; + +private: + // ELF 0x8325C90/0x8325CC0 establish these fields and their ordering. + PortalEventType m_type; // x86 +0x04 + IObject* m_passingObject; // x86 +0x08 + IObject* m_portalObject; // x86 +0x0C + unsigned int m_portalId; // x86 +0x10 +}; + +} } } +#endif diff --git a/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalManager.cpp b/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalManager.cpp index f37fc1d8c..0f017c3d3 100644 --- a/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalManager.cpp +++ b/Code/BF2/Scene/Object/WorldObjTemplPortal/PortalManager.cpp @@ -2,6 +2,8 @@ // Sector transitions remain unimplemented and require the original 0.01 re-test offset. #include "PortalManager.h" +#include +#include #include "../../../Core/Ids.h" // IID_IBase, world::IID_IPortalManager - the two ids // queryInterface compares against, both loaded from globals in @@ -130,12 +132,17 @@ int PortalManager::getDebugLevel() const // [CHOSEN, not recovered] Portal registration, event, and update operations remain // incomplete. Attaching PortalPassing must preserve replacement without deleting the // previous registration data. +// [FRONTIER] Registering a portal-passing object stops here instead of silently dropping the +// object: update() is recovered only for an empty passing-object map. No stock BF2 1.50 object +// template sets isPortalPassing (none of the 9007 files in Objects_server.zip mention portals). void PortalManager::registerPortalPassingObject(IObject* object, const Vec3& portalPassingCoordinate) { (void)object; (void)portalPassingCoordinate; - // [CHOSEN, not recovered] - see above. Does nothing; the real one publishes a PortalPassing - // component onto the object and records it here. + std::fprintf(stderr, "[FRONTIER] dice::hfe::world::PortalManager::registerPortalPassingObject reached" + " (PortalPassing component and passing-object record unrecovered)\n"); + std::fflush(stderr); + std::abort(); } // Removes a portal registration by detaching the component before releasing it, then deletes data and erases the entry. @@ -241,14 +248,19 @@ PortalManager::PortalCollision* PortalManager::checkAddPortalCollision( // against the real one still behaves sanely against this. } -// [CHOSEN, not recovered] portal-transition update; currently performs no work. -// Required behavior uses frame-to-frame position deltas, ignoring deltaTime, with temporary list/vector -// storage per call. Portal event, passing, sector and collider operations remain to be connected. +// ELF 0x8326A70. The body walks the passing-object map (+0x08); with no passing objects it only +// constructs and frees its temporary collision list and vector, so it has no effect (the branch +// at 0x8326AD5 to 0x8327092). deltaTime is not read. The per-object portal crossing, sector and +// event part is unrecovered and stops. void PortalManager::update(float deltaTime) { - (void)deltaTime; // unused in the real body too - see above - // [CHOSEN, not recovered]. Does nothing, so no sector transitions occur and no PortalEvent is - // ever broadcast. This is the single largest behavioural gap in the class. + (void)deltaTime; + if (m_passingObjects.empty()) + return; + std::fprintf(stderr, "[FRONTIER] dice::hfe::world::PortalManager::update reached with portal-passing" + " objects (crossing, sector and event dispatch unrecovered)\n"); + std::fflush(stderr); + std::abort(); } } // namespace world diff --git a/Code/Build/renddx9.cmd b/Code/Build/renddx9.cmd index d7d15cc3d..125b210ca 100644 --- a/Code/Build/renddx9.cmd +++ b/Code/Build/renddx9.cmd @@ -151,6 +151,8 @@ set SOURCES=^ "%BF2%\Math\Mat4Inverse.cpp" ^ "%BF2%\Math\Vec3.cpp" ^ "%BF2%\Math\Frustum.cpp" ^ + "%BF2%\Core\Debug.cpp" ^ + "%BF2%\Core\StringUtil.cpp" ^ "%BF2%\Math\Plane3.cpp" ^ "%BF2%\IO\Tokenizer.cpp" ^ "%BF2%\Geom\ModuleGeom.cpp" ^ From ecffd5f53dd829b904916fd3469cd677dac46593 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Tue, 3 Nov 2026 19:02:06 +0100 Subject: [PATCH 03/71] AI: libaidll reconstruction and engine-side AI interface All 10,961 in-scope libaidll.so functions of BF2 1.50, recovered from the ia-32 ELF with amd-64 and PE cross-checks; evidence vocabulary as in AGENTS.md ([INFERRED], [UNRESOLVED], [PLATFORM], [CHOSEN, not recovered]). Chosen declarations exist only for never-implemented pure slots and null-only member pointers. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: OpenAI Codex --- Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp | 487 + Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h | 77 + Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp | 1407 ++- Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h | 317 +- Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp | 27 +- Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h | 6 +- Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp | 1321 ++- Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h | 195 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp | 1360 ++- Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h | 65 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp | 112 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h | 6 + Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp | 35 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h | 39 +- .../AI/AIDLL/AI/AIBot/CommunicationAgent.cpp | 403 +- .../AI/AIDLL/AI/AIBot/CommunicationAgent.h | 90 +- Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp | 82 + .../AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp | 64 + .../AI/AIDLL/AI/AIBot/RandomSquareMerger.h | 31 + Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp | 58 + Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h | 69 + Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp | 933 +- Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h | 142 +- .../AIDLL/AI/AIBot/SensingAgentPatterns.cpp | 215 +- .../AI/AIDLL/AI/AIBot/SensingAgentPatterns.h | 35 +- .../AI/AIDLL/AI/AIBot/SquadCoordinator.cpp | 1277 ++- Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h | 118 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp | 460 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h | 35 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp | 700 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h | 47 + Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp | 827 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h | 56 +- .../AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp | 82 + .../BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h | 39 + .../AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp | 111 + Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h | 48 + .../AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp | 82 + Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h | 46 + Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp | 95 + Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h | 57 + Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp | 151 + Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h | 42 + Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp | 45 + Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h | 36 + Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp | 203 + Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h | 53 + .../AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp | 178 + .../AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h | 61 + Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp | 82 + Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h | 53 + Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h | 54 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp | 99 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h | 73 + .../AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp | 147 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h | 88 + .../AI/AIBotActionPlan/BAPAAimAtObject.cpp | 205 + .../AI/AIBotActionPlan/BAPAAimAtObject.h | 54 + .../AI/AIBotActionPlan/BAPAAimAtObject3d.cpp | 119 + .../AI/AIBotActionPlan/BAPAAimAtObject3d.h | 45 + .../AI/AIBotActionPlan/BAPAAimAtPoint.cpp | 148 + .../AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h | 53 + .../AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp | 84 + .../AI/AIBotActionPlan/BAPAAimAtPoint3d.h | 39 + .../AI/AIBotActionPlan/BAPAChangeWeapon.cpp | 87 + .../AI/AIBotActionPlan/BAPAChangeWeapon.h | 44 + .../BAPAComponentSoldierPose.cpp | 199 + .../BAPAComponentSoldierPose.h | 64 + .../AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp | 61 + .../AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h | 37 + .../AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp | 47 + .../AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h | 36 + .../AIBotActionPlan/BAPAEvaluateCondition.cpp | 72 + .../AIBotActionPlan/BAPAEvaluateCondition.h | 45 + .../AI/AIBotActionPlan/BAPAForgetTarget.cpp | 50 + .../AI/AIBotActionPlan/BAPAForgetTarget.h | 40 + .../AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp | 52 + .../AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h | 34 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp | 63 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h | 45 + .../AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp | 55 + .../AI/AIDLL/AI/AIBotActionPlan/BAPALook.h | 50 + .../AI/AIBotActionPlan/BAPALookAhead.cpp | 49 + .../AIDLL/AI/AIBotActionPlan/BAPALookAhead.h | 36 + .../AI/AIBotActionPlan/BAPALookAtObject.cpp | 65 + .../AI/AIBotActionPlan/BAPALookAtObject.h | 42 + .../AI/AIBotActionPlan/BAPALookAtPoint.cpp | 48 + .../AI/AIBotActionPlan/BAPALookAtPoint.h | 39 + .../AI/AIBotActionPlan/BAPALookInDir.cpp | 40 + .../AIDLL/AI/AIBotActionPlan/BAPALookInDir.h | 37 + .../BAPAMergeSoldierInputs.cpp | 192 + .../AIBotActionPlan/BAPAMergeSoldierInputs.h | 40 + .../BAPAMoveAwayFrom3dObject.cpp | 92 + .../BAPAMoveAwayFrom3dObject.h | 51 + .../AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp | 356 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h | 83 + .../AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp | 126 + .../AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h | 64 + .../AIBotActionPlan/BAPAMoveTo3dDirection.cpp | 107 + .../AIBotActionPlan/BAPAMoveTo3dDirection.h | 54 + .../AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp | 109 + .../AI/AIBotActionPlan/BAPAMoveTo3dObject.h | 62 + .../AI/AIBotActionPlan/BAPAMoveToDirect.cpp | 62 + .../AI/AIBotActionPlan/BAPAMoveToDirect.h | 40 + .../AIBotActionPlan/BAPAMoveToDirection.cpp | 61 + .../AI/AIBotActionPlan/BAPAMoveToDirection.h | 55 + .../BAPAMoveToDirectionDirect.cpp | 67 + .../BAPAMoveToDirectionDirect.h | 36 + .../BAPAMoveToDirectionFinding.cpp | 74 + .../BAPAMoveToDirectionFinding.h | 37 + .../AI/AIBotActionPlan/BAPAMoveToFinding.cpp | 231 + .../AI/AIBotActionPlan/BAPAMoveToFinding.h | 61 + .../AI/AIBotActionPlan/BAPAMoveToObject.cpp | 111 + .../AI/AIBotActionPlan/BAPAMoveToObject.h | 48 + .../BAPAMoveToObjectDirect.cpp | 52 + .../AIBotActionPlan/BAPAMoveToObjectDirect.h | 36 + .../BAPAMoveToObjectFinding.cpp | 500 + .../AIBotActionPlan/BAPAMoveToObjectFinding.h | 67 + .../AI/AIBotActionPlan/BAPANotifyBot.cpp | 56 + .../AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h | 38 + .../BAPAOverrideSensingAgent.cpp | 49 + .../BAPAOverrideSensingAgent.h | 37 + .../AI/AIBotActionPlan/BAPAPhysicsEnable.cpp | 62 + .../AI/AIBotActionPlan/BAPAPhysicsEnable.h | 34 + .../AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp | 73 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h | 43 + .../AI/AIBotActionPlan/BAPAResetControls.cpp | 104 + .../AI/AIBotActionPlan/BAPAResetControls.h | 53 + .../AIDLL/AI/AIBotActionPlan/BAPARevive.cpp | 73 + .../AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h | 36 + .../AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp | 95 + .../AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h | 54 + .../AI/AIBotActionPlan/BAPARunOverObject.cpp | 138 + .../AI/AIBotActionPlan/BAPARunOverObject.h | 40 + .../AIBotActionPlan/BAPASendRadioMessage.cpp | 57 + .../AI/AIBotActionPlan/BAPASendRadioMessage.h | 41 + .../AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp | 55 + .../AI/AIDLL/AI/AIBotActionPlan/BAPASense.h | 39 + .../BAPASetSensingAgentFocus.cpp | 71 + .../BAPASetSensingAgentFocus.h | 46 + .../AI/AIBotActionPlan/BAPASoldierPose.cpp | 115 + .../AI/AIBotActionPlan/BAPASoldierPose.h | 55 + .../AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp | 108 + .../AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h | 53 + .../BAPATriggerContinously.cpp | 101 + .../AIBotActionPlan/BAPATriggerContinously.h | 51 + .../AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp | 50 + .../AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h | 46 + .../BAPATurnTowardsDirection.cpp | 42 + .../BAPATurnTowardsDirection.h | 34 + .../AIBotActionPlan/BAPATurnTowardsObject.cpp | 61 + .../AIBotActionPlan/BAPATurnTowardsObject.h | 37 + .../AI/AIBotActionPlan/BAPAUpdateVehicle.cpp | 56 + .../AI/AIBotActionPlan/BAPAUpdateVehicle.h | 36 + .../BAPAUseFlareOnMissileLock.cpp | 79 + .../BAPAUseFlareOnMissileLock.h | 43 + .../AI/AIDLL/AI/AIBotActionPlan/BAPAction.h | 37 + .../AI/AIBotActionPlan/BAPActionInline.h | 152 + .../AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h | 40 + .../BAPCConBombPrecision3d.cpp | 91 + .../AIBotActionPlan/BAPCConBombPrecision3d.h | 42 + .../AIBotActionPlan/BAPCConLookDeviation.cpp | 94 + .../AI/AIBotActionPlan/BAPCConLookDeviation.h | 43 + .../AI/AIBotActionPlan/BAPCConPrecision.cpp | 199 + .../AI/AIBotActionPlan/BAPCConPrecision.h | 53 + .../AI/AIBotActionPlan/BAPCConPrecision3d.cpp | 95 + .../AI/AIBotActionPlan/BAPCConPrecision3d.h | 46 + .../AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h | 53 + .../AIBotActionPlan/BAPCombinerParallel.cpp | 168 + .../AI/AIBotActionPlan/BAPCombinerParallel.h | 63 + .../AI/AIBotActionPlan/BAPCombinerSerial.cpp | 152 + .../AI/AIBotActionPlan/BAPCombinerSerial.h | 56 + .../AI/AIBotActionPlan/BAPConAllowFire.cpp | 44 + .../AI/AIBotActionPlan/BAPConAllowFire.h | 36 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp | 77 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h | 40 + .../AIBotActionPlan/BAPConDistanceToProj.cpp | 51 + .../AI/AIBotActionPlan/BAPConDistanceToProj.h | 42 + .../AI/AIBotActionPlan/BAPConEndOfPath.cpp | 31 + .../AI/AIBotActionPlan/BAPConEndOfPath.h | 30 + .../AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp | 34 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h | 35 + .../BAPConInsideBattleZone.cpp | 41 + .../AIBotActionPlan/BAPConInsideBattleZone.h | 37 + .../AI/AIBotActionPlan/BAPConIsSprinting.cpp | 44 + .../AI/AIBotActionPlan/BAPConIsSprinting.h | 36 + .../AI/AIBotActionPlan/BAPConIsTriggered.cpp | 38 + .../AI/AIBotActionPlan/BAPConIsTriggered.h | 35 + .../AI/AIBotActionPlan/BAPConIteration.cpp | 35 + .../AI/AIBotActionPlan/BAPConIteration.h | 36 + .../AI/AIBotActionPlan/BAPConLineOfFire.cpp | 68 + .../AI/AIBotActionPlan/BAPConLineOfFire.h | 39 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp | 72 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h | 42 + .../AIDLL/AI/AIBotActionPlan/BAPConObject.h | 31 + .../AI/AIBotActionPlan/BAPConObjectBehind.cpp | 93 + .../AI/AIBotActionPlan/BAPConObjectBehind.h | 37 + .../AIBotActionPlan/BAPConObjectDistance.cpp | 132 + .../AI/AIBotActionPlan/BAPConObjectDistance.h | 48 + .../BAPConObjectDistanceToPoint.cpp | 91 + .../BAPConObjectDistanceToPoint.h | 42 + .../BAPConObjectEnemyOccupied.cpp | 49 + .../BAPConObjectEnemyOccupied.h | 33 + .../AI/AIBotActionPlan/BAPConObjectExists.cpp | 39 + .../AI/AIBotActionPlan/BAPConObjectExists.h | 33 + .../AI/AIBotActionPlan/BAPConObjectHealth.cpp | 57 + .../AI/AIBotActionPlan/BAPConObjectHealth.h | 41 + .../AIBotActionPlan/BAPConObjectInFront.cpp | 59 + .../AI/AIBotActionPlan/BAPConObjectInFront.h | 38 + .../BAPConObjectInLandingZone.cpp | 46 + .../BAPConObjectInLandingZone.h | 31 + .../BAPConObjectInsideFrustum.cpp | 65 + .../BAPConObjectInsideFrustum.h | 37 + .../BAPConObjectLineOfFire.cpp | 164 + .../AIBotActionPlan/BAPConObjectLineOfFire.h | 45 + .../AIBotActionPlan/BAPConObjectManDown.cpp | 43 + .../AI/AIBotActionPlan/BAPConObjectManDown.h | 31 + .../AI/AIBotActionPlan/BAPConObjectMoved.cpp | 48 + .../AI/AIBotActionPlan/BAPConObjectMoved.h | 42 + .../AIBotActionPlan/BAPConObjectOccupied.cpp | 45 + .../AI/AIBotActionPlan/BAPConObjectOccupied.h | 33 + .../AI/AIBotActionPlan/BAPConObjectSpeed.cpp | 47 + .../AI/AIBotActionPlan/BAPConObjectSpeed.h | 33 + .../BAPConObjectTouchingLand.cpp | 47 + .../BAPConObjectTouchingLand.h | 31 + .../BAPConObjectValidAiming.cpp | 152 + .../AIBotActionPlan/BAPConObjectValidAiming.h | 47 + .../BAPConObjectValidPitchAiming.cpp | 58 + .../BAPConObjectValidPitchAiming.h | 37 + .../BAPConObjectValidPosition.cpp | 57 + .../BAPConObjectValidPosition.h | 35 + .../BAPConObjectValidYawAiming.cpp | 58 + .../BAPConObjectValidYawAiming.h | 37 + .../AIBotActionPlan/BAPConObjectVisible.cpp | 48 + .../AI/AIBotActionPlan/BAPConObjectVisible.h | 33 + .../BAPConOkToThrowGrenade.cpp | 135 + .../AIBotActionPlan/BAPConOkToThrowGrenade.h | 43 + .../AI/AIBotActionPlan/BAPConOpLessThan.h | 62 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp | 77 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h | 40 + .../AI/AIBotActionPlan/BAPConPointAt.cpp | 51 + .../AIDLL/AI/AIBotActionPlan/BAPConPointAt.h | 36 + .../AIBotActionPlan/BAPConPointDistance.cpp | 86 + .../AI/AIBotActionPlan/BAPConPointDistance.h | 48 + .../AI/AIBotActionPlan/BAPConPointInFront.cpp | 56 + .../AI/AIBotActionPlan/BAPConPointInFront.h | 39 + .../AI/AIBotActionPlan/BAPConPosition.cpp | 69 + .../AIDLL/AI/AIBotActionPlan/BAPConPosition.h | 44 + .../AIBotActionPlan/BAPConSharedCondition.cpp | 74 + .../AIBotActionPlan/BAPConSharedCondition.h | 52 + .../AI/AIBotActionPlan/BAPConSplashDamage.cpp | 115 + .../AI/AIBotActionPlan/BAPConSplashDamage.h | 44 + .../BAPConStrategicObjectStatus.cpp | 49 + .../BAPConStrategicObjectStatus.h | 42 + .../AIDLL/AI/AIBotActionPlan/BAPConTime.cpp | 53 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h | 43 + .../AI/AIBotActionPlan/BAPConTotalAmmo.cpp | 63 + .../AI/AIBotActionPlan/BAPConTotalAmmo.h | 34 + .../BAPConTriggerableActive.cpp | 39 + .../AIBotActionPlan/BAPConTriggerableActive.h | 34 + .../AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp | 34 + .../AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h | 35 + .../AIDLL/AI/AIBotActionPlan/BAPConWeapon.h | 34 + .../BAPConWeaponDetonatorIsActive.cpp | 51 + .../BAPConWeaponDetonatorIsActive.h | 38 + .../BAPConWeaponHasLockOnTarget.cpp | 51 + .../BAPConWeaponHasLockOnTarget.h | 41 + .../AI/AIBotActionPlan/BAPConWeaponHeat.cpp | 62 + .../AI/AIBotActionPlan/BAPConWeaponHeat.h | 45 + .../AIBotActionPlan/BAPConWeaponIsActive.cpp | 50 + .../AI/AIBotActionPlan/BAPConWeaponIsActive.h | 33 + .../AIBotActionPlan/BAPConWeaponIsZoomed.cpp | 51 + .../AI/AIBotActionPlan/BAPConWeaponIsZoomed.h | 36 + .../AIBotActionPlan/BAPConWeaponMagAmmo.cpp | 61 + .../AI/AIBotActionPlan/BAPConWeaponMagAmmo.h | 42 + .../BAPConWeaponReadyToFire.cpp | 52 + .../AIBotActionPlan/BAPConWeaponReadyToFire.h | 38 + .../BAPConWeaponTargetReachable.cpp | 98 + .../BAPConWeaponTargetReachable.h | 39 + .../AIBotActionPlan/BAPConWeaponTotalAmmo.cpp | 40 + .../AIBotActionPlan/BAPConWeaponTotalAmmo.h | 36 + .../AIDLL/AI/AIBotActionPlan/BAPCondition.cpp | 38 + .../AIDLL/AI/AIBotActionPlan/BAPCondition.h | 52 + .../AIBotActionPlan/BAPConnectedCondition.h | 29 + .../AIDLL/AI/AIBotActionPlan/BAPExpression.h | 31 + .../AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp | 96 + .../AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h | 46 + .../AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp | 196 + .../AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h | 63 + .../AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp | 55 + .../AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h | 39 + .../AI/AIBotActionPlan/BAPFlowCWhile.cpp | 155 + .../AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h | 55 + .../AIDLL/AI/AIBotActionPlan/BAPFlowControl.h | 29 + .../AI/AIBotActionPlan/BAPICChangeVehicle.cpp | 48 + .../AI/AIBotActionPlan/BAPICChangeVehicle.h | 37 + .../AI/AIBotActionPlan/BAPICTurnLock.cpp | 48 + .../AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h | 40 + .../AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp | 92 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h | 38 + .../AI/AIBotActionPlan/BAPIWDefuseMines.cpp | 39 + .../AI/AIBotActionPlan/BAPIWDefuseMines.h | 35 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp | 67 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h | 59 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp | 44 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h | 40 + .../AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp | 35 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h | 42 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp | 31 + .../AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h | 33 + .../AI/AIBotActionPlan/BAPIWTakeCover.cpp | 47 + .../AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h | 40 + .../AI/AIBotActionPlan/BAPInfoWrapper.cpp | 85 + .../AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h | 51 + .../AI/AIBotActionPlan/BAPInterruptControl.h | 29 + .../AIDLL/AI/AIBotActionPlan/BAPStatement.cpp | 47 + .../AIDLL/AI/AIBotActionPlan/BAPStatement.h | 77 + .../AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h | 144 + .../AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h | 35 + .../AI/AIBotActionPlan/BAPWrapperAiming.cpp | 251 + .../AI/AIBotActionPlan/BAPWrapperAiming.h | 52 + .../AI/AIBotActionPlan/BAPWrapperFinished.cpp | 71 + .../AI/AIBotActionPlan/BAPWrapperFinished.h | 38 + .../AI/AIBotActionPlan/BAPWrapperLookAt.cpp | 156 + .../AI/AIBotActionPlan/BAPWrapperLookAt.h | 48 + .../AI/AIBotActionPlan/BAPWrapperWeapon.cpp | 66 + .../AI/AIBotActionPlan/BAPWrapperWeapon.h | 42 + .../AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp | 407 + Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h | 43 + .../AI/AIBotBehaviour/BBBridgeRepair.cpp | 342 + .../AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h | 53 + Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp | 156 + Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h | 38 + .../AI/AIBotBehaviour/BBCallForMedic.cpp | 147 + .../AIDLL/AI/AIBotBehaviour/BBCallForMedic.h | 31 + .../AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp | 901 ++ .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h | 63 + .../AIBotBehaviour/BBChangeLandingCraft.cpp | 291 + .../AI/AIBotBehaviour/BBChangeLandingCraft.h | 35 + .../AI/AIBotBehaviour/BBChangeTeleport.cpp | 218 + .../AI/AIBotBehaviour/BBChangeTeleport.h | 31 + .../AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp | 260 + .../AIDLL/AI/AIBotBehaviour/BBDefuseMines.h | 47 + .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp | 1039 ++ Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h | 58 + .../AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp | 539 + .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h | 56 + .../AIBotBehaviour/BBFireArtilleryDriver.cpp | 80 + .../AI/AIBotBehaviour/BBFireArtilleryDriver.h | 38 + .../AI/AIBotBehaviour/BBFireInfantery.cpp | 36 + .../AIDLL/AI/AIBotBehaviour/BBFireInfantery.h | 38 + .../AI/AIBotBehaviour/BBFireLargeBore.cpp | 672 ++ .../AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h | 51 + .../AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp | 300 + .../AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h | 39 + .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp | 339 + Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h | 45 + .../AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp | 739 ++ .../AIDLL/AI/AIBotBehaviour/BBMedicAssist.h | 58 + .../AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp | 126 + .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h | 33 + .../AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp | 99 + .../AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h | 36 + .../AIDLL/AI/AIBotBehaviour/BBPendingCalls.h | 68 + .../AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp | 191 + .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h | 48 + .../AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp | 302 + .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h | 50 + .../AI/AIBotBehaviour/BBRunOverSoldier.cpp | 157 + .../AI/AIBotBehaviour/BBRunOverSoldier.h | 38 + .../AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp | 57 + .../AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h | 31 + .../AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp | 387 + .../AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h | 38 + .../AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp | 81 + .../AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h | 31 + .../AI/AIBotBehaviour/BBTakeCoverInfantry.cpp | 543 + .../AI/AIBotBehaviour/BBTakeCoverInfantry.h | 47 + .../AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp | 121 + .../AIDLL/AI/AIBotBehaviour/BBTriggerable.h | 50 + .../AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp | 177 + .../AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h | 85 + .../AIDLL/AI/AIBotBehaviour/CustomCurve.cpp | 160 + .../AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h | 42 + .../AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp | 4 + .../AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp | 93 +- .../AIDLL/AI/AIBotBehaviour/UrgencyMerger.h | 17 +- .../VehicleUrgencyCalculator.cpp | 680 ++ .../AIBotBehaviour/VehicleUrgencyCalculator.h | 28 + .../BBPAvoidCollision.cpp | 46 + .../AIBotBehaviourPattern/BBPAvoidCollision.h | 43 + .../BBPAvoidCollision2d.cpp | 192 + .../BBPAvoidCollision2d.h | 36 + .../BBPAvoidCollision3d.cpp | 183 + .../BBPAvoidCollision3d.h | 39 + .../BBPAvoidCollisionInfantery.cpp | 264 + .../BBPAvoidCollisionInfantery.h | 41 + .../AIBotBehaviourPattern/BBPBridgeRepair.cpp | 225 + .../AIBotBehaviourPattern/BBPBridgeRepair.h | 45 + .../AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp | 171 + .../AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h | 43 + .../AIBotBehaviourPattern/BBPCallForMedic.cpp | 74 + .../AIBotBehaviourPattern/BBPCallForMedic.h | 35 + .../AI/AIBotBehaviourPattern/BBPChange.cpp | 539 + .../AI/AIBotBehaviourPattern/BBPChange.h | 49 + .../BBPChangeLandingCraft.cpp | 133 + .../BBPChangeLandingCraft.h | 38 + .../BBPChangeTeleport.cpp | 125 + .../AIBotBehaviourPattern/BBPChangeTeleport.h | 36 + .../AIBotBehaviourPattern/BBPDefuseMines.cpp | 205 + .../AI/AIBotBehaviourPattern/BBPDefuseMines.h | 43 + .../AI/AIBotBehaviourPattern/BBPFire.cpp | 68 + .../AIDLL/AI/AIBotBehaviourPattern/BBPFire.h | 55 + .../AI/AIBotBehaviourPattern/BBPFire2d.cpp | 464 + .../AI/AIBotBehaviourPattern/BBPFire2d.h | 38 + .../AIBotBehaviourPattern/BBPFire2dDriver.cpp | 464 + .../AIBotBehaviourPattern/BBPFire2dDriver.h | 42 + .../AI/AIBotBehaviourPattern/BBPFire3d.cpp | 532 + .../AI/AIBotBehaviourPattern/BBPFire3d.h | 58 + .../BBPFireInfantery.cpp | 2161 ++++ .../AIBotBehaviourPattern/BBPFireInfantery.h | 120 + .../AIBotBehaviourPattern/BBPGotoWaypoint.h | 33 + .../BBPGotoWaypoints2d.cpp | 320 + .../BBPGotoWaypoints2d.h | 38 + .../BBPGotoWaypoints3d.cpp | 179 + .../BBPGotoWaypoints3d.h | 35 + .../BBPGotoWaypointsBoat.cpp | 287 + .../BBPGotoWaypointsBoat.h | 36 + .../BBPGotoWaypointsInfantery.cpp | 261 + .../BBPGotoWaypointsInfantery.h | 46 + .../AIBotBehaviourPattern/BBPHeliFire3d.cpp | 427 + .../AI/AIBotBehaviourPattern/BBPHeliFire3d.h | 62 + .../AI/AIBotBehaviourPattern/BBPIdle.cpp | 82 + .../AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h | 39 + .../AI/AIBotBehaviourPattern/BBPIdle2d.cpp | 183 + .../AI/AIBotBehaviourPattern/BBPIdle2d.h | 38 + .../AI/AIBotBehaviourPattern/BBPIdle3d.cpp | 237 + .../AI/AIBotBehaviourPattern/BBPIdle3d.h | 39 + .../BBPIdleInfantery.cpp | 158 + .../AIBotBehaviourPattern/BBPIdleInfantery.h | 35 + .../AIBotBehaviourPattern/BBPMedicAssist.cpp | 498 + .../AI/AIBotBehaviourPattern/BBPMedicAssist.h | 45 + .../AI/AIBotBehaviourPattern/BBPPattern.cpp | 53 + .../AI/AIBotBehaviourPattern/BBPPattern.h | 41 + .../AI/AIBotBehaviourPattern/BBPRandom.cpp | 143 + .../AI/AIBotBehaviourPattern/BBPRandom.h | 38 + .../AI/AIBotBehaviourPattern/BBPRevive.cpp | 215 + .../AI/AIBotBehaviourPattern/BBPRevive.h | 42 + .../AI/AIBotBehaviourPattern/BBPRoam.cpp | 39 + .../AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h | 34 + .../AI/AIBotBehaviourPattern/BBPRoam2d.cpp | 80 + .../AI/AIBotBehaviourPattern/BBPRoam2d.h | 34 + .../AI/AIBotBehaviourPattern/BBPRoam3d.cpp | 110 + .../AI/AIBotBehaviourPattern/BBPRoam3d.h | 36 + .../BBPRunOverSoldier.cpp | 107 + .../AIBotBehaviourPattern/BBPRunOverSoldier.h | 37 + .../AI/AIBotBehaviourPattern/BBPSuicide.cpp | 82 + .../AI/AIBotBehaviourPattern/BBPSuicide.h | 36 + .../AI/AIBotBehaviourPattern/BBPTakeCover.cpp | 252 + .../AI/AIBotBehaviourPattern/BBPTakeCover.h | 43 + .../AIBotBehaviourPattern/BBPTakeCover3d.cpp | 116 + .../AI/AIBotBehaviourPattern/BBPTakeCover3d.h | 38 + .../BBPTakeCoverInfantry.cpp | 392 + .../BBPTakeCoverInfantry.h | 43 + .../AIBotBehaviourPattern/BBPTriggerable.cpp | 127 + .../AI/AIBotBehaviourPattern/BBPTriggerable.h | 43 + .../AI/AIBotBehaviourPattern/PlanGenerator.h | 37 + .../AI/AIBotBehaviourPattern/WeaponChoice.cpp | 105 + .../AI/AIBotBehaviourPattern/WeaponChoice.h | 39 + .../AI/AIKnowledge/AIInformationGrid.cpp | 4 + .../AI/AIKnowledge/BFInformationCourier.cpp | 4 + .../AIKnowledge/BFInformationEnvironment.cpp | 264 +- .../AI/AIKnowledge/BFInformationEnvironment.h | 11 +- .../AI/AIDLL/AI/AIKnowledge/DangerObject.cpp | 4 + .../AI/AIDLL/AI/AIKnowledge/DangerObject.h | 95 + .../AI/AIDLL/AI/AIKnowledge/FireObject.cpp | 98 + Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h | 50 + .../AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp | 4 + .../AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp | 64 + .../AIDLL/AI/AIKnowledge/IPIArmamentDummy.h | 46 + .../AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp | 84 + .../AIDLL/AI/AIKnowledge/IPIArmamentKnown.h | 40 + .../AIDLL/AI/AIKnowledge/IPIControlInfo.cpp | 333 + .../AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h | 66 +- Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp | 4 + .../BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp | 4 + Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h | 5 + .../AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp | 81 + .../AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h | 54 + .../AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp | 5 + .../AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp | 5 + .../BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h | 4 +- .../AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp | 93 + .../AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h | 86 + .../AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp | 187 + .../AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h | 60 + .../AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp | 9 +- .../AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h | 2 +- Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp | 4 + .../AI/AIDLL/AI/AIKnowledge/Information.cpp | 4 + .../BF2/AI/AIDLL/AI/AIKnowledge/Information.h | 7 + .../AIDLL/AI/AIKnowledge/InformationDummy.cpp | 136 + .../AIDLL/AI/AIKnowledge/InformationDummy.h | 77 + .../AI/AIKnowledge/InformationFactory.cpp | 33 +- .../AIDLL/AI/AIKnowledge/InformationKnown.cpp | 367 + .../AIDLL/AI/AIKnowledge/InformationKnown.h | 66 + .../AIDLL/AI/AIKnowledge/InformationReal.cpp | 4 + .../AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp | 4 + Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h | 6 + .../AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp | 116 + .../AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h | 46 + .../AI/AIPathFinding/Cluster/Cluster.cpp | 39 + .../AIDLL/AI/AIPathFinding/Cluster/Cluster.h | 18 +- .../AI/AIPathFinding/Cluster/ClusterGraph.cpp | 1238 ++- .../AI/AIPathFinding/Cluster/ClusterGraph.h | 95 +- .../AI/AIPathFinding/Cluster/ClusterNode.cpp | 67 + .../Cluster/ClusterNodeManager.cpp | 465 +- .../Cluster/ClusterNodeManager.h | 117 +- .../AIPathFinding/Cluster/ClusterNodePath.cpp | 66 + .../AI/AIPathFinding/Material/Material.cpp | 9 +- .../Material/MaterialManager.cpp | 14 +- .../NavMesh/GTSDataOptimiser.cpp | 1167 ++ .../AIPathFinding/NavMesh/GTSDataOptimiser.h | 81 + .../AIPathFinding/NavMesh/MapProperties.cpp | 17 +- .../NavMesh/MeshImporterExporter.cpp | 59 + .../NavMesh/MeshImporterExporter.h | 26 + .../AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp | 30 + .../AI/AIPathFinding/NavMesh/QTSearchNode.cpp | 71 + .../NavMesh/QTSearchNodeManager.cpp | 533 +- .../NavMesh/QTSearchNodeManager.h | 120 +- .../AI/AIPathFinding/NavMesh/QuadTree.cpp | 1037 +- .../AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h | 96 +- .../AIPathFinding/NavMesh/QuadTreeManager.cpp | 683 +- .../AIPathFinding/NavMesh/QuadTreeManager.h | 36 +- .../AI/AIPathFinding/NavMesh/QuadTreeNode.cpp | 230 +- .../AI/AIPathFinding/NavMesh/QuadTreeNode.h | 22 +- .../AIDLL/AI/AIPlanInterpreter/BAPContext.h | 6 + .../AI/AIPlanInterpreter/BAPDebugger.cpp | 159 + .../AIDLL/AI/AIPlanInterpreter/BAPDebugger.h | 58 + .../AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp | 826 -- .../AIDLL/AI/AIPlanInterpreter/BAPEntries.h | 526 +- .../AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h | 2 +- .../AI/AIPlanInterpreter/BAPInterpreter.cpp | 165 + .../AI/AIPlanInterpreter/BAPInterpreter.h | 52 + .../AI/AIPlanInterpreter/BoatControl.cpp | 205 + .../AIDLL/AI/AIPlanInterpreter/BoatControl.h | 30 + .../AI/AIDLL/AI/AIPlanInterpreter/BotScript.h | 47 + .../AIPlanInterpreter/BotScriptDebugger.cpp | 22 + .../AI/AIPlanInterpreter/BotScriptDebugger.h | 36 + .../AIDLL/AI/AIPlanInterpreter/CarControl.cpp | 835 ++ .../AIDLL/AI/AIPlanInterpreter/CarControl.h | 37 + .../AI/AIPlanInterpreter/CommonControls.cpp | 477 + .../AI/AIPlanInterpreter/CommonControls.h | 38 + .../AI/AIPlanInterpreter/ControlFunctions.cpp | 622 ++ .../AI/AIPlanInterpreter/ControlFunctions.h | 47 + .../AI/AIPlanInterpreter/EntryBoatMoveTo.cpp | 101 + .../AI/AIPlanInterpreter/EntryBoatMoveTo.h | 27 + .../EntryBoatMoveToDirection.cpp | 129 + .../EntryBoatMoveToDirection.h | 27 + .../EntryBoatMoveToObject.cpp | 108 + .../AIPlanInterpreter/EntryBoatMoveToObject.h | 27 + .../EntryBoatResetControls.cpp | 56 + .../EntryBoatResetControls.h | 28 + .../AI/AIPlanInterpreter/EntryCarMoveTo.cpp | 199 + .../AI/AIPlanInterpreter/EntryCarMoveTo.h | 28 + .../EntryCarMoveToDirection.cpp | 36 + .../EntryCarMoveToDirection.h | 28 + .../EntryCarMoveToObject.cpp | 180 + .../AIPlanInterpreter/EntryCarMoveToObject.h | 28 + .../EntryCarResetControls.cpp | 67 + .../AIPlanInterpreter/EntryCarResetControls.h | 28 + .../AI/AIPlanInterpreter/EntryHeliAimAt.cpp | 201 + .../AI/AIPlanInterpreter/EntryHeliAimAt.h | 27 + .../EntryHeliMoveAwayFromObject.cpp | 82 + .../EntryHeliMoveAwayFromObject.h | 27 + .../AI/AIPlanInterpreter/EntryHeliMoveTo.cpp | 77 + .../AI/AIPlanInterpreter/EntryHeliMoveTo.h | 27 + .../EntryHeliMoveToDirection.cpp | 83 + .../EntryHeliMoveToDirection.h | 27 + .../EntryHeliMoveToObject.cpp | 78 + .../AIPlanInterpreter/EntryHeliMoveToObject.h | 27 + .../EntryHeliResetControls.cpp | 60 + .../EntryHeliResetControls.h | 28 + .../EntryInfanteryMoveTo.cpp | 103 + .../AIPlanInterpreter/EntryInfanteryMoveTo.h | 28 + .../EntryInfanteryMoveToDirection.cpp | 36 + .../EntryInfanteryMoveToDirection.h | 28 + .../EntryInfanteryMoveToObject.cpp | 129 + .../EntryInfanteryMoveToObject.h | 28 + .../EntryInfanteryResetControls.cpp | 57 + .../EntryInfanteryResetControls.h | 28 + .../AI/AIPlanInterpreter/EntryInfoWrapper.cpp | 41 + .../AI/AIPlanInterpreter/EntryInfoWrapper.h | 28 + .../AIPlanInterpreter/EntryKeyTurretAimAt.cpp | 147 + .../AIPlanInterpreter/EntryKeyTurretAimAt.h | 27 + .../EntryMouseTurretAimAt.cpp | 144 + .../AIPlanInterpreter/EntryMouseTurretAimAt.h | 28 + .../EntryMouseTurretLookAt.cpp | 97 + .../EntryMouseTurretLookAt.h | 28 + .../AIPlanInterpreter/EntryMoveToMedium.cpp | 207 + .../AI/AIPlanInterpreter/EntryMoveToMedium.h | 27 + .../EntryMoveToMediumBoat.cpp | 236 + .../AIPlanInterpreter/EntryMoveToMediumBoat.h | 27 + .../EntryMoveToMediumSoldier.cpp | 193 + .../EntryMoveToMediumSoldier.h | 28 + .../EntryMoveToObjectMedium.cpp | 201 + .../EntryMoveToObjectMedium.h | 27 + .../EntryMoveToObjectMediumBoat.cpp | 209 + .../EntryMoveToObjectMediumBoat.h | 27 + .../EntryMoveToObjectMediumSoldier.cpp | 189 + .../EntryMoveToObjectMediumSoldier.h | 28 + .../AI/AIPlanInterpreter/EntryPlaneAimAt.cpp | 234 + .../AI/AIPlanInterpreter/EntryPlaneAimAt.h | 27 + .../AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp | 73 + .../AI/AIPlanInterpreter/EntryPlaneMoveTo.h | 27 + .../EntryPlaneMoveToDirection.cpp | 226 + .../EntryPlaneMoveToDirection.h | 27 + .../EntryPlaneMoveToObject.cpp | 112 + .../EntryPlaneMoveToObject.h | 27 + .../EntryPlaneResetControls.cpp | 59 + .../EntryPlaneResetControls.h | 28 + .../AI/AIPlanInterpreter/EntryPlaneRoll.cpp | 87 + .../AI/AIPlanInterpreter/EntryPlaneRoll.h | 31 + .../AIDLL/AI/AIPlanInterpreter/EntrySense.cpp | 61 + .../AIDLL/AI/AIPlanInterpreter/EntrySense.h | 27 + .../AI/AIPlanInterpreter/EntrySoldierPose.cpp | 65 + .../AI/AIPlanInterpreter/EntrySoldierPose.h | 28 + .../AI/AIPlanInterpreter/EntryTankMoveTo.cpp | 175 + .../AI/AIPlanInterpreter/EntryTankMoveTo.h | 28 + .../EntryTankMoveToDirection.cpp | 143 + .../EntryTankMoveToDirection.h | 27 + .../EntryTankMoveToObject.cpp | 172 + .../AIPlanInterpreter/EntryTankMoveToObject.h | 28 + .../EntryTankResetControls.cpp | 64 + .../EntryTankResetControls.h | 28 + .../AI/AIPlanInterpreter/EntryTankTurnTo.cpp | 183 + .../AI/AIPlanInterpreter/EntryTankTurnTo.h | 30 + .../AI/AIPlanInterpreter/EntryTrigger.cpp | 226 + .../AIDLL/AI/AIPlanInterpreter/EntryTrigger.h | 28 + .../EntryTriggerContinously.cpp | 180 + .../EntryTriggerContinously.h | 28 + .../AIPlanInterpreter/EntryTurnToMedium.cpp | 165 + .../AI/AIPlanInterpreter/EntryTurnToMedium.h | 31 + .../AI/AIPlanInterpreter/HeliControl.cpp | 578 + .../AIDLL/AI/AIPlanInterpreter/HeliControl.h | 38 + .../AI/AIPlanInterpreter/InfanteryControl.cpp | 495 + .../AI/AIPlanInterpreter/InfanteryControl.h | 67 + .../AI/AIPlanInterpreter/MouseControl.cpp | 195 + .../AIDLL/AI/AIPlanInterpreter/MouseControl.h | 32 + .../AI/AIPlanInterpreter/PlanInterpreter.h | 35 + .../AI/AIPlanInterpreter/PlaneControl.cpp | 451 + .../AIDLL/AI/AIPlanInterpreter/PlaneControl.h | 34 + .../AI/AIPlanInterpreter/PrettyPrinter.cpp | 307 + .../AI/AIPlanInterpreter/PrettyPrinter.h | 73 + .../AI/AIPlanInterpreter/TankControl.cpp | 869 ++ .../AIDLL/AI/AIPlanInterpreter/TankControl.h | 38 + .../AIPlanInterpreter/VehicleControlInline.h | 121 + Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp | 1687 ++- Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h | 120 +- Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp | 57 + Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h | 35 + .../AI/AIDLL/AI/AIStrategic/SCConstant.cpp | 34 + Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h | 31 + .../AIDLL/AI/AIStrategic/SCHeterogeneous.cpp | 52 + .../AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h | 30 + .../AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp | 50 + .../AI/AIDLL/AI/AIStrategic/SCHomogeneous.h | 28 + Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h | 21 +- Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp | 274 + Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h | 96 + .../AI/AIStrategic/StrategyCondition.cpp | 158 + .../AIDLL/AI/AIStrategic/StrategyCondition.h | 116 + .../AI/AIStrategic/StrategyPrerequisite.cpp | 84 + .../AI/AIStrategic/StrategyPrerequisite.h | 38 + .../AI/AIStrategicEntity/AILandingZone.cpp | 242 + .../AI/AIStrategicEntity/AILandingZone.h | 81 + .../AILandingZoneManager.cpp | 162 +- .../AIStrategicEntity/AILandingZoneManager.h | 50 +- .../AI/AIStrategicEntity/AIStrategicArea.cpp | 1375 ++- .../AI/AIStrategicEntity/AIStrategicArea.h | 130 +- .../AIStrategicEntity/AIStrategicObject.cpp | 398 +- .../AI/AIStrategicEntity/AIStrategicObject.h | 100 +- .../AIStrategicObjectManager.cpp | 945 +- .../AIStrategicObjectManager.h | 68 +- .../AI/AIStrategicEntity/AreaAssignment.cpp | 409 + .../AI/AIStrategicEntity/AreaAssignment.h | 97 + .../AI/AIStrategicEntity/AreaDistanceInfo.cpp | 35 + .../AI/AIStrategicEntity/AreaDistanceInfo.h | 31 + .../CoverPosition/CPNode.cpp | 122 + .../AIStrategicEntity/CoverPosition/CPNode.h | 129 + .../CoverPosition/CPNodeManager.cpp | 39 +- .../CoverPosition/CPNodeManager.h | 63 +- .../CoverPosition/CoverPosition.cpp | 352 + .../CoverPosition/CoverPosition.h | 108 + .../CoverPosition/CoverPositionManager.cpp | 310 +- .../CoverPosition/CoverPositionManager.h | 64 +- .../AI/AIStrategicEntity/GuardPosition.cpp | 210 + .../AI/AIStrategicEntity/GuardPosition.h | 49 +- .../AIStrategicEntity/GuardPositionBotDCB.cpp | 32 + .../AIStrategicEntity/GuardPositionBotDCB.h | 27 + .../AIStrategicEntity/GuardPositionBotSCB.cpp | 32 + .../AIStrategicEntity/GuardPositionBotSCB.h | 27 + .../AIDLL/AI/AIStrategicEntity/PatrolPath.cpp | 209 + .../AIDLL/AI/AIStrategicEntity/PatrolPath.h | 49 +- .../AI/AIStrategicEntity/PatrolPathBotDCB.cpp | 32 + .../AI/AIStrategicEntity/PatrolPathBotDCB.h | 28 + .../AI/AIStrategicEntity/PatrolPathBotSCB.cpp | 32 + .../AI/AIStrategicEntity/PatrolPathBotSCB.h | 28 + .../AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp | 46 +- .../AIDLL/AI/AIStrategicEntity/SAWayPoint.h | 8 +- .../AI/AIDLL/AI/AIStrategicMap/AICamera.cpp | 28 + .../BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h | 28 + .../AI/AIStrategicMap/AerialHeightMap.cpp | 79 +- .../AIDLL/AI/AIStrategicMap/AerialHeightMap.h | 4 +- .../AIStrategicMap/BFStrategicEnvironment.cpp | 78 +- .../AIStrategicMap/BFStrategicEnvironment.h | 49 +- .../AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp | 179 +- .../AI/AIDLL/AI/AIStrategicMap/BotSpawner.h | 16 + .../BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp | 377 + Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h | 99 + .../AI/AIStrategicMap/SAIMapRenderUtil.cpp | 34 + .../AI/AIStrategicMap/SAIMapRenderUtil.h | 31 + .../AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp | 26 + .../AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h | 28 + .../AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp | 203 + .../AI/AIDLL/AI/AIStrategicMap/ScalarMap.h | 37 + .../AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp | 39 + .../AI/AIStrategicMap/TemperatureTree.cpp | 107 + .../AIDLL/AI/AIStrategicMap/TemperatureTree.h | 44 + .../TemperatureTreeModifiers.cpp | 26 + .../AIStrategicMap/TemperatureTreeModifiers.h | 28 + Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp | 103 + Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h | 38 + Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp | 75 + Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h | 34 + .../AIUtils/DebugRendering/AIRenderUtil.cpp | 542 +- .../AI/AIUtils/DebugRendering/AIRenderUtil.h | 40 +- .../DebugRendering/DPAIObject3dText.cpp | 96 + .../DebugRendering/DPAIObjectCircle.cpp | 96 + .../AIUtils/DebugRendering/DPAIObjectLine.cpp | 140 + .../DebugRendering/DPDynamic3dText.cpp | 118 + .../DebugRendering/DPDynamicCircle.cpp | 106 + .../AIUtils/DebugRendering/DPDynamicLine.cpp | 161 + .../DebugRendering/DPDynamicPrimitives.h | 160 + .../AI/AIUtils/DebugRendering/DPGraph.cpp | 84 + .../AIDLL/AI/AIUtils/DebugRendering/DPGraph.h | 45 + .../AI/AIUtils/DebugRendering/IBFGraph.h | 37 + Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp | 32 + Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h | 35 + .../AIDLL/AI/AIUtils/IgnoreListPredicate.cpp | 33 + .../AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h | 31 + Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp | 153 + Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h | 63 + Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp | 43 + Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h | 29 + .../AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp | 99 + .../AI/AIDLL/AI/AIUtils/VehicleOccupancy.h | 6 + .../AI/AIDLL/AI/DrawPrimitives/DPManager.cpp | 719 +- .../AI/AIDLL/AI/DrawPrimitives/DPManager.h | 135 +- .../AI/DrawPrimitives/DPStatic2dText.cpp | 84 + .../AIDLL/AI/DrawPrimitives/DPStatic2dText.h | 53 + .../AI/DrawPrimitives/DPStatic3dText.cpp | 84 + .../AIDLL/AI/DrawPrimitives/DPStatic3dText.h | 53 + .../AIDLL/AI/DrawPrimitives/DPStaticCircle.h | 45 + .../AI/DrawPrimitives/DPStaticCirlce.cpp | 68 + .../AIDLL/AI/DrawPrimitives/DPStaticLine.cpp | 74 + .../AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h | 42 + .../AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp | 82 + .../AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h | 45 + .../AI/DrawPrimitives/DPStaticPolygon.cpp | 68 + .../AIDLL/AI/DrawPrimitives/DPStaticPolygon.h | 43 + .../AI/DrawPrimitives/DPStaticTriangle.cpp | 64 + .../AI/DrawPrimitives/DPStaticTriangle.h | 45 + .../AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp | 41 + .../AIDLL/AI/DrawPrimitives/DrawPrimitive.h | 40 + .../AI/AIDLL/AI/Main/AICollisionHandler.cpp | 335 +- .../BF2/AI/AIDLL/AI/Main/AICollisionHandler.h | 11 +- Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp | 894 +- Code/BF2/AI/AIDLL/AI/Main/AIConsole.h | 37 +- Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp | 344 +- Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h | 99 +- Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp | 237 +- Code/BF2/AI/AIDLL/AI/Main/AILODManager.h | 50 +- Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp | 427 +- Code/BF2/AI/AIDLL/AI/Main/AIMain.h | 53 +- Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp | 64 +- Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h | 15 +- Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp | 168 +- Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc | 9595 +++++++++++++++++ Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp | 1690 ++- Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h | 78 +- .../AIDLL/AI/Main/AIPathfindingSearchTypes.h | 977 +- Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp | 57 +- Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h | 18 +- Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp | 77 + Code/BF2/AI/AIDLL/AI/Main/AIRadio.h | 46 + Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp | 3 + Code/BF2/AI/AIDLL/AI/Main/AIRandom.h | 6 +- Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp | 455 +- Code/BF2/AI/AIDLL/AI/Main/AISettings.h | 45 +- .../AI/AIDLL/AI/Main/AISettingsInterfaces.h | 7 +- .../AI/AIDLL/AI/Main/AIStreamOperators.cpp | 1026 ++ Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h | 79 + Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp | 49 +- Code/BF2/AI/AIDLL/AI/Main/BF2AI.h | 2 +- .../AI/AIDLL/AI/Main/BFPathfindingCourier.cpp | 110 +- .../AI/AIDLL/AI/Main/BFPathfindingCourier.h | 5 +- .../AI/AIDLL/AI/Main/BotBehaviourManager.cpp | 504 +- .../AI/AIDLL/AI/Main/BotBehaviourManager.h | 11 +- Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp | 755 +- Code/BF2/AI/AIDLL/AI/Main/BotManager.h | 20 +- .../AI/AIDLL/AI/Main/BotPlacementManager.cpp | 96 + .../AI/AIDLL/AI/Main/BotPlacementManager.h | 56 + .../AIDLL/AI/Main/CommonSingletonServer.cpp | 9 + .../BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp | 243 +- Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h | 36 +- Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp | 10 +- Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h | 60 +- Code/BF2/AI/AIDLL/AI/Main/IBotManager.h | 2 +- Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp | 410 +- Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h | 64 +- .../BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp | 80 +- Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h | 6 +- .../AIInterface/BFKnowledge/AIAdapterTypes.h | 12 +- .../BFKnowledge/AIObjectMobile.cpp | 23 +- .../AIInterface/BFKnowledge/AIObjectMobile.h | 2 +- .../BFKnowledge/AIObjectPhysical.cpp | 142 +- .../BFKnowledge/AIObjectPhysical.h | 11 +- .../AI/AIInterface/BFKnowledge/AIPlayer.cpp | 204 +- .../BF2/AI/AIInterface/BFKnowledge/AIPlayer.h | 34 +- .../BFKnowledge/AIPlayerFactory.cpp | 90 +- .../AIInterface/BFKnowledge/AIPlayerFactory.h | 7 + .../BFKnowledge/BFCollisionHandler.cpp | 321 +- .../AIInterface/BFKnowledge/BFCommander.cpp | 181 +- .../AI/AIInterface/BFKnowledge/BFCommander.h | 37 +- .../BF2/AI/AIInterface/BFKnowledge/BFGame.cpp | 229 +- .../BFKnowledge/BFGameEffector.cpp | 105 +- .../AIInterface/BFKnowledge/BFGameEffector.h | 17 +- .../BFKnowledge/BFGraphCreator.cpp | 3 +- .../BFKnowledge/BFObjectEnvironment.cpp | 1315 ++- .../BFKnowledge/BFObjectEnvironment.h | 92 +- .../AI/AIInterface/BFKnowledge/BFPhysics.cpp | 18 +- .../AIInterface/BFKnowledge/BFRadioComm.cpp | 43 +- .../AI/AIInterface/BFKnowledge/BFSquad.cpp | 140 +- Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h | 6 + .../AI/AIInterface/BFKnowledge/BFTerrain.cpp | 275 +- .../AI/AIInterface/BFKnowledge/BFTerrain.h | 12 +- .../AI/AIInterface/BFKnowledge/BFTimer.cpp | 26 +- Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h | 3 +- .../AIInterface/BFKnowledge/DebugRenderer.cpp | 10 +- .../AIInterface/BFKnowledge/DebugRenderer.h | 4 +- .../AIInterface/BFKnowledge/PlanePolygon.cpp | 240 +- .../AI/AIInterface/BFKnowledge/PlanePolygon.h | 11 +- .../AI/AIInterface/Main/AIEventListener.cpp | 275 +- Code/BF2/AI/AIInterface/Module/BFConsole.cpp | 203 +- Code/BF2/AI/AIInterface/Module/BFConsole.h | 18 +- Code/BF2/AI/AIInterface/SingletonServer.h | 1 + 857 files changed, 109577 insertions(+), 5278 deletions(-) create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAction.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOpLessThan.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeapon.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConnectedCondition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPExpression.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInterruptControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBPendingCalls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoint.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/PlanGenerator.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.h delete mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScript.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlanInterpreter.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicPrimitives.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCircle.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.h create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.h create mode 100644 Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc create mode 100644 Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/Main/AIRadio.h create mode 100644 Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h create mode 100644 Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.h diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp new file mode 100644 index 000000000..ca4cff437 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp @@ -0,0 +1,487 @@ +// Ballistic aiming. Evidence: libaidll.so 1.5.3153 (ia-32), AIBot/Aimer.cpp, 0x1C7120..0x1C8EA0 +// (see Aimer.h). Read from the Ghidra decompile and checked against objdump where Ghidra hides x87 +// precision (getFiringDirection's impact time is `double time + float t`, 0x1C8134..0x1C8143). + +#include "Aimer.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1C8EA0, __tcf_0 0x1C8F00, _GLOBAL__I 0x1C8F30). +#include + +#include +#include // _finite (MSVC) +#include + +#include "../../../../Core/PlatformCompat.h" // _finite elsewhere +#include "../../../../Math/Polynom.h" + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x4B7724 (.data, file scope in Aimer.cpp): 0.95 pi, the elevation limit. dice's spelling. +static float WIERD_ANGLE_CONSTANT = 2.984513f; + +namespace { + +// [CHOSEN, not recovered] the image's inlined `x*x + y*y + z*z` sqrt (with its sqrtf retry when +// the x87 fsqrt yields NaN; the retry gives the same value). +inline float length3(float x, float y, float z) +{ + return std::sqrt(x * x + y * y + z * z); +} + +inline float timeStep() +{ + // IBFTimer slot +0xC (getTimeIncrease), narrowed to float as the image does. + return static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); +} + +} // namespace + +// ELF 0x1C7120. +Aimer::Aimer() +{ + m_drag = 0.0f; + m_gravity = 0.0f; + m_speed = 1.0f; + m_hasTargetData = 0; + m_time = 0.0; + m_relativePos.x = 1.0f; m_relativePos.y = 0.0f; m_relativePos.z = 0.0f; + m_targetVelocity.x = 0.0f; m_targetVelocity.y = 0.0f; m_targetVelocity.z = 0.0f; + m_shooterVelocity.x = 0.0f; m_shooterVelocity.y = 0.0f; m_shooterVelocity.z = 0.0f; + m_relativeDir.x = 1.0f; m_relativeDir.y = 0.0f; m_relativeDir.z = 0.0f; + m_forward.x = 0.0f; m_forward.y = 0.0f; m_forward.z = 1.0f; + m_grenade = false; + m_angle = 666.0f; + m_flag69 = false; + m_angleStep = 0.0174533f; + // +0x04 and +0x58 are not written. +} + +// ELF 0x1C72A0. +Aimer::~Aimer() +{ +} + +// ELF 0x1C72C0. +bool Aimer::setTargetData(const Vec3& relativePos, const Vec3& targetVelocity, const Vec3& shooterVelocity, + const Mat4* transform, double time) +{ + m_hasTargetData = 1; + m_relativePos = relativePos; + m_relativeDir = relativePos; + const float lengthSq = m_relativeDir.x * m_relativeDir.x + m_relativeDir.y * m_relativeDir.y + + m_relativeDir.z * m_relativeDir.z; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) < 1.1920929e-07f) + { + m_relativeDir.x = 0.0f; m_relativeDir.y = 0.0f; m_relativeDir.z = 0.0f; + } + else + { + const float inv = 1.0f / std::sqrt(lengthSq); + m_relativeDir.x *= inv; m_relativeDir.y *= inv; m_relativeDir.z *= inv; + } + } + m_targetVelocity = targetVelocity; + m_shooterVelocity = shooterVelocity; + m_forward.x = 0.0f; m_forward.y = 0.0f; m_forward.z = 1.0f; + m_time = time; + if (transform) + { + // (0, 0, 1) rotated by the transform's upper 3x3 (row vector times matrix). + const float* m = transform->m; + const float fx = m_forward.x, fy = m_forward.y, fz = m_forward.z; + m_forward.x = fx * m[0] + fy * m[4] + fz * m[8]; + m_forward.y = fx * m[1] + fy * m[5] + fz * m[9]; + m_forward.z = fx * m[2] + fy * m[6] + fz * m[10]; + } + return true; +} + +// ELF 0x1C74C0. The squared-speed drag applies when the INITIAL speed is above 200. +float Aimer::getImpactTime(float distance, float speed) +{ + const float dt = timeStep(); + float time = 0.0f; + float v = speed; + while (distance > 0.0f) + { + float dragTerm = v; + if (speed > 200.0f) + dragTerm = v * v; + float next = v - dragTerm * m_drag * dt; + if (next < 0.0f) + next = 0.0f; + const float step = (v + next) * 0.5f * dt; + if (step <= 0.0f || 1000.0f * step < distance) + return 1000.0f; + time += (distance < step) ? (distance / step) * dt : dt; + distance -= step; + v = next; + } + return time; +} + +// ELF 0x1C75D0. Trapezoidal integration in timer steps; the drag is linear in the velocity up to +// an initial speed of 200 and quadratic (current |v|) above. +void Aimer::getPredictedImpactPosition(Vec3 velocity, float time, Vec3& out) const +{ + const float speed = length3(velocity.x, velocity.y, velocity.z); + out.x = 0.0f; out.y = 0.0f; out.z = 0.0f; + if (speed == 0.0f) + return; + float dt = timeStep(); + for (; time > 0.0f; time -= dt) + { + if (time < dt) + dt = time; + float dx = 0.0f, dy = 0.0f, dz = 0.0f; + if (m_drag != 0.0f) + { + if (speed <= 200.0f) + { + dx = velocity.x * m_drag; dy = velocity.y * m_drag; dz = velocity.z * m_drag; + } + else + { + const float v = length3(velocity.x, velocity.y, velocity.z); + dx = velocity.x * v * m_drag; dy = velocity.y * v * m_drag; dz = v * velocity.z * m_drag; + } + dx *= dt; dy *= dt; dz *= dt; + } + const float nx = (velocity.x - dx) + dt * 0.0f; + const float ny = (velocity.y - dy) + m_gravity * dt; + const float nz = (velocity.z - dz) + dt * 0.0f; + out.x = (velocity.x + nx) * 0.5f * dt + out.x; + out.y = (velocity.y + ny) * 0.5f * dt + out.y; + out.z = (velocity.z + nz) * 0.5f * dt + out.z; + velocity.x = nx; velocity.y = ny; velocity.z = nz; + } +} + +// ELF 0x1C7970. Drag-free ballistic elevation: the larger root of the trajectory equation. +bool Aimer::getStaticFiringDirection(Vec3& direction, Vec3& target) const +{ + target = m_relativePos; + const float horizontal = std::sqrt(m_relativePos.x * m_relativePos.x + m_relativePos.z * m_relativePos.z); + const float g = -m_gravity; + const float speedSq = m_speed * m_speed; + const float b = -horizontal; + const float a = (horizontal * horizontal * g) / (speedSq + speedSq); + const float disc = b * b - a * 4.0f * (a + m_relativePos.y); + if (disc < 0.0f) + return false; + const float root = std::sqrt(disc); + const float first = std::atan((root - b) / (a + a)); + float angle = std::atan((-b - root) / (a + a)); + if (angle <= first) + angle = first; + const float c = std::cos(angle); + const float s = std::sin(angle); + direction.x = m_relativePos.x * (c / horizontal); + direction.y = s; + direction.z = (c / horizontal) * m_relativePos.z; + return true; +} + +// ELF 0x1C7B80. +bool Aimer::getTurnPointForGrenade(const Vec3& direction, Vec3& point, float& time) const +{ + const float up = direction.y; + if (up > 0.0f) + { + const float t = (up * m_speed) / -m_gravity; + time = t; + point.x = direction.x * t * m_speed; + point.z = direction.z * t * m_speed; + point.y = up * m_speed * 0.5f * t; + } + return up > 0.0f; +} + +// ELF 0x1C7C40. `accuracy` sets the iteration count (accuracy * 8 + 2); `highArc` starts from +// 3/8 pi (or halfway to 0.48 pi from the previous angle) and steps downwards. A zero speed (no +// projectile) aims 20 m above the target. The step (+0x64) is kept between calls; a search that +// did not bracket the target doubles it (at most 0.017) and fails once it is that large. +bool Aimer::getFiringDirection(double time, float accuracy, bool highArc, Vec3& direction, Vec3& target, + double* impactTime) +{ + const bool noSpeed = m_speed == 0.0f; + float relY = m_relativePos.y; + if (noSpeed) + relY += 20.0f; + const float distance = length3(m_relativePos.x, relY, m_relativePos.z); + const float closing = (m_speed - (m_targetVelocity.y * m_relativeDir.y + m_targetVelocity.x * m_relativeDir.x + + m_targetVelocity.z * m_relativeDir.z)) + + m_relativeDir.x * m_shooterVelocity.x + m_relativeDir.y * m_shooterVelocity.y + + m_relativeDir.z * m_shooterVelocity.z; + if (closing < 1.0f) + return false; + const float firstEstimate = distance / closing; + if (firstEstimate < 0.0f) + return false; + double impactAt = time + firstEstimate; + getPredictedTargetPosition(impactAt, target); + float horizontal = std::sqrt(target.z * target.z + target.x * target.x); + if (horizontal == 0.0f) + return false; + float height = target.y; + if (noSpeed) + height += 20.0f; + + float angle; + if (!highArc || m_angle >= 0.7853982f) + { + if (!noSpeed) + { + angle = m_angle; + if (angle != 666.0f) + goto haveAngle; + } + angle = std::atan2(height, horizontal); + } + else + { + angle = 1.1780972f; + } +haveAngle: + { + const float step = m_angleStep; + const float sign = step > 0.0f ? 1.0f : (step >= 0.0f ? 0.0f : -1.0f); + float magnitude = std::fabs(step); + if (magnitude < 0.0001f) + magnitude = 0.0001f; + m_angleStep = magnitude * sign; + } + if (highArc && !noSpeed) + { + angle = (angle + 1.5079645f) * 0.5f; + if (m_angleStep > 0.0f) + m_angleStep = -m_angleStep; + } + + bool converged = false; + int direction0 = 0; // first step direction: +1 up, -1 down + const float drag = m_drag; + const unsigned int iterations = static_cast(accuracy * 8.0f + 2.0f); + unsigned int iteration = 0; + unsigned int convergedCount = 0; + while (convergedCount < iterations) + { + // horizontal unit direction to the predicted target + float hx = target.x, hy = 0.0f, hz = target.z; + const float hSq = hx * hx + 0.0f + hz * hz; + if (std::fabs(hSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(hSq) < 1.1920929e-07f) + { + hx = 0.0f; hz = 0.0f; + } + else + { + const float inv = 1.0f / std::sqrt(hSq); + hy = inv * 0.0f; hx = target.x * inv; hz = inv * target.z; + } + } + float horizontalSpeed = m_shooterVelocity.z * hz + m_shooterVelocity.x * hx + m_shooterVelocity.y * hy + + std::cos(angle) * m_speed; + float verticalSpeed = std::sin(angle) * m_speed + m_shooterVelocity.y; + if (horizontalSpeed <= 0.1f) + return false; + float t = drag != 0.0f ? getImpactTime(horizontal, horizontalSpeed) : horizontal / horizontalSpeed; + if (t > 60.0f) + { + angle = std::atan2(height, horizontal); + m_angle = angle; + horizontalSpeed = m_shooterVelocity.z * hz + m_shooterVelocity.x * hx + m_shooterVelocity.y * hy + + std::cos(angle) * m_speed; + verticalSpeed = std::sin(angle) * m_speed + m_shooterVelocity.y; + getPredictedTargetPosition(time + firstEstimate, target); + const float h = std::sqrt(target.z * target.z + target.x * target.x); + t = drag != 0.0f ? getImpactTime(h, horizontalSpeed) : h / horizontalSpeed; + } + if (t > 100.0f) + return false; + Vec3 velocity; + velocity.x = horizontalSpeed; velocity.y = verticalSpeed; velocity.z = 0.0f; + Vec3 impact; + impact.x = 0.0f; impact.y = 0.0f; impact.z = 0.0f; + getPredictedImpactPosition(velocity, t, impact); + m_verticalExtreme = t * 0.5f; + impactAt = time + t; + getPredictedTargetPosition(impactAt, target); + horizontal = std::sqrt(target.z * target.z + target.x * target.x); + height = target.y; + if (noSpeed) + height += 20.0f; + if (m_grenade && !m_flag69) + height -= 1.3f; + if (!_finite(static_cast(horizontal)) || !_finite(static_cast(height))) + return false; + if (noSpeed) + { + converged = true; + break; + } + if (iteration == iterations - 1) + break; + if (height <= impact.y) + { + if (angle <= -WIERD_ANGLE_CONSTANT) + return false; + if (direction0 == 0) + direction0 = -1; + else if (direction0 > 0) + converged = true; + if (converged) + m_angleStep *= 0.5f; + const float next = angle - m_angleStep; + angle = -WIERD_ANGLE_CONSTANT; + if (-WIERD_ANGLE_CONSTANT <= next) + angle = next; + } + else + { + if (WIERD_ANGLE_CONSTANT <= angle) + return false; + if (direction0 == 0) + direction0 = 1; + else if (direction0 < 0) + converged = true; + if (converged) + m_angleStep *= 0.5f; + angle += m_angleStep; + if (WIERD_ANGLE_CONSTANT < angle) + angle = WIERD_ANGLE_CONSTANT; + } + ++iteration; + if (iteration > 0x400) + break; + if (converged) + ++convergedCount; + } + m_angle = angle; + if (!converged) + { + const float step = m_angleStep; + float doubled = step + step; + if (0.017f < step + step) + doubled = 0.017f; + m_angleStep = doubled; + if (std::fabs(step) >= 0.017f) + return false; + } + const float c = std::cos(angle) / horizontal; + direction.x = target.x * c; + direction.y = std::sin(angle); + direction.z = c * target.z; + const float len = length3(direction.x, direction.y, direction.z); + if (len < 0.95f) + return false; + const float inv = 1.0f / len; + direction.x *= inv; direction.y *= inv; direction.z = inv * direction.z; + if (impactTime) + *impactTime = impactAt; + return true; +} + +// ELF 0x1C8770. A grenade uses its fixed fuse time; a grenade without +0x69 aims 10% short. +void Aimer::getPredictedTargetPosition(double time, Vec3& out) const +{ + static float grenadeExplosionTime = 2.8f; // ELF 0x4B7728 (.data) + float dt = static_cast(time - m_time); + if (m_grenade) + dt = grenadeExplosionTime; + out.x = m_relativePos.x + m_targetVelocity.x * dt; + out.y = m_relativePos.y + m_targetVelocity.y * dt; + out.z = dt * m_targetVelocity.z + m_relativePos.z; + if (m_grenade && !m_flag69) + { + out.x -= m_relativePos.x * 0.1f; + out.y -= m_relativePos.y * 0.1f; + out.z -= m_relativePos.z * 0.1f; + } +} + +// ELF 0x1C8850. +bool Aimer::getImpactPosition(Vec3& out, const Vec3& direction, float time) const +{ + if (time > 100.0f) // 0x1C887A jbe: a NaN time integrates and returns true (0x1C88ED) + return false; + Vec3 velocity; + velocity.x = direction.x * m_speed + m_shooterVelocity.x; + velocity.y = direction.y * m_speed + m_shooterVelocity.y; + velocity.z = m_speed * direction.z + m_shooterVelocity.z; + getPredictedImpactPosition(velocity, time, out); + return true; +} + +// ELF 0x1C8900. Roots of a cubic in t built from the relative motion (the coefficients as the +// image computes them), then the root in [0, 100] whose impact lies closest to the target. +bool Aimer::getNearestImpactPoint(const Vec3& direction, Vec3& out, double& time) const +{ + std::vector roots; + const float vx = direction.x * m_speed + m_shooterVelocity.x; + const float vy = direction.y * m_speed + m_shooterVelocity.y; + const float vz = direction.z * m_speed + m_shooterVelocity.z; + const float k = 1.0f / (1.0f - m_drag); + const float ay = (vy * m_drag + m_gravity) * k; + const float ax = (vx * m_drag + 0.0f) * k; + const float az = k * (vz * m_drag + 0.0f); + const float rx = vx - m_targetVelocity.x; + const float ry = vy - m_targetVelocity.y; + const float rz = vz - m_targetVelocity.z; + const float c0 = -(rz * m_relativePos.z + m_relativePos.y * ry + m_relativePos.x * rx); + const float c1 = (rz * rz + rx * rx + ry * ry) + - (m_relativePos.x * ax + m_relativePos.y * ay + m_relativePos.z * az); + Polynom polynom(4); + polynom[0] = c0 + c0; + polynom[1] = c1 + c1; + polynom[2] = (rz * az + rx * ax + ry * ay) * 3.0f; + polynom[3] = az * az + ax * ax + ay * ay; + polynom.findRoots(roots); + if (roots.empty()) + return false; + float best = 3.4028235e+38f; + bool found = false; + for (unsigned int i = 0; i < roots.size(); ++i) + { + const float r = roots[i]; + if (0.0f <= r && r <= 100.0f) + { + Vec3 impact; + impact.x = 0.0f; impact.y = 0.0f; impact.z = 0.0f; + getImpactPosition(impact, direction, r); + const float t = roots[i]; + const float px = m_targetVelocity.x * t + m_relativePos.x; + const float py = m_targetVelocity.y * t + m_relativePos.y; + const float pz = t * m_targetVelocity.z + m_relativePos.z; + const float dx = px - impact.x, dy = py - impact.y, dz = pz - impact.z; + const float d2 = dx * dx + dy * dy + dz * dz; + if (d2 < best) + { + time = t; + out = impact; + found = true; + best = d2; + } + } + } + return found; +} + +// ELF 0x1C8E90. +double Aimer::getVerticalExtreme() const +{ + return m_verticalExtreme; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h b/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h new file mode 100644 index 000000000..d66eac7e9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h @@ -0,0 +1,77 @@ +// Ballistic aiming for one weapon at one target: given the shooter-relative target state and the +// projectile's speed, drag and gravity, finds the firing direction by iterating the elevation. +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/Aimer.cpp (FILE symbol beside +// 0x1C8EA0, after CommunicationAgent.cpp); constructors 0x1C7120 / 0x1C71E0, destructors +// 0x1C72A0 / 0x1C72B0 (empty, not virtual). sizeof 0x6C: BAPAAimAt embeds it at +0xA4 and its next +// member is at +0x110 (BAPAAimAt::BAPAAimAt 0x1CD5E0). +// +// The fields are public: the aim actions write the projectile parameters in place before +// setTargetData (BAPAAimAtObject::getAimVec 0x1CEA00: +0 = drag, +4 = 1 / drag when the drag is +// not 0, +0xC = speed, +8 = physics gravity * the weapon's gravity modifier). Names are +// [INFERRED] from those uses unless noted. + +#ifndef AI_AIDLL_AI_AIBOT_AIMER_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_AIMER_H + +#include "../../../../Math/Vec3.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Aimer +{ +public: + Aimer(); // ELF 0x1C7120 + ~Aimer(); // ELF 0x1C72A0 (empty) + + // ELF 0x1C72C0. relativePos = target - shooter, targetVelocity, shooterVelocity, the shooter's + // transform (may be 0) and the time the data was sampled. Always returns true. + bool setTargetData(const Vec3& relativePos, const Vec3& targetVelocity, const Vec3& shooterVelocity, + const Mat4* transform, double time); + // ELF 0x1C74C0: time a projectile fired at `speed` needs to cover `distance` with drag. + float getImpactTime(float distance, float speed); + // ELF 0x1C75D0: integrates the projectile (drag, gravity) for `time`; `out` is the displacement. + void getPredictedImpactPosition(Vec3 velocity, float time, Vec3& out) const; + // ELF 0x1C7970: the analytic (drag-free) elevation for a static target. + bool getStaticFiringDirection(Vec3& direction, Vec3& target) const; + // ELF 0x1C7B80: apex of a throw in `direction`; false when the throw does not rise. + bool getTurnPointForGrenade(const Vec3& direction, Vec3& point, float& time) const; + // ELF 0x1C7C40: iterates the elevation until the trajectory meets the predicted target. + bool getFiringDirection(double time, float accuracy, bool highArc, Vec3& direction, Vec3& target, + double* impactTime); + // ELF 0x1C8770: the target relative position at `time`. + void getPredictedTargetPosition(double time, Vec3& out) const; + // ELF 0x1C8850: where a shot in `direction` is after `time` (false beyond 100 s). + bool getImpactPosition(Vec3& out, const Vec3& direction, float time) const; + // ELF 0x1C8900: closest approach of a shot in `direction` to the moving target. + bool getNearestImpactPoint(const Vec3& direction, Vec3& out, double& time) const; + // ELF 0x1C8E90: +0x58. + double getVerticalExtreme() const; + + /* +0x00 */ float m_drag; // ctor 0 + /* +0x04 */ float m_inverseDrag; // 1 / drag, written by the aim actions only + /* +0x08 */ float m_gravity; // ctor 0; y acceleration + /* +0x0C */ float m_speed; // ctor 1.0f; projectile speed (0 = no projectile) + /* +0x10 */ double m_time; // setTargetData's time + /* +0x18 */ Vec3 m_relativePos; // ctor (1, 0, 0) + /* +0x24 */ Vec3 m_relativeDir; // normalised m_relativePos; ctor (1, 0, 0) + /* +0x30 */ Vec3 m_targetVelocity; + /* +0x3C */ Vec3 m_shooterVelocity; + /* +0x48 */ Vec3 m_forward; // transform * (0, 0, 1); ctor (0, 0, 1) + /* +0x54 */ int m_hasTargetData; // ctor 0, setTargetData 1 + /* +0x58 */ double m_verticalExtreme; // half the last impact time (getFiringDirection) + /* +0x60 */ float m_angle; // last elevation; ctor 666.0f = none yet + /* +0x64 */ float m_angleStep; // ctor 0.0174533f (one degree) + /* +0x68 */ bool m_grenade; // ctor false; fixed fuse time in the prediction + /* +0x69 */ bool m_flag69; // [UNRESOLVED] name; ctor false; with m_grenade + // unset, the grenade aim point is pulled in + /* +0x6A */ char m_pad6A[2]; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_AIMER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp index fcca14ec8..d29b96c15 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp @@ -1,6 +1,12 @@ // Bot implementation: owns its behavior, movement, sensing and communication state. // The manager schedules work through the Bot interface; unimplemented operations stop by name. +#include +#include +#include +#include +// Bot.cpp and BotMain.cpp are combined here; both original TUs only initialized iostreams. +// static init: ELF 0x185D60, 0x185DC0, 0x185DF0, 0x18DA90, 0x18DAF0, 0x18DB20 #include "BotMain.h" #include "BotOrder.h" #include "BotCallBack.h" @@ -12,16 +18,36 @@ #include "BotNavigation.h" #include "BotSquad.h" #include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScript.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" #include "SensingAgent.h" #include "CommunicationAgent.h" #include "BotSubObjects.h" +#include "../AIBotBehaviour/BotBehaviour.h" #include "../AIBotBehaviour/UrgencyMerger.h" #include "../AIUtils/checkPointer.h" #include "../AIKnowledge/InformationManager.h" #include "../AIKnowledge/Information.h" // updatePlayerAction: the equipment's mobile plug-in #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" #include "../../../../IO/Input/PlayerInput.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "BotSenses.h" +#include "WaypointList.h" +#include "WPEmpty.h" +#include "WPAltitudeMoveTo.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Core/Debug.h" #include // DBL_MAX - the two 'never happened' timestamps namespace dice { @@ -67,20 +93,18 @@ BotMain::BotMain(IAIPlayer* player, m_float32 = f; m_obedience = 1.0f; m_int40 = i; - m_ptr52 = 0; + m_inverseAttention = 0.0f; m_spawnToStrategicAreaId = -1; m_side = n; m_ptr72 = 0; m_float48 = 0.01f; - m_gap88[1] = 0; // +89 + m_badVehicle = false; // +89 m_memory = memory; - m_gap88[2] = 0; // +90 + m_vehicleChanged = false; // +90 m_inTransitionPhase = false; // +91 m_pad92 = 0; // +92 m_deactivated = false; // +93 - m_ptr100 = 0; - m_ptr104 = 0; - m_ptr108 = 0; + // +100..+108: the empty behaviour-queue vector. m_activePlan = 0; m_planLock = false; // +120 @@ -90,9 +114,7 @@ BotMain::BotMain(IAIPlayer* player, m_planInterpreter = interpreter; m_urgencyMerger = merger; m_urgencyGenerators = generators; - m_ptr160 = 0; - m_ptr164 = 0; - m_ptr168 = 0; + m_lookDir = Vec3::getZero(); // sub-object 1 of 6 m_fireCorrection = checkPointer(new FireCorrectionData()); @@ -109,44 +131,45 @@ BotMain::BotMain(IAIPlayer* player, m_ptr260 = 0; m_firingTarget = -1; m_requestedSoldierPose = 1; - m_int304 = -1; + m_poseTestTarget = -1; m_unresolvedCollision = -1; m_ptr252 = 0; // Use -DBL_MAX for uninitialized timestamps; magnitude sentinels use separate values. m_time276 = -DBL_MAX; - m_time288 = -DBL_MAX; + m_poseChangeTime = -DBL_MAX; m_botStuck = false; - m_flag285 = false; + m_poseInputActive = false; for (int k = 0; k < 4; ++k) - m_flag300[k] = false; // +300..+303 + m_poseTestResults[k] = false; // +300..+303 m_airBorn = false; // +312 for (int k = 0; k < 3; ++k) - m_ptr316[k] = 0; // +316..+324 + m_spawnCoord[k] = 0; // +316..+324 m_deathCallBack = 0; // +328 m_spawnCallBack = 0; // +332 m_squadMember = 0; m_assignedAreas[0] = -1; m_assignedAreas[3] = -1; // +396 m_assignedAreas[2] = -1; // +392 - m_ptr400 = 0; + m_currentWaypoint[0] = 0.0f; m_assignedAreas[1] = -1; // +388 m_manDown = false; // +360 m_isFiring = false; // +372 m_fireAllowed = true; - m_ptr404 = 0; - m_ptr408 = 0; + m_currentWaypoint[1] = 0.0f; + m_currentWaypoint[2] = 0.0f; m_int412 = -1; m_stalledPlanTicks = 0; - for (int k = 0; k < 3; ++k) - m_ptr428[k] = 0; // +428..+436 + m_c4.position.x = 0.0f; // +428..+436 (three zero word stores) + m_c4.position.y = 0.0f; + m_c4.position.z = 0.0f; m_moveToStatus = 0; m_timeOfLastFailedStaticAttack = 0.0; m_timeOfLastFailedStaticSkyAttack = 0.0; m_avoidSide = 0; for (int k = 0; k < 3; ++k) (&m_wantsToSimulateArtillery)[k] = false; // +500..+502 - m_gap512[0] = 0; // +512 + m_avoidSideChanged = false; // +512 m_collidedObject = -1; m_double516 = 0.0; for (int k = 0; k < 3; ++k) @@ -178,7 +201,7 @@ BotMain::BotMain(IAIPlayer* player, // this byte is set in the middle of the allocations, between SensingAgent and // CommunicationAgent, and it is -1 rather than 0. Reproduced in position. - m_gap64[0] = static_cast(-1); // +64 + m_mode = static_cast(-1); m_communication = checkPointer(new CommunicationAgent(this)); // Allocates matching urgency and behavior arrays, but clears only behavior pointers. @@ -196,15 +219,13 @@ BotMain::BotMain(IAIPlayer* player, recieveOrder(order); // dice's spelling m_waypoints = 0; - m_ptr84 = 0; + m_lastScout = 0.0f; m_player = player; if (player) setPlayerInput(); // zeroed A second time - see the block above. - m_ptr160 = 0; - m_ptr164 = 0; - m_ptr168 = 0; + m_lookDir = Vec3::getZero(); // sub-object 6 of 6, and it is the smallest thing here at four bytes m_bapContext = checkPointer(new BAPContext()); @@ -213,22 +234,55 @@ BotMain::BotMain(IAIPlayer* player, // sense every player, and the storage for that is committed at construction. m_sensedObjects.reserve(256); - m_c4Placed = false; // the constructor's last field store + m_c4.placed = false; // the constructor's last field store reset(); } -// [CHOSEN, not recovered] Initial behavior count is zero until configured by the module. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotMain operation. +// ELF .bss 0x4CDFE8: zero until configured by the module. unsigned char BotMain::mu8NBehaviours = 0; -// ELF .bss / PE .data . Set by prepareBehaviourPool, not per bot. +// ELF .bss 0x4CDFEC. Set by prepareBehaviourPool, not per bot. float* BotMain::maBasicWeights = 0; // [FRONTIER] Remaining bot lifecycle operations stop by name. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotMain operation. +// ELF 0x187A50 (D2). In order: the waypoint list (+124, deleting dtor), the behaviour and urgency +// arrays (delete[]), the memory (+76; the constructor's argument, deleted here), the death and +// spawn callbacks (deleting dtors), the BAP context, the player (IAIPlayer +0x78 +// removePlayerFromGame, then IAIPlayerFactory +0x18 destroy), navigation, squad, sensing and +// communication agents, +376 cleared, the fire correction (plain operator delete); then the +// members (+340 vector, +252 vector, the three lists, the behaviour queues) and Bot. BotMain::~BotMain() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::~BotMain"); + if (m_waypoints) + delete m_waypoints; + if (m_behaviours) + delete[] m_behaviours; + if (m_behaviourUrgencies) + delete[] m_behaviourUrgencies; + if (m_memory) + delete m_memory; + if (m_deathCallBack) + delete m_deathCallBack; + if (m_spawnCallBack) + delete m_spawnCallBack; + if (m_bapContext) + delete m_bapContext; + if (m_player) + { + m_player->removePlayerFromGame(); + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->destroy(m_player); + } + if (m_navigation) + delete m_navigation; + if (m_squad) + delete m_squad; + if (m_sensingAgent) + delete m_sensingAgent; + if (m_communication) + delete m_communication; + m_squadMember = 0; + operator delete(m_fireCorrection); } // Releases each behavior's initialized state without deleting the behavior itself. @@ -237,11 +291,9 @@ void BotMain::uninitAllBehaviours() { for (int i = 0; i < mu8NBehaviours; ++i) { - if (m_behaviours[i]) - { - // Retail here is `m_behaviours[i]->something->uninit(this)` - see the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::uninitAllBehaviours (a behaviour is present)"); - } + // ELF 0x18A740: behaviour +0xC (the pattern), when set, vtable +0x10 unInit(this). + if (m_behaviours[i] && m_behaviours[i]->getPattern()) + m_behaviours[i]->getPattern()->unInit(this); } } @@ -251,16 +303,14 @@ void BotMain::reset() { m_double172 = 0.0; + // ELF 0x18B6A5 / 0x18B880: IAIPlayer +0x08 reset(). if (m_player) - { - // Retail calls IAIPlayer byte-slot +8 with no arguments. See the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::reset (IAIPlayer slot +8)"); - } + m_player->reset(); + // ELF 0x18B850: the plan's deleting destructor (BotScript slot +0x08). if (m_activePlan) { - // Retail destroys the plan through byte-slot +8. See the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::reset (active plan present)"); + delete m_activePlan; m_activePlan = 0; m_planInvalid = true; m_sensingAgent->setOverride(false); @@ -278,11 +328,11 @@ void BotMain::reset() m_stalledPlanTicks = 0; m_int200 = -1; - m_int304 = -1; + m_poseTestTarget = -1; m_avoidSide = 0; m_moveToStatus = 0; m_collidedObject = -1; - m_double364 = 0.0; + m_rearmTimer = 0.0; m_unresolvedCollision = -1; m_grenadeThrownTime[0] = 0.0; m_grenadeThrownTime[1] = 0.0; @@ -292,8 +342,8 @@ void BotMain::reset() m_double516 = 0.0; m_wantsToSimulateArtillery = false; m_isSimulatingArtillery = false; - m_flag502 = false; - m_gap512[0] = 0; + m_forcePose = false; + m_avoidSideChanged = false; m_collidedObjectPosition[0] = 0; m_collidedObjectPosition[1] = 0; m_collidedObjectPosition[2] = 0; @@ -312,7 +362,7 @@ void BotMain::reset() m_isGoingForFlag = false; m_useStaticAttack = false; // 9999.0, not the ctor's -DBL_MAX. See the block above. - m_time288 = -9999.0; + m_poseChangeTime = -9999.0; m_timeOfLastFailedSplashDamageAttack = -9999.0; m_takeOffPosition[0] = 0.0f; m_takeOffPosition[1] = 0.0f; @@ -422,15 +472,44 @@ void BotMain::setTakingOrders(bool taking) { m_takingOrders = taking; } // The two plan-execution brackets. not vtable slots - `planExecution` at +0x010 is, but these // two are ordinary members, so whatever calls them does so on a `BotMain*` and not through `Bot`. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] + +// ELF 0x1891E0: only the movement axes are released before the plan runs. void BotMain::prePlanExecution() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::prePlanExecution"); + resetAllControls(true, false, false); } +// ELF 0x189220 (413 bytes). Soldiers only (equipment type flag 0x200000; no null guard on the +// information). One second after friends were last in the line of fire the avoid side is +// cleared; otherwise the bot strafes (PIYaw +-1) towards the avoid side while the navigation +// reports more than 0.5 of space there (+292 / +296), or switches the side when only the other +// side has space. void BotMain::postPlanExecution() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::postPlanExecution"); + Information* const equipment = informationManager->getInformation(getCurrentEquipment()); + if ((equipment->getObjectTypeFlags() & 0x00200000) == 0) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double sinceFriendsInLine = now - getFriendsInLineOfFireTime(); + if (sinceFriendsInLine >= 1.0) + { + setAvoidSide(0); + return; + } + if (m_avoidSide == 1) + { + if (getBotNavigation()->getSpaceLeft() > 0.5f) + m_playerInput->setInput(io::PIYaw, -1.0f); + else if (getBotNavigation()->getSpaceRight() > 0.5f) + setAvoidSide(2); + } + else + { + if (getBotNavigation()->getSpaceRight() > 0.5f) + m_playerInput->setInput(io::PIYaw, 1.0f); + else if (getBotNavigation()->getSpaceLeft() > 0.5f) + setAvoidSide(1); + } } // Bot interface implementations, in virtual declaration order. @@ -448,16 +527,381 @@ BotLodLevel BotMain::getLodLevel() const return m_lodLevel; } -// +0x010 +// +0x010. ELF 0x188B90 (1611 bytes). Returns !m_planInvalid in %al; BotManager discards it. +// 1. Clears the change target, then copies a finished bot projectile's flight data from the +// collision handler into the fire correction data (slots +0x44 .. +0x58, +0x40 removes it). +// 2. An invalid plan is dropped (BotScript deleting destructor, vtable +8) and the sensing +// override released. Without a plan, the equipment unit's default behaviour (IAISettings +// +0x1C, or the man-down equipment type +0xA0) generates one (BotBehaviour +0x2C). +// 3. With a valid plan it runs between pre/postPlanExecution; a failure invalidates it. +// The sensing agent updates and runs its own plan with the override disallowed. +// 4. Non-soldiers release PIWeaponSelect9; a soldier falling faster than 1 m/s (speed.y <= -1) +// presses it (inlined Input::setInput: mapped bit 22 -> inputs[22] = 1). void BotMain::planExecution(const double& slice) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::planExecution"); + bool ok = true; + bool failed = false; + resetChangeTarget(); + + IBFCollisionHandler* const collision = + checkPointer(static_cast(CommonSingletonServer::m_iBFCollisionHandler)); + if (collision->botProjectilePassedPoint(m_botId)) + { + m_fireCorrection->m_projectilePrePoint = collision->botProjectilePrePoint(m_botId); + m_fireCorrection->m_projectilePostPoint = collision->botProjectilePostPoint(m_botId); + m_fireCorrection->m_projectileTargetPoint = collision->botProjectileTargetPoint(m_botId); + m_fireCorrection->m_projectileMaxHeight = collision->botProjectileMaxHeight(m_botId); + m_fireCorrection->m_flag5 = true; + m_fireCorrection->m_flag84 = true; + m_fireCorrection->m_flag85 = true; + collision->removeBotProjectile(m_botId); + } + + Information* const equipment = informationManager->getInformation(getCurrentEquipment()); + bool invalid; + bool havePlan = false; + if (m_planInvalid) + { + // ELF 0x188F80: the invalid plan is deleted (BotScript +8, deleting destructor). + if (m_activePlan) + { + delete m_activePlan; + m_activePlan = 0; + m_sensingAgent->setOverride(false); + } + } + else if (m_activePlan) + { + havePlan = true; + } + if (havePlan) + { + invalid = false; + } + else + { + IPIUnit* const unit = equipment ? equipment->getUnit() : 0; + BotBehaviour* behaviour = 0; + if (unit) + { + int type = unit->getEquipmentType(); + if (!m_manDown) + unit->setTime(); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + if (getManDown()) + type = settings->getManDownEquipmentType(); + behaviour = settings->getDefaultBehaviour(type); + } + // ELF 0x188EFE: the default behaviour's pattern (+0xC) is forced initiated (PlanGenerator + // +0x14), then generatePlan (+0x2C) becomes the active plan; a plan is owned by the bot + // and marks the default plan. + if (behaviour) + { + behaviour->getPattern()->forceInitiated(this); + m_activePlan = behaviour->generatePlan(this); + if (m_activePlan) + { + m_activePlan->m_owner = this; + m_hasDefaultPlan = true; + m_planInvalid = false; + } + } + invalid = m_planInvalid; + } + + if (!invalid) + { + prePlanExecution(); + // ELF 0x188D82: m_planInterpreter (+0x90) vtable +8 execute(plan, this, &ok, &failed); + // the result is ignored. The flag pair: -0x15A first, -0x159 second; the plan stays + // valid only when the first is set and the second clear. + m_planInterpreter->execute(m_activePlan, this, ok, failed); + postPlanExecution(); + m_planInvalid = failed || !ok; + if (m_planInvalid) + { + setPlanLock(false); + resetAllControls(true, true, true); + m_sensingAgent->clearPlanTargetInformation(); + } + m_sensingAgent->update(); + if (m_sensingAgent->getPlan()) + { + m_sensingAgent->disallowOverride(true); + m_sensingAgent->executePlan(); + m_sensingAgent->disallowOverride(false); + } + } + + // No null guard: the ELF reads the flag word of whatever the handle resolves to. + Information* const current = informationManager->getInformation(m_currentEquipment); + if ((current->getObjectTypeFlags() & 0x00200000) == 0) + { + m_playerInput->setInput(io::PIWeaponSelect9, 0.0f); + } + else if (IPIMobile* const mobile = equipment->getMobile()) + { + if (mobile->getSpeed().y <= -1.0f) + m_playerInput->setInput(io::PIWeaponSelect9, 1.0f); + } + pollRequestedSoldierPose(); + (void)slice; } // +0x014. Returns the count BotManager::actionDecisionMaking banks in BotInfo +32 (see BotMain.h). +// ELF 0x1893D0 (3134 bytes). Returns the number of behaviours whose urgency was refreshed. +// 1. A deactivated bot drops its plan and does nothing. +// 2. The inclinations decay; a changed vehicle runs updateBotVehicle and notifies the SAI +// (ISAI +0x40 setBotHasChangedEquipment); a vehicle the bot cannot use is reported. +// 3. Behaviour urgencies are refreshed queue by queue within the slice; once the slice is used +// up the remaining queues only age (each moves into the one before it). +// 4. The urgency merger picks the behaviour (hasChanged(bot, 0.87f, 1.15f) unless the plan is +// invalid), the memory records it, and its generated plan replaces the active one. int BotMain::decisionMaking(const double& slice) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::decisionMaking"); + std::list refreshed; + int count = 0; + if (m_deactivated) + { + // ELF 0x189401: the plan is deleted (BotScript +8, the deleting destructor), the plan + // marked invalid and the sensing override released. + if (m_activePlan) + { + delete m_activePlan; + m_activePlan = 0; + m_planInvalid = true; + m_sensingAgent->setOverride(false); + } + return 0; + } + + const int lastBehaviour = m_memory->m_int0; + stepMoveInclination(); + stepFireInclination(); + if (!m_checkVehicle) + { + IAIObject* const vehicle = m_player->getCurrentVehicle(); + if (!vehicle) + { + m_currentEquipment = static_cast(-1); + m_checkVehicle = true; + } + else + { + m_checkVehicle = vehicle->getInformation(m_side) != m_currentEquipment; + } + } + if (m_checkVehicle) + { + bool usable = false; + if (updateBotVehicle(&usable)) + { + if (m_activePlan) + { + delete m_activePlan; + m_activePlan = 0; + m_planInvalid = true; + m_sensingAgent->setOverride(false); + } + if (!usable || !informationManager->getInformation(m_currentEquipment)) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 749, "") << "Bot in bad vehicle!"; + m_badVehicle = true; + m_currentEquipment = static_cast(-1); + return 0; + } + updateBot(); + IAIMain::m_instance->getSAI(m_side)->setBotHasChangedEquipment(m_botId); + } + else if (m_badVehicle) + { + updateBot(); + m_navigation->reset(); + m_badVehicle = false; + IAIMain::m_instance->getSAI(m_side)->setBotHasChangedEquipment(m_botId); + } + m_checkVehicle = false; + } + + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + if (m_vehicleChanged) + { + m_planInvalid = true; + m_vehicleChanged = false; + } + if (m_planInvalid) + { + m_memory->m_int0 = -1; + m_memory->m_double16 = timer->getGameTime(); + } + + // Step 3 (ELF 0x189700..0x189B5E). While the slice lasts, queue i is consumed from the front: + // null behaviours are dropped, the others get their urgency refreshed (vtable +0x28, with + // `true`) when positive and move to `refreshed`. When start + slice <= now (getUpdateTime) + // the rest only age: from the current queue on (at least queue 1) every behaviour still gets + // calculateUrgency(this, false, urgency) when positive, then the queue's entries are + // appended to the queue before it and the queue is emptied. The urgency is the stored one, + // scaled (unless the plan is invalid or no behaviour was remembered) by + // BotMemory::modifyBehaviourUrgency(behaviour, game time) and the last behaviour's modifier + // row entry; the two loops multiply in different orders (kept). + unsigned int i = 0; + bool exhausted = false; + for (; i < m_behaviourQueues.size() && !exhausted; ++i) + { + std::list& queue = m_behaviourQueues[i]; + while (!queue.empty()) + { + const unsigned short index = queue.front(); + BotBehaviour* const behaviour = m_behaviours[index]; + if (!behaviour) + { + queue.erase(queue.begin()); + } + else + { + const float stored = m_behaviourUrgencies[index]; + float urgency = stored; + if (!m_planInvalid && lastBehaviour != -1) + { + const float modifier = m_memory->modifyBehaviourUrgency(behaviour, timer->getGameTime()); + urgency = modifier * m_behaviours[lastBehaviour]->getModifiers()[index] * stored; + } + if (0.0f < urgency) + { + ++count; + behaviour->calculateUrgency(this, true, urgency); + } + queue.erase(queue.begin()); + refreshed.push_back(index); + } + if (start + slice <= timer->getUpdateTime()) + { + if (i == 0) + i = 1; + exhausted = true; + break; + } + } + if (exhausted) + break; + } + + if (exhausted) + { + for (; i < m_behaviourQueues.size(); ++i) + { + std::list& queue = m_behaviourQueues[i]; + for (std::list::iterator it = queue.begin(); it != queue.end(); ) + { + const unsigned short index = *it; + BotBehaviour* const behaviour = m_behaviours[index]; + if (!behaviour) + { + it = queue.erase(it); + continue; + } + float urgency; + if (!m_planInvalid && lastBehaviour != -1) + { + const float modifier = m_memory->modifyBehaviourUrgency(behaviour, timer->getGameTime()); + urgency = modifier * m_behaviourUrgencies[index] * m_behaviours[lastBehaviour]->getModifiers()[index]; + } + else + { + urgency = m_behaviourUrgencies[index]; + } + if (0.0f < urgency) + behaviour->calculateUrgency(this, false, urgency); + ++it; + } + std::list& previous = m_behaviourQueues[i - 1]; + previous.insert(previous.end(), queue.begin(), queue.end()); + queue.erase(queue.begin(), queue.end()); + } + } + + // Step 4 (ELF 0x189BE0..). The merger picks the behaviour; the memory records it and the + // game time. An existing plan is handed to the chosen behaviour (+4), or deleted when the + // plan is invalid. A different behaviour clears the plan targets. The generated plan + // replaces the active one (the old one is owned back by the bot, deleted, and the controls + // reset); no plan marks the plan invalid. The refreshed behaviours go to the back of their + // queue group (BotBehaviour +5). + UrgencyGenerator* const merger = m_urgencyMerger; + if (m_planInvalid || merger->hasChanged(this, 0.87f, 1.15f)) + merger->updateActiveUrgency(this); + BotBehaviour* const chosen = static_cast(merger->getChosenGenerator()); + // Shipped defect: the selected behaviour is used without a null check. + m_memory->m_int0 = chosen->getIndex(); + m_memory->m_double16 = timer->getGameTime(); + if (m_activePlan) + { + if (!m_planInvalid) + { + m_activePlan->m_owner = chosen; + } + else + { + delete m_activePlan; + m_activePlan = 0; + m_sensingAgent->setOverride(false); + } + } + if (lastBehaviour != static_cast(chosen->getIndex())) + m_sensingAgent->clearPlanTargetInformation(); + BotScript* const plan = chosen->generatePlan(this); + if (m_activePlan != plan) + { + if (m_activePlan) + { + m_activePlan->m_owner = this; + delete m_activePlan; + m_activePlan = 0; + m_sensingAgent->setOverride(false); + } + resetAllControls(true, true, true); + } + m_activePlan = plan; + if (!plan) + { + m_planInvalid = true; + } + else + { + m_planInvalid = false; + m_hasDefaultPlan = false; + plan->m_owner = this; + } + for (std::list::iterator it = refreshed.begin(); it != refreshed.end(); ++it) + { + std::list& queue = m_behaviourQueues[m_behaviours[*it]->getQueueGroup()]; + queue.insert(queue.end(), static_cast(*it)); + } + return count; +} + +// ELF 0x18C850: decays below 0.01 to zero, else by 0.8; the accumulated delta enters at 0.2. +void BotMain::stepMoveInclination() +{ + if (m_moveInclination <= 0.01f) + m_moveInclination = 0.0f; + else + m_moveInclination = m_moveInclination * 0.8f; + const float delta = m_moveInclinationDelta; + m_moveInclinationDelta = 0.0f; + m_moveInclination = delta * 0.2f + m_moveInclination; +} + +// ELF 0x18C920: the same on the fire pair. +void BotMain::stepFireInclination() +{ + if (m_fireInclination <= 0.01f) + m_fireInclination = 0.0f; + else + m_fireInclination = m_fireInclination * 0.8f; + const float delta = m_fireInclinationDelta; + m_fireInclinationDelta = 0.0f; + m_fireInclination = delta * 0.2f + m_fireInclination; } // +0x018 @@ -466,34 +910,165 @@ void BotMain::cheatExecution() // five bytes - A bare `ret`. The hook exists and does nothing. Reproduced. } + + // +0x01C +// ELF 0x18A1D0: forwards to the sensing agent's BotSenses (+192 -> +104). void BotMain::see(const double& dt) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::see"); + m_sensingAgent->getSenses()->see(dt); } // +0x020 +// ELF 0x18A210: forwards like see. void BotMain::updateSensing(const double& dt) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateSensing"); + m_sensingAgent->getSenses()->updateSensing(dt); } // +0x024 +// ELF 0x188AA0: tail of BotNavigation::update (+188). Its bool result is returned in %al +// and BotManager discards it, so the slot keeps its void declaration. void BotMain::updatePathfinding(bool& a, bool* b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updatePathfinding"); + m_navigation->update(a, b); } // +0x02C -void BotMain::updateBotVehicle(bool* out) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateBotVehicle"); +// ELF 0x18BCC0 (655 bytes). Returns false only when the bot already uses the vehicle's +// information for its side and is not man-down. Otherwise the manager takes the vehicle +// (IBotManager +0x2C), the old equipment's strength drops to 3/4 and the new one's rises by 4/3, +// and the bot restarts on it. *out tells whether there is a vehicle at all. +bool BotMain::updateBotVehicle(bool* out) +{ + IAIObject* const vehicle = m_player->getCurrentVehicle(); + getPlan(); + m_vehicleChanged = true; + m_planInvalid = true; + m_hasDefaultPlan = false; + if (!vehicle) + { + m_navigation->reset(); + setCurrentEquipment(static_cast(-1)); + if (out) + *out = false; + return true; + } + if (out) + *out = true; + const unsigned int handle = vehicle->getInformation(m_side); + if (handle != static_cast(-1) && getCurrentEquipment() == handle && !m_manDown) + return false; + IBotManager::instance->updateBotVehicle(this, vehicle); + m_airBorn = false; + Information* const previous = informationManager->getInformation(getCurrentEquipment()); + m_lastChangeTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const unsigned int next = vehicle->getInformation(getSide()); + Information* const current = informationManager->getInformation(next); + if (previous) + previous->setStrength(previous->getStrength() * 0.75f); + if (!current) + { + setCurrentEquipment(static_cast(-1)); + return true; + } + m_sensingAgent->deletePlan(); + current->setStrength(current->getStrength() * 1.3333334f); + setCurrentEquipment(next); + setPlanLock(false); + m_navigation->reset(); + m_takeOffPosition[0] = 0.0f; + m_takeOffPosition[1] = 0.0f; + m_takeOffPosition[2] = 0.0f; + resetAllControls(true, true, true); + return true; } // +0x030 -void BotMain::updateBot() +// ELF 0x18BF50 (1488 bytes). (Re)builds the bot for its current equipment: the plan +// interpreter and the applicable behaviours for the equipment type (the man-down type while man +// down), the vehicle modifiers, then a fresh memory and a waypoint list - an empty one at the +// bot's position, or for flags & 0x10 (byte +4 of the information) a climb to 100 m above it. +// False without equipment or without its unit plug-in. +bool BotMain::updateBot() +{ + Information* const equipment = informationManager->getInformation(getCurrentEquipment()); + if (!equipment || !equipment->getUnit()) + return false; + UrgencyGenerator** const generators = getBehaviourUrgencyGenerators(); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + const int type = m_manDown ? settings->getManDownEquipmentType() // slot +0xA0 + : equipment->getUnit()->getEquipmentType(); + setPlanInterpreter(static_cast(settings->getPlanInterpreter(type))); // +0x20 + const int count = settings->getNumberOfBehaviours(); // +0x0C + for (int i = 0; i < count; ++i) + { + BotBehaviour* behaviour = settings->getBehaviour(type, i); // +0x18 + if (behaviour) + { + if (!behaviour->isAplicable(equipment, this)) // BotBehaviour +0x30 + behaviour = 0; + if (behaviour) + behaviour->reset(this); // +0x24 + } + addBehaviour(behaviour, i); + generators[i] = behaviour; + if (behaviour && behaviour->getPattern()) + behaviour->getPattern()->unInit(this); // PlanGenerator +0x10 + } + m_ptr72 = settings->getVehicleMods(type); // +0x14 + calculateMods(); + getSelector()->updateActiveUrgency(this); // UrgencyGenerator +0x10 + getMemory()->reset(); + if ((equipment->getObjectTypeFlags() & 0x10) == 0) + { + // The image re-reads +0x8C (m_currentEquipment) inline here; no null guard. + Information* const self = informationManager->getInformation(m_currentEquipment); + setWaypoints(checkPointer(new WPEmpty(self->getPosition()))); + } + else + { + std::list path; + const Vec3& position = equipment->getPosition(); + Vec3 above; + above.x = position.x + 0.0f; + above.y = position.y + 100.0f; + above.z = position.z + 0.0f; + path.push_back(above); + setWaypoints(checkPointer(new WPAltitudeMoveTo(1.0f, 1.0f, 25.0f, 1, path))); + } + return true; +} + +// ELF 0x18AAD0. +UrgencyGenerator** BotMain::getBehaviourUrgencyGenerators() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateBot"); + return m_urgencyGenerators; +} + +// ELF 0x18AAC0. +UrgencyGenerator* BotMain::getSelector() +{ + return m_urgencyMerger; +} + +// ELF 0x18A540 (496 bytes). Grows the queue table to the behaviour's group (+5), queues its +// index (+4) when that slot was empty, and stores it in both the behaviour and generator tables. +void BotMain::addBehaviour(BotBehaviour* b, int i) +{ + if (b) + { + if (m_behaviourQueues.size() <= b->getQueueGroup()) + m_behaviourQueues.resize(static_cast(b->getQueueGroup()) + 1, std::list()); + if (m_behaviours[b->getIndex()] == 0) + { + std::list& queue = m_behaviourQueues[b->getQueueGroup()]; + // `insert(header, idx)`: the list's header node is end() in this STL - a push_back. + queue.insert(queue.end(), static_cast(b->getIndex())); + } + } + m_behaviours[i] = b; + m_urgencyGenerators[i] = b; } // +0x034 @@ -508,6 +1083,13 @@ float BotMain::getObedience() return m_obedience; } +// ELF 0x18ABA0: the int at +0x28 (the ctor's `i`). BBFireUnarmed::calculateUrgency converts the +// answer with cvtsi2ss, hence int. +int BotMain::getHarmlessThrsh() +{ + return m_int40; +} + // +0x03C float* BotMain::getCurrentOrders() { @@ -521,15 +1103,29 @@ WaypointList* BotMain::getWaypoints() } // +0x044 +// ELF 0x18A3D0: the previous list is destroyed through its deleting destructor (vtable +4) +// before the replacement is stored. void BotMain::setWaypoints(WaypointList* w) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setWaypoints"); + if (m_waypoints) + delete m_waypoints; + m_waypoints = w; } // +0x04C -void BotMain::recieveOrder(BotOrder* order, std::list& targets) +// ELF 0x18A080 (272 bytes). As the one-argument order, with the target list copied in order and +// the modifiers always recalculated. +bool BotMain::recieveOrder(BotOrder* order, std::list& targets) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::recieveOrder"); + if (!m_takingOrders) + return false; + m_currentOrders = order->m_weights; + m_orderedBehaviour = static_cast(order->m_behaviour); + m_list128.clear(); + for (std::list::const_iterator it = targets.begin(); it != targets.end(); ++it) + m_list128.push_back(*it); + calculateMods(); + return true; } // +0x050 @@ -586,6 +1182,18 @@ bool BotMain::isTakingOrders() return m_takingOrders; } +// ELF 0x18A9F0: +0x58 = true. +void BotMain::setUpdateCurrentEquipment() +{ + m_checkVehicle = true; +} + +// ELF 0x18AA00: +0x58. +bool BotMain::getUpdateCurrentEquipment() +{ + return m_checkVehicle; +} + // +0x074 bool BotMain::isOrderedBehaviour(unsigned char behaviour) { @@ -593,15 +1201,48 @@ bool BotMain::isOrderedBehaviour(unsigned char behaviour) } // +0x078 +// ELF 0x18A450 (208 bytes). Only while taking orders, with ordered targets, for the ordered +// behaviour (BotBehaviour's index byte +4): whether `handle` is one of the targets. bool BotMain::isOrderedObject(unsigned int handle, BotBehaviour* b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::isOrderedObject"); + if (!m_takingOrders || m_list128.empty()) + return false; + if (b->getIndex() != static_cast(m_orderedBehaviour)) + return false; + return std::find(m_list128.begin(), m_list128.end(), handle) != m_list128.end(); +} + +// ELF 0x18A780: +144. +PlanInterpreter* BotMain::getPlanInterpreter() +{ + return m_planInterpreter; +} + +// ELF 0x18A790: +144. +void BotMain::setPlanInterpreter(PlanInterpreter* p) +{ + m_planInterpreter = p; +} + +// ELF 0x18C7D0: +276. +void BotMain::setHadPrecisionTimeStamp(double time) +{ + m_time276 = time; } // +0x07C +// ELF 0x18C5E0 (432 bytes). A new target restarts the fire correction and drops the bot's +// tracked projectile. void BotMain::setFiringTarget(unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setFiringTarget"); + if (m_firingTarget == handle) + return; + m_firingTarget = handle; + m_firingTargetTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_fireCorrection->newTarget(handle); + m_fireCorrection->m_flag84 = false; + checkPointer(static_cast(CommonSingletonServer::m_iBFCollisionHandler)) + ->removeBotProjectile(m_botId); // slot +0x40 } // +0x080 @@ -623,21 +1264,23 @@ SensingAgent* BotMain::getSensingAgent() } // +0x08C +// ELF 0x18AA10: forwarded to the sensing agent. void BotMain::insertBehaviourInformation(float f, const Vec3& v, unsigned char c) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::insertBehaviourInformation"); + m_sensingAgent->insertBehaviourInformation(f, v, c); } // +0x090 -const std::vector& BotMain::getSensedObjects() const +// ELF 0x18AA60: BotSenses::getSensedObjects, the handle -> SensedObject* map at senses +112. +const std::map& BotMain::getSensedObjects() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSensedObjects"); + return m_sensingAgent->getSenses()->getSensedObjects(); } -// +0x094 -void* BotMain::getSensedObjectFromHandle(unsigned int handle) const +// +0x094. ELF 0x18A280: BotSenses::getSensedObjectFromHandle. +SensedObject* BotMain::getSensedObjectFromHandle(unsigned int handle) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSensedObjectFromHandle"); + return m_sensingAgent->getSenses()->getSensedObjectFromHandle(handle); } // +0x098 @@ -653,27 +1296,28 @@ unsigned int BotMain::getUnresolvedCollisionHandle() } // +0x0A0 -void* BotMain::getIncommingFire() +// ELF 0x18B0C0: `lea 0x54(senses)` - the fire-object list. +std::list >* BotMain::getIncommingFire() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getIncommingFire"); + return m_sensingAgent->getSenses()->getIncommingFire(); } -// +0x0A4 +// +0x0A4. ELF 0x18B0E0: `flds 0x58(senses)`. float BotMain::getIncommingFireTotalStrength() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getIncommingFireTotalStrength"); + return m_sensingAgent->getSenses()->getIncommingFireTotalStrength(); } -// +0x0A8 +// +0x0A8. ELF 0x18B100: `flds 0x5c(senses)`. float BotMain::getIncommingFireTotalStrengthAgainstSelf() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getIncommingFireTotalStrengthAgainstSelf"); + return m_sensingAgent->getSenses()->getIncommingFireTotalStrengthAgainstSelf(); } -// +0x0AC +// +0x0AC. ELF 0x18B120: `flds 0x60(senses)`. float BotMain::getAttackerStrength() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getAttackerStrength"); + return m_sensingAgent->getSenses()->getAttackerStrength(); } // +0x0B0 @@ -689,9 +1333,10 @@ int BotMain::getPlayerId() const } // +0x0B8 +// ELF 0x18A7D0: IAIPlayer::getInputId (+0x20), no null guard. int BotMain::getInputId() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getInputId"); + return m_player->getInputId(); } // +0x0BC @@ -741,10 +1386,243 @@ void BotMain::updatePlayerAction(bool stalled) // the speed along the facing (clamped by minThrottle) or to zero; the second releases both look // axes; the third releases fire, alt-fire, the nine weapon and eight position selects, flares // crouch and lie (conditionally), use and reload. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -void BotMain::resetAllControls(bool, bool, bool) +// ELF 0x18ABB0 (1208 bytes). Every release writes 0.0f through Input::setInput(float). +// The soldier test is the equipment's type flag 0x200000; the vehicle throttle is +// -clamp(dot(speed, facing) * 0.5, -minThrottle, minThrottle) with minThrottle = 0.4f +// (ELF 0x4b6884). Flag 0x10 on the equipment skips the throttle; no null guard on that read. +void BotMain::resetAllControls(bool movement, bool look, bool actions) +{ + static float minThrottle = 0.4f; + Information* const equipment = informationManager->getInformation(m_currentEquipment); + const bool soldier = equipment && (equipment->getObjectTypeFlags() & 0x00200000) != 0; + if (movement) + { + m_playerInput->setInput(io::PISprint, 0.0f); + m_playerInput->setInput(io::PIYaw, 0.0f); + m_playerInput->setInput(io::PIPitch, 0.0f); + m_playerInput->setInput(io::PIRoll, 0.0f); + if ((equipment->getObjectTypeFlags() & 0x10) == 0) + { + IPIMobile* const mobile = equipment->getMobile(); + float throttle = 0.0f; + if (mobile && !soldier) + { + const Vec3 facing = equipment->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + const float along = (speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) * 0.5f; + // the ELF's fucomi/fcmovnbe order: a NaN product passes through unclamped. + float clamped; + if (-minThrottle > along) + clamped = -minThrottle; + else + clamped = along > minThrottle ? minThrottle : along; + throttle = -clamped; + } + m_playerInput->setInput(io::PIThrottle, throttle); + } + } + if (look) + { + m_playerInput->setInput(io::PIMouseLookX, 0.0f); + m_playerInput->setInput(io::PIMouseLookY, 0.0f); + } + if (actions) + { + m_playerInput->setInput(io::PIFire, 0.0f); + m_playerInput->setInput(io::PIAltFire, 0.0f); + for (int i = io::PIWeaponSelect1; i <= io::PIPositionSelect8; ++i) + m_playerInput->setInput(static_cast(i), 0.0f); + m_playerInput->setInput(io::PIFlareFire, 0.0f); + if (isDead() || !soldier) + { + m_playerInput->setInput(io::PICrouch, 0.0f); + m_playerInput->setInput(io::PILie, 0.0f); + } + m_playerInput->setInput(io::PIUse, 0.0f); + m_playerInput->setInput(io::PIReload, 0.0f); + } +} + +// ELF 0x18CAF0. +void BotMain::resetChangeTarget() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::resetAllControls"); + m_changeTarget = static_cast(-1); +} + +// ELF 0x18CE60. +void BotMain::clearTestResults() +{ + m_poseTestTarget = -1; + for (int k = 0; k < 4; ++k) + m_poseTestResults[k] = false; +} + +// ELF 0x18D660 (223 bytes). A pose is acceptable unless the firing target is an enemy; then +// the results of the last pose test count, if they were made against that target. +bool BotMain::checkPoseOk(bool& out, int pose) +{ + Information* const target = informationManager->getInformation(getFiringTarget()); + if (target && target->getSide() != getSide()) + { + if (m_poseTestTarget != static_cast(getFiringTarget())) + return false; + if (pose != SPCrouching) + { + out = m_poseTestResults[3]; + return m_poseTestResults[2]; + } + out = m_poseTestResults[1]; + return m_poseTestResults[0]; + } + return true; +} + +// ELF 0x18CEE0 (1856 bytes): drives PICrouch / PILie from the current pose (the equipment's +// SoldierPose) towards the requested one. Lying down toggles PILie against its current input +// value (inlined Input read: mapped bit 37 -> inputs[37]). An unknown requested pose reports +// "Internal error, unknown pose." (BotMain.cpp lines 2723 / 2760) and returns early. +void BotMain::pollRequestedSoldierPose() +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + Information* const equipment = informationManager->getInformation(m_currentEquipment); + if (!equipment) + return; + + bool unused = false; + const int current = equipment->getSoldierPose(); + const int requested = m_requestedSoldierPose; + io::PlayerInput* const input = m_playerInput; + // Presses PILie unless it is already fully pressed. + struct Lie + { + static void toggle(io::PlayerInput* in) + { + const float value = ((in->mappingFlags >> io::PILie) & 1) ? in->inputs[io::PILie] : 0.0f; + in->setInput(io::PILie, value != 1.0f ? 1.0f : 0.0f); + } + }; + + bool release = false; // the LAB_19d067 arm: release both, input inactive + if (current == SPCrouching) + { + if (requested == SPCrouching) + { + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = false; + } + else if (requested == SPStanding) + { + input->setInput(io::PILie, 0.0f); + input->setInput(io::PICrouch, 0.0f); + clearTestResults(); + m_poseInputActive = true; + } + else if (requested == SPLying) + { + if (checkPoseOk(unused, SPLying) || m_forcePose) + { + input->setInput(io::PICrouch, 0.0f); + Lie::toggle(input); + m_poseChangeTime = now; + m_poseInputActive = true; + } + } + else if (requested == SPSwimming) + { + release = true; + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 2723, "") << "Internal error, unknown pose."; + return; + } + } + else if (current == SPStanding) + { + if (requested == SPCrouching) + { + if (checkPoseOk(unused, SPCrouching) || m_forcePose) + { + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = true; + } + } + else if (requested == SPStanding) + { + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = false; + } + else if (requested == SPLying) + { + if (checkPoseOk(unused, SPLying) || m_forcePose) + { + input->setInput(io::PICrouch, 0.0f); + Lie::toggle(input); + m_poseChangeTime = now; + m_poseInputActive = true; + } + } + else if (requested == SPSwimming) + { + release = true; + } + else + { + return; + } + } + else if (current == SPLying) + { + if (requested == SPCrouching) + { + if (checkPoseOk(unused, SPCrouching) || m_forcePose) + { + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + m_poseChangeTime = now; + m_poseInputActive = true; + } + } + else if (requested == SPStanding) + { + input->setInput(io::PICrouch, 0.0f); + Lie::toggle(input); + clearTestResults(); + m_poseChangeTime = now; + m_poseInputActive = true; + } + else if (requested == SPLying || requested == SPSwimming) + { + release = true; + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 2760, "") << "Internal error, unknown pose."; + return; + } + } + else if (current == SPSwimming) + { + release = true; + } + else + { + m_requestedSoldierPose = SPStanding; + m_poseInputActive = false; + } + if (release) + { + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 0.0f); + m_poseInputActive = false; + } + + m_forcePose = false; + if (m_poseInputActive && (equipment->getObjectTypeFlags() & 0x00200000) != 0) + input->setInput(io::PIFire, 0.0f); } // deactivated bots are dead without consulting the player. @@ -760,10 +1638,8 @@ bool BotMain::setSide(int side) Information* const equipment = informationManager->getInformation(m_currentEquipment); if (equipment) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // IAIObject has no recovered typed interface yet. Retail calls its setSide at ELF - // +0x128 / PE +0x124 through Information's object (+0x20 ELF / +0x28 PE). - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setSide (equipment IAIObject::setSide)"); + // ELF 0x18C9E0: `mov 0x20(info),%eax; call *0x128(vtbl)` - IAIObject::setSide. + equipment->getAIObject()->setSide(side); } m_side = side; m_player->setSide(side); @@ -771,9 +1647,10 @@ bool BotMain::setSide(int side) } // +0x0CC +// ELF 0x18CA80: IAIPlayer::setName (+0x7C). void BotMain::setName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setName"); + m_player->setName(name); } // +0x0D0 @@ -825,15 +1702,25 @@ BotMemory* BotMain::getMemory() } // +0x0F0 +// ELF 0x18C990: IAIPlayer::getName (+0x18). const std::string& BotMain::getName() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getName"); + return m_player->getName(); } // +0x0F4 +// ELF 0x18D960: a three-deep history; a repeated time is ignored, otherwise the older two +// shift down (+460 -> +468 -> +476). void BotMain::setTimeOfLastGrenadeThrown(double t) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setTimeOfLastGrenadeThrown"); + const double last = m_grenadeThrownTime[0]; + if (t != last) + { + const double older = m_grenadeThrownTime[1]; + m_grenadeThrownTime[0] = t; + m_grenadeThrownTime[1] = last; + m_grenadeThrownTime[2] = older; + } } // +0x0F8 @@ -855,15 +1742,18 @@ int BotMain::getSpawnPoint() const } // +0x104 +// ELF 0x18B9E0: IAIPlayer::getSpawnKit (+0x44). int BotMain::getSpawnKit() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSpawnKit"); + return m_player->getSpawnKit(); } // +0x108 +// ELF 0x18BA00: spawn group (+0x40) then kit (+0x44). void BotMain::getSpawnTarget(int& a, int& b) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getSpawnTarget"); + a = m_player->getSpawnGroup(); + b = m_player->getSpawnKit(); } // Keep fresh player/side/id reads @@ -895,9 +1785,19 @@ int BotMain::getSpawnToStrategicAreaId() } // +0x118 +// ELF 0x18BB80: true while the player is dead (and arms +313), then true exactly once on the +// first call that sees the player alive again. bool BotMain::isJustSpawned() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::isJustSpawned"); + if (!m_player->getIsAlive()) + { + m_spawnPending = true; + return true; + } + if (!m_spawnPending) + return false; + m_spawnPending = false; + return true; } // +0x11C @@ -978,33 +1878,51 @@ void BotMain::setBotStuck(bool b) } // +0x14C +// ELF 0x1888F0: the record with the game time and a 240 s life time (0x49CB3C). void BotMain::placeC4(int placementType, Vec3 v, AIStrategicObject* o) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::placeC4"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_c4.placed = true; + m_c4.placementType = placementType; + m_c4.object = o; + m_c4.position = v; + m_c4.placedTime = now; + m_c4.lifeTime = 240.0; } // +0x150 +// ELF 0x1889C0. bool BotMain::isC4Placed() { - return m_c4Placed; + return m_c4.placed; } // +0x154 +// ELF 0x188980: type and position stay. void BotMain::removeC4() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::removeC4"); + m_c4.placed = false; + m_c4.object = 0; + m_c4.placedTime = 0.0; + m_c4.lifeTime = 0.0; } // +0x158 -void* BotMain::getC4() +// ELF 0x188880: a copy of +0x1A4..+0x1CB. +Bot::C4State BotMain::getC4() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getC4"); + return m_c4; } // +0x15C +// ELF 0x1889D0: a placed charge past its life time is removed (virtual +0x154). void BotMain::updateC4() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::updateC4"); + if (!m_c4.placed) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_c4.placedTime + m_c4.lifeTime) + removeC4(); } // +0x160 @@ -1026,25 +1944,54 @@ void* BotMain::getDebugger() // +0x16C void BotMain::event_projectile(FireObject* f, unsigned int h) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_projectile"); + // ELF 0x18B1A0: forwards to the senses (+0xC0 -> +0x68). + m_sensingAgent->getSenses()->event_projectile(f, h); } // +0x170 +// ELF 0x18B1E0: a hit on the fire-correction target (+80) confirms the shot (+4, +5 set, +84 +// cleared); any other hit counts as a miss (Bot +0x174 event_shotMissed). void BotMain::event_shotHit(int i, world::IObject* o, const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_shotHit"); + if (o == m_fireCorrection->m_shotTarget) + { + m_fireCorrection->m_flag4 = true; + m_fireCorrection->m_flag5 = true; + m_fireCorrection->m_flag84 = false; + return; + } + event_shotMissed(i, v); } // +0x174 +// ELF 0x18B230 (736 bytes). A miss of the correction shot (+0 the weapon) records where it went +// and the projectile's points from the collision handler, then drops the projectile. void BotMain::event_shotMissed(int i, const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_shotMissed"); + FireCorrectionData* const correction = m_fireCorrection; + if (i != correction->m_weapon) + return; + correction->m_missedPosition = v; + m_fireCorrection->m_double72 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_fireCorrection->m_flag4 = false; + m_fireCorrection->m_flag5 = true; + IBFCollisionHandler* const collision = + checkPointer(static_cast(CommonSingletonServer::m_iBFCollisionHandler)); + m_fireCorrection->m_projectilePrePoint = collision->botProjectilePrePoint(m_botId); // +0x4C + m_fireCorrection->m_projectilePostPoint = collision->botProjectilePostPoint(m_botId); // +0x50 + m_fireCorrection->m_projectileTargetPoint = collision->botProjectileTargetPoint(m_botId); // +0x54 + m_fireCorrection->m_projectileMaxHeight = collision->botProjectileMaxHeight(m_botId); // +0x58 + m_fireCorrection->m_flag5 = true; + m_fireCorrection->m_flag84 = true; + m_fireCorrection->m_flag85 = collision->botProjectilePassedPoint(m_botId); // +0x44 + collision->removeBotProjectile(m_botId); // +0x40 } // +0x178 void BotMain::event_heardObject(unsigned int h) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_heardObject"); + // ELF 0x18A190: forwards to the senses (+0xC0 -> +0x68). + m_sensingAgent->getSenses()->event_heardObject(h); } // +0x17C @@ -1084,9 +2031,19 @@ float BotMain::getFireInclination() } // +0x194 +// ELF 0x18CDC0. An unforced change waits while a pose input is held and for one second after +// the last pose change. void BotMain::requestSoldierPose(int pose, bool b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::requestSoldierPose"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (pose != m_requestedSoldierPose) + { + if ((m_poseInputActive || now <= 1.0 + m_poseChangeTime) && !b) + return; + m_requestedSoldierPose = pose; + } + if (b) + m_forcePose = true; } // +0x198 @@ -1096,15 +2053,28 @@ int BotMain::getRequestedSolderPose() } // +0x19C +// ELF 0x18D620. void BotMain::setPoseStatus(int pose, unsigned int h, bool a, bool b) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setPoseStatus"); + m_poseTestTarget = static_cast(h); + if (pose == SPCrouching) + { + m_poseTestResults[0] = a; + m_poseTestResults[1] = b; + } + else + { + m_poseTestResults[2] = a; + m_poseTestResults[3] = b; + } } // +0x1A0 +// ELF 0x18D740: airborne when the equipment carries type flag 0x10 or 0x20. void BotMain::event_airborn() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_airborn"); + Information* const equipment = informationManager->getInformation(m_currentEquipment); + m_airBorn = equipment && (equipment->getObjectTypeFlags() & 0x30) != 0; } // +0x1A4 @@ -1132,9 +2102,30 @@ bool BotMain::getManDown() const } // +0x1B4 +// ELF 0x18D7D0 (382 bytes). While not man-down, every REARM_PERIOD (6.0, double) of +// accumulated time increase each weapon of the armament is topped up by REARM_PERCENT (0.125f) +// for the bot's side. The weapon handles are copied first (a local vector). void BotMain::rearm(Information* i) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::rearm"); + static double REARM_PERIOD = 6.0; + static float REARM_PERCENT = 0.125f; + if (m_manDown) + return; + m_rearmTimer += static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + if (m_rearmTimer > REARM_PERIOD) + { + IPIArmament* const armament = i->getArmament(); + const std::vector weapons = armament->getWeapons(); + for (std::vector::const_iterator it = weapons.begin(); it != weapons.end(); ++it) + { + if (*it == static_cast(-1)) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(*it); + if (weapon) + armament->rearm(weapon, REARM_PERCENT, getSide()); + } + m_rearmTimer = 0.0; + } } // +0x1B8 @@ -1253,9 +2244,14 @@ void BotMain::setNewAssignedAreas(int a, int b) } // +0x204 +// ELF 0x18CCB0: the assigned areas equal their copies, `a` is the current waypoint's int, and an +// area is assigned at all. bool BotMain::hasSameAssignedAreas(int a) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::hasSameAssignedAreas"); + bool same = false; + if (m_assignedAreas[0] == m_assignedAreas[2] && m_assignedAreas[3] == m_assignedAreas[1] && a == m_int412) + same = m_assignedAreas[0] != -1; + return same; } // +0x208 @@ -1266,15 +2262,26 @@ void BotMain::copyAssignedAreas() } // +0x20C +// ELF 0x18CD40: the Vec3 at +400 and the int at +412. void BotMain::setCurrentWaypoint(Vec3 v, int i) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setCurrentWaypoint"); + float* const waypoint = m_currentWaypoint; + waypoint[0] = v.x; + waypoint[1] = v.y; + waypoint[2] = v.z; + m_int412 = i; } // +0x210 -const Vec3& BotMain::getCurrentWaypoint() +// ELF 0x18CD90: the Vec3 at +400, by value. +Vec3 BotMain::getCurrentWaypoint() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::getCurrentWaypoint"); + const float* const waypoint = m_currentWaypoint; + Vec3 v; + v.x = waypoint[0]; + v.y = waypoint[1]; + v.z = waypoint[2]; + return v; } // +0x214 @@ -1334,9 +2341,20 @@ bool BotMain::getBotIsSimulatingArtillery() const } // +0x238 -void BotMain::setAvoidSide(int side) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setAvoidSide"); +// ELF 0x18DA20 (112 bytes). Answers whether an earlier switch is still flagged and the side +// changes to another non-zero one; the flag (+512) is set by a switch between two non-zero +// sides and cleared by side 0. +bool BotMain::setAvoidSide(int side) +{ + bool result = false; + if (m_avoidSideChanged && side != m_avoidSide && side != 0) + result = true; + if (side == 0) + m_avoidSideChanged = false; + else if (m_avoidSide != side && m_avoidSide != 0) + m_avoidSideChanged = true; + m_avoidSide = side; + return result; } // +0x23C @@ -1352,9 +2370,18 @@ int BotMain::getMoveToStatus() const } // +0x244 +// ELF 0x18D9A0 (128 bytes). At most one status change per game-time stamp; a stamp ahead of the +// clock (after a time reset) is cleared first. void BotMain::setMoveToStatus(int status) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setMoveToStatus"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (m_double516 > now) + m_double516 = 0.0; + if (now - m_double516 > 0.0) + { + m_double516 = now; + m_moveToStatus = status; + } } // +0x248 @@ -1370,9 +2397,12 @@ unsigned int BotMain::getCollidedObject() const } // +0x250 +// ELF 0x18EC60: +528. void BotMain::setCollidedObjectPosition(const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setCollidedObjectPosition"); + m_collidedObjectPosition[0] = v.x; + m_collidedObjectPosition[1] = v.y; + m_collidedObjectPosition[2] = v.z; } // +0x254 @@ -1444,9 +2474,12 @@ bool BotMain::getIsGoingForFlag() const } // +0x280 +// ELF 0x18CE90: within changeTime (0.8, double, ELF 0x4b6888) of the last pose change. bool BotMain::botInPoseTransition() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::botInPoseTransition"); + static double changeTime = 0.8; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return now - m_poseChangeTime < changeTime; } // +0x284 @@ -1474,9 +2507,12 @@ double BotMain::getTimeOfLastFailedSplashDamageAttack() const } // +0x294 +// ELF 0x18EE00: +576. void BotMain::setTakeOffPosition(const Vec3& v) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setTakeOffPosition"); + m_takeOffPosition[0] = v.x; + m_takeOffPosition[1] = v.y; + m_takeOffPosition[2] = v.z; } // +0x298 @@ -1488,25 +2524,150 @@ const Vec3& BotMain::getTakeOffPosition() const // +0x29C void BotMain::setQuadSeen() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::setQuadSeen"); + // ELF 0x18A250: forwards to the sensing agent (+0xC0). + m_sensingAgent->setQuadSeen(); } // +0x2A0 bool BotMain::isAttacking(unsigned int handle, double& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::isAttacking"); + // ELF 0x18B140: forwards to the senses (+0xC0 -> +0x68). + return m_sensingAgent->getSenses()->isAttacking(handle, out); } // +0x2A4 +// ELF 0x18B510 (368 bytes). The correction shot timed out: drop the projectile. void BotMain::event_shotTimeOut(int i) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_shotTimeOut"); + IBFCollisionHandler* const collision = static_cast(CommonSingletonServer::m_iBFCollisionHandler); + if (i == m_fireCorrection->m_weapon) + checkPointer(collision)->removeBotProjectile(m_botId); // slot +0x40 } // +0x2A8 -void BotMain::event_firing(bool& b, int i, const Vec3& v) +// ELF 0x18C520 (192 bytes). Stamps the last-fire time (+172). A shot may carry a fire correction +// when the previous one was confirmed (+5) and none is pending (+84): it is booked (+5 cleared, +// +6 set, +72 = -1.0, the weapon and target stored); otherwise +6 is cleared. Both paths return +// the fire-correction record + 56 (the predicted target), re-reading the record pointer; +// AICollisionHandler::handleProjectileFire (0x382340) books it as the projectile's target point. +// [INFERRED] reference rather than pointer spelling. +const Vec3& BotMain::event_firing(bool& b, int i, const Vec3& v) +{ + m_double172 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + FireCorrectionData* const correction = m_fireCorrection; + b = correction->m_flag5 && !correction->m_flag84; + if (!b) + { + correction->m_flag6 = false; + return m_fireCorrection->m_predictedTarget; + } + correction->m_flag5 = false; + correction->m_flag6 = true; + correction->m_double72 = -1.0f; + correction->m_weapon = i; + correction->m_firedTarget[0] = v.x; + correction->m_firedTarget[1] = v.y; + correction->m_firedTarget[2] = v.z; + return m_fireCorrection->m_predictedTarget; +} + +// ELF 0x18BBD0: `lea 0x13c(this)`. +const Vec3& BotMain::getSpawnCoord() const +{ + return *reinterpret_cast(m_spawnCoord); +} + +// ELF 0x18BBE0: a component copy into +316. BotManager::setBotIsAlive calls it on every spawn. +void BotMain::setSpawnCoord(const Vec3& v) +{ + m_spawnCoord[0] = v.x; + m_spawnCoord[1] = v.y; + m_spawnCoord[2] = v.z; +} + +// ELF 0x18C7B0: `fldl 0xac(this)` - the double at +172. +double BotMain::getTimeOfLastFire() const +{ + return m_double172; +} + +// ELF 0x18AB80: fst preserves the returned value in st(0). +float BotMain::setInvAttention(float value) +{ + m_inverseAttention = value; + return value; +} + +// ELF 0x18A360. +unsigned char BotMain::getMode() { return m_mode; } + +// ELF 0x18A520. +void BotMain::setMode(unsigned char mode) { m_mode = mode; } + +// ELF 0x18A390. +float BotMain::getLastScout() { return m_lastScout; } + +// ELF 0x18A6C0: does not delete the behaviour or remove its queued index. +void BotMain::removeBehaviour(BotBehaviour* behaviour) +{ + m_behaviours[behaviour->getIndex()] = 0; + m_urgencyGenerators[behaviour->getIndex()] = 0; +} + +// ELF 0x18A6F0. +BotBehaviour* BotMain::getActiveBehaviour() +{ + const int index = m_memory->m_int0; + return index == -1 ? 0 : m_behaviours[index]; +} + +// ELF 0x18AB40. +float BotMain::setObedience(float value) { return m_obedience = value; } + +// ELF 0x18AB50. +float BotMain::getAttention() { return m_float48; } + +// ELF 0x18AB60. +float BotMain::setAttention(float value) { return m_float48 = value; } + +// ELF 0x18AB70. +float BotMain::getInvAttention() { return m_inverseAttention; } + +// ELF 0x18AB90. +float BotMain::getMarksmanship() { return m_float32; } + +// ELF 0x18B070. +const Vec3& BotMain::getLookDir() { return m_lookDir; } + +// ELF 0x18B080. +void BotMain::setLookDir(const Vec3& direction) { m_lookDir = direction; } + +// ELF 0x18B180: borrowed attacker map owned by the sensing state. +void* BotMain::getAttackers() const { return &m_sensingAgent->getSenses()->m_map100; } + +// ELF 0x18B890. Shipped defect: this validation only reports an error. +bool BotMain::validateDataStructures() +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotMain.cpp", 1764, "") + << "Doesn't work, didn't think it needed to."; + return true; +} + +// ELF 0x18C7C0. +double BotMain::getHadPrecisionTimeStamp() const { return m_time276; } + +// ELF 0x18C820. +void BotMain::clearMoveInclination() +{ + m_moveInclination = 0.0f; + m_moveInclinationDelta = 0.0f; +} + +// ELF 0x18C8F0. +void BotMain::clearFireInclination() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMain::event_firing"); + m_fireInclination = 0.0f; + m_fireInclinationDelta = 0.0f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h index 68e261a63..99be9382a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h @@ -7,6 +7,8 @@ #include "../../../../Math/Vec3.h" #include +#include +#include #include #include @@ -37,38 +39,58 @@ class IBotDeathCallBack; class IBotSpawnCallBack; class Information; class PlanInterpreter; +class SensedObject; class SensingAgent; class SquadMember; class UrgencyGenerator; class WaypointList; +#if defined(BF2_PLATFORM_POSIX) +// [CHOSEN, not recovered] Match AISettingsInterfaces.h's forward declaration on Clang/GCC. +enum BotLodLevel : int { BotLodFull = 0, BotLodMedium = 1, BotLodLight = 2 }; +#else enum BotLodLevel { BotLodFull = 0, BotLodMedium = 1, BotLodLight = 2 }; // [CHOSEN] - see BotManager +#endif // Base interface used by the bot manager to schedule and query bots. // [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. class Bot { public: + // The C4 record BotMain keeps at +0x1A4 and getC4 (ELF 0x188880, `ret $4`) returns by value: + // placeC4 (0x1888F0) and removeC4 (0x188980) write it. BBC4::calculateUrgency reads it. + // [INFERRED] type and field names; placement type stays an int (the enum's labels are not + // recovered; Bot::C4PlacementType is attested by the placeC4 mangling). + struct C4State + { + /* +0x00 */ bool placed; + /* +0x04 */ int placementType; + /* +0x08 */ Vec3 position; + /* +0x14 */ AIStrategicObject* object; + /* +0x18 */ double placedTime; // game time at placeC4 + /* +0x20 */ double lifeTime; // 240.0 (0x49CB3C) at placeC4; updateC4 removes after it + }; + virtual ~Bot(); // - one instruction each virtual void setLodLevel(BotLodLevel level) = 0; // +0x008 virtual BotLodLevel getLodLevel() const = 0; // +0x00C - virtual void planExecution(const double& slice) = 0; // +0x010 [FRONTIER] - virtual int decisionMaking(const double& slice) = 0; // +0x014 [FRONTIER] + virtual void planExecution(const double& slice) = 0; // +0x010 partial [FRONTIER] + virtual int decisionMaking(const double& slice) = 0; // +0x014 partial [FRONTIER] virtual void cheatExecution() = 0; // +0x018 - virtual void see(const double& dt) = 0; // +0x01C [FRONTIER] - virtual void updateSensing(const double& dt) = 0; // +0x020 [FRONTIER] - virtual void updatePathfinding(bool& a, bool* b) = 0; // +0x024 [FRONTIER] + virtual void see(const double& dt) = 0; // +0x01C + virtual void updateSensing(const double& dt) = 0; // +0x020 + virtual void updatePathfinding(bool& a, bool* b) = 0; // +0x024 virtual void reset() = 0; // +0x028 - virtual void updateBotVehicle(bool* out) = 0; // +0x02C [FRONTIER] - virtual void updateBot() = 0; // +0x030 [FRONTIER] + virtual bool updateBotVehicle(bool* out) = 0; // +0x02C + virtual bool updateBot() = 0; // +0x030 (ELF bool) virtual BotSquad* getBotSquad() const = 0; // +0x034 virtual float getObedience() = 0; // +0x038 virtual float* getCurrentOrders() = 0; // +0x03C order weights virtual WaypointList* getWaypoints() = 0; // +0x040 - virtual void setWaypoints(WaypointList* w) = 0; // +0x044 [FRONTIER] + virtual void setWaypoints(WaypointList* w) = 0; // +0x044 virtual bool recieveOrder(BotOrder* order) = 0; // +0x048 - virtual void recieveOrder(BotOrder* order, std::list& targets) = 0; // +0x04C [FRONTIER] + virtual bool recieveOrder(BotOrder* order, std::list& targets) = 0; // +0x04C (ELF answers 0/1) virtual std::list* getOrderList(unsigned char behaviour) = 0; // +0x050 virtual bool hasPlan() = 0; // +0x054 virtual bool hasDefaultPlan() const = 0; // +0x058 @@ -79,28 +101,28 @@ class Bot virtual void setPlanLock(bool b) = 0; // +0x06C virtual bool isTakingOrders() = 0; // +0x070 virtual bool isOrderedBehaviour(unsigned char behaviour) = 0; // +0x074 - virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b) = 0; // +0x078 [FRONTIER] + virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b) = 0; // +0x078 virtual void setFiringTarget(unsigned int handle) = 0; // +0x07C [FRONTIER] virtual unsigned int getFiringTarget() const = 0; // +0x080 virtual double getFiringTargetTime() const = 0; // +0x084 virtual SensingAgent* getSensingAgent() = 0; // +0x088 virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c) = 0; // +0x08C [FRONTIER] - virtual const std::vector& getSensedObjects() const = 0; // +0x090 [FRONTIER] - virtual void* getSensedObjectFromHandle(unsigned int handle) const = 0; // +0x094 [FRONTIER] + virtual const std::map& getSensedObjects() const = 0; // +0x090 + virtual SensedObject* getSensedObjectFromHandle(unsigned int handle) const = 0; // +0x094 virtual void setUnresolvedCollisionObject(unsigned int handle) = 0; // +0x098 virtual unsigned int getUnresolvedCollisionHandle() = 0; // +0x09C - virtual void* getIncommingFire() = 0; // +0x0A0 [FRONTIER] - virtual float getIncommingFireTotalStrength() = 0; // +0x0A4 [FRONTIER] - virtual float getIncommingFireTotalStrengthAgainstSelf() = 0; // +0x0A8 [FRONTIER] - virtual float getAttackerStrength() const = 0; // +0x0AC [FRONTIER] + virtual std::list >* getIncommingFire() = 0; // +0x0A0 + virtual float getIncommingFireTotalStrength() = 0; // +0x0A4 + virtual float getIncommingFireTotalStrengthAgainstSelf() = 0; // +0x0A8 + virtual float getAttackerStrength() const = 0; // +0x0AC virtual CommunicationAgent* getCommunicationAgent() = 0; // +0x0B0 virtual int getPlayerId() const = 0; // +0x0B4 - virtual int getInputId() = 0; // +0x0B8 [FRONTIER] + virtual int getInputId() = 0; // +0x0B8 virtual IAIPlayer* getPlayer() const = 0; // +0x0BC virtual void updatePlayerAction(bool stalled) = 0; // +0x0C0 virtual bool isDead() const = 0; // +0x0C4 - virtual bool setSide(int side) = 0; // +0x0C8 equipment arm [FRONTIER] - virtual void setName(const std::string& name) = 0; // +0x0CC [FRONTIER] + virtual bool setSide(int side) = 0; // +0x0C8 + virtual void setName(const std::string& name) = 0; // +0x0CC virtual bool isDeactivated() const = 0; // +0x0D0 virtual void setAsDeactivated(bool b) = 0; // +0x0D4 virtual unsigned int getCurrentEquipment() const = 0; // +0x0D8 @@ -109,17 +131,17 @@ class Bot virtual int getBotType() const; // +0x0E4 virtual unsigned int getBotId() const = 0; // +0x0E8 virtual BotMemory* getMemory() = 0; // +0x0EC - virtual const std::string& getName() const = 0; // +0x0F0 [FRONTIER] - virtual void setTimeOfLastGrenadeThrown(double t) = 0; // +0x0F4 [FRONTIER] + virtual const std::string& getName() const = 0; // +0x0F0 + virtual void setTimeOfLastGrenadeThrown(double t) = 0; // +0x0F4 virtual double getTimeOfGrenadeThrown(int i) const = 0; // +0x0F8 virtual BotNavigation* getBotNavigation() = 0; // +0x0FC virtual int getSpawnPoint() const = 0; // ELF +0x100 / PE +0xFC - virtual int getSpawnKit() const = 0; // +0x104 [FRONTIER] - virtual void getSpawnTarget(int& a, int& b) const = 0; // +0x108 [FRONTIER] + virtual int getSpawnKit() const = 0; // +0x104 + virtual void getSpawnTarget(int& a, int& b) const = 0; // +0x108 virtual void setSpawnTarget(int spawnGroup, int kit) = 0; // ELF +0x10C / PE +0x10C (overload order) virtual void setSpawnTarget(int strategicArea, int spawnGroup, int kit) = 0; // +0x110 virtual int getSpawnToStrategicAreaId() = 0; // +0x114 - virtual bool isJustSpawned() = 0; // +0x118 [FRONTIER] + virtual bool isJustSpawned() = 0; // +0x118 virtual IBotDeathCallBack* getDeathCallBack() const = 0; // +0x11C virtual void setDeathCallBack(IBotDeathCallBack* cb) = 0; // +0x120 virtual IBotSpawnCallBack* getSpawnCallBack() const = 0; // +0x124 @@ -132,33 +154,33 @@ class Bot virtual SquadMember* getSquadMember() = 0; // +0x140 virtual bool isBotStuck() = 0; // +0x144 virtual void setBotStuck(bool b) = 0; // +0x148 - virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o) = 0; // +0x14C [FRONTIER] + virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o) = 0; // +0x14C virtual bool isC4Placed() = 0; // +0x150 - virtual void removeC4() = 0; // +0x154 [FRONTIER] - virtual void* getC4() = 0; // +0x158 [FRONTIER] - virtual void updateC4() = 0; // +0x15C [FRONTIER] + virtual void removeC4() = 0; // +0x154 + virtual C4State getC4() = 0; // +0x158 + virtual void updateC4() = 0; // +0x15C virtual void enableBotScriptDebugger(bool /*enable*/) = 0; // +0x160 virtual void* getDebugger() = 0; // +0x164 virtual BAPContext* getScriptContext(); // +0x168 - virtual void event_projectile(FireObject* f, unsigned int h) = 0; // +0x16C [FRONTIER] - virtual void event_shotHit(int i, world::IObject* o, const Vec3& v) = 0; // +0x170 [FRONTIER] - virtual void event_shotMissed(int i, const Vec3& v) = 0; // +0x174 [FRONTIER] - virtual void event_heardObject(unsigned int h) = 0; // +0x178 [FRONTIER] + virtual void event_projectile(FireObject* f, unsigned int h) = 0; // +0x16C + virtual void event_shotHit(int i, world::IObject* o, const Vec3& v) = 0; // +0x170 + virtual void event_shotMissed(int i, const Vec3& v) = 0; // +0x174 + virtual void event_heardObject(unsigned int h) = 0; // +0x178 virtual bool isInTransitionPhase() const = 0; // +0x17C virtual void setIsInTransitionPhase(bool b) = 0; // +0x180 virtual void addToMoveInclination(float f) = 0; // +0x184 virtual void addToFireInclination(float f) = 0; // +0x188 virtual float getMoveInclination() = 0; // +0x18C virtual float getFireInclination() = 0; // +0x190 - virtual void requestSoldierPose(int pose, bool b) = 0; // +0x194 [FRONTIER] + virtual void requestSoldierPose(int pose, bool b) = 0; // +0x194 virtual int getRequestedSolderPose() = 0; // +0x198 - virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b) = 0; // +0x19C [FRONTIER] - virtual void event_airborn() = 0; // +0x1A0 [FRONTIER] + virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b) = 0; // +0x19C + virtual void event_airborn() = 0; // +0x1A0 virtual bool isAirBorn() const = 0; // +0x1A4 virtual void setLastChangeTime(double t) = 0; // +0x1A8 virtual void setManDown(bool b) = 0; // +0x1AC virtual bool getManDown() const = 0; // +0x1B0 - virtual void rearm(Information* i) = 0; // +0x1B4 [FRONTIER] + virtual void rearm(Information* i) = 0; // +0x1B4 virtual void setChangeTarget(unsigned int h) = 0; // +0x1B8 virtual unsigned int getChangeTarget() const = 0; // +0x1BC virtual void setRepairTarget(unsigned int h) = 0; // +0x1C0 @@ -173,6 +195,12 @@ class Bot // [INFERRED] friendship, like BotMain's below: BotManager::actionExecutePlan reads +4 inline // through a `Bot*` to press a climbing bot's inputs. friend class BotManager; + // [INFERRED] likewise: CommunicationAgent::shutOffHorn (ELF 0x1C53F0) reads +4 inline. + friend class CommunicationAgent; + // [INFERRED] likewise: SquadMember::update (ELF 0x1B1ED0) presses the weapon input via +4. + friend class SquadMember; + // [INFERRED] inline reader of +4 (no symbol): the BAP actions and entries read the bound input directly. + io::PlayerInput* getInput() const { return m_playerInput; } protected: // Base construction leaves both pointers uninitialized. Player input is borrowed and @@ -205,23 +233,23 @@ class BotMain : public Bot // [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. virtual void setLodLevel(BotLodLevel level); // +0x008 virtual BotLodLevel getLodLevel() const; // +0x00C - virtual void planExecution(const double& slice); // +0x010 [FRONTIER] + virtual void planExecution(const double& slice); // +0x010 partial [FRONTIER] // [INFERRED] Returns an integer work count accumulated by BotManager. - virtual int decisionMaking(const double& slice); // +0x014 [FRONTIER] + virtual int decisionMaking(const double& slice); // +0x014 partial [FRONTIER] virtual void cheatExecution(); // +0x018 - virtual void see(const double& dt); // +0x01C [FRONTIER] - virtual void updateSensing(const double& dt); // +0x020 [FRONTIER] - virtual void updatePathfinding(bool& a, bool* b); // +0x024 [FRONTIER] + virtual void see(const double& dt); // +0x01C + virtual void updateSensing(const double& dt); // +0x020 + virtual void updatePathfinding(bool& a, bool* b); // +0x024 virtual void reset(); // +0x028 - virtual void updateBotVehicle(bool* out); // +0x02C [FRONTIER] - virtual void updateBot(); // +0x030 [FRONTIER] + virtual bool updateBotVehicle(bool* out); // +0x02C + virtual bool updateBot(); // +0x030 ELF 0x18BF50 virtual BotSquad* getBotSquad() const; // +0x034 virtual float getObedience(); // +0x038 virtual float* getCurrentOrders(); // +0x03C order weights virtual WaypointList* getWaypoints(); // +0x040 - virtual void setWaypoints(WaypointList* w); // +0x044 [FRONTIER] + virtual void setWaypoints(WaypointList* w); // +0x044 virtual bool recieveOrder(BotOrder* order); // +0x048 - virtual void recieveOrder(BotOrder* order, std::list& targets); // +0x04C [FRONTIER] + virtual bool recieveOrder(BotOrder* order, std::list& targets); // +0x04C (ELF answers 0/1) virtual std::list* getOrderList(unsigned char behaviour); // +0x050 virtual bool hasPlan(); // +0x054 virtual bool hasDefaultPlan() const; // +0x058 @@ -232,28 +260,28 @@ class BotMain : public Bot virtual void setPlanLock(bool b); // +0x06C virtual bool isTakingOrders(); // +0x070 virtual bool isOrderedBehaviour(unsigned char behaviour); // +0x074 - virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b); // +0x078 [FRONTIER] + virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b); // +0x078 virtual void setFiringTarget(unsigned int handle); // +0x07C [FRONTIER] virtual unsigned int getFiringTarget() const; // +0x080 virtual double getFiringTargetTime() const; // +0x084 virtual SensingAgent* getSensingAgent(); // +0x088 - virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c); // +0x08C [FRONTIER] - virtual const std::vector& getSensedObjects() const; // +0x090 [FRONTIER] - virtual void* getSensedObjectFromHandle(unsigned int handle) const; // +0x094 [FRONTIER] + virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c); // +0x08C + virtual const std::map& getSensedObjects() const; // +0x090 + virtual SensedObject* getSensedObjectFromHandle(unsigned int handle) const; // +0x094 virtual void setUnresolvedCollisionObject(unsigned int handle); // +0x098 virtual unsigned int getUnresolvedCollisionHandle(); // +0x09C - virtual void* getIncommingFire(); // +0x0A0 [FRONTIER] - virtual float getIncommingFireTotalStrength(); // +0x0A4 [FRONTIER] - virtual float getIncommingFireTotalStrengthAgainstSelf(); // +0x0A8 [FRONTIER] - virtual float getAttackerStrength() const; // +0x0AC [FRONTIER] + virtual std::list >* getIncommingFire(); // +0x0A0 + virtual float getIncommingFireTotalStrength(); // +0x0A4 + virtual float getIncommingFireTotalStrengthAgainstSelf(); // +0x0A8 + virtual float getAttackerStrength() const; // +0x0AC virtual CommunicationAgent* getCommunicationAgent(); // +0x0B0 virtual int getPlayerId() const; // +0x0B4 - virtual int getInputId(); // +0x0B8 [FRONTIER] + virtual int getInputId(); // +0x0B8 virtual IAIPlayer* getPlayer() const; // +0x0BC virtual void updatePlayerAction(bool stalled); // +0x0C0 virtual bool isDead() const; // +0x0C4 - virtual bool setSide(int side); // +0x0C8 equipment arm [FRONTIER] - virtual void setName(const std::string& name); // +0x0CC [FRONTIER] + virtual bool setSide(int side); // +0x0C8 + virtual void setName(const std::string& name); // +0x0CC virtual bool isDeactivated() const; // +0x0D0 virtual void setAsDeactivated(bool b); // +0x0D4 virtual unsigned int getCurrentEquipment() const; // +0x0D8 @@ -262,17 +290,17 @@ class BotMain : public Bot virtual int getBotType() const; // +0x0E4 virtual unsigned int getBotId() const; // +0x0E8 virtual BotMemory* getMemory(); // +0x0EC - virtual const std::string& getName() const; // +0x0F0 [FRONTIER] - virtual void setTimeOfLastGrenadeThrown(double t); // +0x0F4 [FRONTIER] + virtual const std::string& getName() const; // +0x0F0 + virtual void setTimeOfLastGrenadeThrown(double t); // +0x0F4 virtual double getTimeOfGrenadeThrown(int i) const; // +0x0F8 virtual BotNavigation* getBotNavigation(); // +0x0FC virtual int getSpawnPoint() const; - virtual int getSpawnKit() const; // +0x104 [FRONTIER] - virtual void getSpawnTarget(int& a, int& b) const; // +0x108 [FRONTIER] + virtual int getSpawnKit() const; // +0x104 + virtual void getSpawnTarget(int& a, int& b) const; // +0x108 virtual void setSpawnTarget(int spawnGroup, int kit); virtual void setSpawnTarget(int strategicArea, int spawnGroup, int kit); // +0x110 virtual int getSpawnToStrategicAreaId(); // +0x114 - virtual bool isJustSpawned(); // +0x118 [FRONTIER] + virtual bool isJustSpawned(); // +0x118 virtual IBotDeathCallBack* getDeathCallBack() const; // +0x11C virtual void setDeathCallBack(IBotDeathCallBack* cb); // +0x120 virtual IBotSpawnCallBack* getSpawnCallBack() const; // +0x124 @@ -285,33 +313,33 @@ class BotMain : public Bot virtual SquadMember* getSquadMember(); // +0x140 virtual bool isBotStuck(); // +0x144 virtual void setBotStuck(bool b); // +0x148 - virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o); // +0x14C [FRONTIER] + virtual void placeC4(int placementType, Vec3 v, AIStrategicObject* o); // +0x14C virtual bool isC4Placed(); // +0x150 - virtual void removeC4(); // +0x154 [FRONTIER] - virtual void* getC4(); // +0x158 [FRONTIER] - virtual void updateC4(); // +0x15C [FRONTIER] + virtual void removeC4(); // +0x154 + virtual C4State getC4(); // +0x158 + virtual void updateC4(); // +0x15C virtual void enableBotScriptDebugger(bool /*enable*/); // +0x160 virtual void* getDebugger(); // +0x164 // Inherits Bot::getScriptContext; do not add a derived override for that slot. - virtual void event_projectile(FireObject* f, unsigned int h); // +0x16C [FRONTIER] - virtual void event_shotHit(int i, world::IObject* o, const Vec3& v); // +0x170 [FRONTIER] - virtual void event_shotMissed(int i, const Vec3& v); // +0x174 [FRONTIER] - virtual void event_heardObject(unsigned int h); // +0x178 [FRONTIER] + virtual void event_projectile(FireObject* f, unsigned int h); // +0x16C + virtual void event_shotHit(int i, world::IObject* o, const Vec3& v); // +0x170 + virtual void event_shotMissed(int i, const Vec3& v); // +0x174 + virtual void event_heardObject(unsigned int h); // +0x178 virtual bool isInTransitionPhase() const; // +0x17C virtual void setIsInTransitionPhase(bool b); // +0x180 virtual void addToMoveInclination(float f); // +0x184 virtual void addToFireInclination(float f); // +0x188 virtual float getMoveInclination(); // +0x18C virtual float getFireInclination(); // +0x190 - virtual void requestSoldierPose(int pose, bool b); // +0x194 [FRONTIER] + virtual void requestSoldierPose(int pose, bool b); // +0x194 virtual int getRequestedSolderPose(); // +0x198 - virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b); // +0x19C [FRONTIER] - virtual void event_airborn(); // +0x1A0 [FRONTIER] + virtual void setPoseStatus(int pose, unsigned int h, bool a, bool b); // +0x19C + virtual void event_airborn(); // +0x1A0 virtual bool isAirBorn() const; // +0x1A4 virtual void setLastChangeTime(double t); // +0x1A8 virtual void setManDown(bool b); // +0x1AC virtual bool getManDown() const; // +0x1B0 - virtual void rearm(Information* i); // +0x1B4 [FRONTIER] + virtual void rearm(Information* i); // +0x1B4 virtual void setChangeTarget(unsigned int h); // +0x1B8 virtual unsigned int getChangeTarget() const; // +0x1BC virtual void setRepairTarget(unsigned int h); // +0x1C0 @@ -331,10 +359,10 @@ class BotMain : public Bot virtual void setMineTarget(unsigned int h); // +0x1F8 virtual unsigned int getMineTarget() const; // +0x1FC virtual void setNewAssignedAreas(int a, int b); // +0x200 - virtual bool hasSameAssignedAreas(int a); // +0x204 [FRONTIER] + virtual bool hasSameAssignedAreas(int a); // +0x204 virtual void copyAssignedAreas(); // +0x208 - virtual void setCurrentWaypoint(Vec3 v, int i); // +0x20C [FRONTIER] - virtual const Vec3& getCurrentWaypoint(); // +0x210 [FRONTIER] + virtual void setCurrentWaypoint(Vec3 v, int i); // +0x20C + virtual Vec3 getCurrentWaypoint(); // +0x210 by value (ELF sret) virtual void resetAssignedAreas(); // +0x214 virtual void setTimeOfLastFailedStaticSkyAttack(double t); // +0x218 virtual double getTimeOfLastFailedStaticSkyAttack() const; // +0x21C @@ -344,13 +372,13 @@ class BotMain : public Bot virtual bool getBotWantsToSimulateArtillery() const; // +0x22C virtual void setBotIsSimulatingArtillery(bool b); // +0x230 virtual bool getBotIsSimulatingArtillery() const; // +0x234 - virtual void setAvoidSide(int side); // +0x238 [FRONTIER] + virtual bool setAvoidSide(int side); // +0x238 (ELF answers 0/1) virtual int getAvoidSide() const; // +0x23C virtual int getMoveToStatus() const; // +0x240 - virtual void setMoveToStatus(int status); // +0x244 [FRONTIER] + virtual void setMoveToStatus(int status); // +0x244 virtual void setCollidedObject(unsigned int h); // +0x248 virtual unsigned int getCollidedObject() const; // +0x24C - virtual void setCollidedObjectPosition(const Vec3& v); // +0x250 [FRONTIER] + virtual void setCollidedObjectPosition(const Vec3& v); // +0x250 virtual const Vec3& getCollidedObjectPosition() const; // +0x254 virtual void setIgnoreObstacles(bool b); // +0x258 virtual bool getIgnoreObstacles() const; // +0x25C @@ -362,17 +390,17 @@ class BotMain : public Bot virtual double getLastCheckMoveToFinishedTime() const; // +0x274 virtual void setIsGoingForFlag(bool b); // +0x278 virtual bool getIsGoingForFlag() const; // +0x27C - virtual bool botInPoseTransition() const; // +0x280 [FRONTIER] + virtual bool botInPoseTransition() const; // +0x280 virtual void setUseStaticAttack(bool b); // +0x284 virtual bool getUseStaticAttack() const; // +0x288 virtual void setTimeOfLastFailedSplashDamageAttack(double t); // +0x28C virtual double getTimeOfLastFailedSplashDamageAttack() const; // +0x290 - virtual void setTakeOffPosition(const Vec3& v); // +0x294 [FRONTIER] + virtual void setTakeOffPosition(const Vec3& v); // +0x294 virtual const Vec3& getTakeOffPosition() const; // +0x298 - virtual void setQuadSeen(); // +0x29C [FRONTIER] - virtual bool isAttacking(unsigned int handle, double& out) const; // +0x2A0 [FRONTIER] - virtual void event_shotTimeOut(int i); // +0x2A4 [FRONTIER] - virtual void event_firing(bool& b, int i, const Vec3& v); // +0x2A8 [FRONTIER] + virtual void setQuadSeen(); // +0x29C + virtual bool isAttacking(unsigned int handle, double& out) const; // +0x2A0 + virtual void event_shotTimeOut(int i); // +0x2A4 + virtual const Vec3& event_firing(bool& b, int i, const Vec3& v); // +0x2A8 returns the record's +56 Vec3 // not in the vtable. Ordinary members; the vtable dump above is the authority on which // every name here is absent from all 171 slots. @@ -382,8 +410,12 @@ class BotMain : public Bot void removeBehaviour(BotBehaviour* b); void uninitAllBehaviours(); BotBehaviour* getActiveBehaviour(); - UrgencyGenerator** getBehaviourUrgencyGenerators(); + UrgencyGenerator** getBehaviourUrgencyGenerators(); // ELF 0x18AAD0: +152 + UrgencyGenerator* getSelector(); // ELF 0x18AAC0: +148 void calculateMods(); + unsigned char getMode(); + void setMode(unsigned char mode); + float getLastScout(); float* getBasicBehaviourMods(); float* getCurrentBehaviourMods(); // these two touch the class static, not A member. See the header. @@ -394,6 +426,11 @@ class BotMain : public Bot void setTakingOrders(bool b); PlanInterpreter* getPlanInterpreter(); void setPlanInterpreter(PlanInterpreter* p); + void setHadPrecisionTimeStamp(double time); // ELF 0x18C7D0: +276 + double getHadPrecisionTimeStamp() const; + // [INFERRED] inline reader (no symbol): +180 is read inline by BAPAAimAt::correctAim 0x1CDA3D and + // EntryMouseTurretAimAt 0x2B9A5C. Added by ai-w1-c-actions (requested from ai-bot). + FireCorrectionData* getFireCorrection() const { return m_fireCorrection; } double getTimeOfLastFire() const; void stepFireInclination(); // thunk void* getAttackers() const; @@ -401,17 +438,29 @@ class BotMain : public Bot // initialises. The old note that one of the two pairs was +576 is settled. const Vec3& getSpawnCoord() const; void setSpawnCoord(const Vec3& v); - void setObedience(float f); + const Vec3& getLookDir(); + void setLookDir(const Vec3& direction); + float setObedience(float f); float getAttention(); - void setAttention(float f); + float setAttention(float f); float getInvAttention(); - void setInvAttention(float f); + float setInvAttention(float f); // ELF 0x18AB80: stores and returns the supplied value float getMarksmanship(); // no setter - float getHarmlessThrsh(); // no setter, dice's spelling + int getHarmlessThrsh(); // ELF 0x18ABA0: +0x28 (cvtsi2ss at the caller); no setter, dice's spelling void setPlayer(IAIPlayer* p); void setPlayerInput(); - void resetAllControls(bool a, bool b, bool c); // [FRONTIER] - void validateDataStructures(); + void resetAllControls(bool a, bool b, bool c); + // Ask the next action to re-check the bot's vehicle (+0x58 m_checkVehicle). + void setUpdateCurrentEquipment(); // ELF 0x18A9F0 + bool getUpdateCurrentEquipment(); // ELF 0x18AA00 + void resetChangeTarget(); + void pollRequestedSoldierPose(); + bool checkPoseOk(bool& out, int pose); + void clearTestResults(); + void stepMoveInclination(); + void clearMoveInclination(); + void clearFireInclination(); + bool validateDataStructures(); // A class static, shared by every bot. See the header - the constructor reads it three times. static unsigned char mu8NBehaviours; static float* maBasicWeights; // ELF .bss @@ -419,6 +468,13 @@ class BotMain : public Bot private: // [INFERRED] friendship: addUnspawnedBot directly replaces +28 in both images. friend class BotManager; + // [INFERRED] friendship: SensingAgent::quadInFocus (ELF 0x1BDA60) reads +0x9C (m_player) inline. + friend class SensingAgent; + // [INFERRED] friendship: the WPBeachLanding constructors (ELF 0x1B8370, 0x1B8470) store their + // landing zone into +0xE8 (m_ptr232) through the Bot pointer. + friend class WPBeachLanding; + // ELF 0x1EEB90 reads the landing-zone pointer written by WPBeachLanding. + friend class BAPConObjectInLandingZone; // [CHOSEN] Names for fields whose original identifiers are unavailable. Offsets describe the retail x86 layout. /* 12 */ void* m_debugger; // = 0 getDebugger /* 16 */ BotLodLevel m_lodLevel; // = 0 get/setLodLevel @@ -431,26 +487,32 @@ class BotMain : public Bot /* 40 */ int m_int40; // ctor arg `i` [UNRESOLVED] /* 44 */ int m_side; // ctor arg `n` getSide /* 48 */ float m_float48; // = 0.01f [UNRESOLVED] a small threshold - /* 52 */ void* m_ptr52; // = 0 + /* 52 */ float m_inverseAttention; // = 0; get/setInvAttention /* 56 */ BotSquad* m_squad; // new(0xC) /* 60 */ int m_spawnToStrategicAreaId;// = -1 getSpawnToStrategicAreaId - /* 64 */ char m_gap64[4]; // +64 byte set to -1 [UNRESOLVED] + /* 64 */ unsigned char m_mode; // = 0xFF + /* 65 */ char m_pad65[3]; /* 68 */ float* m_currentOrders; // borrowed BotOrder weights, not the order object /* 72 */ float* m_ptr72; // = 0; per-behaviour modifiers in calculateMods /* 76 */ BotMemory* m_memory; // Borrowed; construction also initializes its first word and +16 double. /* 80 */ bool m_takingOrders; // isTakingOrders /* 81 */ char m_pad81[3]; - /* 84 */ void* m_ptr84; // = 0 - /* 88 */ char m_gap88[3]; // +89, +90 zeroed [UNRESOLVED] + /* 84 */ float m_lastScout; // = 0 + // decisionMaking (ELF 0x1893D0): +88 the equipment must be re-checked against the player's + // vehicle, +89 the last vehicle check failed ("Bot in bad vehicle!"), +90 updateBotVehicle + // asks for a fresh plan. The ctor zeroes +89/+90 only. [CHOSEN] names. + /* 88 */ bool m_checkVehicle; + /* 89 */ bool m_badVehicle; + /* 90 */ bool m_vehicleChanged; /* 91 */ bool m_inTransitionPhase; // isInTransitionPhase /* 92 */ char m_pad92; /* 93 */ bool m_deactivated; // isDeactivated /* 94 */ char m_pad94[2]; // Parallel per-behaviour arrays: scalar urgency values and behaviour pointers. /* 96 */ float* m_behaviourUrgencies; // new[] sized by mu8NBehaviours - one per behaviour - /* 100 */ void* m_ptr100; // = 0 - /* 104 */ void* m_ptr104; // = 0 - /* 108 */ void* m_ptr108; // = 0 + // Behaviour indices queued by urgency group (BotBehaviour +5); addBehaviour grows it and + // decisionMaking rotates it. ELF `std::vector >` (12 bytes). + /* 100 */ std::vector > m_behaviourQueues; // ctor: empty /* 112 */ BotBehaviour** m_behaviours; // new[] sized by mu8NBehaviours, zero-filled. // Owns the active BotScript. reset destroys it virtually and clears the pointer. /* 116 */ BotScript* m_activePlan; // Initially null; get/setPlan access it. @@ -468,9 +530,7 @@ class BotMain : public Bot /* 148 */ UrgencyGenerator* m_urgencyMerger; // ctor arg `merger` /* 152 */ UrgencyGenerator** m_urgencyGenerators;// ctor arg `generators` /* 156 */ IAIPlayer* m_player; // ctor arg; getPlayer reads it - /* 160 */ void* m_ptr160; // = 0 (written twice - before and after - /* 164 */ void* m_ptr164; // setPlayerInput; see the .cpp) - /* 168 */ void* m_ptr168; // = 0 + /* 160 */ Vec3 m_lookDir; // zeroed before and after setPlayerInput // reset clears this double before the other fields. /* 172 */ double m_double172; // reset: 0.0 /* 180 */ FireCorrectionData* m_fireCorrection; // new(0x80) @@ -491,7 +551,7 @@ class BotMain : public Bot /* 226 */ bool m_shouldWaitForRepairs; // reset: false /* 227 */ char m_pad227; /* 228 */ unsigned int m_mineTarget; // = -1 - /* 232 */ void* m_ptr232; // = 0 + /* 232 */ void* m_ptr232; // = 0; WPBeachLanding stores its AILandingZone* /* 236 */ float m_moveInclination; // = 0 /* 240 */ float m_fireInclination; // = 0 /* 244 */ float m_moveInclinationDelta; // = 1.0f addToMoveInclination accumulates here @@ -501,19 +561,28 @@ class BotMain : public Bot /* 260 */ void* m_ptr260; // = 0 /* 264 */ unsigned int m_firingTarget; // = -1 /* 268 */ double m_firingTargetTime; // getFiringTargetTime - /* 276 */ double m_time276; // = -DBL_MAX - "never happened" + /* 276 */ double m_time276; // = -DBL_MAX - "never happened"; setHadPrecisionTimeStamp /* 284 */ bool m_botStuck; // = false - /* 285 */ bool m_flag285; // = false + // pollRequestedSoldierPose (ELF 0x18CEE0): a pose input is held this tick; requestSoldierPose + // refuses an unforced change while it is set. [CHOSEN] name. + /* 285 */ bool m_poseInputActive; // = false /* 286 */ char m_pad286[2]; // Construction uses -DBL_MAX as the timestamp sentinel; reset uses -9999.0. - /* 288 */ double m_time288; // ctor: -DBL_MAX, reset: -9999.0 + // When pollRequestedSoldierPose last pressed lie/crouch; botInPoseTransition is 0.8 s after it. + /* 288 */ double m_poseChangeTime; // ctor: -DBL_MAX, reset: -9999.0 /* 296 */ int m_requestedSoldierPose; // = 1 dice spells the getter "Solder" - /* 300 */ bool m_flag300[4]; // +300..+303, all false - /* 304 */ int m_int304; // = -1 + // setPoseStatus / checkPoseOk / clearTestResults: [0],[1] crouch, [2],[3] lie. + /* 300 */ bool m_poseTestResults[4]; // +300..+303, all false + // the firing target the pose tests were made against (setPoseStatus); -1 = none. + /* 304 */ int m_poseTestTarget; // = -1 /* 308 */ unsigned int m_unresolvedCollision; // = -1 /* 312 */ bool m_airBorn; // = false isAirBorn - /* 313 */ char m_pad313[3]; - /* 316 */ void* m_ptr316[3]; // +316..+324, all = 0 + // isJustSpawned (ELF 0x18BB80) sets this byte while the player is dead and clears it on the + // first alive call. [CHOSEN] name. + /* 313 */ bool m_spawnPending; + /* 314 */ char m_pad314[2]; + // get/setSpawnCoord (ELF 0x18BBD0 / 0x18BBE0) return and copy this Vec3. + /* 316 */ float m_spawnCoord[3]; // +316..+324, all = 0 /* 328 */ IBotDeathCallBack* m_deathCallBack; // = 0 /* 332 */ IBotSpawnCallBack* m_spawnCallBack; // = 0 /* 336 */ char m_gap336[4]; // [UNRESOLVED] @@ -523,7 +592,8 @@ class BotMain : public Bot /* 360 */ bool m_manDown; // get/setManDown /* 361 */ char m_pad361[3]; // A double, found by `reset`. The old 12-byte gap swallowed it. - /* 364 */ double m_double364; // reset: 0.0 + // rearm (ELF 0x18D7D0) accumulates the time increase here and rearms past 6 s. + /* 364 */ double m_rearmTimer; // reset: 0.0 /* 372 */ bool m_isFiring; // isFiring / setIsFiring /* 373 */ char m_pad373[3]; /* 376 */ SquadMember* m_squadMember; // = 0 @@ -531,18 +601,15 @@ class BotMain : public Bot /* 381 */ char m_pad381[3]; // four, and the second pair is A copy of the first - see copyAssignedAreas. /* 384 */ int m_assignedAreas[4]; // +384..+396, all = -1 - /* 400 */ void* m_ptr400; // = 0 - /* 404 */ void* m_ptr404; // = 0 - /* 408 */ void* m_ptr408; // = 0 - /* 412 */ int m_int412; // = -1 + /* 400 */ float m_currentWaypoint[3]; // = 0 (three zero stores); a Vec3 - set/getCurrentWaypoint + /* 412 */ int m_int412; // = -1; setCurrentWaypoint's int // [INFERRED] Consecutive plan-executor skips, cleared when execution resumes. // A signed comparison against 15 decides when a stalled bot stops coasting. /* 416 */ int m_stalledPlanTicks; // = 0 - /* 420 */ bool m_c4Placed; // = false - the ctor's last field store - /* 421 */ char m_pad421[7]; - /* 428 */ void* m_ptr428[3]; // +428..+436, all = 0 - /* 440 */ char m_gap440[20]; // [UNRESOLVED] + // +420..+459: placed (= false, the ctor's last field store), type, position (+428..+436, the + // ctor zeroes it), object, placed time, life time. + /* 420 */ C4State m_c4; // Three grenade timestamps. getTimeOfGrenadeThrown requires an index in [0, 3); // it performs no bounds check and larger indices read adjacent attack timestamps. /* 460 */ double m_grenadeThrownTime[3]; // +460, +468, +476 @@ -550,12 +617,14 @@ class BotMain : public Bot /* 492 */ double m_timeOfLastFailedStaticSkyAttack; // = 0.0 /* 500 */ bool m_wantsToSimulateArtillery; // = false /* 501 */ bool m_isSimulatingArtillery; // = false - /* 502 */ bool m_flag502; // = false [UNRESOLVED] + // requestSoldierPose(pose, true) sets it; pollRequestedSoldierPose clears it every call. + /* 502 */ bool m_forcePose; // = false [UNRESOLVED] /* 503 */ char m_pad503; /* 504 */ int m_moveToStatus; // = 0 /* 508 */ int m_avoidSide; // = 0 - /* 512 */ char m_gap512[4]; // +512 byte = 0 - /* 516 */ double m_double516; // = 0.0 + /* 512 */ bool m_avoidSideChanged; // +512 byte = 0; setAvoidSide: switched between two non-zero sides [INFERRED] + /* 513 */ char m_pad513[3]; + /* 516 */ double m_double516; // = 0.0; setMoveToStatus: the game time of the last status change /* 524 */ unsigned int m_collidedObject; // = -1 /* 528 */ float m_collidedObjectPosition[3]; // a Vec3 - getCollidedObjectPosition /* 540 */ bool m_ignoreObstacles; // = false @@ -567,10 +636,6 @@ class BotMain : public Bot /* 565 */ bool m_useStaticAttack; // = false /* 566 */ char m_pad566[2]; /* 568 */ double m_timeOfLastFailedSplashDamageAttack; // = -9999.0 - // The last field. `Vec3::getZero` is copied in component by component. `getLookDir` - // `setLookDir` and `getSpawnCoord` / `setSpawnCoord` have identical shapes - // so one of the two pairs is this field and the other is a Vec3 the ctor never initialises. - // [UNRESOLVED] which; reading either 56-byte setter settles it in one step. /* 576 */ float m_takeOffPosition[3]; // Vec3, = Vec3::getZero }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp index d81aa9862..6df5267d8 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.cpp @@ -1,10 +1,13 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotMemory operations. #include "BotMemory.h" -#include "../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x18F320, __tcf_0 0x18F380, _GLOBAL__I 0x18F3B0). +#include + +#include "../AIBotBehaviour/BotBehaviour.h" +#include "../AIBotBehaviour/UrgeCurve.h" namespace dice { namespace hfe { @@ -26,14 +29,26 @@ BotMemory::~BotMemory() { } +// ELF 0x18F2A0: the constructor's four stores again, in the image's order +// (+4 = -1, +0xC = 1, +8 = 1.0f from GOT-0x16598 -> 0x49CB2C 0x3F800000, +0 = -1). +// m_double16 is not touched. void BotMemory::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::BotMemory::reset"); + m_int4 = -1; + m_int12 = 1; + m_float8 = 1.0f; + m_int0 = -1; } -void BotMemory::modifyBehaviourUrgency(BotBehaviour*, double) +// ELF 0x18F2D0: for the remembered behaviour (index byte +4 == m_int0) the behaviour's urge +// curve (+0x20, vtable +8 calculate) is evaluated at (float)(time - m_double16) +// (`fldl 0x10(%ebp); fsubl 0x10(%ecx); fstps`); any other behaviour gets 1.0f +// (`flds -0x16598(%ebx)`, 0x49CB2C = 0x3F800000). +float BotMemory::modifyBehaviourUrgency(BotBehaviour* behaviour, double time) { - BF2_AI_FRONTIER("dice::hfe::ai::BotMemory::modifyBehaviourUrgency"); + if (static_cast(behaviour->getIndex()) == m_int0) + return behaviour->getUrgeCurve()->calculate(static_cast(time - m_double16)); + return 1.0f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h index 1d1fe802d..78d2af29f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMemory.h @@ -16,9 +16,9 @@ class BotMemory BotMemory(); ~BotMemory(); - void reset(); // [FRONTIER] - // Adjusts the urgency assigned to behaviour by amount. - void modifyBehaviourUrgency(BotBehaviour* behaviour, double amount); // [FRONTIER] + void reset(); + // ELF 0x18F2D0 returns a float (x87 st0): the urgency factor for behaviour at time. + float modifyBehaviourUrgency(BotBehaviour* behaviour, double time); // Retail x86 field offsets. /* 0 */ int m_int0; // = -1 and BotMain writes it again from outside diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp index 541cb8489..b308e220f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp @@ -3,30 +3,56 @@ #include "BotNavigation.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x195420, __tcf_0 0x195480, _GLOBAL__I 0x1954B0). +#include + #include "BotMain.h" // getBotId / getCurrentEquipment - vtable +0xE8, +0xD8 #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" +#include "../Main/IAIPathfinding.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPathFinding/NavMesh/QuadTree.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::isParachuting +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Core/Debug.h" +#include namespace dice { namespace hfe { namespace ai { +namespace { + +// [CHOSEN, not recovered] the image's inlined sqrt of a squared length (with its sqrtf retry). +inline float length3(float x, float y, float z) +{ + return std::sqrt(x * x + y * y + z * z); +} + +} // namespace + // Creates navigation paths and initializes movement state for the supplied bot. BotNavigation::BotNavigation(BotMain* owner) : m_bot(owner) - , m_float4(2.0f) + , m_arriveDistance(2.0f) , m_float8(2.0f) - , m_int16(-1) - , m_int20(-1) - , m_int36(-1) - , m_flag40(false) + , m_island(-1) + , m_startPolygon(-1) + , m_goalPolygon(-1) + , m_goalMaterial(0) // the two paths, in the order the binary builds them: the fine one first. , m_polygonPath(checkPointer(new QTPath())) , m_int76(-1) - , m_int116(0) + , m_currentPoint(0) , m_clusterPath(checkPointer(new ClusterNodePath())) , m_int128(-1) , m_double144(0.0) @@ -38,44 +64,56 @@ BotNavigation::BotNavigation(BotMain* owner) , m_flag192(false) , m_flag193(false) , m_flag195(false) - , m_int200(-1) - , m_int204(-1) - , m_int208(-1) - , m_int212(-1) + , m_vehiclePolygon(-1) + , m_vehicleIsland(-1) + , m_infantryPolygon(-1) + , m_infantryIsland(-1) , m_int240(0) - , m_double268(0.0) - , m_flag276(false) + , m_grenadeTime(0.0) + , m_grenadeFlag(false) // Independent sentinel, initialized to -1.0. , m_double300(-1.0) { for (int i = 0; i < 3; ++i) { - m_zero24[i] = 0; - m_zero44[i] = 0; - m_zero88[i] = 0; m_zero176[i] = 0; - m_zero216[i] = 0; - m_zero256[i] = 0; - } - m_pathOwner = 0; // +60 - a pointer, see BotNavigation.h - m_zero64 = 0; - m_zero308[0] = 0; - m_zero308[1] = 0; - for (int i = 0; i < 5; ++i) + } + m_tracePosition.x = 0.0f; + m_tracePosition.y = 0.0f; + m_tracePosition.z = 0.0f; + m_grenadePosition.x = 0.0f; m_grenadePosition.y = 0.0f; m_grenadePosition.z = 0.0f; + m_startPosition.x = 0.0f; m_startPosition.y = 0.0f; m_startPosition.z = 0.0f; + m_goal.x = 0.0f; m_goal.y = 0.0f; m_goal.z = 0.0f; + m_pathfinding = 0; // +60 + m_quadTree = 0; + m_largestAngleDiff = 0.0f; + m_pathLength = 0.0f; + for (int i = 0; i < 3; ++i) m_zero280[i] = 0; - for (int i = 0; i < 6; ++i) - m_zero320[i] = 0; + m_spaceLeft = 0; + m_spaceRight = 0; + m_searchStart.x = 0.0f; // +320..+340 + m_searchStart.y = 0.0f; + m_searchStart.z = 0.0f; + m_searchGoal.x = 0.0f; + m_searchGoal.y = 0.0f; + m_searchGoal.z = 0.0f; // the dead resize - see the block above. Written as what it is rather than dropped. m_points.resize(0); } -// [FRONTIER] Remaining navigation operations stop until implemented. // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x18FF30: reset (releases the search resources), then the two owned paths; the set and the +// two vectors are members. BotNavigation::~BotNavigation() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::~BotNavigation"); + reset(); + if (m_polygonPath) + delete m_polygonPath; + if (m_clusterPath) + delete m_clusterPath; } // Resets navigation, movement flags and progress timing. @@ -84,37 +122,30 @@ void BotNavigation::resetAll() reset(); m_int252 = 0; - m_flag276 = false; + m_grenadeFlag = false; // Not the constructor's 0.0 - see the block above. - m_double268 = -9999.0; - m_zero308[0] = 0; + m_grenadeTime = -9999.0; + m_largestAngleDiff = 0.0f; m_double300 = -1.0; clearProgress(); } -// Resets navigation state and returns path resources to their owners. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Incomplete resource paths stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate path release and progress reset. -// [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. +// ELF 0x190A70. Releases both search slots, empties the paths and points, and re-reads the +// equipment's last valid positions. void BotNavigation::reset() { m_flag316 = false; - // giving the polygon path back. See the block above. - if (m_int76 != -1) + if (m_int76 != 0xFFFFFFFFu) { - // Retail: `m_pathOwner->release(&m_int76, m_bot->getBotId)`. The bot half is typed now; - // the object at +60 still has no class, so the slot cannot be. - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::reset (a polygon path is reserved)"); - m_int76 = -1; + m_pathfinding->releaseResource(m_int76, m_bot->getBotId()); // slot +0x9C + m_int76 = 0xFFFFFFFFu; } - - // and the cluster path, through a different slot on the same object. - if (m_int128 != -1) + if (m_int128 != 0xFFFFFFFFu) { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::reset (a cluster path is reserved)"); - m_int128 = -1; + m_pathfinding->releaseClusterResource(m_int128, m_bot->getBotId()); // slot +0xA4 + m_int128 = 0xFFFFFFFFu; } // Reaching through both path objects - see the block above. @@ -130,29 +161,33 @@ void BotNavigation::reset() m_points.resize(0); m_int240 = 0; - m_int116 = 0; + m_currentPoint = 0; m_double160 = 0.0; m_flag195 = false; m_flag193 = false; m_flag194 = false; m_double244 = 0.0; - // Resolves the bot's current equipment handle; skips equipment work when it has no object. - const unsigned int equipment = m_bot->getCurrentEquipment(); - Information* const info = informationManager->getPool()->get(equipment); + // the equipment's last valid positions (no mobile plug-in: unchanged) + Information* const info = informationManager->getPool()->get(m_bot->getCurrentEquipment()); if (info) { - // Retail: `IPIMobile* m = info->m_mobile56; if (m) { m_int80 = m->getVehicleNumber; - // const Vec* p = m->getLastValidPosition(m_int80); m_int200 = p[0]; ... }` - // `Information` and `IPIMobile` are both unrecovered - `Information` is a forward - // declaration behind the handle pool and `IPIMobile` is not in this tree at all. - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::reset (the bot has equipment)"); + IPIMobile* const mobile = info->getMobile(); + if (mobile) + { + m_mapIndex = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& vehicle = mobile->getLastValidPosition(m_mapIndex); + m_vehicleIsland = static_cast(vehicle.quadTree); + m_vehiclePolygon = static_cast(vehicle.polygon); + m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().quadTree); + m_infantryPolygon = static_cast(mobile->getLastValidInfantryPos().polygon); + } } // The sentinel is the interesting one - see the block above. m_sentinel188 = 9999999.0f; - m_zero280[3] = 0; - m_zero280[4] = 0; + m_spaceLeft = 0; + m_spaceRight = 0; } // Clears progress counters and restarts the progress timer at the current game time. @@ -178,19 +213,1113 @@ void BotNavigation::clearProgress() // [FRONTIER] Obstacle updates for living, standing bots are not implemented. // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] // Replace the stop when the corresponding navigation behavior is recovered. +namespace { + +// ELF 0x197560 (vtable 0x4b6c38): a primary object with a mobile plug-in (+0x38), or any +// information whose type flags carry bit 25 (`testb $0x2,0x7(info)`). +class MobileOrObstaclePredicate : public IAIInformationGridPredicate +{ +public: + virtual bool includeInformation(Information* information) const + { + return (information->isPrimary() && information->hasMobile()) + || (information->getObjectTypeFlags() & 0x02000000) != 0; + } +}; + +} // namespace + +// ELF 0x194B60 (399 bytes). The obstacle list is emptied, then filled from both grids (the +// bool argument 1, then 0) within 50 m of the equipment's position for the bot's side. +// No null guard on the equipment information. void BotNavigation::updateObstacles() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::updateObstacles"); + m_obstacles.resize(0); + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = equipment->getPosition(); + MobileOrObstaclePredicate predicate; + const IAIInformationEnvironment* const environment = + static_cast(AISingletonServer::m_iaiInformationEnvironment); + environment->getObjectsWithinRadius(m_obstacles, position, 50.0f, m_bot->getSide(), true, &predicate); + environment->getObjectsWithinRadius(m_obstacles, position, 50.0f, m_bot->getSide(), false, &predicate); + m_int252 = static_cast(m_obstacles.size()); } +// ELF 0x194E40. Empty in the shipped dedicated image. +void BotNavigation::drawPath() +{ +} + +// ELF 0x192160: active for three seconds of game time after +244. bool BotNavigation::isActive() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::isActive"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return now - m_double244 < 3.0; } +// ELF 0x192830 (123 bytes). void BotNavigation::updateOccationally() { - BF2_AI_FRONTIER("dice::hfe::ai::BotNavigation::updateOccationally"); + updateNavPoints(); + updateClosestDistance(); + if (m_int56 == 2) + { + if (hasIllegalPath()) + reset(); + else if (!checkProgress()) + m_flag192 = true; + } + if (m_updateSpaceLeftAndRight) + updateSpaceLeftAndRight(); +} + +// ELF 0x191320 (372 bytes). Without a path owner (+60), or in state 4, there is nothing to +// search. A pending point reset (+195) empties the points and requests a polygon search. +bool BotNavigation::update(bool& a, bool* b) +{ + if (m_pathfinding == 0) + return false; + m_flag316 = false; + if (m_int56 == 4) + return false; + a = false; + if (b) + *b = false; + if (m_flag195) + { + m_points.resize(0); + m_currentPoint = 0; + m_polygonSearchPending = true; + m_flag195 = false; + } + if (m_useClusterSearch) + return doClusterSearch(a, b); + if (!m_polygonSearchPending) + return true; + return doPolygonSearch(a, b); +} + +// ELF 0x1901B0 (256 bytes). Finds the goal's polygon on the equipment's vehicle map, then starts +// the search; without equipment or a polygon nothing is started. +bool BotNavigation::initPathfinding(const Vec3& to, float arriveDistance, float b) +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (info) + { + const int equipmentType = info->getUnit()->getEquipmentType(); + const int vehicle = info->getMobile()->getVehicleNumber(); + unsigned int polygon; + unsigned int island; + if (IAIPathfinding::instance->getPolygon(to, vehicle, polygon, island, equipmentType)) // slot +0x44 + return initPathfinding(island, polygon, to, arriveDistance, b); + } + m_flag193 = false; + return false; +} + +// ELF 0x1902B0 (1744 bytes). The same goal on the same map and equipment keeps the current path +// (one point; the bot's polygon is the current point's; still on the path; or retrace). A new +// search needs the bot within 10 m of its last valid position and on the goal's island. +bool BotNavigation::initPathfinding(unsigned int island, unsigned int goalPolygon, const Vec3& to, + float arriveDistance, float b) +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info) + { + m_flag193 = false; + return false; + } + m_updateSpaceLeftAndRight = (info->getObjectTypeFlags() & 0x00200000) != 0; // byte +6 & 0x20 + if (m_pathfinding == 0) + m_pathfinding = IAIPathfinding::instance; + IPIMobile* const mobile = info->getMobile(); + const IPIMobile::ValidPos& valid = mobile->getLastValidPosition(); + + const bool sameGoal = std::fabs(to.x - m_goal.x) <= 1.1920929e-07f + && std::fabs(to.y - m_goal.y) <= 1.1920929e-07f + && std::fabs(to.z - m_goal.z) <= 1.1920929e-07f; + if (!sameGoal) + clearProgress(); + if (m_flag193 + && std::fabs(m_goal.x - to.x) <= 1.1920929e-07f + && std::fabs(m_goal.y - to.y) <= 1.1920929e-07f + && std::fabs(m_goal.z - to.z) <= 1.1920929e-07f + && m_mapIndex == mobile->getVehicleNumber() + && m_equipmentType == info->getUnit()->getEquipmentType()) + { + if (static_cast(m_int56) < 2) + return true; + if (!m_points.empty() && m_points[m_currentPoint].m_polygon == static_cast(valid.polygon)) + return true; + if (!m_points.empty() && stillOnPath()) + return true; + if (m_points.size() > 1) + { + retrace(); + return true; + } + } + + if (island != 0xFFFFFFFFu && goalPolygon != 0xFFFFFFFFu) + { + m_goalPolygon = static_cast(goalPolygon); + m_goal = to; + if (valid.quadTree != 0xFFFFFFFFu && valid.polygon != 0xFFFFFFFFu) + { + const Vec3& position = info->getPosition(); // Information slot +0x30 + const float dx = position.x - valid.position.x; + const float dy = position.y - valid.position.y; + const float dz = position.z - valid.position.z; + if (dx * dx + dy * dy + dz * dz <= 100.0f) + { + if (island == valid.quadTree) + { + m_polygonSearchPending = true; + m_useClusterSearch = true; + m_flag192 = false; + m_island = static_cast(valid.quadTree); + m_pathIsland = static_cast(valid.quadTree); + m_startPolygon = static_cast(valid.polygon); + m_startPosition = valid.position; + m_arriveDistance = arriveDistance; + m_float8 = b; + m_float8Squared = b * b; + m_mapIndex = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& vehicle = mobile->getLastValidPosition(m_mapIndex); + m_vehicleIsland = static_cast(vehicle.quadTree); + m_vehiclePolygon = static_cast(vehicle.polygon); + m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().quadTree); + m_infantryPolygon = static_cast(mobile->getLastValidInfantryPos().polygon); + m_equipmentType = info->getUnit()->getEquipmentType(); + m_flag195 = false; + m_int240 = 0; + reset(); + m_flag193 = true; + m_radius = info->getPhysical()->getSmallestRadius(); // IPIPhysical slot +0x34 + m_pathfinding->getMaterial(m_mapIndex, island, static_cast(m_goalPolygon), + m_goalMaterial); // slot +0x5C + testDirectPath(); + void* const quadTree = m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_island)); + m_flag316 = true; + m_quadTree = static_cast(quadTree); // slot +0x64 + return true; + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotNavigation.cpp", 0xC4, "") + << "Bot " << m_bot->getName() << " is ordered to go to an island that it is not on (" + << island << " != " << valid.quadTree << ")"; + m_flag193 = false; + return false; + } + } + } + m_flag193 = false; + m_flag192 = true; + return false; +} + +// ELF 0x1920A0 (192 bytes). Once the cluster path is used up and no search is pending, the last +// point follows the bot's last valid position on the path island. +void BotNavigation::updateLastPoint(Information* info) +{ + const ClusterNodePath* const cluster = m_clusterPath; + if (cluster->m_nodes.size() <= static_cast(cluster->m_i0) && !m_useClusterSearch + && !m_polygonSearchPending && static_cast(m_points.size()) > 0) + { + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(m_mapIndex); + if (static_cast(m_pathIsland) == valid.quadTree) + { + NavigationPoint& last = m_points[m_points.size() - 1]; + last.m_position = valid.position; + last.m_polygon = static_cast(valid.polygon); + } + } +} + +// ELF 0x1921B0. A parachuting bot is never stuck. +void BotNavigation::setIsStuck(bool stuck) +{ + if (m_bot->getPlayer()->isParachuting()) // Bot +0xBC, IAIPlayer +0x34 + m_flag192 = false; + else + m_flag192 = stuck; +} + +// ELF 0x192200 (1440 bytes). +bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float distance) +{ + static bool useSkipTrace = false; // ELF 0x4CE00E (.bss) + if (m_flag192) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_double244 = now; + if (!m_flag193) + return false; + arrived = false; + direct = false; + if (static_cast(m_int56) < 2) + m_double244 = 0.0; + if (m_useClusterSearch || m_flag195 || (m_polygonSearchPending && m_points.size() <= m_currentPoint)) + { + direct = true; + return true; + } + + // a soldier firing at an enemy does not walk onto material 4 polygons + Information* const target = informationManager->getInformation(m_bot->getFiringTarget()); + if (!m_points.empty() && m_updateSpaceLeftAndRight && m_bot->isFiring() && target) + { + if (target->getSide() != m_bot->getSide()) + { + const unsigned int polygon = m_points.size() < 2 + ? static_cast(m_goalPolygon) + : static_cast(m_points[m_currentPoint].m_polygon); + unsigned char material; + if (m_pathfinding->getMaterial(m_mapIndex, static_cast(m_pathIsland), polygon, material) + && material == 4) + { + direct = true; + m_double244 = 0.0; + return true; + } + } + } + + if (m_double168 == -666.0) + { + m_bot->getInput()->setInput(static_cast(9), 1.0f); // PIAction + m_double168 = now; + } + + if (checkArrivedAtPoint(distance)) + { + if (m_currentPoint == m_points.size() - 1) + { + m_double244 = 0.0; + m_sentinel188 = 100000000.0f; + clearProgress(); + arrived = true; + } + else + { + ++m_currentPoint; + if (m_int240 > 0) + --m_int240; + } + } + + ClusterNodePath* const cluster = m_clusterPath; + bool trim = true; + if (m_pathLength >= 30.0f && m_currentPoint + 10 < m_points.size()) + { + const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_points[m_currentPoint].m_polygon)); + if (static_cast(polygon->m_cluster) != static_cast(cluster->m_i0)) + { + const Polygon* const again = m_quadTree->getPolygon(static_cast(m_points[m_currentPoint].m_polygon)); + unsigned short current = 0xFFFF; + if (cluster->m_i0 < static_cast(cluster->m_nodes.size())) + current = cluster->m_nodes[cluster->m_i0].first; + if (again->m_cluster != current) + trim = false; + } + } + if (trim && static_cast(cluster->m_i0) + 1 <= cluster->m_nodes.size() && !m_polygonSearchPending) + { + // keep at most ten points ahead and search the rest again + m_polygonSearchPending = true; + unsigned int keep = static_cast(m_points.size()); + if (m_currentPoint + 10 < keep) + keep = m_currentPoint + 10; + m_points.resize(keep, NavigationPoint()); + } + + if (!m_flag195) + { + if (m_int56 != 2 && (!m_polygonSearchPending || static_cast(m_int56) > 1)) + return false; + stillOnPath(); + if (!m_flag194) + { + m_double160 = now; + } + else + { + const float delay = m_updateSpaceLeftAndRight ? 2.0f : 0.5f; + if (static_cast(delay) < now - m_double160) + { + m_flag194 = false; + m_int240 = (useSkipTrace && m_updateSpaceLeftAndRight) ? 1 : 0; + retrace(); + } + } + } + vec3ToVec2XZ(m_points[m_currentPoint].m_position, point); + return true; +} + +// ELF 0x193EC0 (512 bytes). On the path when the bot's last valid polygon is the previous or the +// current point's, or one behind; or within the next 20 points (which becomes the current one). +bool BotNavigation::stillOnPath() +{ + if (m_points.size() < 2) + return false; + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const int polygon = static_cast(info->getMobile()->getLastValidPosition().polygon); + if (polygon == -1) + return false; + const unsigned int current = m_currentPoint; + if (current >= m_points.size()) + return false; + const int previous = current != 0 ? m_points[current - 1].m_polygon : -1; + if (polygon == previous || polygon == m_points[current].m_polygon) + return true; + for (int i = static_cast(current); i >= 0; --i) + if (m_points[i].m_polygon == polygon) + return true; + unsigned int ahead = static_cast(m_points.size()) - current; + if (ahead > 0x14) + ahead = 0x14; + const unsigned int end = ahead + current; + for (unsigned int i = current; i < end; ++i) + { + if (m_points[i].m_polygon == polygon) + { + m_currentPoint = i; + const int left = m_int240 - static_cast(i - current); + m_int240 = left > 0 ? left : 0; + return true; + } + } + return false; +} + +// ELF 0x1910C0 (608 bytes). Restarts from the bot's last valid position on the cluster path: +// at the bot's cluster, or at the first path cluster neighbouring it; otherwise a full reset. +void BotNavigation::retrace() +{ + ClusterNodePath* const cluster = m_clusterPath; + const unsigned int count = static_cast(cluster->m_nodes.size()); + if (count < 2) + { + m_flag195 = false; + reset(); + return; + } + cluster->m_i0 = 0; + m_points.resize(0, NavigationPoint()); + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(); + m_island = static_cast(valid.quadTree); + m_startPolygon = static_cast(valid.polygon); + m_startPosition = valid.position; + m_flag195 = true; + const short own = static_cast(m_pathfinding->getClusterOfPolygon( + m_mapIndex, static_cast(m_island), valid.polygon)); // slot +0x7C + for (unsigned int i = 0; i < count - 1; ++i) + { + short node = -1; + if (m_clusterPath->m_i0 < static_cast(m_clusterPath->m_nodes.size())) + node = static_cast(m_clusterPath->m_nodes[m_clusterPath->m_i0].first); + if (own == node) + return; + ++m_clusterPath->m_i0; + } + m_clusterPath->m_i0 = 0; + for (unsigned int i = 0; i < count - 1; ++i) + { + unsigned short node = 0xFFFF; + if (m_clusterPath->m_i0 < static_cast(m_clusterPath->m_nodes.size())) + node = m_clusterPath->m_nodes[m_clusterPath->m_i0].first; + if (m_pathfinding->areNeighbouringClusters(m_mapIndex, static_cast(m_island), + static_cast(own), node)) // slot +0x80 + return; + ++m_clusterPath->m_i0; + } + m_flag195 = false; + reset(); +} + +// ELF 0x190DA0 (800 bytes). A goal within 200 m (minDistSqr 40000) that a straight trace reaches +// becomes a one-point path. +void BotNavigation::testDirectPath() +{ + static float minDistSqr = 40000.0f; // ELF 0x4B6C24 (.data) + const float dx = m_goal.x - m_startPosition.x; + const float dy = m_goal.y - m_startPosition.y; + const float dz = m_goal.z - m_startPosition.z; + if (!(dx * dx + dy * dy + dz * dz < minDistSqr)) + return; + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info || !info->getMobile()) + return; + Vec3 hit; + hit.x = 0.0f; hit.y = 0.0f; hit.z = 0.0f; + unsigned int polygon; + unsigned char material; + if (!m_pathfinding->trace(static_cast(m_startPolygon), static_cast(m_pathIsland), + m_mapIndex, m_startPosition, m_goal, hit, polygon, m_equipmentType, -1, 0.0f, 5, + &material)) // slot +0x8C + return; + const unsigned int index = static_cast(m_points.size()); + m_points.resize(index + 1, NavigationPoint()); + NavigationPoint& last = m_points[index]; + last.m_position = m_goal; + last.m_polygon = static_cast(polygon); + last.m_point0 = m_goal; + last.m_pointC = m_goal; + m_goalPolygon = static_cast(polygon); + m_goalMaterial = material; + m_polygonSearchPending = false; + m_useClusterSearch = false; + m_currentPoint = 0; + m_int56 = 2; + updateClosestDistance(); +} + +// ELF 0x1949E0 (384 bytes). Within 3 m in height and the arrive distance in the plane: a soldier +// uses soldierMinDist; a vehicle max(+4, 1), at the last point max(radius - 1, that). +bool BotNavigation::checkArrivedAtPoint(float) +{ + static float soldierMinDist = 0.5f; // ELF 0x4B6C30 (.data) + // The image reads BotMain +0x8C (m_currentEquipment) inline; getCurrentEquipment returns it. + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + if (m_points.empty()) + return false; + const NavigationPoint& p = m_points[m_currentPoint]; + if (!(std::fabs(position.y - p.m_position.y) <= 3.0f)) + return false; + float distance = soldierMinDist; + if (!m_updateSpaceLeftAndRight) + { + distance = m_arriveDistance; + if (m_arriveDistance <= 1.0f) + distance = 1.0f; + } + float limit = distance; + if (!m_updateSpaceLeftAndRight && m_currentPoint == m_points.size() - 1) + { + limit = m_radius - 1.0f; + if (limit <= distance) + limit = distance; + } + const float x = position.x - p.m_position.x; + const float z = position.z - p.m_position.z; + return z * z + x * x + 0.0f < limit * limit; +} + +// ELF 0x1940C0. +bool BotNavigation::getSecondPoint(Vec2& out) +{ + const unsigned int next = m_currentPoint + 1; + const bool exists = next < m_points.size(); + if (exists) + vec3ToVec2XZ(m_points[next].m_position, out); + return exists; +} + +// ELF 0x194120 (1408 bytes). Every 0.5 s: the largest absolute heading change between the bot's +// facing and the path legs within max(speed * timeStep, 3) metres ahead; cached in +308. +bool BotNavigation::getLargestAngleDiff(float& out) +{ + static float timeStep = 2.0f; // ELF 0x4B6C2C (.data) + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(now - m_double300 >= 0.5)) + { + out = m_largestAngleDiff; + return true; + } + m_double300 = now; + // The image reads BotMain +0x8C inline (no null guard). + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + unsigned int index = m_currentPoint; + const Vec3& first = m_points[index].m_position; + float covered = length3(position.x - first.x, position.y - first.y, position.z - first.z); + Vec2 facing; + facing.x = 0.0f; facing.y = 0.0f; + const Vec3 faceing = info->getFaceing(); // Information slot +0x40 + vec3ToVec2XZ(faceing, facing); + out = 0.0f; + float range = info->getMobile()->getSpeedMagnitude() * timeStep; // IPIMobile slot +0x24 + if (range <= 3.0f) + range = 3.0f; + for (; covered < range && index < m_points.size(); ++index) + { + Vec3 from; + if (index == 0) + from = info->getPosition(); + else + from = m_points[index - 1].m_position; + const Vec3& to = m_points[index].m_position; + covered = length3(from.x - to.x, from.y - to.y, from.z - to.z) + covered; + Vec3 leg; + leg.x = to.x - from.x; leg.y = to.y - from.y; leg.z = to.z - from.z; + Vec2 dir; + dir.x = 0.0f; dir.y = 0.0f; + vec3ToVec2XZ(leg, dir); + const float lengthSq = dir.x * dir.x + dir.y * dir.y; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) < 1.4210855e-14f) + { + dir.x = 0.0f; dir.y = 0.0f; + } + else + { + const float inv = 1.0f / std::sqrt(lengthSq); + dir.x = dir.x * inv; dir.y = inv * dir.y; + } + } + const float diff = std::fabs(getSignedDiffAngleToDir(facing, dir)); + if (out < diff) + out = diff; + } + m_largestAngleDiff = out; + return true; +} + +// ELF 0x194E50 (192 bytes). The first point from the current one farther than `distance` from +// `from` in the plane; `out` keeps the last point looked at. +void BotNavigation::getFirstPointBeyondDist(const Vec2& from, float distance, Vec2& out) +{ + for (unsigned int i = m_currentPoint; i < m_points.size(); ++i) + { + const Vec3& p = m_points[i].m_position; + out.x = p.x; + out.y = p.z; + const float dx = from.x - p.x; + const float dz = from.y - p.z; + if (distance * distance < dz * dz + dx * dx) + return; + } +} + +// ELF 0x195280. The game-time query's result is discarded, as in the image. +void BotNavigation::setGrenadeWarning(const Vec3& position, double time, bool b) +{ + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_grenadeTime = time; + m_grenadePosition = position; + m_grenadeFlag = b; +} + +// ELF 0x195310. +bool BotNavigation::getGrenadeWarning(Vec3& position, double& timeLeft) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + position = m_grenadePosition; + timeLeft = 2.8 - (now - m_grenadeTime); + return timeLeft > 0.0; +} + +// ELF 0x1914B0 (1535 bytes). A local (polygon) search for the next path segment: the first call +// acquires a search resource (none free: *blocked), turns on topology smoothing off the trace map, +// and allows the start's cluster, the next three clusters of the cluster path and the segment +// goal's cluster; the segment runs from the last point (or the start) to the cluster portal two +// steps ahead, or to the goal. Each call runs the search (IAIPathfinding +0x24): 1 is in progress +// (*finished = true, true); 2 found - the points are rebuilt and optimised, the goal appended when +// the segment ended there (and the cluster path emptied), the cluster step advanced; 3 / 4 failed. +bool BotNavigation::doPolygonSearch(bool& finished, bool* blocked) +{ + if (m_int76 == 0xFFFFFFFFu) + { + if (!m_pathfinding->acquireResource(m_int76, m_bot->getBotId())) + { + if (blocked) + *blocked = true; + return false; + } + if (m_mapIndex != m_pathfinding->getTraceMapIndex()) + m_pathfinding->setUsePathTopologySmoothing(m_int76, true); + if (m_points.empty()) + { + m_searchStart = m_startPosition; + m_searchStartPolygon = static_cast(m_startPolygon); + } + else + { + const NavigationPoint& last = m_points.back(); + m_searchStart = last.m_position; + m_searchStartPolygon = static_cast(last.m_polygon); + } + m_set132.clear(); + m_set132.insert(m_quadTree->getPolygon(m_searchStartPolygon)->m_cluster); + m_searchGoalIsFinal = false; + if (!m_clusterPath->getPoint(m_searchGoal, m_searchGoalPolygon, static_cast(m_clusterPath->m_i0 + 2))) + { + m_searchGoal = m_goal; + m_searchGoalIsFinal = true; + m_searchGoalPolygon = static_cast(m_goalPolygon); + } + for (int k = 0; k < 3; ++k) + { + const unsigned int index = static_cast(k + m_clusterPath->m_i0); + const unsigned int nodes = static_cast(m_clusterPath->m_nodes.size()); + if (nodes < index) + break; + const unsigned short cluster = + static_cast(index) < static_cast(nodes) ? m_clusterPath->m_nodes[index].first : 0xFFFF; + m_set132.insert(cluster); + } + m_set132.insert(m_quadTree->getPolygon(m_searchGoalPolygon)->m_cluster); + m_pathfinding->setAllowedClusters(m_int76, &m_set132); + } + m_int56 = m_pathfinding->localSearch(static_cast(m_int76), m_mapIndex, static_cast(m_island), + m_searchStartPolygon, m_searchStart, m_searchGoalPolygon, m_searchGoal, + m_equipmentType, m_polygonPath); + if (m_int56 != 1) + { + m_pathfinding->releaseResource(m_int76, m_bot->getBotId()); + m_int76 = 0xFFFFFFFFu; + if (m_int56 == 2) + { + calculatePoints(); + if (m_searchGoalIsFinal) + { + const unsigned int n = static_cast(m_points.size()); + m_points.resize(n + 1, NavigationPoint()); + m_points[n].m_position = m_goal; + m_points[n].m_polygon = m_goalPolygon; + m_clusterPath->m_nodes.resize(0); + m_clusterPath->m_i0 = 0; + } + m_flag192 = false; + m_quadTree = static_cast( + m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_polygonPath->m_island))); + optimizePoints(); + updateNavPoints(); + updateNavPoints(); + ++m_clusterPath->m_i0; + m_polygonSearchPending = false; + return true; + } + if (static_cast(m_int56 - 3) < 2) + return false; + } + finished = true; + return true; +} + +// ELF 0x191AB0 (315 bytes). The coarse (cluster) search: on success the polygon search takes +// over (+0x44 set, state 0); a failure (3 / 4) resets the navigation. +bool BotNavigation::doClusterSearch(bool& finished, bool* blocked) +{ + if (m_int128 == 0xFFFFFFFFu) + { + if (!m_pathfinding->acquireClusterResource(m_int128, m_bot->getBotId())) + { + if (blocked) + *blocked = true; + return false; + } + } + m_int56 = m_pathfinding->clusterSearch(static_cast(m_int128), m_mapIndex, static_cast(m_island), + static_cast(m_startPolygon), m_startPosition, + static_cast(m_goalPolygon), m_goal, m_equipmentType, + m_clusterPath); + if (m_int56 != 1) + { + m_pathfinding->releaseClusterResource(m_int128, m_bot->getBotId()); + m_int128 = 0xFFFFFFFFu; + if (m_int56 == 2) + { + m_useClusterSearch = false; + m_polygonSearchPending = true; + m_int56 = 0; + return true; + } + if (static_cast(m_int56 - 3) < 2) + { + reset(); + return false; + } + } + finished = true; + return true; +} + +// ELF 0x194CF0: within the smallest radius of a non-soldier obstacle (+0x58) with a physical. +bool BotNavigation::pointWithinObstacleRadius(const Vec3& point) +{ + for (unsigned int i = 0; i < m_obstacles.size(); ++i) + { + Information* const info = informationManager->getInformation(m_obstacles[i]); + if (!info || (info->getObjectTypeFlags() & 0x00200000u) || !info->getPhysical()) + continue; + const Vec3& p = info->getPosition(); + const float radius = info->getPhysical()->getSmallestRadius(); + if ((point.x - p.x) * (point.x - p.x) + (point.y - p.y) * (point.y - p.y) + (point.z - p.z) * (point.z - p.z) + < radius * radius) + return true; + } + return false; +} + +// ELF 0x1932A0. The local path's steps become navigation points, appended after the last point +// (or replacing all when the current point is past the end): each point's position and polygon +// from the step, and its portal edge (+0 / +0xC) from IAIPathfinding +0x70 getEdge(map, previous +// entered-from polygon, polygon, island), or the position twice for the first step. The path is +// emptied afterwards. +void BotNavigation::calculatePoints() +{ + m_polygonPath->m_i0 = 0; + QTPath* path = m_polygonPath; + const unsigned int island = static_cast(path->m_island); + const unsigned int steps = static_cast(path->m_nodes.size()); + const unsigned int count = static_cast(m_points.size()); + unsigned int base = count - 1; + if (count <= m_currentPoint) + base = 0; + unsigned int size = 0; + if (static_cast(path->m_i0) <= steps + base) + size = steps + base - static_cast(path->m_i0); + int from = -1; + if (path->m_i0 < static_cast(steps)) + from = static_cast(path->m_nodes[path->m_i0].second); + int polygon = -1; + if (path->m_i0 < static_cast(path->m_nodes.size())) + polygon = static_cast(path->m_nodes[path->m_i0].first); + m_points.resize(size, NavigationPoint()); + path = m_polygonPath; + unsigned int k = base; + while (static_cast(path->m_i0) < steps) + { + int entered = polygon; + NavigationPoint& point = m_points[k]; + point.m_position = *path->getPosition(static_cast(path->m_i0)); + point.m_polygon = static_cast(m_polygonPath->getPolygon(static_cast(m_polygonPath->m_i0))); + if (from == -1) + { + point.m_point0 = *m_polygonPath->getPosition(static_cast(m_polygonPath->m_i0)); + point.m_pointC = *m_polygonPath->getPosition(static_cast(m_polygonPath->m_i0)); + } + else + { + m_pathfinding->getEdge(point.m_point0, point.m_pointC, m_mapIndex, static_cast(from), + static_cast(entered), island); + } + ++m_polygonPath->m_i0; + path = m_polygonPath; + int next = -1; + if (path->m_i0 < static_cast(path->m_nodes.size())) + next = static_cast(path->m_nodes[path->m_i0].second); + if (next != -1) + entered = next; + polygon = -1; + if (path->m_i0 < static_cast(path->m_nodes.size())) + polygon = static_cast(path->m_nodes[path->m_i0].first); + ++k; + from = entered; + } + path->m_nodes.resize(0); + path->m_i0 = 0; + path->m_i20 = 0.0f; +} + +// ELF 0x1937D0. Two passes pull each point (5 m or more from the bot) onto its portal edge where +// the line from the previous point (the bot first) to the next point crosses it, kept a margin +// (max(0.8 radius, 1), at most half the edge) from the edge's ends; a final pass places every +// point where that line crosses its edge, when it does within the edge. +void BotNavigation::optimizePoints() +{ + if (m_points.empty()) + return; + Vec2 from; + from.x = 0.0f; + from.y = 0.0f; + // BotMain +0x8C read inline (here through the accessor). + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + vec3ToVec2XZ(info->getPosition(), from); + for (int pass = 0; pass < 2; ++pass) + { + for (unsigned int i = 0; i < m_points.size() - 1; ++i) + { + const Vec3& p = info->getPosition(); + const Vec3& at = m_points[i].m_position; + const float dx = p.x - at.x; + const float dy = p.y - at.y; + const float dz = p.z - at.z; + if (25.0f <= dx * dx + dy * dy + dz * dz) + { + Vec2 next, a, b; + next.x = 0.0f; next.y = 0.0f; + a.x = 0.0f; a.y = 0.0f; + b.x = 0.0f; b.y = 0.0f; + vec3ToVec2XZ(m_points[i + 1].m_position, next); + vec3ToVec2XZ(m_points[i].m_point0, a); + vec3ToVec2XZ(m_points[i].m_pointC, b); + float s; + float t; + if (lineIntersect(from, next, a, b, s, t)) + { + const float ex = b.x - a.x; + const float ey = b.y - a.y; + const float length = std::sqrt(ey * ey + ex * ex); + const float along = length * t; + const float half = length * 0.5f; + float margin = m_radius * 0.8f; + if (margin <= 1.0f) + margin = 1.0f; + if (half <= margin) + margin = half; + if (half <= along) + { + if (length - margin < along) + t = 1.0f - margin / length; + } + else if (along < margin) + { + t = margin / length; + } + NavigationPoint& point = m_points[i]; + const float u = t <= 1.0f ? t : 1.0f; + point.m_position.x = point.m_point0.x + (point.m_pointC.x - point.m_point0.x) * u; + point.m_position.y = (point.m_pointC.y - point.m_point0.y) * u + point.m_point0.y; + point.m_position.z = (point.m_pointC.z - point.m_point0.z) * u + point.m_point0.z; + } + } + vec3ToVec2XZ(m_points[i].m_position, from); + } + } + vec3ToVec2XZ(info->getPosition(), from); + for (unsigned int i = 0; i < m_points.size() - 1; ++i) + { + Vec2 next, a, b; + next.x = 0.0f; next.y = 0.0f; + a.x = 0.0f; a.y = 0.0f; + b.x = 0.0f; b.y = 0.0f; + vec3ToVec2XZ(m_points[i + 1].m_position, next); + vec3ToVec2XZ(m_points[i].m_point0, a); + vec3ToVec2XZ(m_points[i].m_pointC, b); + float s; + float t; + if (lineIntersect(from, next, a, b, s, t) && 0.0f <= t && t <= 1.0f) + { + NavigationPoint& point = m_points[i]; + point.m_position.x = (point.m_pointC.x - point.m_point0.x) * t + point.m_point0.x; + point.m_position.y = (point.m_pointC.y - point.m_point0.y) * t + point.m_point0.y; + point.m_position.z = (point.m_pointC.z - point.m_point0.z) * t + point.m_point0.z; + } + vec3ToVec2XZ(m_points[i].m_position, from); + } +} + +// ELF 0x192C00 (670 bytes). Following a path (state 2) from a valid position: unless +240 is set, +// when the current point is within 10 m (soldier) / 20 m, skip ahead while the next point is +// directly reachable (trace with clearance 0.5 / 0, 8 / 30, at most 1 / 4 points); otherwise a +// failed trace to the current point sets +194. minClearanceVehicle is a zero-initialised static +// (.bss 0x4CE010, no guard); minClearanceSoldier is 0.5 (0x4B6C28). +void BotNavigation::updateNavPoints() +{ + static float minClearanceSoldier = 0.5f; + static float minClearanceVehicle; + + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info || !info->getMobile() || m_int56 != 2) + return; + if (info->getMobile()->getLastValidPosition().polygon == 0xFFFFFFFFu) + return; + Vec3 hit; + hit.x = 0.0f; + hit.y = 0.0f; + hit.z = 0.0f; + const Vec3& position = info->getPosition(); + const bool soldier = m_updateSpaceLeftAndRight; + const int steps = soldier ? 8 : 30; + const float range = soldier ? 10.0f : 20.0f; + bool advanced = false; + const float clearance = soldier ? minClearanceSoldier : minClearanceVehicle; + unsigned int polygon; + if (m_int240 == 0) + { + const Vec3& current = m_points[m_currentPoint].m_position; + const float dx = position.x - current.x; + const float dy = position.y - current.y; + const float dz = position.z - current.z; + if (dz * dz + dx * dx + dy * dy < range * range) + { + for (int i = 0; i < (soldier ? 1 : 4); ++i) + { + if (m_points.size() - 1 <= m_currentPoint + || !m_pathfinding->trace(this, false, m_points[m_currentPoint + 1].m_position, hit, polygon, + m_equipmentType, steps, clearance, 5, 0)) + break; + ++m_currentPoint; + advanced = true; + } + if (advanced) + return; + } + } + if (!m_pathfinding->trace(this, false, m_points[m_currentPoint].m_position, hit, polygon, m_equipmentType, -1, + 0.0f, 0, 0)) + m_flag194 = true; +} + +// ELF 0x1946A0 (824 bytes). +0xBC: the distance from the bot along the remaining points, plus +// the remaining cluster path (its points 1.. from the last navigation point); +0x138 the points +// part. No points: 0. ClusterNodePath::getPoint is indexed from 1, not from the current step, +// as in the image. +void BotNavigation::updateClosestDistance() +{ + if (m_points.empty()) + { + m_sentinel188 = 0.0f; + return; + } + // The image reads BotMain +0x8C inline (no null guard). + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + const Vec3& current = m_points[m_currentPoint].m_position; + float distance = length3(position.x - current.x, position.y - current.y, position.z - current.z); + unsigned int i = m_currentPoint + 1; + for (; i < m_points.size(); ++i) + { + const Vec3& a = m_points[i - 1].m_position; + const Vec3& b = m_points[i].m_position; + distance = length3(a.x - b.x, a.y - b.y, a.z - b.z) + distance; + } + ClusterNodePath* const cluster = m_clusterPath; + m_pathLength = distance; + const unsigned int nodes = static_cast(cluster->m_nodes.size()); + if (static_cast(cluster->m_i0) < nodes) + { + const unsigned int remaining = nodes - static_cast(cluster->m_i0); + Vec3 previous = m_points[i - 1].m_position; + for (unsigned int k = 1; k < remaining; ++k) + { + Vec3 point; + point.x = 0.0f; point.y = 0.0f; point.z = 0.0f; + unsigned int polygon; + m_clusterPath->getPoint(point, polygon, k); + distance = length3(previous.x - point.x, previous.y - point.y, previous.z - point.z) + distance; + previous = point; + } + } + m_sentinel188 = distance; +} + +// ELF 0x1927A0 (130 bytes): a point on a missing or non-walkable (material 0) polygon. +bool BotNavigation::hasIllegalPath() +{ + for (unsigned int i = 0; i < m_points.size(); ++i) + { + const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_points[i].m_polygon)); + if (!polygon || polygon->m_material == 0) + return true; + } + return false; +} + +namespace { + +// Bot +4 inputs read inline: an unmapped input reads 0 (`(mappingFlags >> i) & 1`). +float mappedInput(const io::PlayerInput* input, io::PlayerInputMap index) +{ + return ((input->mappingFlags >> static_cast(index)) & 1ULL) ? input->inputs[index] : 0.0f; +} + +float distanceSq(const float* a, const Vec3& b) +{ + return (a[0] - b.x) * (a[0] - b.x) + (a[1] - b.y) * (a[1] - b.y) + (a[2] - b.z) * (a[2] - b.z); +} + +} // namespace + +// ELF 0x191BF0 (1192 bytes). The action input is released one second after +168. While a path +// is followed (state 2): no move input (max of throttle, sprint, yaw within 0.1) for 0.1 s +// (soldier) / 0.5 s restamps +144 and is progress; otherwise the bot progresses when it got +// 2 m (soldier) / 4 m from +280 (restamped then) or when it stayed within that for less than +// 10 s / 20 s since +144. A soldier standing still (0.001) for 2 s, 3 s after +168, sets +168 +// to -666 (BotNavigation +0x1D0's action press, see updatePath). +bool BotNavigation::checkProgress() +{ + io::PlayerInput* const input = m_bot->getInput(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (1.0 < now - m_double168 && ((input->mappingFlags >> io::PIAction) & 1ULL)) + input->inputs[io::PIAction] = 0.0f; + if (m_points.empty() || m_int56 != 2) + return true; + float move = mappedInput(input, io::PIThrottle); + const float sprint = mappedInput(input, io::PISprint); + if (move <= sprint) + move = sprint; + const float yaw = mappedInput(input, io::PIYaw); + if (move < yaw) + move = yaw; + const double still = m_updateSpaceLeftAndRight ? 0.1 : 0.5; + if (std::fabs(move) <= 0.1f) + { + if (still < now - m_double152) + { + m_double144 = now; + m_flag192 = false; + return true; + } + } + else + { + m_double152 = now; + } + const float radius = m_updateSpaceLeftAndRight ? 2.0f : 4.0f; + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const Vec3& position = info->getPosition(); + if (distanceSq(m_zero280, position) <= radius * radius) + { + const float limit = m_updateSpaceLeftAndRight ? 10.0f : 20.0f; + const double since = m_double144; + if (m_updateSpaceLeftAndRight && 2.0f < static_cast(now - since) && 3.0 < now - m_double168) + { + if (distanceSq(m_zero176, info->getPosition()) < 0.001f) + m_double168 = -666.0; + const Vec3& p = info->getPosition(); + m_zero176[0] = p.x; + m_zero176[1] = p.y; + m_zero176[2] = p.z; + } + return now - since < static_cast(limit); + } + m_zero280[0] = position.x; + m_zero280[1] = position.y; + m_zero280[2] = position.z; + m_double144 = now; + m_flag192 = false; + return true; +} + +// ELF 0x1928B0 (840 bytes). From the last valid position, a trace 2 m along the transformation's +// right axis (row 0) and one 2 m the other way (IAIPathfinding +0x90, trace(BotNavigation*, ...), +// map index 0, the equipment type, -1, 0, 5): +296 / +292 get the free distance, 2 when the trace +// reports true. +void BotNavigation::updateSpaceLeftAndRight() +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!info || !info->getMobile() || m_int56 != 2) + return; + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(); + if (valid.polygon == 0xFFFFFFFFu) + return; + Vec3 hit; + hit.x = 0.0f; + hit.y = 0.0f; + hit.z = 0.0f; + const Mat4& transformation = info->getTransformation(); + unsigned int polygon; + Vec3 probe; + probe.x = transformation.m[0] * 2.0f + valid.position.x; + probe.y = transformation.m[1] * 2.0f + valid.position.y; + probe.z = transformation.m[2] * 2.0f + valid.position.z; + float space = 2.0f; + if (!m_pathfinding->trace(this, false, probe, hit, polygon, m_equipmentType, -1, 0.0f, 5, 0)) + space = length3(hit.x - valid.position.x, hit.y - valid.position.y, hit.z - valid.position.z); + m_spaceRight = space; + probe.x = probe.x - transformation.m[0] * 2.0f * 2.0f; + probe.y = probe.y - transformation.m[1] * 2.0f * 2.0f; + probe.z = probe.z - transformation.m[2] * 2.0f * 2.0f; + space = 2.0f; + if (!m_pathfinding->trace(this, false, probe, hit, polygon, m_equipmentType, -1, 0.0f, 5, 0)) + space = length3(hit.x - valid.position.x, hit.y - valid.position.y, hit.z - valid.position.z); + m_spaceLeft = space; } // Always returns true, leaving BotManager's final pathfinding sweep gated by isSearchActive. @@ -199,6 +1328,80 @@ bool BotNavigation::isRunning() return true; } +// ELF 0x194F10. The bot's equipment's last valid position for `mapIndex` (IPIMobile, unchecked +// lookups as in the image). A new map or a moved position (any coordinate more than +// 1.1920929e-07f away) is kept (+0xD8, +0xE4) and returned with its polygon / island; it also +// refreshes the vehicle pair (+0xC8, when it is the navigation's own map +0x50) and the infantry +// pair (+0xD0, for IAIPathfinding::getTraceMapIndex). Otherwise the kept position is returned +// with the stored pair of that map, or Debug line 0x630 "Should not be here!" (pair untouched). +void BotNavigation::getTraceData(int mapIndex, unsigned int& polygon, unsigned int& island, Vec3& position) +{ + Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); + const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(mapIndex); + if (m_traceMapIndex != mapIndex + || std::fabs(valid.position.x - m_tracePosition.x) > 1.1920929e-07f + || std::fabs(valid.position.y - m_tracePosition.y) > 1.1920929e-07f + || std::fabs(valid.position.z - m_tracePosition.z) > 1.1920929e-07f) + { + m_traceMapIndex = mapIndex; + m_tracePosition = valid.position; + position = valid.position; + polygon = valid.polygon; + island = valid.quadTree; + if (m_mapIndex == mapIndex) + { + m_vehiclePolygon = static_cast(valid.polygon); + m_vehicleIsland = static_cast(valid.quadTree); + } + if (mapIndex == IAIPathfinding::instance->getTraceMapIndex()) + { + m_infantryPolygon = static_cast(valid.polygon); + m_infantryIsland = static_cast(valid.quadTree); + } + return; + } + position = m_tracePosition; + if (mapIndex == IAIPathfinding::instance->getTraceMapIndex()) + { + polygon = static_cast(m_infantryPolygon); + island = static_cast(m_infantryIsland); + } + else if (mapIndex == m_mapIndex) + { + polygon = static_cast(m_vehiclePolygon); + island = static_cast(m_vehicleIsland); + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotNavigation.cpp", 0x630, "") << "Should not be here!"; + } +} + +// ELF 0x192EA0: append the old route's remaining interior points after recalculating the prefix. +void BotNavigation::mergeNavigationPoints() +{ + const std::vector previous(m_points); + unsigned int index = m_currentPoint; + m_polygonPath->m_i0 = 0; + calculatePoints(); + // Shipped defect: an empty previous route underflows this unsigned bound. + for (; index < previous.size() - 1; ++index) + m_points.push_back(previous[index]); + NavigationPoint last; + last.m_point0 = m_goal; + last.m_pointC = m_goal; + last.m_position = m_goal; + last.m_polygon = m_goalPolygon; + m_points.push_back(last); +} + +// ELF 0x195390: appends to the caller's vector without clearing it. +void BotNavigation::getNavigationPoints(std::vector& points) const +{ + for (std::vector::const_iterator it = m_points.begin(); it != m_points.end(); ++it) + points.push_back(it->m_position); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h index c9b6fd8c0..4a111c0ef 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h @@ -5,6 +5,7 @@ #include #include +#include #include "../Main/AIPathfindingSearchTypes.h" // QTPath, ClusterNodePath - both already written #include "../../../../Math/Vec3.h" // Vec2 and Vec3 both live here, and both are typedefs @@ -16,6 +17,8 @@ namespace ai { class BotMain; class Information; +class IAIPathfinding; +class QuadTree; class BotNavigation { @@ -24,22 +27,28 @@ class BotNavigation ~BotNavigation(); // [FRONTIER] // [FRONTIER] Navigation methods below remain incomplete unless implemented explicitly. - void update(bool& a, bool* b); + bool update(bool& a, bool* b); void updateOccationally(); // dice's spelling - "Occationally" - void updatePath(Vec2& a, bool& b, bool& c, float d); + // ELF 0x192200: the point to walk to; `arrived` at the last point, `direct` when the bot + // should not follow points (no path, retracing, or blocked by a hostile vehicle's material). + bool updatePath(Vec2& point, bool& arrived, bool& direct, float distance); void updateNavPoints(); void updateObstacles(); + void drawPath(); void updateLastPoint(Information* info); void updateSpaceLeftAndRight(); void updateClosestDistance(); - void initPathfinding(const Vec3& to, float a, float b); - void initPathfinding(unsigned int a, unsigned int b, const Vec3& to, float c, float d); - void doPolygonSearch(bool& a, bool* b); - void doClusterSearch(bool& a, bool* b); + // ELF 0x1901B0 / 0x1902B0: start a path search to `to`; false when none can be started. + bool initPathfinding(const Vec3& to, float arriveDistance, float b); + bool initPathfinding(unsigned int island, unsigned int goalPolygon, const Vec3& to, float arriveDistance, float b); + bool doPolygonSearch(bool& a, bool* b); + bool doClusterSearch(bool& a, bool* b); void calculatePoints(); + void mergeNavigationPoints(); + void getNavigationPoints(std::vector& points) const; void optimizePoints(); - bool testDirectPath(); + void testDirectPath(); // ELF 0x190DA0 (void: no eax on its exits) void retrace(); bool stillOnPath(); @@ -58,110 +67,180 @@ class BotNavigation bool isActive(); // returns true, unconditionally, in both images. bool isRunning(); - void checkProgress(); + int getMapIndex() const { return m_mapIndex; } + // [INFERRED] readers of fields the BAP actions read inline (ai-w1-c-actions request): + // +0x2C (BAPAMoveTo*), +0xBC, +0xC0, +0xCC (BAPAMoveToObjectFinding::initObjectFinding). + const Vec3& getGoal() const { return m_goal; } + float getTargetDistance() const { return m_sentinel188; } + bool getIsStuck() const { return m_flag192; } + unsigned int getLastValidIsland() const { return static_cast(m_vehicleIsland); } + // [INFERRED] reader of +0x58 (InfanteryControl / BBAvoid read begin/end inline). + const std::vector& getObstacles() const { return m_obstacles; } + float getSpaceLeft() const { return m_spaceLeft; } + float getSpaceRight() const { return m_spaceRight; } + bool checkProgress(); void clearProgress(); bool checkArrivedAtPoint(float distance); void setIsStuck(bool stuck); bool pointWithinObstacleRadius(const Vec3& point); void getFirstPointBeyondDist(const Vec2& from, float distance, Vec2& out); - void getSecondPoint(Vec2& out); - void getLargestAngleDiff(float& out); + bool getSecondPoint(Vec2& out); // ELF 0x1940C0 + bool getLargestAngleDiff(float& out); // ELF 0x194120 (always true) void getTraceData(int a, unsigned int& b, unsigned int& c, Vec3& d); - void getGrenadeWarning(Vec3& position, double& time); - void setGrenadeWarning(const Vec3& position, double time, bool b); + // ELF 0x195310: the warned position and the time left of 2.8 s; true while some is left. + bool getGrenadeWarning(Vec3& position, double& timeLeft); + // [INFERRED] reader of +0x114 (BBRandom / BBAvoid::calculateUrgency read it inline). + bool getGrenadeFlag() const { return m_grenadeFlag; } + void setGrenadeWarning(const Vec3& position, double time, bool b); // ELF 0x195280 void reset(); // - (one arm frontier) void resetAll(); - // attested as a nested type by the container instantiations, which spell - // `std::vector` in full. sizeof is 40, from - // the constructor's divide; the members are [UNRESOLVED] because nothing recovered so far builds - // one. Declared as a sized block rather than guessed at. + // attested as a nested type by the container instantiations. sizeof 40. testDirectPath + // (ELF 0x190DA0) writes all three Vec3 = the goal and +0x24 = trace's polygon; the walkers + // (updatePath, getSecondPoint, ...) read +0x18 and +0x24. The first two Vec3 are + // [UNRESOLVED] names. struct NavigationPoint { - // Initializes the index to -1 and clears the preceding 36 bytes. - // [UNRESOLVED] The contents of that byte range remain unknown. NavigationPoint() - : m_index36(-1) + : m_polygon(-1) { - for (int i = 0; i < 36; ++i) - m_bytes[i] = 0; + m_point0.x = 0.0f; m_point0.y = 0.0f; m_point0.z = 0.0f; + m_pointC.x = 0.0f; m_pointC.y = 0.0f; m_pointC.z = 0.0f; + m_position.x = 0.0f; m_position.y = 0.0f; m_position.z = 0.0f; } - char m_bytes[36]; // [UNRESOLVED] - int m_index36; // = -1 + /* +0x00 */ Vec3 m_point0; + /* +0x0C */ Vec3 m_pointC; + /* +0x18 */ Vec3 m_position; + /* +0x24 */ int m_polygon; // = -1 }; private: + // ELF 0x22A429 reads the infantry polygon inline; reset writes it at 0x190D14. + friend class BBPAvoidCollision2d; /* 0 */ BotMain* m_bot; // the ctor argument, and the first store - /* 4 */ float m_float4; // = 2.0f [UNRESOLVED] + // initPathfinding's two floats (ELF 0x1902B0 stores +4 = a, +8 = b, +0xC = b * b); + // checkArrivedAtPoint arrives within max(+4, 1) for a vehicle. [INFERRED] names. + /* 4 */ float m_arriveDistance; // = 2.0f /* 8 */ float m_float8; // = 2.0f [UNRESOLVED] - /* 12 */ char m_gap12[4]; // [UNRESOLVED] - never written - /* 16 */ int m_int16; // = -1 - /* 20 */ int m_int20; // = -1 - /* 24 */ int m_zero24[3]; // +24..+32, all 0 - /* 36 */ int m_int36; // = -1 - /* 40 */ bool m_flag40; // = false + /* 12 */ float m_float8Squared; // initPathfinding: b * b + // initPathfinding / retrace: the bot's last valid position (IPIMobile::ValidPos fields). + /* 16 */ int m_island; // = -1; ValidPos::quadTree + /* 20 */ int m_startPolygon; // = -1 + /* 24 */ Vec3 m_startPosition; // all 0 + /* 36 */ int m_goalPolygon; // = -1 + // IAIPathfinding::getMaterial's answer for the goal polygon (initPathfinding) or trace's. + /* 40 */ unsigned char m_goalMaterial; // = 0 /* 41 */ char m_pad41[3]; - /* 44 */ int m_zero44[3]; // +44..+52, all 0 + /* 44 */ Vec3 m_goal; // all 0; initPathfinding's target + // path state: 0 reset, 2 path ready (testDirectPath), 4 (update stops). [INFERRED] /* 56 */ int m_int56; // not a gap - `reset` zeroes it - // Owns polygon and cluster path reservations, released through virtual slots +156 and - // +164 during reset. [UNRESOLVED] The interface type is not yet known. - /* 60 */ void* m_pathOwner; // = 0 - /* 64 */ int m_zero64; // = 0 - /* 68 */ char m_gap68[4]; // [UNRESOLVED] - never written + // IAIPathfinding::instance, set by initPathfinding; reset releases the two reservations + // through it (releaseResource +0x9C, releaseClusterResource +0xA4). + /* 60 */ IAIPathfinding* m_pathfinding; // = 0 + // IAIPathfinding::getQuadTree(map, island) (+0x64), set by initPathfinding. + /* 64 */ QuadTree* m_quadTree; // = 0 + // update (ELF 0x191320) sets it with the point reset and runs the polygon search while it + // is set. [CHOSEN] name. + /* 68 */ bool m_polygonSearchPending; + /* 69 */ char m_pad69[3]; /* 72 */ QTPath* m_polygonPath; // new(0x18) - the fine path - /* 76 */ int m_int76; // = -1 - /* 80 */ char m_gap80[8]; // [UNRESOLVED] - never written - /* 88 */ int m_zero88[3]; // +88, +92, +96 + // IAIPathfinding::acquireResource's polygon-search slot; -1 = none. + /* 76 */ unsigned int m_int76; // = -1 + // AIPathfinding::trace (ELF 0x3A81C0) reads +0x50 as the map index passed to getTraceData + // when it does not use the trace map. [INFERRED] name. + /* 80 */ int m_mapIndex; // never written by the constructor + // IPIUnit::getEquipmentType of the bot's equipment, set by initPathfinding. [INFERRED] name. + /* 84 */ int m_equipmentType; // never written by the constructor + // updateObstacles (ELF 0x194B60) clears and fills it through getObjectsWithinRadius, and + // stores its size at +252. + /* 88 */ std::vector m_obstacles; // the walkable result - see the header note. The constructor's dead resize targets this. /* 100 */ std::vector m_points; - /* 112 */ char m_gap112[4]; // [UNRESOLVED] - never written - /* 116 */ int m_int116; // = 0 - /* 120 */ char m_gap120[4]; // [UNRESOLVED] - never written + // the island the path was searched on (initPathfinding: the start island). + /* 112 */ int m_pathIsland; // never written by the constructor + // index of the point being walked to. + /* 116 */ unsigned int m_currentPoint; // = 0 + // update: nonzero selects the cluster search. [CHOSEN] name. + /* 120 */ bool m_useClusterSearch; + /* 121 */ char m_pad121[3]; /* 124 */ ClusterNodePath* m_clusterPath; // new(0x1C) - the coarse path - /* 128 */ int m_int128; // = -1 + // the cluster-search slot (acquireClusterResource); -1 = none. + /* 128 */ unsigned int m_int128; // = -1 // `allocate(20)` with 0 / 0 / self / self is an `_Rb_tree` header at 16 + sizeof(value_type) // so the value type is four bytes - a set of pointers or handles. Which is [UNRESOLVED]; // `void*` holds the width and claims nothing. - /* 132 */ std::set m_set132; + /* 132 */ std::set m_set132; // doPolygonSearch: the clusters the local search may use (setAllowedClusters) /* 144 */ double m_double144; // = 0.0 /* 152 */ double m_double152; // = 0.0 /* 160 */ double m_double160; // = 0.0 /* 168 */ double m_double168; // = 0.0 - /* 176 */ int m_zero176[3]; // +176, +180, +184 + /* 176 */ float m_zero176[3]; // +176..+184; checkProgress: the soldier position at the last action-press check // is 9,999,999.0f - a "no distance yet" sentinel, and a third kind after the // DBL_MAX timestamps and -9999.0 magnitudes BotMain uses. Do not normalise them together. + // distance to the target (C's reader); reset 9999999.0f, updatePath's arrival 1e8f. /* 188 */ float m_sentinel188; // = 9999999.0f + // setIsStuck writes it (never while parachuting); initPathfinding sets it when no path can + // be started; updatePath does nothing while it is set. /* 192 */ bool m_flag192; // = false /* 193 */ bool m_flag193; // = false /* 194 */ bool m_flag194; // not padding - `reset` clears it /* 195 */ bool m_flag195; // = false /* 196 */ char m_gap196[4]; // [UNRESOLVED] - never written - /* 200 */ int m_int200; // = -1 - /* 204 */ int m_int204; // = -1 - /* 208 */ int m_int208; // = -1 - /* 212 */ int m_int212; // = -1 - /* 216 */ int m_zero216[3]; // +216, +220, +224 - /* 228 */ char m_gap228[12]; // [UNRESOLVED] - never written + // the last valid positions (reset / initPathfinding): the vehicle's (getLastValidPosition of + // the vehicle number) and the infantry one (IPIMobile +8 / +0xC). + /* 200 */ int m_vehiclePolygon; // = -1 + /* 204 */ int m_vehicleIsland; // = -1 + /* 208 */ int m_infantryPolygon; // = -1 + /* 212 */ int m_infantryIsland; // = -1 + // getTraceData (ELF 0x194F10): the last traced valid position and its map index. The + // constructor zeroes the position (three word stores); the index is never initialised. + /* 216 */ Vec3 m_tracePosition; + /* 228 */ int m_traceMapIndex; + // IPIPhysical::getSmallestRadius of the equipment (initPathfinding). [INFERRED] name. + /* 232 */ float m_radius; + // initPathfinding: the equipment's type flags carry 0x200000 (byte +6 bit 0x20). The soldier + // arms test it (checkArrivedAtPoint's soldierMinDist, updatePath's 0.5 s retrace delay); + // updateOccationally (ELF 0x192830) calls updateSpaceLeftAndRight while it is set. + /* 236 */ bool m_updateSpaceLeftAndRight; + /* 237 */ char m_pad237[3]; + // updatePath: useSkipTrace && soldier before a retrace; stillOnPath counts it down. /* 240 */ int m_int240; // = 0 + // updatePath's game time (isActive: three seconds). /* 244 */ double m_double244; // not a gap - `reset` zeroes it // resetAll clears this field. /* 252 */ int m_int252; // resetAll: 0 - /* 256 */ int m_zero256[3]; // +256, +260, +264 - /* 268 */ double m_double268; // = 0.0 - /* 276 */ bool m_flag276; // = false + // setGrenadeWarning (ELF 0x195280) writes all three; getGrenadeWarning answers 2.8 s from + // +268. [INFERRED] names. + /* 256 */ Vec3 m_grenadePosition; // all 0 + /* 268 */ double m_grenadeTime; // = 0.0; resetAll -9999.0 + /* 276 */ bool m_grenadeFlag; // = false; setGrenadeWarning's bool /* 277 */ char m_pad277[3]; - /* 280 */ int m_zero280[5]; // +280..+296 + /* 280 */ float m_zero280[3]; // +280..+288; checkProgress: the position at the last progress + // BotMain::postPlanExecution (ELF 0x189220) strafes towards avoid side 1 while +292 > 0.5 + // and towards side 2 while +296 > 0.5; updateSpaceLeftAndRight writes them. [INFERRED] names. + /* 292 */ float m_spaceLeft; + /* 296 */ float m_spaceRight; /* 300 */ double m_double300; // Initially -1.0; independent of the distance sentinel. - /* 308 */ int m_zero308[2]; // +308, +312 + // getLargestAngleDiff's cached answer (recomputed every 0.5 s, +300 the time). + /* 308 */ float m_largestAngleDiff; // = 0 + // updateClosestDistance: the walked-points length from the bot (updatePath re-checks the + // cluster path at 30 or more). [INFERRED] name. + /* 312 */ float m_pathLength; // = 0 // `reset`'s first statement clears the byte here. /* 316 */ bool m_flag316; // reset: false /* 317 */ char m_pad317[3]; - /* 320 */ int m_zero320[6]; // +320..+340 - /* 344 */ char m_gap344[12]; // +344..+355 - the ctor never reaches them [UNRESOLVED] + // doPolygonSearch's local search segment: from the last point (or the start) to the next + // cluster portal two steps ahead (or the goal). [INFERRED] names. + /* 320 */ Vec3 m_searchStart; // ctor: 0 + /* 332 */ Vec3 m_searchGoal; // ctor: 0 + /* 344 */ unsigned int m_searchStartPolygon; // never written by the ctor + /* 348 */ unsigned int m_searchGoalPolygon; + /* 352 */ bool m_searchGoalIsFinal; // the segment ends at the goal + /* 353 */ char m_pad353[3]; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp index fa52c41be..e5b2e6646 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp @@ -5,6 +5,37 @@ #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "BotMain.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../Main/AIRandom.h" +#include "CommunicationAgent.h" +#include "SensedObject.h" +#include "SensingAgent.h" + +#include +#include +#include +#include +// static init: ELF 0x19E110, 0x19E200, 0x19E230: iostream Init and six cosine thresholds. + +#include "../../../AIInterface/BFKnowledge/AIAdapterTypes.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Core/Debug.h" +#include "../../../../Math/Mat4.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIUtils/DebugRendering/AIRenderUtil.h" +#include "../Main/IBotManager.h" namespace dice { namespace hfe { @@ -15,12 +46,12 @@ BotSenses::BotSenses(BotMain* owner) : m_bot(owner) // the camera. See the block above. , m_frustum(checkPointer(new Frustum())) - , m_double12(-1000000.0) - , m_int32(0) - , m_int36(0) - , m_int40(0) - , m_int88(0) - , m_int92(0) + , m_collectTime(-1000000.0) + , m_frustumStep(0) + , m_seeState(0) + , m_seeIndex(0) + , m_fireTotalStrength(0) + , m_fireTotalStrengthAgainstSelf(0) { // the constructor'S last statement - see the block above. The binary copies the list's head // pointer; in source that is the list's own end. The cursor at +80 is deliberately not here. @@ -31,11 +62,17 @@ BotSenses::BotSenses(BotMain* owner) // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. void BotSenses::reset() { + // ELF 0x199D40: a record holding a contact (+0x64) releases it on its own information + // (slot 7, removeContact), then the record is deleted and its node erased. for (SensedObjectMap::iterator it = m_sensedObjects.begin(); it != m_sensedObjects.end(); ) { - // Retail here releases the object's `Information` through `informationManager` and then - // deletes `it->second`. See the block above for why this tree cannot write it yet. - BF2_AI_FRONTIER("dice::hfe::ai::BotSenses::reset (sensed objects present)"); + if (it->second->m_hasContact) + { + if (Information* const information = informationManager->getInformation(it->second->m_handle)) + information->removeContact(); + } + if (it->second) + delete it->second; m_sensedObjects.erase(it++); } m_sensedObjects.clear(); @@ -45,25 +82,26 @@ void BotSenses::reset() m_cursor60 = m_list56.end(); m_sortBuffer.clear(); - m_int40 = 0; - m_int36 = 0; - m_int32 = 0; - m_double12 = -1000000.0; + m_seeIndex = 0; + m_seeState = 0; + m_frustumStep = 0; + m_collectTime = -1000000.0; m_set64.clear(); m_list76.clear(); // The constructor never did this; the cursor at +80 becomes valid here for the first time. m_cursor80 = m_list76.end(); + // The fire list owns its objects; the attacker map below only borrows them. for (std::list::iterator it = m_list84.begin(); it != m_list84.end(); ++it) { - // Retail here is `delete it->first;`. See the block above. - BF2_AI_FRONTIER("dice::hfe::ai::BotSenses::reset (fire objects present)"); + if (it->first) + delete it->first; } m_list84.clear(); - m_int88 = 0; - m_int92 = 0; + m_fireTotalStrength = 0; + m_fireTotalStrengthAgainstSelf = 0; m_map100.clear(); } @@ -78,6 +116,1294 @@ BotSenses::~BotSenses() // [FRONTIER] Remaining sight, hearing and communication operations require implementation. // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x19A040 (172 bytes). Hearing gets a tenth and the fire objects three tenths of the slice; +// seeing gets what is left of the deadline (start + slice - now). The ELF reads the update time +// (IBFTimer +0x10) three times; the middle read's result is discarded. +void BotSenses::updateSensing(const double& slice) +{ + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + const double total = slice; + const double hearing = total * 0.1; + updateHearing(hearing); + timer->getUpdateTime(); + const double fire = slice * 0.3; + updateFireObjects(fire); + const double seeing = (start + total) - timer->getUpdateTime(); + updateSeeing(seeing); +} + +// ELF 0x19D8A0: map find at +112, the mapped SensedObject* or null. +SensedObject* BotSenses::getSensedObjectFromHandle(unsigned int handle) const +{ + const SensedObjectMap::const_iterator it = m_sensedObjects.find(handle); + return it == m_sensedObjects.end() ? 0 : it->second; +} + +namespace { + +// ELF data 0x4B6CA0 (BotSenses.cpp's anonymous namespace): two rows (m_viewMode) of three +// {angle, threshold} pairs. see() takes the frustum angle from a row's first pair only, and the +// frustum-step threshold from pair m_frustumStep. The thresholds are initialized with cosf. +struct FrustumUpdateAngle +{ + float angle; + float threshold; +}; +FrustumUpdateAngle tweak_frustumUpdateAngle[2][3] = +{ + { { 1.7453293f, std::cos(0.436332315f) }, { 1.0471976f, std::cos(0.261799395f) }, + { 0.5235988f, std::cos(0.130899698f) } }, + { { 1.3089969f, std::cos(0.327249229f) }, { 0.7853982f, std::cos(0.196349546f) }, + { 0.2617994f, std::cos(0.065449849f) } }, +}; + +// The sort order of the candidate buffer (std::__unguarded_linear_insert ELF 0x19FED0): +// ascending squared distance. +struct InfoDistPred +{ + bool operator()(const std::pair& a, const std::pair& b) const + { + return a.first < b.first; + } +}; + +// ELF vtable 0x4B6CD0, predicate 0x1A0E30: which player-occupied objects a bot considers. +// Neutral objects within the view radius; never its own side; a dead physical object of type 21 +// is skipped; with `vehicleSight` the radius is also capped at 300 m (90000), otherwise a unit +// must also be within its own cull distance. +class SideFilter : public AIObjectPredicate +{ +public: + SideFilter(int side, const Vec3& position, float radiusSq, bool vehicleSight) + : m_side(side), m_position(position), m_radiusSq(radiusSq), m_vehicleSight(vehicleSight) + { + } + + virtual bool predicate(IAIObject* object) + { + const int side = object->getSide(); + if (side == 0) + return m_radiusSq > distanceSq(object); + if (side == m_side) + return false; + if (object->isOfType(static_cast(0x15))) + { + if (!object->isPhysical()) + return false; + if (0.0f >= object->getPhysical()->getHealth()) + return false; + } + const float distSq = distanceSq(object); + if (object->isUnit() && !m_vehicleSight) + { + if (!(m_radiusSq > distSq)) + return false; + return object->getUnit()->getCullDistanceSqr() > distSq; + } + if (!m_vehicleSight) + return m_radiusSq > distSq; + if (!(m_radiusSq > distSq)) + return false; + return 90000.0f > distSq; + } + +private: + float distanceSq(IAIObject* object) const + { + const Vec3& position = object->getPosition(); + const float dx = position.x - m_position.x; + const float dy = position.y - m_position.y; + const float dz = position.z - m_position.z; + return dx * dx + dy * dy + dz * dz; + } + + /* +0x04 */ int m_side; + /* +0x08 */ Vec3 m_position; + /* +0x14 */ float m_radiusSq; + /* +0x18 */ bool m_vehicleSight; +}; + +float distanceSqTo(const Vec3& own, IAIObject* object) +{ + const Vec3& position = object->getPosition(); + const float dx = own.x - position.x; + const float dy = own.y - position.y; + const float dz = own.z - position.z; + return dx * dx + dy * dy + dz * dz; +} + +} // namespace + +// ELF 0x198420 (6421 bytes). A time-sliced state machine over m_seeState: +// (3 -> 0) mark the camera's quadrants seen and step the frustum (m_frustumStep cycles 0, 1, 2 +// and drops to 0 once the camera has turned away from the last frustum direction); +// always rebuild the frustum from the camera (tweak angle, aspect 1, near 0.01, the player's +// view distance); +// 0 gather the player-occupied candidates (SideFilter), keep those in the frustum, close +// and in front (vehicle sight), or within three own radii, with their exposed +// occupiers, as (squared distance, handle); +// 1 sort them by distance; +// 2 for each not yet in the seen list, sample up to 1..10 sense points (bounding radius * +// 30 / distance) and cast a ray from the eye (camera position, y - 0.1); the first clear +// ray reports the object as seen to the bot and to every bot riding with it. +// Between the states the slice is checked against the update time. +void BotSenses::see(const double& slice) +{ + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + // As in the image, the equipment information is used without a null check. + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + m_bot->getName(); + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + m_viewMode = (equipment->getObjectTypeFlags() & 0x400000u) != 0; + if (m_seeState == 3) + { + m_bot->setQuadSeen(); + m_seeState = 0; + const Mat4& previous = m_frustum->m_transformation; + const float turn = camera.m[8] * previous.m[8] + camera.m[9] * previous.m[9] + + camera.m[10] * previous.m[10]; + if (m_frustumStep == 1) + m_frustumStep = 2; + else if (m_frustumStep == 0) + m_frustumStep = 1; + else + m_frustumStep = 0; + if (turn <= tweak_frustumUpdateAngle[m_viewMode][m_frustumStep].threshold) + m_frustumStep = 0; + } + IAIPlayer* const player = m_bot->getPlayer(); + player->getFieldOfView(); + const float viewDistance = player->getViewDistance(); + m_frustum->setPerspective(tweak_frustumUpdateAngle[m_viewMode][0].angle, 1.0f, 0.01f, viewDistance, camera); + + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + switch (m_seeState) + { + case 0: + { + m_candidates.resize(0); + const int side = m_bot->getSide(); + bool vehicleSight = false; + if ((equipment->getObjectTypeFlags() & 0x10u) || (equipment->getObjectTypeFlags() & 0x20u)) + vehicleSight = true; + SideFilter filter(side, equipment->getPosition(), viewDistance * viewDistance, vehicleSight); + const float ownRadius = equipment->getPhysical()->getRadius(); + environment->getWorldPlayerOccupiedObjects(m_candidates, &filter); + m_sortBuffer.resize(0); + const Vec3& own = equipment->getPosition(); + const float closeSq = static_cast(static_cast(ownRadius) * 3.0 * ownRadius * 3.0); + for (std::vector::iterator it = m_candidates.begin(); it != m_candidates.end(); ++it) + { + IAIObject* const object = *it; + Information* const information = informationManager->getInformation(object->getInformation(m_bot->getSide())); + const float radius = object->getBoundingRadius(); + bool take = m_frustum->inside(object->getPosition(), radius); + if (!take) + { + if (!(equipment->getObjectTypeFlags() & 0x200000u) + && (!information || (information->getObjectTypeFlags() & 0x200000u))) + { + take = vehicleSight && isCloseAndInFront(equipment, object); + } + else + { + const Vec3& position = object->getPosition(); + const float dx = position.x - own.x; + const float dy = position.y - own.y; + const float dz = position.z - own.z; + take = dx * dx + dy * dy + dz * dz <= closeSq; + } + } + if (!take) + continue; + { + const float distSq = distanceSqTo(own, object); + m_sortBuffer.push_back(std::make_pair(distSq, object->forceGetInformation(side, false))); + } + if (!object->isUnit()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotSenses.cpp", 413, "") + << object->getName() << " has no unit."; + } + else + { + IAIObjectUnit* const unit = object->getUnit(); + if (unit->hasExposedSoldier() && unit->isOccupied()) + { + IAIObject* const occupier = unit->getOccupier(); + const float distSq = distanceSqTo(own, occupier); + m_sortBuffer.push_back(std::make_pair(distSq, occupier->forceGetInformation(side, false))); + } + } + int iterator; + for (IAIObject* secondary = object->getFirstSecondaryObject(iterator); secondary; + secondary = object->getSecondaryObject(iterator)) + { + IAIObjectUnit* const unit = secondary->getUnit(); + if (!unit || !unit->hasExposedSoldier() || !unit->isOccupied()) + continue; + IAIObject* const occupier = unit->getOccupier(); + if (!occupier) + continue; + const float distSq = distanceSqTo(own, occupier); + m_sortBuffer.push_back(std::make_pair(distSq, occupier->forceGetInformation(side, false))); + } + } + m_seeIndex = 0; + m_collectTime = timer->getGameTime(); + m_seeState = 1; + if (slice < timer->getUpdateTime() - start) + return; + } + // fall through + case 1: + equipment->getPosition(); + if (!m_sortBuffer.empty()) + std::sort(m_sortBuffer.begin(), m_sortBuffer.end(), InfoDistPred()); + m_seeState = 2; + if (slice < timer->getUpdateTime() - start) + return; + // fall through + case 2: + break; + case 3: + timer->getUpdateTime(); + return; + default: + return; + } + + const Vec3& own = equipment->getPosition(); + std::vector ignore; + ignore.push_back(equipment->getAIObject()->getPrimaryObject()); + ignore.push_back(0); + ignore.push_back(0); + const bool render = IBotManager::instance->getRenderBotSensing(); + AIRenderUtil* const renderUtil = render ? AIRenderUtil::m_instance : 0; + const int side = m_bot->getSide(); + double elapsed = timer->getUpdateTime() - start; + equipment->getPhysical()->getRadius(); + bool finished = true; + while (m_seeIndex < static_cast(m_sortBuffer.size())) + { + if (slice <= elapsed) + { + finished = false; + break; + } + const unsigned int handle = m_sortBuffer[m_seeIndex].second; + Information* const target = m_map44.find(handle) == m_map44.end() + ? informationManager->getInformation(handle) : 0; + if (target && target->isRootObject()) + { + IAIObject* const targetObject = target->getAIObject(); + Bot* const targetBot = IBotManager::instance->getBot(targetObject); + bool activeBot = false; + if (targetBot) + activeBot = 0 < static_cast(targetBot->getLodLevel()); + targetObject->getBoundingRadius(); + ignore[1] = targetObject; + // [CHOSEN, not recovered] The image stores the third ignored object even after an + // earlier target shrank the list to two (inside the capacity, past the size, so the + // ray test never sees it); the size test keeps that store out of a native vector. + IAIObject* rider = 0; + bool keepRider = false; + if (IPIUnit* const unit = target->getUnit()) + { + if (!(target->getObjectTypeFlags() & 0x200000u)) + { + if (unit->hasExposedSoldier()) + { + if (Information* const occupier = + informationManager->getInformation(unit->getOccupier(m_bot->getSide()))) + { + rider = occupier->getAIObject(); + keepRider = true; + } + } + } + else if (Information* const occupied = + informationManager->getInformation(unit->getOccupiedObject(m_bot->getSide()))) + { + if (occupied->getUnit() && occupied->getUnit()->hasExposedSoldier()) + { + rider = occupied->getAIObject(); + keepRider = true; + } + } + } + if (keepRider) + { + if (ignore.size() > 2) + ignore[2] = rider; + } + else + { + ignore.resize(2); + } + + Vec3 eye; + eye.x = camera.m[12]; + eye.y = camera.m[13] - 0.1f; + eye.z = camera.m[14]; + const Vec3& targetPosition = targetObject->getPosition(); + const float dx = own.x - targetPosition.x; + const float dy = own.y - targetPosition.y; + const float dz = own.z - targetPosition.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + // The image converts with fistp: 1e14 (and any value past INT_MAX) becomes INT_MIN, + // i.e. one sample after the clamp. [CHOSEN] spelled out for a native conversion. + const double ratio = 0.0f < distance + ? static_cast(targetObject->getBoundingRadius()) * 30.0 / distance : 1e14; + int samples = ratio >= 2147483648.0 || ratio <= -2147483649.0 ? INT_MIN : static_cast(ratio); + if (samples < 1) + samples = 1; + else if (10 < samples) + samples = 10; + unsigned int part = static_cast(-1); + const bool soldier = (target->getObjectTypeFlags() & 0x200000u) != 0; + for (int k = 0; k < samples; ++k) + { + Vec3 point; + point.x = 0.0f; + point.y = 0.0f; + point.z = 0.0f; + Vec3 normal = point; + if (!soldier && k == 0 && samples != 1) + point = targetObject->getPosition(); + else if (!soldier) + environment->pickRandomSensePosition(point, normal, eye, targetObject); + else + environment->pickSoldierRandomSensePosition(point, normal, targetObject, part); + bool hitFlag; + const bool blocked = + environment->collideLineWithWorld(eye, point, ignore, activeBot, 0.8f, true, hitFlag); + if (render) + renderUtil->addSensingLine(eye, point, side, !blocked); + if (blocked) + continue; + Information* self = equipment; + if (!equipment->isPrimary()) + self = informationManager->getInformation(equipment->getPrimaryObject(m_bot->getSide())); + if (Bot* const viewer = IBotManager::instance->getBot(self->getAIObject())) + viewer->getSensingAgent()->getSenses()->event_seenObject( + handle, normal, part, target, viewer == m_bot, hitFlag); + int iterator = -1; + for (Information* secondary = informationManager->getInformation( + self->getFirstSecondaryObject(iterator, m_bot->getSide())); + secondary; + secondary = informationManager->getInformation(self->getSecondaryObject(iterator, m_bot->getSide()))) + { + if (Bot* const viewer = IBotManager::instance->getBot(secondary->getAIObject())) + viewer->getSensingAgent()->getSenses()->event_seenObject( + handle, normal, part, target, viewer == m_bot, hitFlag); + } + break; + } + } + ++m_seeIndex; + elapsed = timer->getUpdateTime() - start; + } + if (finished) + { + m_seeState = 3; + m_seeIndex = 0; + } + if (slice < timer->getUpdateTime() - start) + return; + timer->getUpdateTime(); +} + +// ELF 0x19BE60 (1528 bytes). Nothing is heard within 1.5 s of the bot's own last shot. With +// equipment, the heard list (+76) is worked through once, front to back, within the slice: each +// record is popped; one whose information is gone or has neither mobile nor armament leaves the +// heard set (+64) and loses SENSE_HEARD (and is deleted unless it is also seen); a heard one +// refreshes its primary object and the primary's secondary objects (setTime(now, max(s, 0.1))); +// one unheard for more than 30 s is dropped the same way; the rest are requeued at the back. +void BotSenses::updateHearing(const double& slice) +{ + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double now = timer->getGameTime(); + if (!(now - m_bot->getTimeOfLastFire() >= 1.5)) + return; + const double start = timer->getUpdateTime(); + const double budget = slice; + if (!informationManager->getInformation(m_bot->getCurrentEquipment())) + return; + const unsigned int count = static_cast(m_list76.size()); + const int side = m_bot->getSide(); + for (unsigned int i = 0; i < count && timer->getUpdateTime() < static_cast(start + budget); ++i) + { + SensedObject* const object = m_list76.front().second; + m_list76.erase(m_list76.begin()); + const unsigned int handle = object->m_handle; + Information* information = informationManager->getInformation(handle); + if (!information || (!information->getMobile() && !information->getArmament())) + { + m_set64.erase(handle); + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_HEARD; + if (!(flags & SensedObject::SENSE_SEEN)) + { + m_sensedObjects.erase(object->m_handle); + delete object; + } + continue; + } + const float strength = hear(handle, information); + if (0.0f < strength) + { + object->m_flags |= SensedObject::SENSE_HEARD_NOW; + object->m_lastSense = SensedObject::SENSE_HEARD_NOW; + object->m_lastSensedTime = now; + information = informationManager->getInformation(information->getPrimaryObject(side)); + float weight = 0.1f; + if (0.1f <= strength) + weight = strength; + if (information->setTime(timer->getGameTime(), weight)) + information->getAIObject()->addInformationToGrid(side); + int iterator = -1; + Information* secondary = + informationManager->getInformation(information->getFirstSecondaryObject(iterator, side)); + while (secondary) + { + float secondaryWeight = strength; + if (strength < 0.1f) + secondaryWeight = 0.1f; + secondary->setTime(timer->getGameTime(), secondaryWeight); + secondary = informationManager->getInformation(information->getSecondaryObject(iterator, side)); + } + } + else if (!(object->m_flags & SensedObject::SENSE_HEARD_NOW)) + { + if (30.0 < now - object->m_lastSensedTime) + { + m_set64.erase(handle); + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_HEARD; + if (!(flags & SensedObject::SENSE_SEEN)) + { + m_sensedObjects.erase(object->m_handle); + delete object; + } + continue; + } + } + else + { + object->m_flags &= ~SensedObject::SENSE_HEARD_NOW; + object->m_lastSensedTime = now; + } + m_list76.push_back(TimedObject(now, object)); + } +} + +// ELF 0x19C460 (1232 bytes). The incoming-fire strengths (+88 over the six strength types, +92 +// against the equipment's own strength type), each shot weighted x10 when direct, over the fire +// list (+84). Shots younger than min(60 / max(n, 1), 5) s are recorded per shooter in the attacker +// map (+100) when newer than the one there; an older duplicate, or an old shot the map does not +// hold, is deleted. Then the attacker strength (+96) over the map, whose entries older than +// max(30 / max(size, 1), 15) s are erased (not deleted: the list owns them). The slice is unused. +void BotSenses::updateFireObjects(const double&) +{ + m_fireTotalStrength = 0.0f; + m_fireTotalStrengthAgainstSelf = 0.0f; + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + IPIPhysical* physical = 0; + if (equipment) + physical = equipment->getPhysical(); + int ownStrengthType = 0; + if (physical) + ownStrengthType = physical->getStrengthType(); + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + + float divisor = static_cast(static_cast(m_list84.size())); + if (divisor < 1.0f) + divisor = 1.0f; + float window = 60.0f / divisor; + if (5.0f < 60.0f / divisor) + window = 5.0f; + for (std::list::iterator it = m_list84.begin(); it != m_list84.end(); ) + { + FireObject* const fire = it->first; + float weight = 10.0f; + if (!fire->isDirect()) + weight = 1.0f; + for (int type = 0; type < 6; ++type) + m_fireTotalStrength = fire->getBattleStrength(type) * weight + m_fireTotalStrength; + if (physical) + m_fireTotalStrengthAgainstSelf = + fire->getBattleStrength(ownStrengthType) * weight + m_fireTotalStrengthAgainstSelf; + if (timer->getGameTime() - fire->getTime() <= static_cast(window)) + { + std::pair::iterator, bool> inserted = + m_map100.insert(std::make_pair(it->second, fire)); + if (inserted.second || inserted.first->second->getTime() < fire->getTime()) + { + inserted.first->second = fire; + } + else if (inserted.first->second != fire) + { + delete fire; + it = m_list84.erase(it); + continue; + } + ++it; + } + else + { + const std::map::iterator held = m_map100.find(it->second); + if (held != m_map100.end() && held->second == fire) + { + ++it; + continue; + } + delete fire; + it = m_list84.erase(it); + } + } + + m_attackerStrength = 0.0f; + float attackers = 1.0f; + if (1.0f <= static_cast(static_cast(m_map100.size()))) + attackers = static_cast(static_cast(m_map100.size())); + float memory = 30.0f / attackers; + if (30.0f / attackers <= 15.0f) + memory = 15.0f; + const double now = timer->getGameTime(); + for (std::map::iterator it = m_map100.begin(); it != m_map100.end(); ) + { + if (static_cast(memory) <= now - it->second->getTime()) + { + m_map100.erase(it++); + } + else + { + m_attackerStrength = it->second->getBattleStrength(ownStrengthType) + m_attackerStrength; + ++it; + } + } +} + +// ELF 0x19C930: `fldl 0x20(fire)` when found, else -1000.0f widened. +bool BotSenses::isAttacking(unsigned int handle, double& time) const +{ + const std::map::const_iterator it = m_map100.find(handle); + const bool found = it != m_map100.end(); + if (found) + time = it->second->getTime(); + else + time = -1000.0f; + return found; +} + +// ELF 0x19C9A0. The shot goes to the back of the fire list. When the shooter's information is of +// another side, its primary object is reported as seen (zero position, part -1, not direct, +// flag40 off) and the shooter's seen record - looked up by the shooter's handle, not the primary's +// - gets the attack time (+0x3C). +void BotSenses::event_projectile(FireObject* fire, unsigned int handle) +{ + m_list84.push_back(FireEntry(fire, handle)); + Information* information = informationManager->getInformation(handle); + if (!information) + return; + if (information->getSide() == m_bot->getSide()) + return; + const unsigned int primaryHandle = information->getPrimaryObject(m_bot->getSide()); + information = informationManager->getInformation(primaryHandle); + if (!information) + return; + Vec3 zero; + zero.x = 0.0f; + zero.y = 0.0f; + zero.z = 0.0f; + event_seenObject(primaryHandle, zero, static_cast(-1), information, false, true); + const std::map::iterator seen = m_map44.find(handle); + if (seen != m_map44.end()) + seen->second->second->m_lastAttackTime = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +// ELF 0x19CB60 (1803 bytes). The information's time is refreshed (setTime(now); a true result puts +// its object into the side's grid). A handle not in the seen list gets a record (a new one is +// SENSE_INDIRECT with +0x14 = now) that becomes SENSE_SEEN with both positions refreshed; a direct +// sighting clears INDIRECT and, once per record, books a contact (reporting a new enemy first when +// the information had none); an indirect one tells the sensing agent. It then joins the back of +// the seen list and the handle -> list-position map. A handle already in the list is only moved to +// the back when it was INDIRECT and this sighting is direct. +void BotSenses::event_seenObject(unsigned int handle, const Vec3& position, unsigned int part, + Information* information, bool direct, bool notFlag40) +{ + const int side = m_bot->getSide(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (information->setTime(now)) + information->getAIObject()->addInformationToGrid(side); + + const std::map::iterator listed = m_map44.find(handle); + if (listed == m_map44.end()) + { + SensedObject* object; + const SensedObjectMap::iterator known = m_sensedObjects.find(handle); + if (known == m_sensedObjects.end()) + { + object = checkPointer(new SensedObject(handle, true, information->getSide() != 0)); + object->m_flags |= SensedObject::SENSE_INDIRECT; + object->m_lastSense = SensedObject::SENSE_INDIRECT; + object->m_firstSeenTime = now; + m_sensedObjects.insert(std::make_pair(handle, object)); + } + else + { + object = known->second; + } + object->m_flags |= SensedObject::SENSE_SEEN; + object->m_lastSense = SensedObject::SENSE_SEEN; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + object->m_lastSeenPosition = information->getPosition(); + object->m_lastSeenTime = now; + if (direct) + { + object->m_flags &= ~SensedObject::SENSE_INDIRECT; + if (!object->m_hasContact) + { + if (!information->hasContact()) + m_bot->getCommunicationAgent()->setSeenNewEnemy(information); + information->addContact(); + object->m_hasContact = true; + } + } + else + { + m_bot->getSensingAgent()->setSensedNewObject(); + } + if (!notFlag40) + { + object->m_flags |= SensedObject::SENSE_FLAG40; + object->m_lastSense = SensedObject::SENSE_FLAG40; + } + object->m_lastSensedTime = now; + object->m_seenPosition = position; + object->m_seenPart = part; + m_list56.push_back(TimedObject(now, object)); + m_map44[handle] = --m_list56.end(); + return; + } + + const TimedList::iterator entry = listed->second; + SensedObject* const object = entry->second; + if ((object->m_flags & SensedObject::SENSE_INDIRECT) && direct) + { + if (m_cursor60 == entry) + ++m_cursor60; + m_list56.erase(entry); + if (!object->m_hasContact) + { + information->addContact(); + object->m_hasContact = true; + } + object->m_seenPosition = position; + object->m_seenPart = part; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + object->m_lastSeenPosition = information->getPosition(); + object->m_flags &= ~SensedObject::SENSE_INDIRECT; + object->m_lastSeenTime = now; + m_list56.push_back(TimedObject(now, object)); + listed->second = --m_list56.end(); + } +} + +// ELF 0x19D270 (1632 bytes). Needs the bot's equipment information and 1.5 s since its own last +// shot; the bot does not hear its own equipment, its own side, or - from a non-soldier equipment - +// a soldier (type flag 0x200000). When hear() > 0: a handle already in the heard set (+64) only +// refreshes its record and the primary object's time; a new one books the information into the +// side's grid, gets (or reuses) a record, refreshes the primary (grid on a true setTime) and +// joins the back of the heard list. A brand-new record tells the sensing agent. +void BotSenses::event_heardObject(unsigned int handle) +{ + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!equipment) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(1.5 <= now - m_bot->getTimeOfLastFire())) + return; + if (handle == m_bot->getCurrentEquipment()) + return; + Information* const information = informationManager->getInformation(handle); + if (!information) + return; + if (information->getSide() == m_bot->getSide()) + return; + if (!(equipment->getObjectTypeFlags() & 0x200000u) && (information->getObjectTypeFlags() & 0x200000u)) + return; + const float strength = hear(handle, information); + if (!(0.0f < strength)) + return; + const int side = m_bot->getSide(); + const std::pair::iterator, bool> inserted = m_set64.insert(handle); + if (!inserted.second) + { + // The image does not check the find result. + SensedObject* const object = m_sensedObjects.find(handle)->second; + object->m_flags |= SensedObject::SENSE_HEARD; + object->m_lastSense = SensedObject::SENSE_HEARD; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + object->m_lastSensedTime = now; + Information* const primary = informationManager->getInformation(information->getPrimaryObject(side)); + float weight = 0.1f; + if (0.1f <= strength) + weight = strength; + primary->setTime(now, weight); + return; + } + + const SensedObjectMap::iterator known = m_sensedObjects.find(handle); + information->getAIObject()->addInformationToGrid(information->getSide()); + SensedObject* object; + if (known == m_sensedObjects.end()) + { + object = checkPointer(new SensedObject(handle, false, information->getSide() != 0)); + m_sensedObjects.insert(std::make_pair(handle, object)); + m_bot->getSensingAgent()->setSensedNewObject(); + } + else + { + object = known->second; + object->m_flags |= SensedObject::SENSE_HEARD; + object->m_lastSense = SensedObject::SENSE_HEARD; + } + object->m_handle = handle; + object->m_flags |= SensedObject::SENSE_HEARD; + object->m_lastSense = SensedObject::SENSE_HEARD; + object->m_lastSensedTime = now; + object->m_lastPosition = information->getPosition(); + object->m_lastPositionTime = now; + Information* const primary = informationManager->getInformation(information->getPrimaryObject(side)); + float weight = 0.1f; + if (0.1f <= strength) + weight = strength; + if (primary->setTime(now, weight)) + primary->getAIObject()->addInformationToGrid(side); + m_list76.push_back(TimedObject(now, object)); +} + +// ELF 0x19D8F0 (1152 bytes). Zero unless the bot has equipment, 1.5 s have passed since its own +// last shot, the object is alive (its physical plug-in's and its engine object's health > 0) and it +// has a mobile or an armament plug-in. The audible radius is the larger of the object's mobile +// sound radius (zeroed for a soldier in pose 2 or 3) and, within 5 s of a shot, its weapon's sound +// radius. Within that radius the hearing probability P interpolates the listener's mobile +// min..max by distance / the object's maximum sound radius (1 without a listener mobile); the +// object is heard (P returned) when a uniform draw exceeds (1 - max(speed / maxSpeed, 1)) * P. +// As in the image, the object's mobile is used for the maximum radius without a null check. +float BotSenses::hear(unsigned int, Information* information) +{ + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!equipment) + return 0.0f; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double now = timer->getGameTime(); + if (1.5 > now - m_bot->getTimeOfLastFire()) + return 0.0f; + if (IPIPhysical* const physical = information->getPhysical()) + { + if (0.0f >= physical->getHealth()) + return 0.0f; + } + IPIMobile* const mobile = information->getMobile(); + IPIArmament* const armament = information->getArmament(); + if (!armament && !mobile) + return 0.0f; + if (IAIObjectPhysical* const objectPhysical = information->getAIObject()->getPhysical()) + { + if (0.0f >= objectPhysical->getHealth()) + return 0.0f; + } + IPIMobile* const listener = equipment->getMobile(); + float mobileRadius; + if (mobile) + mobileRadius = mobile->getSoundSphereRadius(); + else + mobileRadius = 0.0f; + float weaponRadius = 0.0f; + if (armament) + { + if (WeaponInfo* const weapon = armament->getLastFiredWeapon()) + { + if (5.0 > now - weapon->getTimeOfFiring()) + weaponRadius = weapon->getSoundSphereRadius(); + } + } + if (information->getObjectTypeFlags() & 0x200000u) + { + const int pose = information->getSoldierPose(); + if (pose != 1 && !(pose < 1)) + { + if (pose <= 3) + mobileRadius = 0.0f; + } + } + float radius = weaponRadius; + if (weaponRadius <= mobileRadius) + radius = mobileRadius; + float moving; + if (listener) + { + moving = listener->getSpeedMagnitude() / listener->getMaxSpeed(); + if (moving <= 1.0f) + moving = 1.0f; + } + else + { + moving = 0.0f; + } + const Vec3& target = information->getAIObject()->getPosition(); + const Vec3& own = equipment->getPosition(); + const float dx = own.x - target.x; + const float dy = own.y - target.y; + const float dz = own.z - target.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (distance > radius) + return 0.0f; + const float fraction = distance / mobile->getSoundSphereRadiusMax(); + float probability; + if (listener) + probability = (1.0f - fraction) * listener->getHearingProbabilityMin() + + listener->getHearingProbabilityMax() * fraction; + else + probability = 1.0f; + const float threshold = (1.0f - moving) * probability; + const float draw = AIRandom::m_instance->nextFloat(); + return draw > threshold ? probability : 0.0f; +} + +// ELF 0x19DD70 (480 bytes). The information's primary object is looked up first (its contact is +// what a record releases). A listed handle leaves the seen list (the cursor at +60 resets to the +// end when it points at this record) and the position map, drops its contact and SENSE_SEEN, and +// is deleted unless it is also heard. +void BotSenses::forgetObject(unsigned int handle) +{ + Information* const information = informationManager->getInformation(handle); + if (!information) + return; + Information* const primary = + informationManager->getInformation(information->getPrimaryObject(m_bot->getSide())); + const std::map::iterator listed = m_map44.find(handle); + if (listed == m_map44.end()) + return; + SensedObject* const object = listed->second->second; + // [CHOSEN, not recovered] The image reads the cursor's element even at end() (its sentinel is a + // full node in that library); the end test keeps a native list's sentinel unread. + if (m_cursor60 != m_list56.end() && m_cursor60->second == object) + m_cursor60 = m_list56.end(); + m_list56.erase(listed->second); + m_map44.erase(listed); + if (object->m_hasContact) + { + primary->removeContact(); + object->m_hasContact = false; + } + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_SEEN; + if (!(flags & SensedObject::SENSE_HEARD)) + { + m_sensedObjects.erase(handle); + delete object; + } +} + +// ELF 0x19DF50 (352 bytes). `information`'s primary object's transformation (row 2 forward, +// row 3 position) is read before `object` is tested; `object`'s information for that side must +// be a primary one, within 200 m (squared < 40000) and in front (positive dot with forward). +bool BotSenses::isCloseAndInFront(Information* information, IAIObject* object) const +{ + Information* const primary = + informationManager->getInformation(information->getPrimaryObject(m_bot->getSide())); + if (!primary) + return false; + const Mat4& transformation = primary->getTransformation(); + if (!object) + return false; + Information* const other = informationManager->getInformation(object->getInformation(information->getSide())); + if (!other || !other->isPrimary()) + return false; + const Vec3& position = object->getPosition(); + const float dx = position.x - transformation.m[12]; + const float dy = position.y - transformation.m[13]; + const float dz = position.z - transformation.m[14]; + return dx * dx + dy * dy + dz * dz < 40000.0f + && 0.0f < dx * transformation.m[8] + dy * transformation.m[9] + dz * transformation.m[10]; +} + +namespace { + +// ELF 0x197650 (448 bytes). The centre of a soldier for the sight ray: its position plus a pose +// offset (lying: y - 0.7; standing and crouching: none). Any other pose logs "Unknown pose" +// (DebugTypeError, BotSenses.cpp line 207) and leaves `offset` as the caller set it. +void soldierHack_getSoldierCentre(Vec3& centre, Vec3& offset, Information* information) +{ + if (information->getSoldierPose() == SPLying) + { + offset.x = 0.0f; + offset.y = -0.7f; + offset.z = 0.0f; + } + else if (information->getSoldierPose() == SPCrouching || information->getSoldierPose() == SPStanding) + { + offset.x = 0.0f; + offset.y = 0.0f; + offset.z = 0.0f; + } + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotSenses.cpp", 207, "") << "Unknown pose"; + } + const Vec3& position = information->getPosition(); + centre.x = offset.x + position.x; + centre.y = offset.y + position.y; + centre.z = offset.z + position.z; +} + +// The pose probe of updateSeeing (four inlined copies in the image): while the bot is changing +// pose (requested pose 2 or 3 differs from the equipment's current one), a second ray from where +// the eye will be tells the bot whether its firing target stays visible after the change. +// Crouching (2): y - 0.53 from standing, otherwise y + 0.38; lying (3): y - 0.91 from standing, +// otherwise y - 0.38. Reported through Bot +0x19C setPoseStatus(pose, handle, visible, hit). +void probePose(BotMain* bot, IAIObjectEnvironment* environment, const Vec3& eye, const Vec3& point, + const std::vector& ignore, bool activeBot, float width, SoldierPose pose, + int requested, unsigned int handle) +{ + Vec3 probe = eye; + if (requested == 2) + probe.y = pose == SPStanding ? eye.y - 0.53f : eye.y + 0.38f; + else if (requested == 3) + probe.y = eye.y - (pose == SPStanding ? 0.91f : 0.38f); + else + return; + bool hit; + const bool blocked = environment->collideLineWithWorld(probe, point, ignore, activeBot, width, true, hit); + bot->setPoseStatus(requested, handle, !blocked, hit); +} + +} // namespace + +// ELF 0x19A0F0 (7533 bytes). Reads the render flag (IBotManager +0x78), the update time and the +// game time, then works through the seen list (+56) from the cursor (+60, wrapping to the front) +// until the cursor is back where it started, the slice is spent or the list is empty. Per record: +// * dropped (seen bit cleared, deleted unless heard) when its information is gone, has no +// object, is not a root object, is on the bot's side or side 0, or is physically dead; +// * "in view" for a primary object or a soldier when it attacked the bot within 5 s, or the bot +// is a soldier and it is within 2r + 3 * own radius, or it is inside the frustum and within its +// unit's cull distance; or, with vehicle sight (equipment flag 0x10 / 0x20), close and in front; +// * in view, a ray (0.75) from the eye (camera row 3, y - 0.1) ignoring {own primary, target, +// rider}: an active bot target is sensed at its centre (soldier) or position; otherwise the +// stored sense point (+4) through the object matrix (non-soldier) or the stored body part +// (soldier, IAIObjectEnvironment +0x58); failing that, a fresh pick (+0x54 / +0x50); +// * visible: setTime, a contact booked when it was indirect, positions and times refreshed, +// flag 0x40 from the ray's hit output, and every other bot riding in the bot's primary object +// and its secondaries told (event_seenObject, indirect); +// * not visible: INDIRECT set (+0x14 = now) once; later the contact is released after 2 s, and +// the record forgotten after 60 s, or when the target is not primary, or after 5 s when the +// bot's equipment has no mobile, can engage it (anti-aircraft against flag 0x10), or the bot +// is going for a flag (Bot +0x27C). +// Kept records move to the back of the list (time = now) and re-register in the map (+44). +void BotSenses::updateSeeing(const double& slice) +{ + IBotManager* const botManager = IBotManager::instance; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + const bool render = botManager->getRenderBotSensing(); + AIRenderUtil* const renderUtil = render ? AIRenderUtil::m_instance : 0; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double start = timer->getUpdateTime(); + const double now = timer->getGameTime(); + if (m_list56.empty()) + return; + + // As in the image, the equipment information is used without a null check. + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + const bool ownSoldier = (equipment->getObjectTypeFlags() & 0x200000u) != 0; + const float ownRadius3 = equipment->getPhysical()->getRadius() * 3.0f; + std::vector ignore; + ignore.push_back(equipment->getAIObject()->getPrimaryObject()); + ignore.push_back(0); + ignore.push_back(0); + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + Vec3 eye; + eye.x = camera.m[12]; + eye.y = camera.m[13] - 0.1f; + eye.z = camera.m[14]; + + // [CHOSEN, not recovered] The image stops when the cursor reaches the node it started on. A + // kept record is erased and re-inserted at the back, and the pool allocator hands the freed + // node straight back, so the start node survives that move; splice keeps the node the same + // way. When the start record is forgotten its node is gone, and the image's test then only + // matches if the pool reuses the node later; here the start is dropped and the slice or an + // empty list ends the pass. + const TimedList::iterator stop = m_cursor60; + bool stopValid = true; + double elapsed; + do + { + if (m_cursor60 == m_list56.end()) + m_cursor60 = m_list56.begin(); + const TimedList::iterator current = m_cursor60++; + SensedObject* const object = current->second; + const unsigned int handle = object->m_handle; + Information* const information = informationManager->getInformation(handle); + + bool drop = !information || !information->getAIObject() || !information->isRootObject() + || information->getSide() == m_bot->getSide() || information->getSide() == 0 + || (information->getPhysical() && information->getPhysical()->getHealth() <= 0.0f); + bool forget = false; + if (!drop) + { + IAIObject* const target = information->getAIObject(); + const bool primary = information->isPrimary(); + const bool soldier = (information->getObjectTypeFlags() & 0x200000u) != 0; + const float radius = target->getBoundingRadius(); + const Vec3& position = target->getPosition(); + const float dx = position.x - eye.x; + const float dy = position.y - eye.y; + const float dz = position.z - eye.z; + const float distSq = dz * dz + dy * dy + dx * dx; + bool inView = false; + if (primary || soldier) + { + inView = true; + if (5.0 < now - object->m_lastAttackTime) + { + const float close = radius + radius + ownRadius3; + if (!ownSoldier || close * close < distSq) + { + if (!m_frustum->inside(target->getPosition(), radius) + || (information->getUnit() && information->getUnit()->getCullDistanceSqr() < distSq)) + inView = false; + } + } + } + const bool vehicleSight = (equipment->getObjectTypeFlags() & 0x10u) || (equipment->getObjectTypeFlags() & 0x20u); + const bool consider = inView || (vehicleSight && isCloseAndInFront(equipment, target)); + bool visible = consider; + Vec3 point; + point.x = 0.0f; + point.y = 0.0f; + point.z = 0.0f; + Vec3 sense = point; + Bot* const targetBot = IBotManager::instance->getBot(target); + bool activeBot = false; + if (targetBot) + activeBot = 0 < static_cast(targetBot->getLodLevel()); + unsigned int part = static_cast(-1); + bool hit = false; + + if (consider) + { + ignore[1] = target; + // The rider slot keeps the previous record's object when none is found here. + if (IPIUnit* const unit = information->getUnit()) + { + if (!soldier) + { + if (unit->hasExposedSoldier()) + { + if (Information* const occupier = + informationManager->getInformation(unit->getOccupier(m_bot->getSide()))) + ignore[2] = occupier->getAIObject(); + } + } + else if (Information* const occupied = + informationManager->getInformation(unit->getOccupiedObject(m_bot->getSide()))) + { + if (occupied->getUnit() && occupied->getUnit()->hasExposedSoldier()) + ignore[2] = occupied->getAIObject(); + } + } + + // First ray: an active bot target at its centre (soldier) or any target at its + // position (non-soldier); a soldier that is not an active bot gets no first ray. + if (soldier) + { + if (!activeBot) + { + visible = false; + } + else + { + soldierHack_getSoldierCentre(point, sense, information); + visible = !environment->collideLineWithWorld(eye, point, ignore, activeBot, 0.75f, true, hit); + const SoldierPose pose = equipment->getSoldierPose(); + const int requested = m_bot->getRequestedSolderPose(); + if (visible && pose != requested && pose != SPSwimming + && m_bot->getFiringTarget() == handle) + probePose(m_bot, environment, eye, point, ignore, activeBot, 0.75f, pose, requested, handle); + } + } + else + { + sense.x = 0.0f; + sense.y = 0.0f; + sense.z = 0.0f; + point = target->getPosition(); + visible = !environment->collideLineWithWorld(eye, point, ignore, activeBot, 0.75f, true, hit); + } + + // Second ray (not for an active bot): the stored sense point. + if (!visible && !activeBot) + { + if (!soldier) + { + sense = object->m_seenPosition; + const Mat4& matrix = target->getTransformation(); + point.x = matrix.m[8] * sense.z + matrix.m[0] * sense.x + matrix.m[4] * sense.y + matrix.m[12]; + point.y = matrix.m[1] * sense.x + matrix.m[5] * sense.y + matrix.m[9] * sense.z + matrix.m[13]; + point.z = sense.y * matrix.m[6] + matrix.m[2] * sense.x + sense.z * matrix.m[10] + matrix.m[14]; + visible = !environment->collideLineWithWorld(eye, point, ignore, false, 0.75f, true, hit); + } + else + { + const bool sensed = environment->getSoldierSensePosition(point, sense, target, object->m_seenPart); + part = object->m_seenPart; + if (sensed) + { + visible = !environment->collideLineWithWorld(eye, point, ignore, false, 0.75f, true, hit); + const SoldierPose pose = equipment->getSoldierPose(); + const int requested = m_bot->getRequestedSolderPose(); + if (visible && pose != requested && m_bot->getFiringTarget() == handle) + probePose(m_bot, environment, eye, point, ignore, false, 0.8f, pose, requested, handle); + } + } + } + + // Third ray (not for an active bot): a fresh sense point. + if (!visible && !activeBot) + { + if (soldier) + { + environment->pickSoldierRandomSensePosition(point, sense, target, part); + object->m_seenPart = part; + } + else + { + environment->pickRandomSensePosition(point, sense, eye, target); + } + visible = !environment->collideLineWithWorld(eye, point, ignore, false, 0.75f, true, hit); + const SoldierPose pose = equipment->getSoldierPose(); + const int requested = m_bot->getRequestedSolderPose(); + if (visible && requested != pose && m_bot->getFiringTarget() == handle) + probePose(m_bot, environment, eye, point, ignore, false, 0.8f, pose, requested, handle); + } + } + + if (visible) + { + information->setTime(now); + if (object->m_flags & SensedObject::SENSE_INDIRECT) + { + if (!object->m_hasContact) + { + information->addContact(); + object->m_hasContact = true; + } + object->m_flags &= ~SensedObject::SENSE_INDIRECT; + } + object->m_lastPosition = point; + object->m_lastPositionTime = now; + object->m_lastSeenPosition = point; + object->m_lastSeenTime = now; + object->m_seenPosition = sense; + if (!hit) + { + object->m_flags |= SensedObject::SENSE_FLAG40; + object->m_lastSense = SensedObject::SENSE_FLAG40; + } + else + { + object->m_flags &= ~SensedObject::SENSE_FLAG40; + } + + // Every other bot riding in this bot's primary object or its secondaries. + Information* self = equipment; + if (!equipment->isPrimary()) + self = informationManager->getInformation(equipment->getPrimaryObject(m_bot->getSide())); + const auto tellRider = [&](Bot* rider) + { + if (!rider || rider == m_bot) + return; + rider->getSensingAgent()->getSenses()->event_seenObject( + handle, object->m_seenPosition, part, information, false, hit); + if (botManager->getRenderBotSensing() && AIRenderUtil::m_instance) + AIRenderUtil::m_instance->addSensingLine(eye, sense, m_bot->getPlayer()->getSide(), visible); + }; + tellRider(IBotManager::instance->getBot(self->getAIObject())); + int iterator = -1; + for (Information* secondary = informationManager->getInformation( + self->getFirstSecondaryObject(iterator, m_bot->getSide())); + secondary; + secondary = informationManager->getInformation(self->getSecondaryObject(iterator, m_bot->getSide()))) + tellRider(IBotManager::instance->getBot(secondary->getAIObject())); + } + else if (!(object->m_flags & SensedObject::SENSE_INDIRECT)) + { + object->m_lastSense = SensedObject::SENSE_INDIRECT; + object->m_flags |= SensedObject::SENSE_INDIRECT; + object->m_firstSeenTime = now; // here: when it went out of sight + } + else + { + const double unseen = now - object->m_firstSeenTime; + Information* const lost = informationManager->getInformation(handle); + if (2.0 < unseen && object->m_hasContact) + { + object->m_hasContact = false; + lost->removeContact(); + int iterator = -1; + for (Information* secondary = informationManager->getInformation( + lost->getFirstSecondaryObject(iterator, m_bot->getSide())); + secondary; + secondary = informationManager->getInformation(lost->getSecondaryObject(iterator, m_bot->getSide()))) + secondary->removeContact(); + } + // As in the image, the equipment information is used without a null check. + Information* const own = informationManager->getInformation(m_bot->getCurrentEquipment()); + IPIArmament* const armament = own->getArmament(); + const bool canEngage = armament && (lost->getObjectTypeFlags() & 0x10u) && 0 < armament->isAntiAircraft(); + if (60.0 < unseen || !primary || (!own->getMobile() && 5.0 < unseen) + || (canEngage && 5.0 < unseen) || (m_bot->getIsGoingForFlag() && 5.0 < unseen)) + forget = true; + } + if (render) + renderUtil->addSensingLine(eye, point, m_bot->getSide(), visible); + } + + if (drop || forget) + { + if (current == stop) + stopValid = false; + m_list56.erase(current); + m_map44.erase(handle); + const unsigned int flags = object->m_flags; + object->m_flags = flags & ~SensedObject::SENSE_SEEN; + if (!(flags & SensedObject::SENSE_HEARD)) + { + m_sensedObjects.erase(handle); + delete object; + } + } + else + { + current->first = now; + m_list56.splice(m_list56.end(), m_list56, current); + m_map44[handle] = --m_list56.end(); + } + elapsed = timer->getUpdateTime() - start; + } while ((!stopValid || m_cursor60 != stop) && elapsed < slice && !m_list56.empty()); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h index dfb256b7d..f945c6617 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h @@ -16,9 +16,9 @@ namespace hfe { namespace ai { class BotMain; -// The two things a bot's perception owns and deletes. Both are [FRONTIER] classes - `reset` and -// the destructor delete them through an inlined, non-virtual destructor, so neither can be written -// until the class itself is recovered. See the reset block in the .cpp. +class IAIObject; +class Information; +// The two things a bot's perception owns and deletes (AIBot/SensedObject.h, AIKnowledge/FireObject.h). class FireObject; class SensedObject; @@ -33,22 +33,58 @@ class BotSenses // attested: an 11-byte body that returns `this + 112`. const std::map& getSensedObjects() const { return m_sensedObjects; } + typedef std::pair FireEntry; + + // ELF 0x198420 (6421 bytes) [FRONTIER]. + void see(const double& slice); + // ELF 0x19a040: hearing, fire objects, then seeing with the remaining slice. + void updateSensing(const double& slice); + void updateHearing(const double& slice); // ELF 0x19be60 [FRONTIER] + void updateFireObjects(const double& slice); // ELF 0x19c460 [FRONTIER] + void updateSeeing(const double& slice); // ELF 0x19a0f0 [FRONTIER] + // ELF 0x19d8a0: the record for a handle, or null. + SensedObject* getSensedObjectFromHandle(unsigned int handle) const; + // ELF 0x19C930: the attacker map's fire time for a shooter, else -1000.0. + bool isAttacking(unsigned int handle, double& time) const; + // ELF 0x19C9A0: queue a reported shot; an enemy shooter's primary object counts as seen. + void event_projectile(FireObject* fire, unsigned int handle); + // ELF 0x19CB60: a seen object (handle, seen position, seen part, information, direct, flag40 off). + void event_seenObject(unsigned int handle, const Vec3& position, unsigned int part, + Information* information, bool direct, bool notFlag40); + // ELF 0x19D270: an engine sound event for a handle. + void event_heardObject(unsigned int handle); + // ELF 0x19D8F0: the hearing probability of an object, or 0 when not heard. + float hear(unsigned int handle, Information* information); + // ELF 0x19DD70: drop a handle from the seen list. + void forgetObject(unsigned int handle); + // ELF 0x19DF50: `object`'s primary information is within 200 m and in front of `information`'s + // primary object. + bool isCloseAndInFront(Information* information, IAIObject* object) const; + // ELF 0x18b0c0..0x18b120 (BotMain's forwarders read these fields inline). + std::list* getIncommingFire() { return &m_list84; } + float getIncommingFireTotalStrength() const { return m_fireTotalStrength; } + float getIncommingFireTotalStrengthAgainstSelf() const { return m_fireTotalStrengthAgainstSelf; } + float getAttackerStrength() const { return m_attackerStrength; } + private: + // BotMain::getAttackers (ELF 0x18B180) returns the map at +100 inline. + friend class BotMain; typedef std::pair TimedObject; // a time and a thing typedef std::list TimedList; - typedef std::pair FireEntry; typedef std::map SensedObjectMap; /* 0 */ BotMain* m_bot; // the ctor argument, and the first store /* 4 */ Frustum* m_frustum; // new(0x1E8) - . See the header block. - /* 8 */ char m_gap8[4]; // [UNRESOLVED] - never written, by anything read so far - /* 12 */ double m_double12; // = -1000000.0 a fifth kind of sentinel + // see (ELF 0x198420): 1 when the equipment has type flag 0x400000 (meaning [UNRESOLVED]); the + // row of tweak_frustumUpdateAngle used for the frustum. + /* 8 */ int m_viewMode; + /* 12 */ double m_collectTime; // = -1000000.0; see: the game time of the last candidate scan // the distance sort buffer - what `InfoDistPred` and `partial_sort` operate on. Held as a // member rather than a local, so the seeing path does not reallocate every tick. /* 20 */ std::vector > m_sortBuffer; - /* 32 */ int m_int32; // ctor: 0, reset: 0 - /* 36 */ int m_int36; // ctor: 0, reset: 0 - /* 40 */ int m_int40; // ctor: 0, reset: 0 + /* 32 */ int m_frustumStep; // ctor/reset 0; see cycles it 0 -> 1 -> 2 -> 0 + /* 36 */ int m_seeState; // ctor/reset 0; see: 0 scan, 1 sort, 2 test, 3 done + /* 40 */ int m_seeIndex; // ctor/reset 0; see: the next sort-buffer entry to test // handle -> position in the list at +56. See the header block. /* 44 */ std::map m_map44; /* 56 */ TimedList m_list56; @@ -60,14 +96,17 @@ class BotSenses // Only `reset` makes it valid. See the header block. /* 80 */ TimedList::iterator m_cursor80; /* 84 */ std::list m_list84; - /* 88 */ int m_int88; // ctor: 0, reset: 0 - /* 92 */ int m_int92; // ctor: 0, reset: 0 - /* 96 */ char m_gap96[4]; // [UNRESOLVED] - never written + // Floats: BotMain::getIncommingFireTotalStrength (ELF 0x18b0e0) and + // ...AgainstSelf (0x18b100) return `flds 0x58/0x5c(senses)`, getAttackerStrength (0x18b120) + // `flds 0x60`. The zero stores of ctor/reset are the same bits. + /* 88 */ float m_fireTotalStrength; // ctor: 0, reset: 0 + /* 92 */ float m_fireTotalStrengthAgainstSelf; // ctor: 0, reset: 0 + /* 96 */ float m_attackerStrength; // not written by ctor/reset /* 100 */ std::map m_map100; /* 112 */ SensedObjectMap m_sensedObjects; // the only two containers `reset` does not empty. Element width 4 and trivially destructible // (the destructor deallocates without a per-element loop); the element type is [INFERRED]. - /* 124 */ std::vector m_vector124; + /* 124 */ std::vector m_candidates; // see: getWorldPlayerOccupiedObjects' output /* 136 */ std::vector m_vector136; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp index 9a9b152d9..3559c4f79 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.cpp @@ -1,13 +1,19 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotSquad operations. #include "BotSquad.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A1930, __tcf_0 0x1A1990, _GLOBAL__I 0x1A19C0). +#include #include "BotMain.h" #include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFSquad.h" +#include "../AIKnowledge/Information.h" +#include "SquadCoordinator.h" +#include "SquadManager.h" namespace dice { namespace hfe { @@ -59,84 +65,130 @@ bool BotSquad::joinSquad(int squad) return joined; } +namespace { + +IBFSquad* squadAdapter() +{ + return static_cast(CommonSingletonServer::m_iBFSquad); +} + +IAIObject* objectOf(Information* info) +{ + return info ? info->getAIObject() : 0; // Information +0x20 +} + +} // namespace + +// ELF 0x1A11B0: joins the side's next empty squad (the id is not stored; the engine's join event +// sets it). bool BotSquad::createSquad() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::createSquad"); + IAIPlayer* const player = m_bot->getPlayer(); + const int squad = squadAdapter()->getNextEmptySquad(m_bot->getSide()); + return squadAdapter()->joinSquad(squad, player); } +// ELF 0x1A1230. void BotSquad::exitSquad() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::exitSquad"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->exitSquad(m_squadId, player); } +// ELF 0x1A1280. bool BotSquad::isSquadLeader() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::isSquadLeader"); + IAIPlayer* const player = m_bot->getPlayer(); + return squadAdapter()->isSquadLeader(m_squadId, player); } +// ELF 0x1A12D0: the argument is not read. void BotSquad::applyAsSquadLeader(int) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::applyAsSquadLeader"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->assignAsSquadLeader(m_squadId, player); } +// ELF 0x1A1320: the argument is not read. void BotSquad::retireAsSquadLeader(int) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::retireAsSquadLeader"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->retireAsSquadLeader(m_squadId, player); +} + +// ELF 0x1A13F0 / 0x1A1460 / 0x1A14D0: (position, squad, side, the target's object or null). +void BotSquad::issueSquadAttackOrder(const Vec3& position, Information* info) +{ + IAIObject* const object = objectOf(info); + squadAdapter()->issueSquadAttackOrder(position, m_squadId, m_bot->getSide(), object); } -void BotSquad::issueSquadAttackOrder(const Vec3&, Information*) +void BotSquad::issueSquadMoveOrder(const Vec3& position, Information* info) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::issueSquadAttackOrder"); + IAIObject* const object = objectOf(info); + squadAdapter()->issueSquadMoveOrder(position, m_squadId, m_bot->getSide(), object); } -void BotSquad::issueSquadMoveOrder(const Vec3&, Information*) +void BotSquad::issueSquadDefendOrder(const Vec3& position, Information* info) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::issueSquadMoveOrder"); + IAIObject* const object = objectOf(info); + squadAdapter()->issueSquadDefendOrder(position, m_squadId, m_bot->getSide(), object); } -void BotSquad::issueSquadDefendOrder(const Vec3&, Information*) +namespace { + +// ELF 0x1A1540 / 0x1A1640 / 0x1A1740: the squad order's position (IBFSquad +0x54 getSquadOrder), +// the order type stored, and the squad's mission requested unless it is the same already. +void receiveSquadOrder(BotMain* bot, int squadId, BotSquad::OrderType& order, BotSquad::OrderType type) { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::issueSquadDefendOrder"); + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + squadAdapter()->getSquadOrder(bot->getSide(), squadId, position, 0); + order = type; + SquadCoordinator* const squad = SquadManager::m_instance->getSquadFromId(squadId, bot->getSide()); + if (!squad->isSameMission(order, position, 0)) + squad->requestMission(order, position, 0, false); } +} // namespace + void BotSquad::recieveAttackSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveAttackSquadOrder"); + receiveSquadOrder(m_bot, m_squadId, m_order, OrderAttack); } void BotSquad::recieveDefendSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveDefendSquadOrder"); + receiveSquadOrder(m_bot, m_squadId, m_order, OrderDefend); } void BotSquad::recieveMoveSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveMoveSquadOrder"); -} - -void BotSquad::recieveAttackCommanderOrder() -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveAttackCommanderOrder"); + receiveSquadOrder(m_bot, m_squadId, m_order, OrderMove); } -void BotSquad::recieveDefendCommanderOrder() -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveDefendCommanderOrder"); -} +// ELF 0x1A18E0 / 0x1A18F0 / 0x1A1900: empty. +void BotSquad::recieveAttackCommanderOrder() {} +void BotSquad::recieveDefendCommanderOrder() {} +void BotSquad::recieveMoveCommanderOrder() {} -void BotSquad::recieveMoveCommanderOrder() -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::recieveMoveCommanderOrder"); -} +// ELF 0x1A1910 / 0x1A1920: empty (a 0x148-byte frame and no code). +void BotSquad::acceptCommanderOrder() {} +void BotSquad::declineCommanderOrder() {} +// ELF 0x1A1840 / 0x1A1890. void BotSquad::acceptSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::acceptSquadOrder"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->acceptSquadOrder(m_squadId, player); } void BotSquad::declineSquadOrder() { - BF2_AI_FRONTIER("dice::hfe::ai::BotSquad::declineSquadOrder"); + IAIPlayer* const player = m_bot->getPlayer(); + squadAdapter()->declineSquadOrder(m_squadId, player); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h index 574f008e4..fe71c56f1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h @@ -58,9 +58,15 @@ class BotSquad void recieveAttackCommanderOrder(); void recieveDefendCommanderOrder(); void recieveMoveCommanderOrder(); + void acceptCommanderOrder(); + void declineCommanderOrder(); void acceptSquadOrder(); void declineSquadOrder(); + // [INFERRED] inline accessor: CommanderInterface's Bot overloads (ELF 0x3232D0..) read +4 + // directly. + int getSquadId() const { return m_squadId; } + private: /* 0 */ BotMain* m_bot; // the ctor argument /* 4 */ int m_squadId; // = 0; `joinSquad` sets it on success. `createSquad` does not diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp index 755b8760a..fdbdeac0d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp @@ -2,6 +2,14 @@ #include "BotSubObjects.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A2210, __tcf_0 0x1A2270, _GLOBAL__I 0x1A22A0). +#include + +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + namespace dice { namespace hfe { namespace ai { @@ -14,12 +22,31 @@ FireCorrectionData::FireCorrectionData() , m_flag84(false) { // +0..+3 and +68..+83 are deliberately untouched - see above. - for (int i = 0; i < 15; ++i) - m_zero8[i] = 0; - for (int i = 0; i < 9; ++i) - m_zero88[i] = 0; + for (int i = 0; i < 3; ++i) + m_firedTarget[i] = 0.0f; + Vec3* const zeroed[4] = { &m_missedPosition, &m_aimDirection, &m_vec44, &m_predictedTarget }; + for (int i = 0; i < 4; ++i) + zeroed[i]->x = zeroed[i]->y = zeroed[i]->z = 0.0f; + // +88..+120 zeroed: the three points. + Vec3* const points[3] = { &m_projectilePrePoint, &m_projectilePostPoint, &m_projectileTargetPoint }; + for (int i = 0; i < 3; ++i) + points[i]->x = points[i]->y = points[i]->z = 0.0f; } +// ELF 0x1A2170 (160 bytes). +void FireCorrectionData::newTarget(unsigned int handle) +{ + m_flag5 = true; + m_flag4 = true; + m_flag6 = true; + m_double72 = -1.0f; + Information* const information = informationManager->getInformation(handle); + m_vec44.x = 0.0f; m_vec44.y = 0.0f; m_vec44.z = 0.0f; + if (information) + m_shotTarget = information->getAIObject()->getObject(); // IAIObject slot +0x20 + else + m_shotTarget = 0; +} } // namespace ai } // namespace hfe diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h index a6c0a9b63..f91154556 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.h @@ -3,6 +3,8 @@ #ifndef AI_AIDLL_AI_AIBOT_BOTSUBOBJECTS_H #define AI_AIDLL_AI_AIBOT_BOTSUBOBJECTS_H +#include "../../../../Math/Vec3.h" + namespace dice { namespace hfe { namespace ai { @@ -14,18 +16,35 @@ class FireCorrectionData { public: FireCorrectionData(); // for the class + // ELF 0x1A2170: +4/+5/+6 set, +72 = -1.0, +44 zeroed, +80 = the target's world object. + void newTarget(unsigned int handle); -private: - /* 0 */ char m_gap0[4]; // [UNRESOLVED] - not initialised by the ctor + // BotMain::planExecution (ELF 0x188B90) writes these inline once the collision handler + // reports that the bot's projectile passed its point: the pre/post/target points and the + // maximum height from IBFCollisionHandler, then sets +5, +84 and +85. + /* 0 */ int m_weapon; // not initialised by the ctor; event_firing's int (the weapon) [INFERRED] /* 4 */ bool m_flag4; // = true - /* 5 */ bool m_flag5; // = true - /* 6 */ char m_pad6[2]; - /* 8 */ int m_zero8[15]; // +8..+64, all zeroed - /* 68 */ char m_gap68[16]; // [UNRESOLVED] - the ctor skips +68..+83 - /* 84 */ bool m_flag84; // = false - /* 85 */ char m_pad85[3]; - /* 88 */ int m_zero88[9]; // +88..+120, all zeroed - /* 124 */ char m_gap124[4]; // [UNRESOLVED] - 128 - 124 + /* 5 */ bool m_flag5; // = true; planExecution: true + /* 6 */ bool m_flag6; // not initialised by the ctor; event_firing: a correction shot is out + /* 7 */ char m_pad7[1]; + /* 8 */ float m_firedTarget[3]; // zeroed; event_firing's target (a Vec3) + // +20..+64 zeroed by the ctor. event_shotMissed (ELF 0x18B230) stores the miss at +0x14; + // newTarget (0x1A2170) zeroes +0x2C; EntryMouseTurretAimAt (0x2B9A5C) writes +0x20 (the aim + // direction) and +0x38 (the predicted target position). [INFERRED] names. + /* 20 */ Vec3 m_missedPosition; + /* 32 */ Vec3 m_aimDirection; + /* 44 */ Vec3 m_vec44; // [UNRESOLVED] name + /* 56 */ Vec3 m_predictedTarget; + /* 68 */ char m_gap68[4]; // [UNRESOLVED] - the ctor skips +68..+83 + /* 72 */ double m_double72; // event_firing / newTarget: -1.0; event_shotMissed: the miss time + /* 80 */ const void* m_shotTarget; // event_shotHit: a hit on this object confirms the shot [INFERRED] + /* 84 */ bool m_flag84; // = false; planExecution: true + /* 85 */ bool m_flag85; // planExecution: true + /* 86 */ char m_pad86[2]; + /* 88 */ Vec3 m_projectilePrePoint; // = 0 + /* 100 */ Vec3 m_projectilePostPoint; // = 0 + /* 112 */ Vec3 m_projectileTargetPoint; // = 0 + /* 124 */ float m_projectileMaxHeight; // not initialised by the ctor }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp index d0a1add9b..98c54f965 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp @@ -1,12 +1,29 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining CommunicationAgent operations. #include "CommunicationAgent.h" -#include "../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1C54D0, __tcf_0 0x1C5530, _GLOBAL__I 0x1C5560). +#include + +#include + +#include "BotMain.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../../../../IO/Input/PlayerInput.h" + +#include "../Main/IBotManager.h" #include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../Main/CommunicationHub.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::getIsAIPlayer +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" // getPlayerFromId #include "../../../AIInterface/Module/BFConsole.h" // IBFModuleCourier, AIRadioMessageSettings namespace dice { @@ -46,6 +63,10 @@ CommunicationAgent::CommunicationAgent(BotMain* owner) reset(); } +CommunicationAgent::~CommunicationAgent() +{ +} + // Resets message state and acquires the shared communication hub. void CommunicationAgent::reset() { @@ -64,22 +85,380 @@ void CommunicationAgent::reset() while (!m_queue.empty()) m_queue.pop(); - m_double60 = 0.0; + m_lastPollTime = 0.0; m_int92 = -1; // This order is the binary's. - m_double104 = 0.0; + m_hornTime = 0.0; m_double96 = 0.0; } -// [FRONTIER] Remaining message operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -// [FRONTIER] Services one bot's radio on the BotManager communication tick. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when radio update behavior is recovered. +// ELF 0x1C4100: old messages are aged out every tick; the radio is polled once a second +// (a game time that went backwards restarts the interval). void CommunicationAgent::update() { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationAgent::update"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + clearOutOldMessages(now); + if (now < m_lastPollTime) + m_lastPollTime = now; + if (now - m_lastPollTime > 1.0) + { + m_lastPollTime = now; + pollForRadioMessage(now); + } +} + +// ELF 0x1C4190: the agent's own messages are queued first, then every due message is sent. +void CommunicationAgent::pollForRadioMessage(double now) +{ + sendCommunicationAgentMessages(now); + CAPrioMessage message; + while (peekRadioMessage(message) && !waitWithSendingMessage(message, now)) + { + postEvent(message); + dequeueRadioMessage(message); + } +} + +// ELF 0x1C4DD0 (396 bytes), all eighteen types: an expired send block is cleared, and the +// inbox (newest first) is cut at the first message older than the type's time to live. +void CommunicationAgent::clearOutOldMessages(double now) +{ + for (unsigned int type = 0; type < 18; ++type) + { + if (m_lastSentTime[type] < now) + m_lastSentTime[type] = 0.0; + std::list& inbox = m_receivedMessages[type]; + std::list::iterator it = inbox.begin(); + while (it != inbox.end() && now < it->m_time + m_receiveTimeToLive[type]) + ++it; + while (it != inbox.end()) + it = inbox.erase(it); + } +} + +// ELF 0x1C4F60: both checks use the bot's current equipment. +void CommunicationAgent::sendCommunicationAgentMessages(double) +{ + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + sendCallForMedic(equipment); + shutOffHorn(equipment); +} + +// ELF 0x1C4FE0 (552 bytes). A wounded primary object (0 < health < 0.5 for strength type 0 +// else 0.75) calls for a medic - type 3 on channel 0 for infantry, type 4 on channel 6 +// otherwise - unless the bot is airborne, rides a fast (speed > 3) vehicle-flagged primary, or +// carries a weapon of type 1 or 3 with strength against its own type. The primary object's +// mobile plug-in is read before its null check (no guard in the ELF). +void CommunicationAgent::sendCallForMedic(Information* equipment) +{ + Information* const primary = + informationManager->getInformation(equipment->getPrimaryObject(m_bot->getSide())); + IPIMobile* const mobile = primary->getMobile(); + bool skip = false; + if (m_bot->isAirBorn() + || (primary && (primary->getObjectTypeFlags() & 0x10) != 0 && mobile + && mobile->getSpeedMagnitude() > 3.0f)) + skip = true; + if (!equipment->isPrimary() || skip) + return; + IPIPhysical* const physical = equipment->getPhysical(); + const float health = physical->getHealth(); + const int strengthType = physical->getStrengthType(); + const float threshold = strengthType == 0 ? 0.5f : 0.75f; + if (!(0.0f < health && health < threshold)) + return; + if (IPIArmament* const armament = equipment->getArmament()) + { + const std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon) + { + const int type = weapon->getWeaponType(); + if ((type == 1 || type == 3) && static_cast(weapon->getStrength(strengthType)) > 0.0f) + return; + } + } + } + if (strengthType == 0) + enqueueRadioMessage(static_cast(3), static_cast(0), 5, 0.0f, -1); + else + enqueueRadioMessage(static_cast(4), static_cast(6), 5, 0.0f, 0); +} + +// ELF 0x1C5460: the side (Bot +0xE0) is read first, then the information's object (+0x20) and the +// player (Bot +0xBC); the hub is +4. +void CommunicationAgent::setSeenNewEnemy(Information* enemy) +{ + const int side = m_bot->getSide(); + IAIObject* const object = enemy->getAIObject(); + m_hub->enemySpottedByAI(m_bot->getPlayer(), object, side); +} + +// ELF 0x1C44A0 (812 bytes). The record: the settings' modifier (+4), the sender, the game time, +// false, `flag`, the type (settings +0). A type-1 message drops the sender's first type-0 entry +// and everything after it; a type-0 message does the same in the type-1 list. In the message's +// own list an entry from the sender is refreshed (modifier, time, +16 false), else the record is +// appended. +void CommunicationAgent::receiveRadioMessage(const AIRadioMessageSettings& settings, int senderPlayerId, bool flag) +{ + int type; + std::memcpy(&type, settings.m_opaque0, sizeof(type)); // +0, opaque in BFConsole.h + AIRadioMessageInfo info; + info.m_modifier = settings.m_modifier; + info.m_senderPlayerId = senderPlayerId; + info.m_time = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + info.m_flag16 = false; + info.m_flag17 = flag; + info.m_int20 = type; + if (type == 1 || type == 0) + { + std::list& other = m_receivedMessages[type == 1 ? 0 : 1]; + for (std::list::iterator it = other.begin(); it != other.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId) + { + while (it != other.end()) + it = other.erase(it); + break; + } + } + } + std::list& inbox = m_receivedMessages[type]; + for (std::list::iterator it = inbox.begin(); it != inbox.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId) + { + it->m_modifier = settings.m_modifier; + it->m_flag16 = false; + it->m_time = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return; + } + } + inbox.push_back(info); +} + +// ELF 0x1C53F0: horn-capable equipment (type flag 0x04000000) releases fire after 2 s. +void CommunicationAgent::shutOffHorn(Information* equipment) +{ + if ((equipment->getObjectTypeFlags() & 0x04000000) == 0) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now - m_hornTime > 2.0) + m_bot->m_playerInput->setInput(io::PIFire, 0.0f); +} + +// ELF 0x1C5210 (478 bytes). Nothing without a target, or when the target's player +// (Information::getPlayerId, IAIPlayerFactory +0x20) is unknown. The interval since the last horn +// (+104) must reach 20 s towards an AI player and 5 s towards a human. With horn-capable current +// equipment (type flag 0x04000000; the equipment information is not null-tested) the bot presses +// fire (PIFire 1.0); otherwise it radios type 11 on channel 6, priority 3, naming the target's +// player. The horn time is then renewed, and a target flagged 0x00200000 whose object is a bot +// (IBotManager +0x24) gets the time in its own agent (+96). +void CommunicationAgent::honkHorn(Information* target) +{ + if (!target) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const int targetPlayerId = target->getPlayerId(); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(target->getPlayerId()); + if (!player) + return; + const float interval = player->getIsAIPlayer() ? 20.0f : 5.0f; + if (interval > now - m_hornTime) + return; + Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); + if ((equipment->getObjectTypeFlags() & 0x04000000) != 0) + m_bot->m_playerInput->setInput(io::PIFire, 1.0f); + else + sendImmediately(static_cast(11), static_cast(6), 3, + targetPlayerId); + m_hornTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if ((target->getObjectTypeFlags() & 0x00200000) == 0) + return; + Bot* const horned = IBotManager::instance->getBot(target->getAIObject()); + if (!horned) + return; + const double time = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + horned->getCommunicationAgent()->m_double96 = time; +} + +// ELF 0x1C4A50: `0.0 > now - m_lastSentTime[type]`. +bool CommunicationAgent::getSentMessage(AIRadioMessageType type) const +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + return 0.0f > now - m_lastSentTime[type]; +} + +// ELF 0x1C4AA0: IBFModuleCourier +0x1C for the voice, +0x18 for its settings (modifier at +4). +float CommunicationAgent::getModifierForMessageType(AIRadioMessageType type) const +{ + IBFModuleCourier* const courier = static_cast(CommonSingletonServer::m_iBFModuleCourier); + int voice; + if (!courier->getVoiceFromAiMessageType(type, voice)) + return 1.0f; + AIRadioMessageSettings settings; + courier->getAIMessageSettings(voice, settings); + return settings.m_modifier; +} + +// ELF 0x1C4C00: the queue top, by copy. +bool CommunicationAgent::peekRadioMessage(CAPrioMessage& out) const +{ + if (m_queue.empty()) + return false; + out = m_queue.top(); + return true; +} + +// ELF 0x1C4C50: copies the top, drops its type's pending entry (+20 map) and pops it. +bool CommunicationAgent::dequeueRadioMessage(CAPrioMessage& out) +{ + if (m_queue.empty()) + return false; + out = m_queue.top(); + m_map20.erase(m_map20.find(out.m_type)); + m_queue.pop(); + return true; +} + +// ELF 0x1C4D40: wait until the send time, and while the newest received message of the type is +// younger than its max send period. +bool CommunicationAgent::waitWithSendingMessage(CAPrioMessage& message, double now) +{ + if (message.m_sendTime > now) + return true; + const std::list& inbox = getReceivedMessages(message.m_type); + if (inbox.empty()) + return false; + const AIRadioMessageInfo& newest = inbox.front(); + return !(static_cast(m_maxSendPeriod[newest.m_int20]) <= now - newest.m_time); +} + +// ELF 0x1C4290 (514 bytes). Outside the type's send block (+48) one message per type is queued +// (the +20 map holds the pending type and its send time); the block is then renewed by the +// type's max send period. +void CommunicationAgent::enqueueRadioMessage(AIRadioMessageType type, AIRadioChannelType channel, + unsigned int priority, float delay, int c) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(m_lastSentTime[type] <= now)) + return; + CAPrioMessage message; + message.m_type = type; + message.m_channel = channel; + message.m_priority = static_cast(priority); + message.m_int12 = c; + message.m_sendTime = now + static_cast(delay); + message.m_delay = delay; + if (m_map20.insert(std::make_pair(type, message.m_sendTime)).second) + m_queue.push(message); + m_lastSentTime[type] = now + static_cast(m_maxSendPeriod[type]); +} + +// ELF 0x1C4B10. The bot's player id (twice, as bytes), side and the message's last argument +// (byte); IBFModuleCourier +0x1C getVoiceFromAiMessageType must know the type, whose voice's low +// byte goes to the hub with channel message type 3. +void CommunicationAgent::postEvent(const CAPrioMessage& message) const +{ + const unsigned char sender = static_cast(m_bot->getPlayerId()); + const unsigned char player = static_cast(m_bot->getPlayerId()); + const unsigned char side = static_cast(m_bot->getSide()); + const unsigned char argument = static_cast(message.m_int12); + int voice; + if (!static_cast(CommonSingletonServer::m_iBFModuleCourier) + ->getVoiceFromAiMessageType(message.m_type, voice)) + return; + m_hub->filterAndSendAIRadioMessage(m_bot, sender, static_cast(3), message.m_channel, + message.m_type, static_cast(voice), player, side, argument); +} + +bool CommunicationAgent::getReceivedMessage(AIRadioMessageInfo& out, AIRadioMessageType type, + int senderPlayerId) const +{ + const std::list& messages = m_receivedMessages[type]; + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId) + { + out = *it; + return true; + } + } + return false; +} + +bool CommunicationAgent::receivedMessageExists(AIRadioMessageType type, int senderPlayerId) const +{ + const std::list& messages = m_receivedMessages[type]; + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + if (senderPlayerId == -1 || it->m_senderPlayerId == senderPlayerId) + return true; + } + return false; +} + +bool CommunicationAgent::generalConfirmReceivedMessage(AIRadioMessageType type) +{ + bool confirmed = false; + std::list& messages = m_receivedMessages[type]; + for (std::list::iterator it = messages.begin(); it != messages.end(); ++it) + { + if (!it->m_flag16 && !it->m_flag17) + { + it->m_flag16 = true; + confirmed = true; + } + } + return confirmed; +} + +bool CommunicationAgent::confirmReceivedMessage(AIRadioMessageType type, int senderPlayerId) +{ + bool confirmed = false; + std::list& messages = m_receivedMessages[type]; + for (std::list::iterator it = messages.begin(); it != messages.end(); ++it) + { + if (it->m_senderPlayerId == senderPlayerId && !it->m_flag16 && !it->m_flag17) + { + it->m_flag16 = true; + confirmed = true; + } + } + return confirmed; +} + +// The search compares type (+20), sender (+4) and the time (+8, `fucompi`, unordered is unequal). +bool CommunicationAgent::confirmReceivedMessage(const AIRadioMessageInfo& info) +{ + std::list& messages = m_receivedMessages[info.m_int20]; + std::list::iterator it = messages.begin(); + for (; it != messages.end(); ++it) + { + if (it->m_int20 == info.m_int20 && it->m_senderPlayerId == info.m_senderPlayerId + && it->m_time == info.m_time) + break; + } + if (it == messages.end() || it->m_flag16 || it->m_flag17) + return false; + it->m_flag16 = true; + return true; +} + +void CommunicationAgent::sendImmediately(AIRadioMessageType type, AIRadioChannelType channel, + unsigned int priority, int c) +{ + CAPrioMessage message; + message.m_type = type; + message.m_channel = channel; + message.m_priority = static_cast(priority); + message.m_sendTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + message.m_int12 = c; + message.m_delay = 0.0f; + postEvent(message); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h index d50780f91..916e2c459 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h @@ -22,13 +22,33 @@ class Information; // enumerator name is recoverable from either binary. enum AIRadioChannelType : int; enum AIRadioMessageType : int; +struct AIRadioMessageSettings; // Radio-message record. [UNRESOLVED] Some fields are not yet identified. struct AIRadioMessageInfo { - /* 0 */ unsigned char m_opaque0[4]; // [UNRESOLVED] + // ELF 0x1C3260: 1.0f, -1, 0.0, false, false, 18. + AIRadioMessageInfo() + : m_modifier(1.0f), m_senderPlayerId(-1), m_time(0.0), m_flag16(false), m_flag17(false), m_int20(0x12) + { + } + + // ELF 0x1C3310 (C1; C2 0x1C32E0 is the same): member by member, out of line in the image. + AIRadioMessageInfo(const AIRadioMessageInfo& other) + : m_modifier(other.m_modifier), m_senderPlayerId(other.m_senderPlayerId), m_time(other.m_time), + m_flag16(other.m_flag16), m_flag17(other.m_flag17), m_int20(other.m_int20) + { + } + + // receiveRadioMessage (ELF 0x1C44A0) copies AIRadioMessageSettings +4 (the modifier) here. + /* 0 */ float m_modifier; /* 4 */ int m_senderPlayerId; - /* 8 */ unsigned char m_opaque8[16]; // [UNRESOLVED] + // clearOutOldMessages (ELF 0x1C4DD0) ages entries by this time; waitWithSendingMessage + // (0x1C4D40) indexes the max-send periods with the int at +20. + /* 8 */ double m_time; + /* 16 */ bool m_flag16; // [UNRESOLVED] false on receipt and on refresh + /* 17 */ bool m_flag17; // receiveRadioMessage's third argument + /* 20 */ int m_int20; // the message type (AIRadioMessageSettings +0); waitWithSendingMessage indexes by it }; class CommunicationAgent @@ -41,20 +61,67 @@ class CommunicationAgent // the largest value here is what the bot says next. bool operator<(const CAPrioMessage& rhs) const { return m_priority < rhs.m_priority; } - /* 0 */ unsigned char m_opaque0[8]; // [UNRESOLVED] - /* 8 */ int m_priority; - /* 12 */ unsigned char m_opaque12[16]; // [UNRESOLVED] + // 28 bytes: peek/dequeueRadioMessage (ELF 0x1C4C00 / 0x1C4C50) copy seven words. + /* 0 */ AIRadioMessageType m_type; // getReceivedMessages(m_type) in waitWithSendingMessage + // enqueueRadioMessage (ELF 0x1C4290) fills all seven words from its arguments. + /* 4 */ AIRadioChannelType m_channel; // postEvent's fifth hub argument + /* 8 */ int m_priority; // the unsigned argument + /* 12 */ int m_int12; // the last argument; postEvent passes its low byte + /* 16 */ double m_sendTime; // now + delay; not sent before this time + /* 24 */ float m_delay; }; explicit CommunicationAgent(BotMain* owner); - // The implicit destructor releases member containers; no custom cleanup is required. + // ELF 0x1C3CF0 (D1; D2 0x1C3B50): an empty body; the members are torn down by the compiler. + ~CommunicationAgent(); void reset(); - void update(); // - [FRONTIER] + void update(); + void pollForRadioMessage(double now); + void clearOutOldMessages(double now); + void sendCommunicationAgentMessages(double now); + void sendCallForMedic(Information* equipment); + void shutOffHorn(Information* equipment); + // ELF 0x1C5210: horns at `target` (or radios type 11 without a horn), at most every 20 s + // towards a bot and every 5 s towards a human. + void honkHorn(Information* target); + // ELF 0x1C4A50: true while the type's send block (+48) lies in the future. + bool getSentMessage(AIRadioMessageType type) const; + // ELF 0x1C4AA0: the type's AIRadioMessages.ai modifier, 1.0 without a voice. + float getModifierForMessageType(AIRadioMessageType type) const; + // ELF 0x1C5460: CommunicationHub::enemySpottedByAI(bot player, information's object, side). + void setSeenNewEnemy(Information* enemy); + // ELF 0x1C44A0: file a received message under its type (one entry per sender). + void receiveRadioMessage(const AIRadioMessageSettings& settings, int senderPlayerId, bool flag); + void enqueueRadioMessage(AIRadioMessageType type, AIRadioChannelType channel, unsigned int priority, + float delay, int c); + bool peekRadioMessage(CAPrioMessage& out) const; + bool dequeueRadioMessage(CAPrioMessage& out); + bool waitWithSendingMessage(CAPrioMessage& message, double now); + void postEvent(const CAPrioMessage& message) const; // ELF 0x1C4B10 // attested by a 7-byte body: `return m_receivedMessages.data + type;` const std::list& getReceivedMessages(AIRadioMessageType type) const { return m_receivedMessages[type]; } + // ELF 0x1C47F0: the first received message of `type` from senderPlayerId, copied out. + bool getReceivedMessage(AIRadioMessageInfo& out, AIRadioMessageType type, int senderPlayerId) const; + // ELF 0x1C4A00: any message of `type` from senderPlayerId (-1: from anyone). + bool receivedMessageExists(AIRadioMessageType type, int senderPlayerId) const; + // ELF 0x1C4850: marks every unconfirmed (+16, +17 clear) message of `type` confirmed (+16). + bool generalConfirmReceivedMessage(AIRadioMessageType type); + // ELF 0x1C4990: the same for the messages of one sender. + bool confirmReceivedMessage(AIRadioMessageType type, int senderPlayerId); + // ELF 0x1C48C0: the first message equal to `info` (type, sender, time) when unconfirmed. + bool confirmReceivedMessage(const AIRadioMessageInfo& info); + // ELF 0x1C4220: posts {type, channel, priority, c, now, 0.0f} without queueing. + void sendImmediately(AIRadioMessageType type, AIRadioChannelType channel, unsigned int priority, int c); + // [INFERRED] inline readers (D's waitForPickup reads +0x5C; F's BBAvoid reads +0x60). + // +0x60 is written by honkHorn on the bot it horns at. +0x5C is written by reset (-1) and by + // BBPChange::createPlan (0x23C474: the driver's player id when the driver is a bot, else 0xFF) + // through the inline setter below ([CHOSEN] name). + int getInt92() const { return m_int92; } + void setInt92(int value) { m_int92 = value; } + double getDouble96() const { return m_double96; } private: typedef std::priority_queue, @@ -72,13 +139,16 @@ class CommunicationAgent // Eighteen doubles, one per type, zeroed by `reset` and paired with the max-send-period cache // below. [INFERRED] that these are the per-type last-sent timestamps. /* 48 */ std::vector m_lastSentTime; - /* 60 */ double m_double60; // reset: 0.0 + // update (ELF 0x1C4100) polls the radio at most once a second from this time. + /* 60 */ double m_lastPollTime; // reset: 0.0 // the two cached columns of `AIRadioMessages.ai`. Filled once, in the constructor. /* 68 */ std::vector m_receiveTimeToLive; /* 80 */ std::vector m_maxSendPeriod; - /* 92 */ int m_int92; // reset: -1, this subsystem's null-index convention + /* 92 */ int m_int92; // reset: -1; BBPChange::createPlan (see above) + // the game time another bot last horned at this one (honkHorn); BBAvoid reads it. /* 96 */ double m_double96; // reset: 0.0 - /* 104 */ double m_double104; // reset: 0.0 + // shutOffHorn (ELF 0x1C53F0) releases the horn (PIFire) two seconds after this time. + /* 104 */ double m_hornTime; // reset: 0.0 }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp new file mode 100644 index 000000000..e350ff01a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CoverDetection.cpp @@ -0,0 +1,82 @@ +// The ELF FILE symbol attests CoverDetection.cpp; directory placement is [INFERRED]. + +#include +#include +// static init: ELF 0x1A20C0, 0x1A2120, 0x1A2150: iostream Init only. + +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/PlanePolygon.h" +#include "../../../../Math/BoundingBox.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x1A19E0. Shipped defect: output is read but never written. +float hasCoverObjects(Information* information, const Vec3& position, IPlanePolygon* polygon, + Vec3& output) +{ + const BoundingBox* const box = information->getPhysical()->getBoundingBox(); + const Vec3& objectPosition = information->getPosition(); + const Vec3 delta = {objectPosition.x - position.x, objectPosition.y - position.y, + objectPosition.z - position.z}; + Vec2 direction = {}; + Vec2 normal = {}; + vec3ToVec2XZ(delta, direction); + getNormal(direction, normal); + const float squared = normal.x * normal.x + normal.y * normal.y; + if (!(std::fabs(squared - 1.0f) < 1.1920928955078125e-7f)) + { + if (!(std::fabs(squared) < 1.4210854715202004e-14f)) + { + const float inverse = 1.0f / std::sqrt(squared); + normal.x *= inverse; + normal.y *= inverse; + } + else + { + normal.x = 0.0f; + normal.y = 0.0f; + } + } + const Vec3 maximum = box->getMax(); + const Vec3 maximumDelta = {maximum.x - position.x, maximum.y - position.y, maximum.z - position.z}; + Vec2 maximumXZ = {}; + vec3ToVec2XZ(maximumDelta, maximumXZ); + Vec2 high = maximumXZ; + Vec2 low = maximumXZ; + // [INFERRED] local packaging of the repeated inlined projection. + const auto projection = [&](const Vec2& point) + { + return (point.x * normal.x + point.y * normal.y) + / std::sqrt(point.x * point.x + point.y * point.y); + }; + float highest = projection(maximumXZ); + float lowest = highest; + const Vec3 minimum = box->getMin(); + const Vec3 minimumDelta = {minimum.x - position.x, minimum.y - position.y, minimum.z - position.z}; + Vec2 minimumXZ = {}; + vec3ToVec2XZ(minimumDelta, minimumXZ); + Vec2 corner = {maximumXZ.x, minimumXZ.y}; + float value = projection(corner); + if (value > highest) { highest = value; high = corner; } + else if (value < lowest) { lowest = value; low = corner; } + corner.x = minimumXZ.x; + value = projection(corner); + if (value > highest) { highest = value; high = corner; } + else if (value < lowest) { lowest = value; low = corner; } + corner.y = maximumXZ.y; + value = projection(corner); + if (value > highest) { high = corner; } + else if (value < lowest) { low = corner; } + Vec2 origin = {}; + Vec2 unused = {}; + vec3ToVec2XZ(position, origin); + vec3ToVec2XZ(output, unused); + unused.x -= origin.x; + unused.y -= origin.y; + if (polygon->intersects(high, origin)) + return polygon->intersects(low, origin) ? 1.0f : 0.25f; + return polygon->intersects(low, origin) ? 0.25f : 0.0f; +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp new file mode 100644 index 000000000..a556b1edc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp @@ -0,0 +1,64 @@ +// RandomSquareMerger. Recovered from libaidll.so 1.5.3153 (ia-32), 0x1A2480..0x1A279F. + +#include "RandomSquareMerger.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A27A0, __tcf_0 0x1A2800, _GLOBAL__I 0x1A2830). +#include + +#include "../Main/AIRandom.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1A24D0 (C1; C2 0x1A2480): the base, then the vptr. +RandomSquareMerger::RandomSquareMerger(int count, float* weights, UrgencyGenerator** generators) + : UrgencyMerger(count, weights, generators) +{ +} + +// ELF 0x1A2560 (D1; D2 0x1A2520, D0 0x1A25A0): the base. +RandomSquareMerger::~RandomSquareMerger() +{ +} + +// ELF 0x1A25E0. Every generator updates; the squares of the updated urgencies are summed. A draw +// in [0, sum) then walks the generators, subtracting each one's active urgency (not squared); +// a generator whose share (active / sum) is above 0.01 becomes the chosen one (its own chosen +// generator, +0x20). The walk stops at the first generator after which the draw is no longer +// positive and a choice exists. Answers that generator's active urgency. Shipped defects: when +// the walk runs through, the index is the count (one past the array), and a null generator at +// the stop index is called; with no generators index 0 is used. +float RandomSquareMerger::updateActiveUrgency(Bot* bot) +{ + float total = 0.0f; + for (int i = 0; i < m_count; ++i) + { + if (m_generators[i]) + { + const float urgency = m_generators[i]->updateActiveUrgency(bot); // +0x10 + total = urgency * urgency + total; + } + } + float pick = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * total; + m_chosen = 0; + int index = 0; + for (; index < m_count; ++index) + { + if (m_generators[index]) + { + const float active = m_generators[index]->getActiveUrgency(bot); // +0x0C + pick = pick - active; + if (active / total > 0.01f) + m_chosen = m_generators[index]->getChosenGenerator(); // +0x20 + } + if (pick <= 0.0f && m_chosen != 0) + break; + } + return m_generators[index]->getActiveUrgency(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h new file mode 100644 index 000000000..37d4d8d93 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h @@ -0,0 +1,31 @@ +// An urgency merger that picks one of its generators at random, weighted by the squares of their +// active urgencies. +// Evidence: libaidll.so 1.5.3153 (ia-32). File RandomSquareMerger.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours, as the ledger files it); vtable 0x4B6D40: the +// destructors and updateActiveUrgency (+0x10) are its own, every other slot is UrgencyMerger's. +// Nothing in libaidll.so constructs one. + +#ifndef AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H + +#include "../AIBotBehaviour/UrgencyMerger.h" + +namespace dice { +namespace hfe { +namespace ai { + +class RandomSquareMerger : public UrgencyMerger +{ +public: + // As UrgencyMerger. + RandomSquareMerger(int count, float* weights, UrgencyGenerator** generators); + virtual ~RandomSquareMerger(); + + virtual float updateActiveUrgency(Bot* bot); // +0x10 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp new file mode 100644 index 000000000..4f4cfe7f1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.cpp @@ -0,0 +1,58 @@ +// One sensed-object record. Evidence: libaidll.so 1.5.3153 (ia-32), see SensedObject.h. + +#include "SensedObject.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A29C0, __tcf_0 0x1A2A20, _GLOBAL__I 0x1A2A50). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1A2860 (C1; C2 0x1A28F0 is identical). The three Vec3 are zeroed, +0x3C gets -1000.0f +// (`flds 0x49CDC8; fstpl 0x3c`), +0x50 = 2, +0x54 / +0x5C = 0.0, +0x64 = 0. The flag word comes +// from the setne/incl/cmov chain: base = seen + 1, then +4 if sided, +8 and +16 if not seen. +SensedObject::SensedObject(unsigned int handle, bool seen, bool sided) + : m_handle(handle) +{ + m_seenPosition.x = 0.0f; + m_seenPosition.y = 0.0f; + m_seenPosition.z = 0.0f; + m_lastPosition.x = 0.0f; + m_lastPosition.y = 0.0f; + m_lastPosition.z = 0.0f; + m_lastSeenPosition.x = 0.0f; + m_lastSeenPosition.y = 0.0f; + m_lastSeenPosition.z = 0.0f; + m_lastAttackTime = -1000.0f; + unsigned int flags = seen ? SENSE_SEEN : SENSE_HEARD; + if (sided) + flags |= SENSE_SIDED; + if (!seen) + flags |= SENSE_INDIRECT; + if (!seen) + flags |= SENSE_HEARD_NOW; + m_lastSense = SENSE_SEEN; + m_lastSeenTime = 0.0f; + m_lastPositionTime = 0.0f; + m_flags = flags; + m_hasContact = false; +} + +// ELF 0x1A2980 (D1; D2 0x1A2990): `push ebp; mov ebp,esp; pop ebp; ret`. +SensedObject::~SensedObject() +{ +} + +// ELF 0x1A29A0: `mov $7,%eax; L: dec %eax; jns L` - eight passes, no body left. +void SensedObject::initStrengths() +{ + for (int i = 7; i >= 0; --i) + { + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h new file mode 100644 index 000000000..9e84de0d1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensedObject.h @@ -0,0 +1,69 @@ +// One thing a bot has seen or heard: BotSenses keeps one record per handle (the map at +112) and +// threads it through the seen list (+56) and the heard list (+76). +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/SensedObject.cpp (FILE symbol +// beside 0x1A29C0); constructors 0x1A2860 / 0x1A28F0, destructors 0x1A2980 / 0x1A2990 (empty, +// not virtual: every owner deletes through `~SensedObject(); operator delete`), initStrengths +// 0x1A29A0. Size 0x68 (`operator new(0x68)` in BotSenses::event_seenObject / event_heardObject). + +#ifndef AI_AIDLL_AI_AIBOT_SENSEDOBJECT_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_SENSEDOBJECT_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SensedObject +{ +public: + // The flag word (+0x4C) and the "last sense" word (+0x50) share these values: every writer + // that sets a bit also stores the same value to +0x50. [INFERRED] names; the bits are attested. + enum SenseFlag + { + SENSE_HEARD = 0x01, // in the heard list; updateHearing / event_heardObject + SENSE_SEEN = 0x02, // in the seen list; event_seenObject sets, forgetObject clears + SENSE_SIDED = 0x04, // the constructor's third argument (the object's side != 0) + SENSE_INDIRECT = 0x08, // seen, but not directly yet (event_seenObject's `direct`) + SENSE_HEARD_NOW = 0x10, // heard during the last hearing pass + SENSE_FLAG40 = 0x40 // event_seenObject with its last argument false; meaning [UNRESOLVED] + }; + + // ELF 0x1A2860. The flag word is built as (seen ? SEEN : HEARD) | (sided ? SIDED : 0) and, for + // a heard record, INDIRECT | HEARD_NOW. +0x10, +0x14, +0x34 and +0x44 are not written here. + SensedObject(unsigned int handle, bool seen, bool sided); + ~SensedObject(); // ELF 0x1A2980: empty + + // ELF 0x1A29A0: a counted loop (8 passes) whose body the compiler removed; no caller in the image. + void initStrengths(); + + /* +0x00 */ unsigned int m_handle; + /* +0x04 */ Vec3 m_seenPosition; // event_seenObject's position argument + /* +0x10 */ unsigned int m_seenPart; // event_seenObject's third argument (-1 from event_projectile) + /* +0x14 */ double m_firstSeenTime; // event_seenObject, new record + /* +0x1C */ Vec3 m_lastPosition; // the information's position at the last sense + /* +0x28 */ Vec3 m_lastSeenPosition; // the information's position when last seen + /* +0x34 */ double m_lastSensedTime; // seen or heard + /* +0x3C */ double m_lastAttackTime; // ctor -1000.0; event_projectile: the game time + // +0x44/+0x48: the fire patterns' per-target state. Writers: BBPFireInfantery::createPlan sets + // both to 0 together with flag 0x20 (0x25CC43/0x25CC4D) and +0x48 = -100 when no weapon fits + // (0x25F36E); BBPFire2d::createPlan sets flag 0x20 and +0x48 = -100 (0x24AF3A). Readers: + // BBFire::calculateUrgency (0x208B58) and BBFireLargeBore::calculateUrgency (0x2118A8) skip the + // target when flag 0x20 is set and +0x48 < 0 (signed: js). BAPANotifyBot::execute (ELF 0x1DD800) + // adds its integer plan variable to +0x44 when its notification type is zero. + // AICollisionHandler::shooterUpdate (0x382B70) increments +0x48 for every confirmed hit. + // [CHOSEN, not recovered] names (ai-w1-e-fire, merged with D's m_unresolved44 use). + /* +0x44 */ int m_unresolved44; // [UNRESOLVED] notification accumulator meaning + /* +0x48 */ int m_fireRating; // < 0: no weapon can engage this target + /* +0x4C */ unsigned int m_flags; // SenseFlag bits + /* +0x50 */ int m_lastSense; // ctor 2; the SenseFlag value last set + /* +0x54 */ double m_lastSeenTime; // ctor 0 + /* +0x5C */ double m_lastPositionTime; // ctor 0; when +0x1C was written + /* +0x64 */ bool m_hasContact; // Information::addContact was called for this record +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_SENSEDOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp index eddc03f29..cb0a89b2c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp @@ -1,10 +1,17 @@ -// [FRONTIER] Remaining methods stop by name until implemented. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SensingAgent operations. #include "SensingAgent.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BF770, __tcf_0 0x1BF7D0, _GLOBAL__I 0x1BF800). +#include + +#include + #include "BotSenses.h" #include "../AIPlanInterpreter/BAPContext.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" #include "SensingAgentPatterns.h" // ISensingAgentPattern::reset - the shared patterns #include "../Main/AIRandom.h" // the per-life reaction time #include "../Main/AISettingsInterfaces.h" @@ -12,7 +19,24 @@ #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include #include "../AIUtils/checkPointer.h" +#include "BotMain.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Math/Mat4.h" +#include #include "../Main/AIDllFrontier.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Core/Debug.h" +#include "../AIPlanInterpreter/BotScript.h" +#include "SensedObject.h" +#include "../DrawPrimitives/DPManager.h" +#include namespace dice { namespace hfe { @@ -23,15 +47,18 @@ SensingAgent::SensingAgent(BotMain* owner, unsigned char /*behaviourCount*/) : m_flag134(false) , m_plan(0) { - for (int i = 0; i < 6; ++i) - m_zero0[i] = 0; // +0..+20 - for (int i = 0; i < 3; ++i) - { - m_zero32[i] = 0; // +32, +36, +40 - m_zero64[i] = 0; // +64, +68, +72 - } - for (int i = 0; i < 5; ++i) - m_zero80[i] = 0; // +80..+96 + // +0..+20: the two focus vectors, empty. + m_focusPosition.x = 0.0f; // +32, +36, +40 + m_focusPosition.y = 0.0f; + m_focusPosition.z = 0.0f; + m_planDirection.x = 0.0f; // +64, +68, +72 + m_planDirection.y = 0.0f; + m_planDirection.z = 0.0f; + m_moveDirection.x = 0.0f; // +80..+96 zeroed + m_moveDirection.y = 0.0f; + m_sprintFocus.x = 0.0f; + m_sprintFocus.y = 0.0f; + m_sprintFocus.z = 0.0f; // the mechanism this agent steers. , and it takes the bot rather than the agent // so `BotSenses` answers to the bot directly and this object is a policy layer over it. @@ -48,24 +75,21 @@ SensingAgent::SensingAgent(BotMain* owner, unsigned char /*behaviourCount*/) reset(); } -// [FRONTIER] Remaining sensing-plan operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - +// ELF 0x1BBB50: the senses (+0x68) and the BAP context (+0x90) are deleted; the plan is not. +// The vectors at +0, +0xC and +0x30 are destroyed as members. SensingAgent::~SensingAgent() { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgent::~SensingAgent"); + delete m_senses; + delete m_bapContext; } // Deletes the owned plan and marks planning state for refresh. -// [FRONTIER] Plan destruction stops until the required statement type is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. void SensingAgent::deletePlan() { if (m_plan) { - // Retail here is `delete m_plan;` - vtable byte-slot +8, the deleting destructor. See the - // block above for why this tree cannot write it yet. - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgent::deletePlan (non-null plan)"); + // `delete m_plan;` - vtable byte-slot +8, the deleting destructor. + delete m_plan; m_plan = 0; } m_flag140 = true; @@ -75,7 +99,7 @@ void SensingAgent::deletePlan() void SensingAgent::clearPlanTargetInformation() { m_planTarget60 = 0; - m_planTarget76 = 0; + m_planWeight = 0.0f; } // Resets sensing state and draws a new reaction delay in [0.5, 1.0). @@ -104,11 +128,11 @@ void SensingAgent::reset() deletePlan(); m_int24 = -1; - m_int28 = 0; + m_focusWeight = 0.0f; m_flag44 = false; m_flag148 = true; - m_zero80[0] = 0; // +80 - m_zero80[1] = 0; // +84 + m_moveDirection.x = 0.0f; // +80 + m_moveDirection.y = 0.0f; // +84 // through the buffer, and the size is not touched. See the block above. for (unsigned q = 0; q <= 7; ++q) @@ -122,7 +146,7 @@ void SensingAgent::reset() m_double124 = 0.0; // Chooses a reaction time in [0.5, 1.0), preserving the arithmetic order. - m_reactionTime = 0.5f + AIRandom::m_instance->nextFloat() * (1.0f - 0.5f); + m_currentPeriod = 0.5f + AIRandom::m_instance->nextFloat() * (1.0f - 0.5f); m_senses->reset(); } @@ -140,6 +164,867 @@ void SensingAgent::setOverride(bool value) } } +namespace { + +// The inline Vec2 normalisation every caller below spells out: left alone within FLT_EPSILON of +// unit length, otherwise scaled by 1 / sqrt(length^2); `zeroIsFalse` reports a degenerate vector +// (computeQuadrantsFromPosition returns false there; quadInFocus zeroes it). +bool normaliseXZ(float& x, float& y, bool zeroIsFalse) +{ + const float lengthSq = y * y + x * x; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) < 1.4210855e-14f) + { + if (zeroIsFalse) + return false; + x = 0.0f; + y = 0.0f; + return true; + } + const float inverse = 1.0f / std::sqrt(lengthSq); + x = x * inverse; + y = inverse * y; + } + return true; +} + +} // namespace + +// ELF 0x1BE110. The point is the camera's row 2 (forward) plus row 3 (position). +void SensingAgent::setQuadSeen() +{ + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + Vec3 ahead; + ahead.x = camera.m[8] + camera.m[12]; + ahead.y = camera.m[9] + camera.m[13]; + ahead.z = camera.m[10] + camera.m[14]; + int quadrants[2]; + if (!computeQuadrantsFromPosition(ahead, quadrants)) + return; + for (int i = 0; i < 2; ++i) + { + if (quadInFocus(quadrants[i])) + { + m_quadrantWeights[quadrants[i]] = 0.0f; + if (m_plan && m_flag148 && quadrants[i] == m_int24) + m_flag44 = true; + } + } +} + +// ELF 0x1BD860. The XZ offset from the camera position (row 3), normalised, is dotted with the +// diagonal axes (+-0.70710677) for the first quadrant and with the world axes for the second. +bool SensingAgent::computeQuadrantsFromPosition(const Vec3& position, int* quadrants) const +{ + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + float x = position.x - camera.m[12]; + float y = position.z - camera.m[14]; + if (!normaliseXZ(x, y, true)) + return false; + const float s = 0.70710677f; + const float b = y * -s + x * s; + if (0.0f <= x * s + y * s) + quadrants[0] = 0.0f <= b ? 1 : 0; + else + quadrants[0] = (b < 0.0f) + 2; + const float d = y * 0.0f + x * 1.0f; + if (0.0f <= x * 0.0f + y * 1.0f) + quadrants[1] = (d < 0.0f) * 3 + 4; + else + quadrants[1] = (d < 0.0f) + 5; + return true; +} + +// ELF 0x1BDA60. The camera is read through the bot's player field (+0x9C) directly. +bool SensingAgent::quadInFocus(int quadrant) const +{ + if (quadrant < 0) + return false; + const Mat4& camera = *static_cast(m_bot->m_player->getCameraTransformation()); + float x = camera.m[8]; + float y = camera.m[10]; + normaliseXZ(x, y, false); + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + getQuadPosition(quadrant, direction); + return 0.9848f < x * direction.x + y * direction.y; +} + +// ELF 0x1BDBC0: an eight-way jump table; the default reports through Debug (type 6, line 770). +void SensingAgent::getQuadPosition(int quadrant, Vec2& position) const +{ + const float s = 0.70710677f; + switch (quadrant) + { + case 0: position.x = 0.0f; position.y = 1.0f; break; + case 1: position.x = 1.0f; position.y = 0.0f; break; + case 2: position.x = 0.0f; position.y = -1.0f; break; + case 3: position.x = -1.0f; position.y = 0.0f; break; + case 4: position.x = s; position.y = s; break; + case 5: position.x = s; position.y = -s; break; + case 6: position.x = -s; position.y = -s; break; + case 7: position.x = -s; position.y = s; break; + default: + Debug(DebugTypeError, __FILE__, __LINE__, "") << "Bad quadrant value " << quadrant; + break; + } +} + +// ELF 0x1BE0A0: also drops the stored override value. +void SensingAgent::disallowOverride(bool b) +{ + m_flag122 = false; + m_flag132 = b; +} + +// ELF 0x1BF230 (130 bytes). Both result flags start false here (BotMain's `ok` starts true); +// a failed or unfinished plan sets +140 and clears the plan targets. +void SensingAgent::executePlan() +{ + bool ok = false; + bool failed = false; + // ELF 0x1BF258: m_bot->getPlanInterpreter() vtable +8 execute(m_plan, m_bot, &ok, &failed). + m_bot->getPlanInterpreter()->execute(m_plan, m_bot, ok, failed); + m_flag140 = failed || !ok; + if (m_flag140) + clearPlanTargetInformation(); +} + +namespace { + +// Bot +4 is the bound PlayerInput; an unmapped input reads as zero (`(mappingFlags >> i) & 1`, +// e.g. checkForPlanInvalidation 0x1BD0F7 `shrdl $0x3` then `flds 0xc(%ecx)`). +float boundInput(const io::PlayerInput* input, io::PlayerInputMap index) +{ + return ((input->mappingFlags >> static_cast(index)) & 1ULL) ? input->inputs[index] + : 0.0f; +} + +// The inline Vec3 normalisation of createPlan: left alone within FLT_EPSILON of unit length, +// zeroed within FLT_EPSILON of zero (not FLT_EPSILON^2 as the Vec2 copies above). +void normalise3(Vec3& v) +{ + const float lengthSq = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.1920929e-07f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; + } + else + { + v.x = 0.0f; + v.y = 0.0f; + v.z = 0.0f; + } + } +} + +// The vehicle's forward (transformation row 2), turned about Y by the control info's camera DOF +// offset when it is positive (withinCamView 0x1BD5DA, createPlan): row vector times the rotation. +Vec3 cameraForward(BotMain* bot, Information* equipment) +{ + const float offset = equipment->getControlInfo()->getCameraRelativeDofRotationOffset(); + const Mat4& transformation = bot->getPlayer()->getCurrentVehicle()->getTransformation(); + Vec3 forward; + forward.x = transformation.m[8]; + forward.y = transformation.m[9]; + forward.z = transformation.m[10]; + if (0.0f < offset) + { + Mat4 rotation; + for (int i = 0; i < 16; ++i) + rotation.m[i] = 0.0f; + rotation.m[0] = 1.0f; + rotation.m[5] = 1.0f; + rotation.m[10] = 1.0f; + rotation.m[15] = 1.0f; + setRotateYDeg(rotation, offset * 57.295776f); + const Vec3 f = forward; + forward.x = f.z * rotation.m[8] + f.x * rotation.m[0] + f.y * rotation.m[4]; + forward.y = f.x * rotation.m[1] + f.y * rotation.m[5] + f.z * rotation.m[9]; + forward.z = f.x * rotation.m[2] + f.y * rotation.m[6] + f.z * rotation.m[10]; + } + return forward; +} + +// The angle between `direction` and the quadrant's unit direction (dot clamped to [-1, 1]); +// isForward / isBehind share it. +float angleToQuadrant(const SensingAgent* agent, int quadrant, const Vec2& direction) +{ + Vec2 q; + q.x = 0.0f; + q.y = 0.0f; + agent->getQuadPosition(quadrant, q); + float dot = direction.x * q.x + direction.y * q.y; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + return std::acos(dot); +} + +// AIRandom::nextFloat inline with a range: (hi - lo) * r + lo (calculateCurrentPeriod 0x1BE31F). +float randomBetween(float lo, float hi) +{ + return (hi - lo) * AIRandom::m_instance->nextFloat() + lo; +} + +// computeTargetQuadrant's random quadrant: floor(r * 2^-32 * 7 + 0.5) in x87 precision, through a +// float, truncated (0x1BCE7D..0x1BCEB1). +int randomQuadrant() +{ + const double r = static_cast(AIRandom::m_instance->next()); + const float rounded = static_cast( + std::floor(r * static_cast(2.3283064e-10f) * 7.0 + 0.5)); + return static_cast(rounded); +} + +} // namespace + +// ELF 0x1BBD30 (1130 bytes), static double waitTime = 2.0 (0x4B7448). +void SensingAgent::update() +{ + static double waitTime = 2.0; + + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + if (!equipment) + return; + if (m_bot->getManDown()) + return; + ISensingAgentPattern* const pattern = + static_cast(CommonSingletonServer::m_iaiSettings) + ->getSensingAgentPattern(equipment->getUnit()->getEquipmentType()); + if (!pattern) + { + deletePlan(); + return; + } + if (m_flag122) + deletePlan(); + const double now = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + // An override (a plan aiming by itself) holds the sensing agent off for waitTime seconds. + if (m_flag122) + { + if (now - m_double124 > waitTime) + m_flag122 = false; + return; + } + if (now < m_double112) + m_double112 = now; + const double elapsed = now - m_double112; + + Information* const current = informationManager->getInformation(m_bot->getCurrentEquipment()); + bool turnedAway = false; + if ((current->getObjectTypeFlags() & 0x00200000) != 0 && m_flag133 + && !isForward(m_int24, m_moveDirection)) + turnedAway = true; + if (!(elapsed >= m_currentPeriod || m_flag120 || m_flag140 == true) && !turnedAway) + return; + if (turnedAway) + m_flag133 = false; + + const int pose = equipment->getSoldierPose(); + bool lookAlongMove = false; + if ((pose == 3 && !m_flag120) || pose == 4) + lookAlongMove = true; + if (!m_bot->isFireAllowed() || lookAlongMove) + { + Vec3 direction; + direction.x = m_moveDirection.x; + direction.y = current->getTransformation().m[9]; + direction.z = m_moveDirection.y; + createDirPlan(direction, pattern); + return; + } + + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + if (!m_flag120) + updateQuadTimeUrgencies(direction, turnedAway); + QuadrantInformation quadrant; + quadrant.position.x = 0.0f; + quadrant.position.y = 0.0f; + quadrant.position.z = 0.0f; + Vec2 opposite; + opposite.x = -direction.x; + opposite.y = -direction.y; + calcTargetQuadFromObjects(&quadrant, opposite); + calculateCurrentPeriod(quadrant, current, direction); + if (m_flag120) + deletePlan(); + else + m_flag121 = false; + m_flag120 = false; + m_double112 = now; + checkForPlanInvalidation(quadrant, turnedAway); + if (m_flag140 == true) + createPlan(pattern, quadrant); + clearInformation(); +} + +// ELF 0x1BC1A0. A soldier looks away from its move direction (+0x50); in a vehicle the vehicle's +// backward XZ (transformation row 2, negated) is used. Quadrants the bot is not facing gain +// urgency over time (0.0125 per update; 0.05 ahead, 0.25 ahead when turned away); a primary +// mobile vehicle clears the quadrants behind it. +void SensingAgent::updateQuadTimeUrgencies(Vec2& direction, bool turnedAway) +{ + Information* const current = informationManager->getInformation(m_bot->getCurrentEquipment()); + if ((current->getObjectTypeFlags() & 0x00200000) == 0) + { + Information* const primary = + informationManager->getInformation(current->getPrimaryObject(m_bot->getSide())); + const Mat4& transformation = primary->getTransformation(); + direction.x = -transformation.m[8]; + direction.y = -transformation.m[10]; + } + else + { + Vec2 move = m_moveDirection; + if (move.x * move.x + move.y * move.y < 0.01f) + return; + direction.x = -move.x; + direction.y = -move.y; + } + bool clearBehind = false; + if ((current->getObjectTypeFlags() & 0x00200000) == 0 && current->hasMobile() && current->isPrimary()) + clearBehind = true; + for (int q = 0; q < 8; ++q) + { + if (clearBehind && isBehind(q, direction)) + { + m_quadrantWeights[q] = 0.0f; + continue; + } + Vec2 ahead; + ahead.x = -direction.x; + ahead.y = -direction.y; + if (!isForward(q, ahead)) + m_quadrantWeights[q] = m_quadrantWeights[q] + 0.0125f; + else if (turnedAway) + m_quadrantWeights[q] = m_quadrantWeights[q] + 0.25f; + else + m_quadrantWeights[q] = m_quadrantWeights[q] + 0.05f; + } +} + +// ELF 0x1BC410. The direction argument is not read. +void SensingAgent::calcTargetQuadFromObjects(QuadrantInformation* info, const Vec2& /*direction*/) +{ + evaluateSensedObjects(); + evaluateFireObjects(); + std::pair > zero; + zero.first = 0.0f; + zero.second.first.x = 0.0f; + zero.second.first.y = 0.0f; + zero.second.first.z = 0.0f; + zero.second.second = 0; + QuadrantWeights weights(8, zero); // operator new(0xA0): 8 x 20 bytes + getQuadrantWeights(weights); + computeTargetQuadrant(weights, info); +} + +// ELF 0x1BC5B0. Every living sensed object is a candidate: seen directly 0.5; seen indirectly +// 0.25 when heard or a fire target (flag 0x20, BBPFireInfantery), else 0; not seen 0.3 when +// heard, + 0.25 for a fire target. The weight is scaled by the information's getSecurity(). +void SensingAgent::evaluateSensedObjects() +{ + FocusInformation empty; + empty.weight = 0.0f; + empty.position.x = 0.0f; + empty.position.y = 0.0f; + empty.position.z = 0.0f; + m_sensedFocus.resize(0, empty); // the image's resize: _M_fill_insert / erase + const std::map& sensed = m_senses->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); + it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info) + continue; + IPIPhysical* const physical = info->getPhysical(); + if (physical && !(0.0f < physical->getHealth())) + continue; + float weight = 0.0f; + const unsigned int flags = object->m_flags; + if ((flags & SensedObject::SENSE_SEEN) == 0) + { + if (flags & SensedObject::SENSE_HEARD) + weight = 0.3f; + if (flags & 0x20) + weight = weight + 0.25f; + } + else if (flags & SensedObject::SENSE_INDIRECT) + { + if ((flags & 0x20) || (flags & SensedObject::SENSE_HEARD)) + weight = weight + 0.25f; + } + else + { + weight = 0.5f; + } + FocusInformation focus; + focus.weight = weight * info->getSecurity(); + focus.position = info->getPosition(); + m_sensedFocus.push_back(focus); + } +} + +// ELF 0x1BC7E0. A friendly shot draws the eye to where it lands (FireObject +0x14), weight 0.5; +// an enemy shot to the shooter, 0.7 for 5 s, then 0.5, and books a re-plan once (+0x78 / +0x79). +void SensingAgent::evaluateFireObjects() +{ + FocusInformation empty; + empty.weight = 0.0f; + empty.position.x = 0.0f; + empty.position.y = 0.0f; + empty.position.z = 0.0f; + m_fireFocus.resize(0, empty); + const double now = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + std::list* const fire = m_senses->getIncommingFire(); + for (std::list::iterator it = fire->begin(); it != fire->end(); ++it) + { + Information* const info = informationManager->getInformation(it->second); + if (!info) + continue; + FireObject* const shot = it->first; + FocusInformation focus; + float weight; + if (info->getSide() == m_bot->getSide()) + { + focus.position = shot->getTarget(); + weight = 0.5f; + } + else + { + if (!m_flag121) + { + m_flag120 = true; + m_flag121 = true; + } + weight = 0.5f; + if (now - shot->getTime() < 5.0) + weight = 0.7f; + focus.position = info->getPosition(); + } + focus.weight = info->getSecurity() * weight; + m_fireFocus.push_back(focus); + } +} + +// ELF 0x1BCA90. Each candidate adds its weight and position to both of its quadrants; then the +// time urgencies (+0x30) are added and the positions averaged. +void SensingAgent::getQuadrantWeights(QuadrantWeights& weights) +{ + const std::vector* const lists[2] = { &m_sensedFocus, &m_fireFocus }; + for (int l = 0; l < 2; ++l) + { + for (std::vector::const_iterator it = lists[l]->begin(); + it != lists[l]->end(); ++it) + { + int quadrants[2]; + if (!computeQuadrantsFromPosition(it->position, quadrants)) + continue; + for (int k = 0; k < 2; ++k) + { + std::pair >& w = weights[quadrants[k]]; + w.first = it->weight + w.first; + w.second.first.x = it->position.x + w.second.first.x; + w.second.first.y = it->position.y + w.second.first.y; + w.second.first.z = it->position.z + w.second.first.z; + w.second.second = w.second.second + 1; + } + } + } + for (unsigned int q = 0; q < 8; ++q) + { + std::pair >& w = weights[q]; + w.first = m_quadrantWeights[q] + w.first; + if (w.second.second != 0) + { + const float inverse = 1.0f / static_cast(w.second.second); + w.second.first.x = w.second.first.x * inverse; + w.second.first.y = w.second.first.y * inverse; + w.second.first.z = inverse * w.second.first.z; + } + } +} + +// ELF 0x1BCD50. The heaviest feasible quadrant wins; with none, up to seven random tries for a +// feasible one, at weight 0.1 and no position. The getQuadPosition calls' results are unused. +void SensingAgent::computeTargetQuadrant(const QuadrantWeights& weights, QuadrantInformation* info) +{ + info->quadrant = -1; + info->weight = 0.0f; + float best = 0.0f; + int q = 0; + for (QuadrantWeights::const_iterator it = weights.begin(); it != weights.end(); ++it, ++q) + { + Vec2 unused; + unused.x = 0.0f; + unused.y = 0.0f; + getQuadPosition(q, unused); + if (best < it->first && targetFeasible(q)) + { + best = it->first; + info->weight = best; + info->quadrant = q; + info->position = it->second.first; + } + } + if (info->quadrant < 0) + { + unsigned int tries = 0; + info->quadrant = randomQuadrant(); + while (!targetFeasible(info->quadrant) && tries <= 5) + { + ++tries; + info->quadrant = randomQuadrant(); + Vec2 unused; + unused.x = 0.0f; + unused.y = 0.0f; + getQuadPosition(info->quadrant, unused); + } + info->weight = 0.1f; + info->position.x = 0.0f; + info->position.y = 0.0f; + info->position.z = 0.0f; + } +} + +// ELF 0x1BCFF0. Vehicles and borrowed armament never keep a sensing plan. Otherwise the plan goes +// when its focus is out of the camera's reach, a quadrant plan's quadrant changed, a target plan's +// target is still sensed (sic: `test %eax,%eax; je` keeps the plan only when the lookup is null), +// a pose-3 soldier throttles backwards, or `force`. +void SensingAgent::checkForPlanInvalidation(const QuadrantInformation& info, bool force) +{ + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + bool vehicle = false; + if ((equipment->getObjectTypeFlags() & 0x20) || (equipment->getObjectTypeFlags() & 0x10)) + vehicle = true; + if (equipment->getUnit()->mustBorrowArmament() || vehicle) + { + deletePlan(); + return; + } + bool invalid = false; + if (!targetFeasible(m_int24)) + invalid = true; + if (m_flag148) + { + if (info.quadrant != m_int24) + { + m_flag44 = false; + invalid = true; + } + } + else if (m_bot->getSensedObjectFromHandle(m_planTarget60)) + { + invalid = true; + } + if (equipment->getSoldierPose() == 3 && boundInput(m_bot->getInput(), io::PIThrottle) < 0.0f) + invalid = true; + if (force) + invalid = true; + if (m_plan && invalid) + deletePlan(); +} + +// ELF 0x1BD170. A quadrant is tested by its unit direction; quadrant < 0 means the plan target, +// whose world position's XZ is passed as is (not relative to the bot). +bool SensingAgent::targetFeasible(int quadrant) const +{ + Vec2 direction; + if (quadrant < 0) + { + Information* const target = informationManager->getInformation(m_planTarget60); + if (!target) + return false; + const Vec3& position = target->getPosition(); + direction.x = position.x; + direction.y = position.z; + } + else + { + direction.x = 0.0f; + direction.y = 0.0f; + getQuadPosition(quadrant, direction); + } + return withinCamView(direction); +} + +// ELF 0x1BD250: within 20 degrees (0.34906584 rad) of the quadrant. +bool SensingAgent::isForward(int quadrant, const Vec2& direction) const +{ + if (direction.y * direction.y + direction.x * direction.x < 0.01f || quadrant < 0) + return false; + return angleToQuadrant(this, quadrant, direction) < 0.34906584f; +} + +// ELF 0x1BD340: within 90 degrees of the quadrant. +bool SensingAgent::isBehind(int quadrant, const Vec2& direction) const +{ + if (direction.y * direction.y + direction.x * direction.x < 0.01f || quadrant < 0) + return false; + return angleToQuadrant(this, quadrant, direction) < 1.5707964f; +} + +// ELF 0x1BD430. The camera's XZ forward against `direction`: inside the control info's relative +// rotation limits (max on the left of the forward, min on the right); without limits always. +bool SensingAgent::withinCamView(const Vec2& direction) const +{ + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + IPIControlInfo* const control = equipment->getControlInfo(); + const Vec3 forward3 = cameraForward(m_bot, equipment); + float x = forward3.x; + float y = forward3.z; + normaliseXZ(x, y, false); + float dot = y * direction.y + x * direction.x; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + const float angle = std::acos(dot); + const Vec3& maxRotation = control->getCameraRelativeMaxRotation(); + const Vec3& minRotation = control->getCameraRelativeMinRotation(); + if (maxRotation.x == 0.0f && minRotation.x == 0.0f) + return true; + if (y * direction.x - x * direction.y <= 0.0f) + return minRotation.x <= -angle; + return angle <= maxRotation.x; +} + +// ELF 0x1BE020: the plan target and the candidates' weights (positions are kept). +void SensingAgent::clearInformation() +{ + clearPlanTargetInformation(); + for (std::vector::iterator it = m_sensedFocus.begin(); it != m_sensedFocus.end(); ++it) + it->weight = 0.0f; + for (std::vector::iterator it = m_fireFocus.begin(); it != m_fireFocus.end(); ++it) + it->weight = 0.0f; +} + +// ELF 0x1BE250. The re-plan period (+0x98), drawn from a range: vehicle or borrowed armament +// [1, 1.5); no look direction [1.5, 2); standing still a soldier [3, 4), else [7, 10); moving +// with the focus ahead [7, 10), else a soldier [1.5, 2), a vehicle [5, 7). +void SensingAgent::calculateCurrentPeriod(const QuadrantInformation& info, Information* equipment, + const Vec2& direction) +{ + const io::PlayerInput* const input = m_bot->getInput(); + if (!equipment->getUnit()) + return; + const unsigned int flags = equipment->getObjectTypeFlags(); + if (equipment->getUnit()->mustBorrowArmament() || (flags & 0x20) || (flags & 0x10)) + { + m_currentPeriod = randomBetween(1.0f, 1.5f); + return; + } + Vec2 look = direction; + if (!(0.01f <= look.y * look.y + look.x * look.x)) + { + m_currentPeriod = randomBetween(1.5f, 2.0f); + return; + } + const bool soldier = (flags & 0x00200000) != 0; + if (boundInput(input, io::PIThrottle) < 0.01f && boundInput(input, io::PIYaw) < 0.01f) + { + m_currentPeriod = soldier ? randomBetween(3.0f, 4.0f) : randomBetween(7.0f, 10.0f); + return; + } + look.x = -look.x; + look.y = -look.y; + const bool forward = isForward(info.quadrant, look); + if (forward) + m_currentPeriod = randomBetween(7.0f, 10.0f); + else if (soldier) + m_currentPeriod = randomBetween(1.5f, 2.0f); + else + m_currentPeriod = randomBetween(5.0f, 7.0f); +} + +// ELF 0x1BE850. The previous plan is handed to the pattern first (+4 = pattern), which may reuse +// it. Vehicles and borrowed armament look along the (camera-turned) vehicle forward, a vehicle +// slightly down (-0.4 for flag 0x10, else -0.7). Otherwise the stronger of the plan direction +// (+0x4C weight, or any move) and the focus quadrant wins: a quadrant plan looks at the quadrant's +// mean position (or its direction at eye height), a direction / target plan at the plan's. +void SensingAgent::createPlan(ISensingAgentPattern* pattern, const QuadrantInformation& info) +{ + if (m_plan) + m_plan->m_owner = pattern; + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + bool vehicle = false; + if ((equipment->getObjectTypeFlags() & 0x20) || (equipment->getObjectTypeFlags() & 0x10)) + vehicle = true; + if (equipment->getUnit()->mustBorrowArmament() || vehicle) + { + const Vec3 forward = cameraForward(m_bot, equipment); + if (vehicle) + { + Vec3 down; + down.x = forward.x; + down.y = (equipment->getObjectTypeFlags() & 0x10) ? -0.4f : -0.7f; + down.z = forward.z; + createDirPlan(down, pattern); + } + else + { + createDirPlan(forward, pattern); + } + m_flag133 = false; + return; + } + + if (0.01f <= m_moveDirection.y * m_moveDirection.y + m_moveDirection.x * m_moveDirection.x + || m_planWeight <= info.weight) + { + if (info.quadrant < 0) + { + Debug(DebugTypeError, __FILE__, __LINE__, "") << "Sensing agent plan has nothing to look at!"; + } + else + { + Vec3 direction; + const Mat4& transformation = equipment->getTransformation(); + if (info.position.y != 0.0f) + { + direction.x = info.position.x - transformation.m[12]; + direction.y = info.position.y - transformation.m[13]; + direction.z = info.position.z - transformation.m[14]; + } + else + { + Vec2 q; + q.x = 0.0f; + q.y = 0.0f; + getQuadPosition(info.quadrant, q); + direction.x = q.x; + direction.y = transformation.m[9]; + direction.z = q.y; + } + normalise3(direction); + m_int24 = info.quadrant; + m_focusWeight = info.weight; + m_plan = pattern->createPlan(this, m_bot, direction); + m_flag148 = true; + m_int24 = info.quadrant; + m_focusWeight = info.weight; + m_focusPosition = info.position; + m_flag133 = isForward(m_int24, m_moveDirection); + } + } + else + { + if (m_planTarget60 == m_bot->getCurrentEquipment()) + { + Vec3 direction = m_planDirection; + normalise3(direction); + m_plan = pattern->createPlan(this, m_bot, direction); + m_flag148 = false; + } + else + { + m_plan = pattern->createPlan(this, m_bot, m_planTarget60); + m_flag148 = false; + m_int24 = -1; + m_focusWeight = 0.0f; + } + m_flag133 = false; + } + if (m_plan) + m_plan->m_owner = this; +} + +// ELF 0x1BF120: the previous plan's owner becomes the pattern, the new plan's this agent. +void SensingAgent::createDirPlan(const Vec3& direction, ISensingAgentPattern* pattern) +{ + if (m_plan) + m_plan->m_owner = pattern; + m_plan = pattern->createPlan(this, m_bot, direction); + if (m_plan) + m_plan->m_owner = this; +} + +// ELF 0x1BF180: IAISettings +0x8C getSensingAgentNullPattern, target handle 0. +void SensingAgent::createNullPlan() +{ + ISensingAgentPattern* const pattern = + static_cast(CommonSingletonServer::m_iaiSettings)->getSensingAgentNullPattern(); + if (m_plan) + m_plan->m_owner = pattern; + m_plan = pattern->createPlan(this, m_bot, 0u); + if (m_plan) + m_plan->m_owner = this; +} + +void SensingAgent::insertPlanDirectionInformation(float weight, const Vec3& direction, bool flag) +{ + m_planDirection = direction; + m_planTarget60 = m_bot->getCurrentEquipment(); + m_planWeight = weight; + m_flag120 = flag; +} + +// ELF 0x1BF2C0. Draws the selected quadrant/target, camera direction and soldier movement. +// The current-equipment and positive-weight target lookups are deliberately unchecked. +void SensingAgent::drawSensingAgentDebugStuff() +{ + Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); + const Vec3& position = equipment->getPosition(); + if (m_int24 >= 0) + { + const float axial = 1.0f * 10.0f; + const float zero = 0.0f * 10.0f; + const float diagonal = 0.7071067690849304f * 10.0f; + const float negativeDiagonal = -0.7071067690849304f * 10.0f; + const Vec3 directions[8] = { + {zero, 3.0f, axial}, {axial, 3.0f, zero}, + {-zero, 3.0f, -axial}, {-axial, 3.0f, -zero}, + {diagonal, 3.0f, diagonal}, {diagonal, 3.0f, negativeDiagonal}, + {-diagonal, 3.0f, -diagonal}, {-diagonal, 3.0f, -negativeDiagonal} + }; + const Vec3 end = { position.x + directions[m_int24].x, + position.y + directions[m_int24].y, + position.z + directions[m_int24].z }; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0xFF00, position, end, 0.1f); + } + else if (m_planWeight > 0.0f) + { + Information* const target = informationManager->getInformation(m_planTarget60); + const Vec3& end = target->getPosition(); + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0xF00F00, position, end, 0.1f); + } + + Information* const target = informationManager->getInformation(m_planTarget60); + if (target) + { + target->getPosition(); // The image discards this virtual result. + const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); + const Vec3 direction = { camera.m[8] * 3.0f, camera.m[9] * 3.0f, camera.m[10] * 3.0f }; + const Vec3 start = { camera.m[12], camera.m[13], camera.m[14] }; + const Vec3 end = { start.x + direction.x, start.y + direction.y, start.z + direction.z }; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0xFFFF00, start, end, 0.1f); + } + if (equipment->getObjectTypeFlags() & 0x200000) + { + const Vec3 direction = { m_moveDirection.x * 10.0f, 0.0f * 10.0f, m_moveDirection.y * 10.0f }; + const Vec3 end = { position.x + direction.x, position.y + direction.y, position.z + direction.z }; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(0.1f, 0x550000, position, end, 0.1f); + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h index ca26ba04a..3f7a0dda5 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h @@ -3,6 +3,7 @@ #ifndef AI_AIDLL_AI_AIBOT_SENSINGAGENT_H // [INFERRED] guard style #define AI_AIDLL_AI_AIBOT_SENSINGAGENT_H +#include #include #include "../../../../Math/Vec3.h" // Vec2 and Vec3 live here, and both are typedefs @@ -12,73 +13,164 @@ namespace hfe { namespace ai { class BAPContext; -// the plan'S base class. `SensingAgent` holds one `BAPStatement*` and nothing else about the -// statement tree; see the deletePlan block in the .cpp for how far the evidence goes. -class BAPStatement; +// The plan is a `BotScript*` (the patterns' createPlan returns one; deletePlan deletes it through +// the virtual destructor). class BotMain; class BotSenses; class Information; class ISensingAgentPattern; +class BotScript; class SensingAgent { + // [INFERRED] friendship: AIConsole::sensingAgentDebug ELF 0x396930 stores +0x86 at 0x396970. + friend class AIConsole; public: // The second parameter is in the ABI and is never read - see the header block. SensingAgent(BotMain* owner, unsigned char behaviourCount); ~SensingAgent(); // [FRONTIER] - // [UNRESOLVED] Methods requiring unknown nested-type layouts remain undeclared. + // A focus candidate: one per sensed object (evaluateSensedObjects 0x1BC5B0) or incoming shot + // (evaluateFireObjects 0x1BC7E0); 16 bytes, the vector stride (`>> 4`). [INFERRED] member names. + struct FocusInformation + { + float weight; // +0 + Vec3 position; // +4 + }; + // The chosen focus quadrant: update keeps it on the stack (0x14 bytes used); computeTargetQuadrant + // fills it, createPlan / checkForPlanInvalidation / calculateCurrentPeriod read it. [INFERRED] names. + struct QuadrantInformation + { + int quadrant; // +0, -1 = none + float weight; // +4 + Vec3 position; // +8, the mean position of the quadrant's candidates + }; + // getQuadrantWeights' per-quadrant accumulator: weight, (position sum, candidate count). + typedef std::vector > > QuadrantWeights; + void reset(); // Called by `BotMain::reset` when a bot loses its active plan - losing a plan releases the // bot's aim override. void setOverride(bool); - void deletePlan(); // - (one arm frontier) + void deletePlan(); void clearPlanTargetInformation(); - // attested as a nested type by `std::vector`; its members are - // [UNRESOLVED] - nothing recovered so far constructs one. - struct FocusInformation; + void update(); // ELF 0x1BBD30 + void executePlan(); // ELF 0x1BF230 + void disallowOverride(bool b); // ELF 0x1BE0A0 + void updateQuadTimeUrgencies(Vec2& direction, bool turnedAway); // ELF 0x1BC1A0 + void calcTargetQuadFromObjects(QuadrantInformation* info, const Vec2& direction); // ELF 0x1BC410 + void evaluateSensedObjects(); // ELF 0x1BC5B0 + void evaluateFireObjects(); // ELF 0x1BC7E0 + void getQuadrantWeights(QuadrantWeights& weights); // ELF 0x1BCA90 + void computeTargetQuadrant(const QuadrantWeights& weights, QuadrantInformation* info); // ELF 0x1BCD50 + void checkForPlanInvalidation(const QuadrantInformation& info, bool force); // ELF 0x1BCFF0 + bool targetFeasible(int quadrant) const; // ELF 0x1BD170 + bool isForward(int quadrant, const Vec2& direction) const; // ELF 0x1BD250 + bool isBehind(int quadrant, const Vec2& direction) const; // ELF 0x1BD340 + bool withinCamView(const Vec2& direction) const; // ELF 0x1BD430 + void clearInformation(); // ELF 0x1BE020 + void calculateCurrentPeriod(const QuadrantInformation& info, Information* equipment, + const Vec2& direction); // ELF 0x1BE250 + void createPlan(ISensingAgentPattern* pattern, const QuadrantInformation& info); // ELF 0x1BE850 + void createDirPlan(const Vec3& direction, ISensingAgentPattern* pattern); // ELF 0x1BF120 + void createNullPlan(); // ELF 0x1BF180 + // ELF 0x1BE110: the quadrants one unit ahead of the camera that are in focus are marked seen + // (weight 0); seeing the plan's focus quadrant (+24) sets +44. + void setQuadSeen(); + // ELF 0x1BD860: the two quadrants (0..3 diagonal sectors, 4..7 axis sectors) of a position + // around the camera, in the XZ plane; false when the position is on the camera. + bool computeQuadrantsFromPosition(const Vec3& position, int* quadrants) const; + // ELF 0x1BDA60: the camera's XZ forward is within ~10 degrees (dot > 0.9848) of the quadrant. + bool quadInFocus(int quadrant) const; + // ELF 0x1BDBC0: the quadrant's unit XZ direction; anything else is reported. + void getQuadPosition(int quadrant, Vec2& position) const; + BotScript* getPlan() const { return m_plan; } // BotMain::planExecution reads +136 inline + // BotMain's sensing forwarders read +104 inline (ELF 0x18a1d0 `mov 0xc0(%eax),%eax; mov 0x68(%eax)`). + BotSenses* getSenses() const { return m_senses; } + // ELF 0x1BDF70: empty. + void insertBehaviourInformation(float, const Vec3&, unsigned char) {} + // ELF 0x1BDF80: empty. + void insertPlanTargetInformation(float, unsigned int, bool) {} + // ELF 0x1BDF90: a plan direction - +64 the direction, +60 the bot's current equipment, + // +76 the weight, and the sensed-new flag (+120) set to `flag`. + void insertPlanDirectionInformation(float weight, const Vec3& direction, bool flag); + void drawSensingAgentDebugStuff(); + // BotSenses::event_seenObject (indirect sighting) and event_heardObject (new record) store + // `movb $1, 0x78(agent)` inline. [INFERRED] name. + void setSensedNewObject() { m_flag120 = true; } + // EntryInfanteryMoveTo / MoveToObject (0x2B7CF7 `fstpl 0x7c(%eax)`) store 0.0 here inline, so the + // next update ends a pending override at once. [INFERRED] name. + void setOverrideTime(double time) { m_double124 = time; } + + // [INFERRED] inline accessors for the fields the BAP actions read and write in place + // (ai-w1-c-actions request; ELF 0x1D3F00, 0x1D5660). + const Vec2& getMoveDirection() const { return m_moveDirection; } + void setMoveDirection(const Vec2& direction) { m_moveDirection = direction; } + const Vec3& getSprintFocus() const { return m_sprintFocus; } + void setSprintFocus(const Vec3& point) { m_sprintFocus = point; } + unsigned int getSprintFocusTarget() const { return m_sprintFocusTarget; } + void setSprintFocusTarget(unsigned int handle) { m_sprintFocusTarget = handle; } private: - /* 0 */ int m_zero0[6]; // +0..+20, all 0 + // [INFERRED] friendship: the patterns' createPlan reads and clears +0x88 (the plan) and clears + // +0x90 (the BAP context) inline (e.g. SensingAgentNullPattern 0x1C1A93 / 0x1C1AD1). + friend class SensingAgentTurretPattern; + friend class SensingAgentMouseFreeLookPattern; + friend class SensingAgentSoldierPattern; + friend class SensingAgentNullPattern; + // the candidates of the last update; clearInformation zeroes their weights. Constructed empty. + /* 0 */ std::vector m_sensedFocus; // evaluateSensedObjects + /* 12 */ std::vector m_fireFocus; // evaluateFireObjects // neither is A gap - the constructor skips them and `reset` writes both. A field the // constructor misses is not necessarily unused; check the reset before calling it dead. - /* 24 */ int m_int24; // reset: -1 - /* 28 */ int m_int28; // reset: 0 - /* 32 */ int m_zero32[3]; // +32, +36, +40 - /* 44 */ bool m_flag44; // reset: false + // the focus quadrant of the current quadrant plan (createPlan 0x1BE850). [INFERRED] names. + /* 24 */ int m_int24; // reset: -1; the focus quadrant + /* 28 */ float m_focusWeight; // reset: 0 + /* 32 */ Vec3 m_focusPosition; // ctor: 0 + /* 44 */ bool m_flag44; // reset: false; the focus quadrant was looked at // the eight-quadrant weight ring - the constructor's only container, and the only thing it // sizes. Eight zeroed floats; see the header block. /* 48 */ std::vector m_quadrantWeights; // [INFERRED] Plan-target handle, cleared to zero and passed to BotMain when checking // plan invalidation; the neighboring words are also cleared. /* 60 */ unsigned int m_planTarget60; // clearPlanTargetInformation: 0 - /* 64 */ int m_zero64[3]; // +64, +68, +72 - /* 76 */ unsigned int m_planTarget76; // clearPlanTargetInformation: 0 - /* 80 */ int m_zero80[5]; // +80..+96 - /* 100 */ char m_gap100[4]; // [UNRESOLVED] - never written + // insertPlanDirectionInformation's direction and weight; createPlan compares the weight with + // the focus quadrant's and normalises the direction. + /* 64 */ Vec3 m_planDirection; // ctor: 0 + /* 76 */ float m_planWeight; // clearPlanTargetInformation: 0 + // BAPAMergeSoldierInputs::execute (ELF 0x1D3F00) reads +0x50/+0x54 as floats (a Vec2), + // +0x58..+0x60 as a Vec3 and compares +0x64 with -1 (a handle); BAPAMoveTo::setIsSprinting + // (0x1D5660) writes +0x58 / +0x64. [INFERRED] names. The constructor zeroes +80..+96; + // reset zeroes +80 / +84; +100 is never written by either. + /* 80 */ Vec2 m_moveDirection; + /* 88 */ Vec3 m_sprintFocus; + /* 100 */ unsigned int m_sprintFocusTarget; /* 104 */ BotSenses* m_senses; // new(0x94) - the mechanism this agent steers /* 108 */ BotMain* m_bot; // the ctor argument // the whole tail is `reset`'s, not the constructor's - see the note at +24. /* 112 */ double m_double112; // reset: the game time at reset - /* 120 */ bool m_flag120; // reset: false - /* 121 */ bool m_flag121; // reset: false - /* 122 */ bool m_flag122; // reset: false + /* 120 */ bool m_flag120; // reset: false; update re-plans at once while set + /* 121 */ bool m_flag121; // reset: false; evaluateFireObjects: enemy fire booked + /* 122 */ bool m_flag122; // reset: false; disallowOverride: false; the override /* 123 */ char m_pad123; /* 124 */ double m_double124; // reset: 0.0 - /* 132 */ bool m_flag132; // reset: false - /* 133 */ bool m_flag133; // reset: false + /* 132 */ bool m_flag132; // reset: false; disallowOverride(b) stores b + /* 133 */ bool m_flag133; // reset: false; createPlan: the focus is ahead of the move /* 134 */ bool m_flag134; // ctor: false /* 135 */ char m_pad135; // the plan itself - one owned statement, guarded everywhere it is touched. - /* 136 */ BAPStatement* m_plan; // ctor: 0 + /* 136 */ BotScript* m_plan; // ctor: 0 // Set true by `reset` and again by `deletePlan`, and nothing recovered so far reads it. // Meaning [UNRESOLVED]; the name stays neutral rather than guess at `m_planInvalid`. + // executePlan: set when the plan failed or did not finish (failed || !ok). /* 140 */ bool m_flag140; // reset: true, deletePlan: true /* 141 */ char m_pad141[3]; /* 144 */ BAPContext* m_bapContext; // new(4) - shared vocabulary with BotMain's own - /* 148 */ bool m_flag148; // reset: true + /* 148 */ bool m_flag148; // reset: true; createPlan: a quadrant (not target) plan /* 149 */ char m_pad149[3]; - /* 152 */ float m_reactionTime; // reset: a random float in [0.5, 1.0) - see the .cpp + // the time between two re-plans: reset a random float in [0.5, 1.0), calculateCurrentPeriod + // a random float in a range that depends on what the bot does. + /* 152 */ float m_currentPeriod; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp index 8eeec45f9..d5374c38c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp @@ -1,8 +1,28 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SensingAgentPatterns operations. #include "SensingAgentPatterns.h" +#include +// Four original pattern TUs are combined here; each only initialized iostreams. +// static init: ELF 0x1C1780, 0x1C17E0, 0x1C1810 (MouseFreeLook) +// static init: ELF 0x1C1DD0, 0x1C1E30, 0x1C1E60 (Null) +// static init: ELF 0x1C2980, 0x1C29E0, 0x1C2A10 (Soldier) +// static init: ELF 0x1C31A0, 0x1C3200, 0x1C3230 (Turret) -#include "../Main/AIDllFrontier.h" +#include "SensingAgent.h" +#include "BotMain.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIUtils/checkPointer.h" namespace dice { namespace hfe { @@ -86,59 +106,204 @@ void SensingAgentNullPattern::reset(int id) m_id = id; } -// [FRONTIER] Pattern plan creation and soldier helpers require the look/aim plan runtime. -// [RETIRE-WHEN: aidll-02-skeleton] Replace each stop when its plan behavior is recovered. -void SensingAgentTurretPattern::createPlan(SensingAgent *, Bot *, const Vec3&) +// The patterns' shared prologue (inline in every createPlan but the soldier's, e.g. 0x1C2B10): the +// agent's plan is kept when this pattern built it (BAPStatement +0x10 == getId()); otherwise it is +// deleted and the agent's BAP context cleared. The function returns the kept plan or null. +#define SENSING_PATTERN_KEEP_OR_DROP(agent) \ + if (BotScript* const previous = (agent)->m_plan) \ + { \ + if (static_cast(previous)->getPatternId() == getId()) \ + return previous; \ + delete previous; \ + (agent)->m_plan = 0; \ + } \ + (agent)->m_bapContext->clear() + +namespace { + +// The bot's current equipment's control info, or null (Bot +0xD8, Information +0x30). +IPIControlInfo* currentControlInfo(Bot* bot) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + return equipment ? equipment->getControlInfo() : 0; +} + +// BAPATriggerContinously(PIMouseLook, true, false, false, mask 0x800, id, 0.0): the mouse-look +// button held for the plan's life (0x1C06F9..0x1C0727; 0x30 bytes). +BAPATriggerContinously* holdMouseLook(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentTurretPattern::createPlan"); + BAPCondition* const third = checkPointer(new BAPConFalse()); + BAPCondition* const second = checkPointer(new BAPConFalse()); + BAPCondition* const first = checkPointer(new BAPConTrue()); + return checkPointer(new BAPATriggerContinously(io::PIMouseLook, first, second, third, 0x800ULL, id, 0.0)); } -void SensingAgentTurretPattern::createPlan(SensingAgent *, Bot *, unsigned int) +} // namespace + +// ELF 0x1C2B10: look in the direction, 5 degrees (0.08726646 rad) tolerance, never ending. +BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentTurretPattern::createPlan"); + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); + look->m_owner = this; + plan = look; + } + return plan; } -void SensingAgentMouseFreeLookPattern::createPlan(SensingAgent *, Bot *, const Vec3&) +// ELF 0x1C2E50: look at the object, as above. +BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentMouseFreeLookPattern::createPlan"); + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + look->m_owner = this; + plan = look; + } + return plan; } -void SensingAgentMouseFreeLookPattern::createPlan(SensingAgent *, Bot *, unsigned int) +// ELF 0x1C0560: hold the mouse-look button and look in the direction, in parallel. +BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentMouseFreeLookPattern::createPlan"); + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + BAPATriggerContinously* const trigger = holdMouseLook(getId()); + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + parallel->addStatement(trigger); + parallel->addStatement(look); + parallel->m_owner = this; + plan = parallel; + } + return plan; } -void SensingAgentSoldierPattern::createPlan(SensingAgent *, Bot *, const Vec3&) +// ELF 0x1C0E60: as above, looking at the object. +BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::createPlan"); + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + BAPATriggerContinously* const trigger = holdMouseLook(getId()); + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + parallel->addStatement(trigger); + parallel->addStatement(look); + parallel->m_owner = this; + plan = parallel; + } + return plan; } -void SensingAgentSoldierPattern::createPlan(SensingAgent *, Bot *, unsigned int) +// ELF 0x1C1F60. Both createPlan overloads pass a null `plan`, so the reuse arm (the agent's plan +// kept when it is this pattern's: false; otherwise `plan` deleted and the agent's cleared) never +// runs from them. True with the current equipment's control info; otherwise `plan` = 0. +bool SensingAgentSoldierPattern::initPlan(SensingAgent* agent, Bot* bot, IPIControlInfo*& control, + BotScript*& plan) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::createPlan"); + if (plan) + { + if (static_cast(agent->m_plan)->getPatternId() == getId()) + return false; + delete plan; + agent->m_plan = 0; + } + agent->m_bapContext->clear(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (equipment) + { + control = equipment->getControlInfo(); + if (control) + return true; + } + plan = 0; + return false; } -void SensingAgentSoldierPattern::initPlan(SensingAgent *, Bot *, IPIControlInfo *&, BotScript *&) +// ELF 0x1C2050: parallel(look, BAPAMergeSoldierInputs), owned by the pattern. +BotScript* SensingAgentSoldierPattern::endPlan(BAPALook* look, Bot* /*bot*/) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::initPlan"); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + BAPAMergeSoldierInputs* const merge = checkPointer(new BAPAMergeSoldierInputs(getId())); + parallel->addStatement(look); + parallel->addStatement(merge); + parallel->m_owner = this; + return parallel; } -void SensingAgentSoldierPattern::endPlan(BAPALook *, Bot *) +// ELF 0x1C2310: look in the direction exactly (tolerance 0), never ending. +BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentSoldierPattern::endPlan"); + IPIControlInfo* control = 0; + BotScript* plan = 0; + if (initPlan(agent, bot, control, plan)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.0f, checkPointer(new BAPConFalse()), controls, id)); + plan = endPlan(look, bot); + } + return plan; } -// Null-pattern planning still requires an implementation; these overloads stop visibly. -void SensingAgentNullPattern::createPlan(SensingAgent *, Bot *, const Vec3&) +// ELF 0x1C2640: look at the object (tolerance 0). +BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentNullPattern::createPlan"); + IPIControlInfo* control = 0; + BotScript* plan = 0; + if (initPlan(agent, bot, control, plan)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.0f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + plan = endPlan(look, bot); + } + return plan; } -void SensingAgentNullPattern::createPlan(SensingAgent *, Bot *, unsigned int) +// ELF 0x1C1A70: BAPAResetControls(false, true, false, id) (0x1C bytes), owned by the pattern. +BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, const Vec3& /*direction*/) { - BF2_AI_FRONTIER("dice::hfe::ai::SensingAgentNullPattern::createPlan"); + SENSING_PATTERN_KEEP_OR_DROP(agent); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); + reset->m_owner = this; + return reset; } +// ELF 0x1C1C20: identical to the direction overload. +BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, unsigned int /*target*/) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); + reset->m_owner = this; + return reset; +} + +#undef SENSING_PATTERN_KEEP_OR_DROP + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h index 76ab6e007..3c6aa6d33 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h @@ -1,6 +1,5 @@ -// [CHOSEN, not recovered] Grouped sensing-pattern declarations. -// Split into their individual translation units when their plan creation is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// The sensing agent's plan patterns (libaidll.so 0x1C0490..0x1C3250). [CHOSEN, not recovered]: the +// four classes stay grouped in one header and one source file. #ifndef AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNS_H #define AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNS_H @@ -25,8 +24,8 @@ class ISensingAgentPattern // Preserve virtual order: reset precedes the other pattern operations. virtual void reset(int) = 0; // +0x08 - virtual void createPlan(SensingAgent *, Bot *, const Vec3&) = 0; // +0x0C - virtual void createPlan(SensingAgent *, Bot *, unsigned int) = 0; // +0x10 + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&) = 0; // +0x0C + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int) = 0; // +0x10 virtual int getId() const = 0; // +0x14 // Uninitialised by construction - see the block above. @@ -42,8 +41,8 @@ class SensingAgentTurretPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; }; @@ -56,8 +55,8 @@ class SensingAgentMouseFreeLookPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; }; @@ -70,16 +69,18 @@ class SensingAgentSoldierPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; - // Non-virtual, and unique to this pattern: it brackets the plan it builds. - void initPlan(SensingAgent *, Bot *, IPIControlInfo *&, BotScript *&); - void endPlan(BAPALook *, Bot *); + // Unique to this pattern and virtual (vtable 0x4B7640 slots +0x18 / +0x1C): they bracket the + // plan it builds. initPlan (ELF 0x1C1F60) finds the control info; endPlan (0x1C2050) wraps the + // look in a parallel combiner with BAPAMergeSoldierInputs. + virtual bool initPlan(SensingAgent *, Bot *, IPIControlInfo *&, BotScript *&); + virtual BotScript* endPlan(BAPALook *, Bot *); }; -// The null object. Both createPlan overloads are and do nothing useful. +// The null object: both createPlan overloads build (or keep) a BAPAResetControls. class SensingAgentNullPattern : public ISensingAgentPattern { public: @@ -88,8 +89,8 @@ class SensingAgentNullPattern : public ISensingAgentPattern // Preserve virtual order: reset occupies the first slot. virtual void reset(int); - virtual void createPlan(SensingAgent *, Bot *, const Vec3&); - virtual void createPlan(SensingAgent *, Bot *, unsigned int); + virtual BotScript* createPlan(SensingAgent *, Bot *, const Vec3&); + virtual BotScript* createPlan(SensingAgent *, Bot *, unsigned int); virtual int getId() const; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp index 5299a585d..197cd95a3 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp @@ -3,20 +3,43 @@ #include "SquadCoordinator.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1A8DE0, __tcf_0 0x1A8E40, _GLOBAL__I 0x1A8E70). +#include + +#include +#include +#include + #include "SquadFormation.h" #include "SquadMember.h" #include "BotMain.h" +#include "BotSenses.h" +#include "SensingAgent.h" #include "CommunicationAgent.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/InformationManager.h" #include "../Main/AIDllFrontier.h" #include "../Main/AIMain.h" +#include "SquadManager.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" #include "../AIStrategic/SAI.h" #include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/IBotManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../../../AIInterface/BFKnowledge/BFSquad.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Math/Vec3.h" // rotateXZ, vec3ToVec2XZ namespace dice { namespace hfe { @@ -387,9 +410,9 @@ void SquadCoordinator::updateNeedOrdersMessage(double time) return; static_cast(CommonSingletonServer::m_iBFSquad) ->requestNewCommanderOrder(m_squadIndex + 1, leader->getPlayer()); - CommunicationAgent* const radio = leader->getBot()->getCommunicationAgent(); - (void)radio; - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateNeedOrdersMessage (CommunicationAgent::enqueueRadioMessage)"); + // ELF 0x1A3CB6: radio message 14 on channel 4, priority 3, delay 1 s. + leader->getBot()->getCommunicationAgent()->enqueueRadioMessage( + static_cast(14), static_cast(4), 3, 1.0f, 0); } } } @@ -430,7 +453,10 @@ void SquadCoordinator::updateIncomingMessages() return; m_formation->joinSquadLeader(); - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateIncomingMessages (CommunicationAgent::enqueueRadioMessage)"); + // ELF 0x1A3760: the bot answers with radio message 6 (channel 3, priority 3, delay 2 s), and + // every member's path is invalidated. + radio->enqueueRadioMessage(static_cast(6), static_cast(3), 3, 2.0f, 0); + updateSquadPaths(); } // Returns whether a living, standing squad member is inside the assigned control point @@ -478,11 +504,11 @@ void SquadCoordinator::updateSquadManeuver() } break; case 1: - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateSquadManeuver (squadManeuverAlternateFire)"); + squadManeuverAlternateFire(); + break; case 2: - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateSquadManeuver (squadManeuverStaticFlank)"); + squadManeuverStaticFlank(); + break; } } @@ -525,12 +551,161 @@ int SquadCoordinator::chooseSquadManeuver() if (m_i120 != 2) return 0; - Vec3 target = m_v28; - (void)target; - // The remaining terrain-altitude/distance/assignment policy is evidenced but - // not implemented here. Preserve its entry before any height call or flag store. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::chooseSquadManeuver (terrain altitude and flank policy)"); + // ELF 0x1A5741: the mission target (+28) at terrain height (IAITerrain +0x14), 50..173 m from the + // squad, a commander mission (+56) on an area this side holds (status 1): flank. A new flank + // (previous maneuver != 2) clears its two flags. + const float x = m_v28.x; + const float z = m_v28.z; + const float height = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(x, z); + const float dx = x - m_v108.x; + const float dy = height - m_v108.y; + const float dz = z - m_v108.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + if (distanceSq < 30000.0f && 2500.0f < distanceSq && m_b56 && m_strategicAreaAssignment + && static_cast(m_strategicAreaAssignment->getStatus(m_side + 1)) == 1) + { + if (m_i148 != 2) + { + m_b156 = false; + m_b157 = false; + } + return 2; + } + return 0; +} + +// ELF 0x1A4E90. Every 4 s (+124 the update time, +140 the next time): all bots may fire; the +// living bots firing on foot from a mobile primary within 90 m of the squad take turns in two +// halves (phase +152: 0 the first half holds fire 1.5 s, 1 a 1-3 s pause, 2 the second half +// 1.5 s, 3 a pause). A held bot only stops when it faces (dot > 0.85) its target more than 40 m away. +void SquadCoordinator::squadManeuverAlternateFire() +{ + if (!(m_d140 < m_d124)) + return; + m_d140 = m_d124 + 4.0f; + std::vector firing; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (m_squadMembers[i]->isBot()) + m_squadMembers[i]->getBot()->setAllowFire(true); + } + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + if (!member->isBot() || !member->getPlayer()->getIsAlive()) + continue; + Bot* const bot = member->getBot(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!bot->isFiring() || !equipment->isPrimary() || !equipment->hasMobile()) + continue; + const unsigned int flags = equipment->getObjectTypeFlags(); + if ((flags & 0x10u) || (flags & 0x20u) || (flags & 0x80u) || !member->getPosition(position)) + continue; + const float dx = m_v108.x - position.x; + const float dy = m_v108.y - position.y; + const float dz = m_v108.z - position.z; + if (dx * dx + dy * dy + dz * dz < 8100.0f) + firing.push_back(member); + } + const unsigned int count = static_cast(firing.size()); + if (count < 2) + return; + unsigned int start = 0; + unsigned int end = 0; + switch (m_i152) + { + case 0: + end = count >> 1; + m_i152 = 1; + m_d140 = 1.5f + m_d124; + break; + case 1: + m_d140 = (1.0f + m_d124) + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 2.0; + ++m_i152; + break; + case 2: + end = count; + start = count >> 1; + m_i152 = 3; + m_d140 = 1.5f + m_d124; + break; + case 3: + m_d140 = (1.0f + m_d124) + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 2.0; + m_i152 = 0; + break; + default: + break; + } + for (unsigned int i = start; i < end; ++i) + { + SquadMember* const member = firing[i]; + Information* const target = informationManager->getInformation(member->getBot()->getFiringTarget()); + if (!target || !member->getPosition(position)) + continue; + const Vec3& t = target->getPosition(); + Vec3 direction; + direction.x = t.x - position.x; + direction.y = t.y - position.y; + direction.z = t.z - position.z; + const float lengthSq = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.1920929e-07f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + } + else + { + direction.x = 0.0f; + direction.y = 0.0f; + direction.z = 0.0f; + } + } + const Vec3 facing = + informationManager->getInformation(member->getBot()->getCurrentEquipment())->getFaceing(); + if (0.85f < facing.z * direction.z + facing.x * direction.x + facing.y * direction.y) + { + const Vec3& again = target->getPosition(); + const float ex = again.x - position.x; + const float ey = again.y - position.y; + const float ez = again.z - position.z; + if (1600.0f < ex * ex + ey * ey + ez * ez) + firing[i]->getBot()->setAllowFire(false); + } + } +} + +// ELF 0x1A4060. All bots may fire. Once per mission (+157) on an area mission (+120 == 2) with a +// formed squad and an area, at 65 %: the flanking pair closest to the squad (into +160) when both +// are valid for the leader (slot 0) marks the flank (+156) and re-paths the leader. +void SquadCoordinator::squadManeuverStaticFlank() +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (m_squadMembers[i]->isBot()) + m_squadMembers[i]->getBot()->setAllowFire(true); + } + if (m_b157 || m_i120 != 2) + return; + if (!m_formation->hasSquadMembers() || !m_strategicAreaAssignment) + return; + m_b157 = true; + if (!(AIRandom::m_instance->nextFloat() < 0.65f)) + return; + SquadMember* const leader = m_squadMembers[m_formation->getSquadMemberIndexAtSlot(0)]; + if (m_strategicAreaAssignment->getClosestFlankingPositions(m_v108, m_positions[0], m_positions[1]) + && isValidPosition(leader, m_positions[0]) && isValidPosition(leader, m_positions[1])) + { + m_b156 = true; + leader->setHavePath(false); + } } // [INFERRED] void return, as above. @@ -571,8 +746,8 @@ bool SquadCoordinator::isSquadAssignedToArea(int areaIndex) return m_strategicAreaAssignment && m_strategicAreaAssignment->getIndex() == areaIndex; } -// Each qualifying -// live member needs an IAIObject information-handle query before any strength can be added. +// ELF 0x1A7FF0 (277 bytes): the sum of the members' unit strategic strengths of the type +// (IPIUnit +0xC), rounded by +0.5 and truncation. int SquadCoordinator::getStrategicStrength(StrategicStrengthType type) { float total = 0.0f; @@ -584,19 +759,347 @@ int SquadCoordinator::getStrategicStrength(StrategicStrengthType type) IAIObject* const vehicle = player->getCurrentVehicle(); if (!vehicle) continue; - - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // Both ports next call vehicle's unknown slot (ELF +0xB8 / PE +0xB4), passing - // m_side + 1, then resolve its unsigned handle and sum unit strategic strengths[type]. - // ELF captures informationManager before that call; PE captures it afterwards for a - // nonzero low handle word. Stop before the untyped call; do not invent an owner ABI. - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::getStrategicStrength (IAIObject information query)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit()) + total = total + info->getUnit()->getStrategicStrengths()[type]; } - // The shipped empty/filtered paths reach this rounding tail with the unchanged zero sum. - // Every possible contributor above still stops before its unrecovered object query. return static_cast(total + 0.5f); } +// ELF 0x1A7BC0. The order position of the strategic object closest to the squad position +// (+28), for the member's vehicle number, when the member has mobile unit information. +bool SquadCoordinator::getValidSaPos(SquadMember* member, Vec3& position) +{ + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(m_v28, m_side + 1); + bool valid = false; + if (member && object) + { + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (vehicle) + { + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit() && info->getMobile()) + { + position = object->getOrderPos(info->getMobile()->getVehicleNumber(), m_side + 1); + valid = true; + } + } + } + return valid; +} + +// ELF 0x1A7D30 (320 bytes). As the overload above, but the order position of the given area. +bool SquadCoordinator::getValidSaPos(SquadMember* member, AIStrategicArea* area, Vec3& position) +{ + bool valid = false; + if (member && area) + { + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (vehicle) + { + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit() && info->getMobile()) + { + position = area->getOrderPos(info->getMobile()->getVehicleNumber(), m_side + 1); + valid = true; + } + } + } + return valid; +} + +// ELF 0x1A6B60 (856 bytes). Whether `position` lies on the member's navigation mesh: the +// polygon under it (IAIPathfinding +0x44 getPolygon(position, vehicle number, polygon, island, +// equipment type)) must be valid for the vehicle (+0x30 isValidPosition(vehicle number, +// equipment type, position, island, true)). A member whose vehicle information has no mobile +// is tested with its soldier (IAIPlayer +0x4C) instead, and then the island must also be the +// one of the soldier's last valid position. As in the image, neither information is null-checked. +bool SquadCoordinator::isValidPosition(SquadMember* member, const Vec3& position) +{ + Information* const info = informationManager->getInformation( + member->getPlayer()->getCurrentVehicle()->getInformation(m_side + 1)); + IPIMobile* mobile = info->getMobile(); + unsigned int polygon; + unsigned int island; + if (mobile) + { + mobile->getLastValidPosition(); + const int equipment = info->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->getPolygon(position, mobile->getVehicleNumber(), polygon, island, equipment)) + return false; + return IAIPathfinding::instance->isValidPosition( + mobile->getVehicleNumber(), info->getUnit()->getEquipmentType(), position, island, true); + } + Information* const soldier = informationManager->getInformation( + member->getPlayer()->getSoldier()->getInformation(m_side + 1)); + mobile = soldier->getMobile(); + const IPIMobile::ValidPos last = mobile->getLastValidPosition(); + const int equipment = soldier->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->getPolygon(position, mobile->getVehicleNumber(), polygon, island, equipment)) + return false; + if (last.quadTree == static_cast(-1) || island != last.quadTree) + return false; + return IAIPathfinding::instance->isValidPosition( + mobile->getVehicleNumber(), soldier->getUnit()->getEquipmentType(), position, last.quadTree, true); +} + +// ELF 0x1A3A40: the requested-mission record (+60..+95) by value. +SquadCoordinator::MissionRequest SquadCoordinator::getMissionRequest() +{ + MissionRequest request; + request.m_area = m_requestedArea; + request.m_position = m_v64; + request.m_type = m_i76; + request.m_object = m_requestedObject; + request.m_time = m_d84; + request.m_commander = m_b92; + return request; +} + +// ELF 0x1A4950: a repair request at `position`, unconfirmed, valid for 60 s of game time. +void SquadCoordinator::requestRepair(const Vec3& position) +{ + m_b172 = true; + m_v176 = position; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_b196 = false; + m_d188 = now + 60.0f; +} + +// ELF 0x1A6F30 (560 bytes). A squad order from a human squad leader (not `commander`) only moves +// the squad leader's goto position (+200) when it changed (componentwise beyond FLT_EPSILON) and +// the leader is not a bot: the roger-that flag is set, the paths invalidated and the formation +// leaves the leader. A commander order is taken when the side has a player commander, or when +// the squad has no mission and is not close to a non-owned target: the mission state (+120) +// becomes 1 (requested) until the update time + 10 s (+132), and the request record is filled. +void SquadCoordinator::requestMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object, bool commander) +{ + SquadMember* const leader = getSquadLeader(); + if (!commander) + { + if (m_squadMembers.size() == 0) + return; + bool same = false; + if (std::fabs(position.x - m_v200.x) <= 1.1920929e-07f && std::fabs(position.y - m_v200.y) <= 1.1920929e-07f) + same = std::fabs(position.z - m_v200.z) <= 1.1920929e-07f; + if (same || leader->isBot()) + return; + m_b220 = true; + m_v200 = position; + updateSquadPaths(); + m_formation->leaveSquadLeader(); + return; + } + if ((!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && isSquadCloseToNonOwnedTarget()) + || m_i120 != 0) + { + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + return; + } + m_i120 = 1; + m_d132 = m_d124 + 10.0f; + m_v64 = position; + m_i76 = type; + m_requestedArea = 0; + m_requestedObject = object; + m_b92 = commander; +} + +// ELF 0x1A79C0 (480 bytes). `position` itself when valid, else up to eight random points in the +// square of half-size `radius` around it, on the terrain; the first valid one replaces it. +bool SquadCoordinator::getRandomValidPosition(SquadMember* member, Vec3& position, float radius) +{ + if (isValidPosition(member, position)) + return true; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + AIRandom* const random = AIRandom::m_instance; + Vec3 candidate; + candidate.x = 0.0f; + candidate.y = 0.0f; + candidate.z = 0.0f; + for (int attempt = 0; attempt <= 7; ++attempt) + { + // The image keeps each draw in x87 precision: u * 2^-32, doubled, times the radius. + const float lowX = position.x - radius; + candidate.x = static_cast(static_cast(random->next()) * 2.3283064e-10f * 2.0 * radius + lowX); + const float lowZ = position.z - radius; + candidate.z = static_cast(static_cast(random->next()) * 2.3283064e-10f * 2.0 * radius + lowZ); + candidate.y = terrain->getTerrainAltitude(candidate.x, candidate.z); + if (isValidPosition(member, candidate)) + { + position = candidate; + return true; + } + } + return false; +} + +// ELF 0x1A7160 (2016 bytes). Turns the requested mission (+60..) into the accepted one (+24..), +// for `member` (the squad leader, or the member itself when the leader is down). +// * The area assignment is cleared first. Without a player commander, an attack request whose +// closest strategic area has status 0 for this side unassigns the squad (false); the same order +// on the same area is already accepted (true - unreachable after the clear unless no area). +// * The closest area is taken when the goal lies inside it, or within the ignore-commander +// distance (IAISettings +0x08) plus the area's size of its centre on the terrain and the area's +// status is non-zero; the goal becomes the area's centre. +// * Without an area, a valid position within 30 m of the goal is taken instead; failing that a +// bot member declines (radio 7; as squad leader the engine's decline for the order type), and +// the squad is unassigned. +// * On acceptance: a human leader gets a commander message (attack 0 / defend 1, 3 s) when there +// is no player commander; a bot leader acknowledges (radio 6 with a player commander), issues the +// squad order and accepts the commander order for the member (attack 0x10, defend 0xF, move +// 0x11 on the radio), and every member's path is invalidated. +bool SquadCoordinator::acceptMission(SquadMember* member) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + bool accepted = false; + m_strategicAreaAssignment = 0; + AIStrategicArea* const closest = static_cast( + AIStrategicObjectManager::getInstance()->getClosestObject(m_v64, m_side + 1)); + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && closest && m_i76 == 0 + && closest->m_status[m_side] == 0) + { + unAssignSquad(); + return false; + } + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && m_i40 == m_i76 + && m_strategicAreaAssignment == closest) + return true; + + if (closest) + { + const Vec2& centre2 = closest->getPosition(m_side + 1); + const float cx = centre2.x; + const float cz = centre2.y; + Vec3 centre; + centre.x = cx; + centre.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(cx, cz); + centre.z = cz; + const float slack = static_cast(CommonSingletonServer::m_iaiSettings)->getIgnoreCommanderDistance(); + const float size = closest->m_size[m_side]; + bool take = closest->isInside(m_v64); + if (!take) + { + const float dx = m_v64.x - centre.x; + const float dy = m_v64.y - centre.y; + const float dz = m_v64.z - centre.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + take = !(static_cast(slack + size) <= distance) && closest->m_status[m_side] != 0; + } + if (take) + { + m_v64 = centre; + m_v28 = centre; + m_i120 = 2; + m_i40 = m_i76; + m_strategicAreaAssignment = closest; + m_i44 = m_requestedObject; + m_d48 = now; + m_b56 = m_b92; + accepted = true; + } + } + + if (!m_strategicAreaAssignment) + { + Vec3 position = m_v64; + if (getRandomValidPosition(member, position, 30.0f)) + { + m_v64 = position; + m_i120 = 2; + m_v28 = m_v64; + m_i40 = m_i76; + m_i44 = m_requestedObject; + m_b56 = m_b92; + m_d48 = now; + accepted = true; + } + else if (member->isBot()) + { + member->getBot()->getCommunicationAgent()->enqueueRadioMessage( + static_cast(7), static_cast(4), 3, 2.0f, 0); + if (member->isSquadLeader()) + { + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + if (m_i76 == 0) + engine->declineCommanderAttackOrder(m_squadIndex + 1, member->getPlayer()); + else if (m_i76 == 1) + engine->declineCommanderDefendOrder(m_squadIndex + 1, member->getPlayer()); + else if (m_i76 == 2) + engine->declineCommanderMoveOrder(m_squadIndex + 1, member->getPlayer()); + } + unAssignSquad(); + updateSquadPaths(); + } + } + if (!accepted) + return false; + + SquadMember* const leader = getSquadLeader(); + if (!leader->isBot()) + { + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && (m_i40 == 0 || m_i40 == 1)) + SquadManager::m_instance->enqueueCommanderMessage( + m_side, m_squadIndex, static_cast(m_i40 == 0 ? 0 : 1), 3.0); + } + else + { + CommunicationAgent* const radio = leader->getBot()->getCommunicationAgent(); + if (IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + radio->enqueueRadioMessage(static_cast(6), static_cast(4), 3, 2.5f, 0); + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + int message = -1; + if (m_i40 == 0) + { + engine->issueSquadAttackOrder(m_v28, m_squadIndex + 1, m_side + 1, 0); + engine->acceptCommanderAttackOrder(m_squadIndex + 1, member->getPlayer()); + message = 0x10; + } + else if (m_i40 == 1) + { + engine->issueSquadDefendOrder(m_v28, m_squadIndex + 1, m_side + 1, 0); + engine->acceptCommanderDefendOrder(m_squadIndex + 1, member->getPlayer()); + message = 0xF; + } + else if (m_i40 == 2) + { + engine->issueSquadMoveOrder(m_v28, m_squadIndex + 1, m_side + 1, 0); + engine->acceptCommanderMoveOrder(m_squadIndex + 1, member->getPlayer()); + message = 0x11; + } + if (message != -1) + radio->enqueueRadioMessage(static_cast(message), static_cast(3), 3, 2.0f, 0); + } + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setHavePath(false); + return true; +} + +// ELF 0x1A4DC0 (208 bytes). Whether the navigation material under `position` for the member's +// vehicle (IAIPathfinding +0x58 getMaterial) is water (4); true without a vehicle. The vehicle +// information is not null-checked, and getMaterial's result is ignored. +bool SquadCoordinator::isPosOnWater(SquadMember* member, Vec3& position) +{ + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (!vehicle) + return true; + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + const int equipment = info->getUnit()->getEquipmentType(); + unsigned char material; + IAIPathfinding::instance->getMaterial(position, info->getMobile()->getVehicleNumber(), equipment, material); + return material == 4; +} + +// ELF 0x1A6B20: the accepted mission's goal (+28), only for a mission without a target object. +bool SquadCoordinator::getSquadMissionTargetPos(Vec3& position) +{ + if (m_i44) + return false; + position = m_v28; + return true; +} + // Stores side and squad identity before constructing the formation, which queries this coordinator. SquadCoordinator::SquadCoordinator(int side, int squadIndex) @@ -608,9 +1111,9 @@ SquadCoordinator::SquadCoordinator(int side, int squadIndex) , m_i40(4) , m_i44(0) , m_d48(-20.0) - , m_i60(0) + , m_requestedArea(0) , m_i76(4) - , m_i80(0) + , m_requestedObject(0) , m_i96(-1) , m_list104() , m_i120(0) @@ -761,11 +1264,16 @@ void SquadCoordinator::updateSquadLeader() if (oldLeader != m_i96 && oldLeader != -1 && !m_squadMembers.empty()) { + // ELF 0x1A5C66: a new leader - the formation rejoins it and the squad position and paths + // are refreshed; a human leader of a squad with more members leaves the AI commander's + // assignment (unless the side has a player commander). m_squadMembers[m_i96]->updateMemberPos(); - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // Next: formation->joinSquadLeader, updateSquadPosition, updateSquadPaths - // then the human-leader/commander policy. Those movement bodies remain unrecovered. - BF2_AI_FRONTIER("dice::hfe::ai::SquadCoordinator::updateSquadLeader (SquadFormation::joinSquadLeader)"); + m_formation->joinSquadLeader(); + updateSquadPosition(); + updateSquadPaths(); + if (getSquadLeader() && !getSquadLeader()->isBot() && m_squadMembers.size() > 1 + && !IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + unAssignSquad(); } if (m_squadMembers.size() == 1) m_formation->resetTrailingPositions(); @@ -827,6 +1335,713 @@ void SquadCoordinator::resetNeedOrderMessageTimer(double now) m_needOrderMessageTimer = now; } +// ELF 0x1A3790: the per-round reset, store by store. The fire records are freed, the formation +// rejoins its leader and reassigns its slots, the need-orders timer restarts at the game time and +// every member resets its own state. +void SquadCoordinator::reset() +{ + m_strategicAreaAssignment = 0; + m_i40 = 4; + m_d48 = -20.0; + m_i44 = 0; + m_i76 = 4; + m_requestedArea = 0; + m_requestedObject = 0; + m_i120 = 0; + m_formation->joinSquadLeader(); + for (std::list::iterator it = m_list12.begin(); it != m_list12.end();) + { + ::operator delete(*it); + it = m_list12.erase(it); + } + m_formation->reassignSlots(); + m_v108.x = m_v108.y = m_v108.z = 0.0f; + m_i148 = 0; + m_i152 = 0; + m_d132 = 0.0; + m_d140 = 0.0; + m_b156 = false; + m_b157 = false; + m_b172 = false; + m_b196 = false; + m_v200.x = m_v200.y = m_v200.z = 0.0f; + resetNeedOrderMessageTimer(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); + m_b220 = false; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->reset(); +} + +// ELF 0x1A64B0: frees and unlinks every fire record of the member's player (IAIPlayer +0x1C). +void SquadCoordinator::removeSquadMemberFire(SquadMember* member) +{ + const int playerId = member->getPlayer()->getId(); + for (std::list::iterator it = m_list12.begin(); it != m_list12.end();) + { + if ((*it)->m_playerId == playerId) + { + ::operator delete(*it); + it = m_list12.erase(it); + } + else + ++it; + } +} + +// ELF 0x1A82E0: the member leaves the fire records and, if it holds a slot, the formation; it is +// unlinked (not deleted - the caller owns it now), the remaining members are renumbered, the +// leader is re-elected and the slots are reassigned. +void SquadCoordinator::removeSquadMember(int index) +{ + SquadMember* const member = m_squadMembers[index]; + removeSquadMemberFire(member); + if (m_formation->isInFormation(member->getMemberIndex())) + m_formation->leaveFormation(member->getMemberIndex()); + m_squadMembers.erase(m_squadMembers.begin() + index); + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setMemberIndex(static_cast(i)); + updateSquadLeader(); + m_formation->reassignSlots(); +} + +// ELF 0x1A84F0: the first member with the same player id is removed by index; none, nothing. +void SquadCoordinator::removeSquadMember(SquadMember* member) +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (member->getPlayerId() == m_squadMembers[i]->getPlayerId()) + { + removeSquadMember(static_cast(i)); + return; + } + } +} + +// ELF 0x1A6EC0: with an assigned area whose status for this squad's side is non-zero, true as +// soon as one member is close to that non-owned target. +bool SquadCoordinator::isSquadCloseToNonOwnedTarget() +{ + if (!m_strategicAreaAssignment || !m_strategicAreaAssignment->m_status[m_side]) + return false; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + if (m_squadMembers[i]->isCloseToNonOwnedTarget()) + return true; + return false; +} + +// ELF 0x1A6B00: the mission state at +0x78 (m_i120) equals 2. +bool SquadCoordinator::squadHasMission() +{ + return m_i120 == 2; +} + +// ELF 0x1A7FA0. +bool SquadCoordinator::isSquadAvailable() +{ + return m_i120 == 0; +} + +// ELF 0x1A7F60: the requested area's index (+0xF0). +bool SquadCoordinator::isSquadRequestedToArea(int areaIndex) +{ + bool requested = false; + if (m_requestedArea) + requested = areaIndex == m_requestedArea->getIndex(); + return requested; +} + +// ELF 0x1A3930: every member's request and record are freed, the list emptied, slots reassigned. +void SquadCoordinator::removeAll() +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + member->removeRequest(); + delete member; + } + m_squadMembers.resize(0); + m_formation->reassignSlots(); +} + +// ELF 0x1A83C0 (290 bytes). Like removeSquadMember, but the member record is destroyed and a +// bot's back-pointer cleared (Bot vtable +0x13C setSquadMember(0)). +void SquadCoordinator::destroySquadMember(int index) +{ + SquadMember* const member = m_squadMembers[index]; + removeSquadMemberFire(member); + member->removeRequest(); + if (m_formation->isInFormation(member->getMemberIndex())) + m_formation->leaveFormation(member->getMemberIndex()); + m_squadMembers.erase(m_squadMembers.begin() + index); + if (member->isBot()) + member->getBot()->setSquadMember(0); + delete member; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setMemberIndex(i); + updateSquadLeader(); + m_formation->reassignSlots(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1A5D90, added by ai-w1-e-fire: a squad mate fired at `target`; every other bot of the +// squad sees the target's primary object (side + 1 = the image's `m_side + 1`) at the origin, +// part -1, neither direct nor flag 0x40. +void SquadCoordinator::shotsFired(int playerId, unsigned int target) +{ + const Vec3 origin = { 0.0f, 0.0f, 0.0f }; + Information* const information = informationManager->getInformation(target); + if (!information) + return; + const unsigned int primary = information->getPrimaryObject(m_side + 1); + Information* const primaryInformation = informationManager->getInformation(primary); + if (!primaryInformation) + return; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + if (!member || !member->isBot() || member->getPlayerId() == playerId) + continue; + member->getBot()->getSensingAgent()->getSenses()->event_seenObject( + primary, origin, static_cast(-1), primaryInformation, false, false); + } +} + +// ELF 0x1A86D0. +bool SquadCoordinator::isAnySquadMemberRespondingToRequest(unsigned int handle, int action) +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + if (m_squadMembers[i]->isSameRequest(handle, action)) + return true; + } + return false; +} + +// ELF 0x1A8730 (1.7 KB). `target` is the squad member occupying the request's object (a hurt or +// downed player, a vehicle needing repair). Request actions as the callers pass them: 1 revive +// (BBRevive), 2 repair (BBBridgeRepair), 4 heal / supply (BBMedicAssist), 5 (any number may answer). +// * No occupant: 0 when someone of the side already answers; else 1, 0 beyond sqrt(20000) m of the +// squad position (+108), doubled when a human occupies the object. +// * Occupant in this squad: 0 for a revive of a living (health > 0.001) medic (kit 5) other than +// `member`; 0 for request 4 to a living engineer (kit 3); otherwise 0 when another member +// already has the request, x0.75 per such member for action 5. +// * Occupant in another squad: actions 1 / 2 / 4 within sqrt(1000) m of the squad position and with +// nobody answering: 0.5, or 0.1 when the occupant's squad has its own medic (5) / kit 4 / +// engineer (3); 0 otherwise; other actions 1. +// Finally doubled when the occupant is human. +float SquadCoordinator::requestResponseModifier(SquadMember* member, unsigned int handle, int action) +{ + SquadManager* const manager = SquadManager::m_instance; + float modifier = 1.0f; + bool skipRequests = false; + float distanceSq = 0.0f; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + SquadMember* const target = manager->getSquadMember(handle, m_side + 1); + bool zero = false; + if (!target) + { + if (manager->isAnySquadMemberRespondingToRequest(handle, action, m_side + 1)) + { + zero = true; + } + else + { + Information* const info = informationManager->getInformation(handle); + modifier = 1.0f; + if (info) + { + const Vec3& p = info->getPosition(); + if (20000.0f < (p.x - m_v108.x) * (p.x - m_v108.x) + (p.y - m_v108.y) * (p.y - m_v108.y) + + (p.z - m_v108.z) * (p.z - m_v108.z)) + modifier = 0.0f; + if (info->getUnit()) + { + const int occupant = info->getUnit()->getOccupyingPlayerId(m_side + 1); + if (occupant != -1 && IBotManager::instance->getBotFromPlayerId(occupant) == 0) + modifier = modifier + modifier; + } + } + } + } + else if (target->getSquadId() == member->getSquadId()) + { + if (target->getMemberIndex() != member->getMemberIndex() && action == 1) + { + // No null guard on the information (0x1A87F8). + IPIPhysical* const physical = informationManager->getInformation(handle)->getPhysical(); + if (physical && 0.001f < physical->getHealth() && target->getPlayer()->getSpawnKit() == 5) + zero = true; + } + if (!zero && action == 4 && target->getMemberIndex() != member->getMemberIndex()) + { + IPIPhysical* const physical = informationManager->getInformation(handle)->getPhysical(); + if (physical && 0.001f < physical->getHealth() && target->getPlayer()->getSpawnKit() == 3) + { + modifier = 0.0f; + skipRequests = true; + } + } + if (!zero && !skipRequests) + { + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const other = m_squadMembers[i]; + if (member->getMemberIndex() != other->getMemberIndex() && other->isSameRequest(handle, action)) + { + if (action != 5) + { + zero = true; + break; + } + modifier = modifier * 0.75f; + } + } + } + } + else + { + const bool responding = manager->isAnySquadMemberRespondingToRequest(handle, action, m_side + 1); + if (target->getPosition(position)) + distanceSq = (position.z - m_v108.z) * (position.z - m_v108.z) + + (position.x - m_v108.x) * (position.x - m_v108.x) + + (position.y - m_v108.y) * (position.y - m_v108.y); + int kit = -1; + switch (action) + { + case 1: kit = 5; break; + case 2: kit = 4; break; + case 4: kit = 3; break; + default: break; + } + if (kit >= 0) + { + if (!responding && distanceSq < 1000.0f) + { + // No null guard on the squad (0x1A8958). + SquadCoordinator* const squad = manager->getSquadFromPlayer(target->getPlayerId(), m_side + 1); + modifier = squad->hasMemberWithKit(static_cast(kit)) ? 0.1f : 0.5f; + } + else + { + zero = true; + } + } + } + if (zero) + modifier = 0.0f; + if (target && !target->isBot()) + modifier = modifier + modifier; + return modifier; +} + +// ELF 0x1A69C0. +bool SquadCoordinator::isSameMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object) +{ + if (m_i40 != static_cast(type) || m_i44 != object) + return false; + const float epsilon = 1.1920929e-07f; + if (epsilon < std::fabs(m_v28.x - position.x)) + return false; + if (epsilon < std::fabs(m_v28.y - position.y)) + return false; + return epsilon >= std::fabs(m_v28.z - position.z); +} + +// ELF 0x1A3270 (D1, 470 B; recovered on the client track, docs/macos-c-singleplayer.md). Each +// member drops its request and leaves the engine squad (IBFSquad +0x10, exitSquad with the +// 1-based squad number) before it is deleted - the member pointer is used before the null test, +// as shipped. Then the formation goes, then every fire record (plain operator delete, the node +// erased behind the iterator). The containers follow as members. +SquadCoordinator::~SquadCoordinator() +{ + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + { + SquadMember* const member = m_squadMembers[i]; + member->removeRequest(); + static_cast(CommonSingletonServer::m_iBFSquad)->exitSquad(m_squadIndex + 1, member->getPlayer()); + delete member; + } + delete m_formation; + std::list::iterator fire = m_list12.begin(); + while (fire != m_list12.end()) + { + delete *fire; + m_list12.erase(fire++); + } +} + +namespace { + +// [CHOSEN, not recovered] packaging: the engine's inline Vec2 / Vec3 normalise as the fire and +// flank bodies below spell it out (0x1A6040.., 0x1A4360..): left alone within FLT_EPSILON of unit +// length, zeroed below the threshold (Vec2: FLT_EPSILON^2, Vec3: FLT_EPSILON), else scaled by +// 1/sqrt. +void normalizeInline(Vec2& v) +{ + const float lsq = v.x * v.x + v.y * v.y; + if (std::fabs(lsq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.4210855e-14f) + { + v.x = 0.0f; + v.y = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x = v.x * inv; + v.y = inv * v.y; +} + +void normalizeInline(Vec3& v) +{ + const float lsq = v.z * v.z + v.x * v.x + v.y * v.y; + if (std::fabs(lsq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.1920929e-07f) + { + v.x = 0.0f; + v.y = 0.0f; + v.z = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x = v.x * inv; + v.y = v.y * inv; + v.z = inv * v.z; +} + +} // anonymous namespace + +// ELF 0x1A4250. No caller in libaidll.so. Every bot may fire. Once per mission (m_b157), with a +// mission (+0x78 == 2) and a formation leader slot: from the squad position (m_v108) towards the +// accepted mission position (m_v28, put on the terrain), with probability 0.3 (0.6 when the squad +// cannot see the target), the leader (slot 0) is given two flank points: the half-distance point +// of the direction turned by 0.781 rad (sign at random), then half the distance further along the +// direction; each is randomised within a quarter of the distance. When either fails the other +// side is tried; on success m_b156 is set and the leader re-paths. The leader's liveness is +// tested only after the null test. +void SquadCoordinator::squadManeuverDynamicFlank() +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + { + SquadMember* const member = m_squadMembers[index]; + if (member->isBot()) + member->getBot()->setAllowFire(true); // +0x134 + } + if (m_b157 || m_i120 != 2 || !m_formation->hasSquadMembers()) + return; + m_b157 = true; + SquadMember* const leader = m_squadMembers[m_formation->getSquadMemberIndexAtSlot(0)]; + + Vec3 direction; + direction.x = m_v28.x - m_v108.x; + direction.y = m_v28.y - m_v108.y; + direction.z = m_v28.z - m_v108.z; + float distance = + std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + normalizeInline(direction); + + Vec3 target = m_v28; + Vec3 turned; + turned.x = 0.0f; + turned.y = 0.0f; + turned.z = 0.0f; + target.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(target.x, target.z); // +0x14 + float probability = 0.3f; + float angle = 0.781f; + if (!canSeePos(m_v108, target)) + probability = probability + probability; + if (!(AIRandom::m_instance->nextFloat() < probability) || leader == 0) + return; + if (!leader->getPlayer()->getIsAlive()) + return; + const float half = 0.5f; + if (half < AIRandom::m_instance->nextFloat()) + angle = -angle; + rotateXZ(direction, turned, angle); + m_positions[0].x = distance * turned.x * half + m_v108.x; + m_positions[0].y = distance * turned.y * half + m_v108.y; + m_positions[0].z = distance * turned.z * half + m_v108.z; + m_positions[1].x = distance * direction.x * half + m_positions[0].x; + m_positions[1].y = distance * direction.y * half + m_positions[0].y; + m_positions[1].z = half * distance * direction.z + m_positions[0].z; + const float radius = distance * 0.25f; + if (!getRandomValidFlankPos(leader, radius, m_positions[0]) + || !getRandomValidFlankPos(leader, radius, m_positions[1])) + { + angle = -angle; + rotateXZ(direction, turned, angle); + m_positions[0].x = distance * turned.x * half + m_v108.x; + m_positions[0].y = distance * turned.y * half + m_v108.y; + m_positions[0].z = distance * turned.z * half + m_v108.z; + m_positions[1].x = distance * direction.x * half + m_positions[0].x; + m_positions[1].y = distance * direction.y * half + m_positions[0].y; + m_positions[1].z = distance * direction.z * half + m_positions[0].z; + distance = distance * 0.25f; + if (!getRandomValidFlankPos(leader, distance, m_positions[0])) + return; + if (!getRandomValidFlankPos(leader, distance, m_positions[1])) + return; + } + m_b156 = true; + leader->setHavePath(false); +} + +// ELF 0x1A4A10. A line one metre above both points, ignoring the squad's vehicles +// (IAIObjectEnvironment +0x40, collideLineWithWorld(from, to, ignore, false, 0, true, hit)): +// visible when nothing is hit. +bool SquadCoordinator::canSeePos(const Vec3& from, const Vec3& to) +{ + Vec3 start = from; + start.y = from.y + 1.0f; + Vec3 end = to; + end.y = 1.0f + to.y; + std::vector ignore; + getSquadIgnoreList(ignore); + bool hit; + const bool collided = static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(start, end, ignore, false, 0.0f, true, hit); + return !collided; +} + +// ELF 0x1A4B10: the two flank points. +void SquadCoordinator::getFlankingCoords(std::vector& coords) +{ + coords = m_positions; +} + +// ELF 0x1A4B60. `position` put on the terrain is kept when it is valid for `member` and not on +// water - then `position` itself is NOT updated (its height stays as given). Otherwise up to ten +// random points in the square of half-side `radius` around it; the first good one is stored. +bool SquadCoordinator::getRandomValidFlankPos(SquadMember* member, float radius, Vec3& position) +{ + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + bool found = true; + Vec3 candidate = position; + candidate.y = terrain->getTerrainAltitude(candidate.x, candidate.z); // +0x14 + if (!isValidPosition(member, candidate) || isPosOnWater(member, candidate)) + { + found = false; + for (int attempt = 0; attempt < 10; ++attempt) + { + const float lowX = position.x - radius; + const float drawX = AIRandom::m_instance->nextFloat() * radius; + candidate.x = drawX + drawX + lowX; + const float lowZ = position.z - radius; + const float drawZ = AIRandom::m_instance->nextFloat() * radius; + candidate.z = drawZ + drawZ + lowZ; + candidate.y = terrain->getTerrainAltitude(candidate.x, candidate.z); + if (isValidPosition(member, candidate) && !isPosOnWater(member, candidate)) + { + position = candidate; + return true; + } + } + } + return found; +} + +// ELF 0x1A5F00 (SquadManager::shotsFired). Nothing unless the shooter has a position. An existing +// record of the shooter is refreshed: when the shot's XZ direction turns away from the record's +// re-path direction (normalised dot below 0.1) that direction is replaced and the whole squad +// re-paths; then the latest direction and position, the expiry (now + 10 s) and the firing target +// (Bot +0x80 for a bot, else -1) are stored. Without a record a new one is appended with both +// directions and both positions from this shot, and the squad re-paths. +void SquadCoordinator::shotsFired(int playerId, const Vec3& direction) +{ + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + Vec2 shot; + shot.x = direction.x; + shot.y = direction.z; + int target = -1; + int index = 0; + Vec2 previous; + previous.x = 0.0f; + previous.y = 0.0f; + SquadMember* const shooter = getSquadMember(playerId, index); + if (!shooter->getPosition(position)) + return; + + std::list::iterator it = m_list12.begin(); + for (; it != m_list12.end(); ++it) + { + SquadMemberFire* const fire = *it; + if (playerId != fire->m_playerId) + continue; + vec3ToVec2XZ(fire->m_v20, previous); + normalizeInline(previous); + normalizeInline(shot); + if (shot.x * previous.x + shot.y * previous.y < 0.1f) + { + fire->m_v20 = direction; + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setHavePath(false); + m_formation->updateMovementFlag(true); + } + fire->m_v8 = direction; + fire->m_v40 = position; + fire->m_time = now + 10.0f; + if (shooter->isBot()) + target = static_cast(shooter->getBot()->getFiringTarget()); // +0x80 + fire->m_i64 = target; + break; + } + if (it != m_list12.end()) + return; + + if (shooter->isBot()) + target = static_cast(shooter->getBot()->getFiringTarget()); + SquadMemberFire* const fire = new SquadMemberFire; + fire->m_v8.x = fire->m_v8.y = fire->m_v8.z = 0.0f; + fire->m_v20.x = fire->m_v20.y = fire->m_v20.z = 0.0f; + fire->m_v40.x = fire->m_v40.y = fire->m_v40.z = 0.0f; + fire->m_position.x = fire->m_position.y = fire->m_position.z = 0.0f; + fire->m_v20 = direction; + fire->m_v8 = direction; + fire->m_playerId = playerId; + fire->m_member = getSquadMember(playerId, index); + fire->m_v40 = position; + fire->m_position = position; + fire->m_i64 = target; + fire->m_time = now + 10.0f; + m_list12.push_back(fire); + for (unsigned int i = 0; i < m_squadMembers.size(); ++i) + m_squadMembers[i]->setHavePath(false); + m_formation->updateMovementFlag(true); +} + +// ELF 0x1A6570: any fire record (the list is counted). +bool SquadCoordinator::anyFiring() +{ + return m_list12.size() != 0; +} + +// ELF 0x1A65B0: a fire record of `playerId`. +bool SquadCoordinator::isFiring(int playerId) +{ + for (std::list::iterator it = m_list12.begin(); it != m_list12.end(); ++it) + if (playerId == (*it)->m_playerId) + return true; + return false; +} + +// ELF 0x1A6610: distance output is written only when a nearer eligible shooter is found. +SquadMember* SquadCoordinator::getClosestFiringMember(SquadMember* member, float& distanceSquared) +{ + SquadMember* closest = 0; + Vec3 position = {}; + Vec3 candidatePosition = {}; + const int playerId = member->getPlayerId(); + float nearest = FLT_MAX; + if (!member->getPosition(position)) + return closest; + for (std::list::iterator it = m_list12.begin(); it != m_list12.end(); ++it) + { + SquadMemberFire* const fire = *it; + SquadMember* const candidate = fire->m_member; + if (candidate->getPlayerId() == playerId || !candidate->getPosition(candidatePosition) + || !candidate->getPlayer()->getIsAlive() + || !m_formation->isInFormation(candidate->getMemberIndex()) + || !member->canDamageTarget(static_cast(fire->m_i64))) + continue; + if (candidate->isSquadLeader() && m_formation->shouldLeaveSquadLeader()) + continue; + const float dx = position.x - candidatePosition.x; + const float dy = position.y - candidatePosition.y; + const float dz = position.z - candidatePosition.z; + const float squared = dx * dx + dy * dy + dz * dz; + if (nearest > squared) + { + nearest = squared; + closest = candidate; + distanceSquared = squared; + } + } + return closest; +} + +// ELF 0x1A6820: the member's latest shot direction, (1, 0, 0) without a record. +Vec3 SquadCoordinator::getFiringDir(SquadMember* member) +{ + Vec3 direction; + direction.y = 0.0f; + direction.z = 0.0f; + direction.x = 1.0f; + for (std::list::iterator it = m_list12.begin(); it != m_list12.end(); ++it) + { + SquadMemberFire* const fire = *it; + if (fire->m_playerId == member->getPlayerId()) + { + direction = fire->m_v8; + return direction; + } + } + return direction; +} + +// ELF 0x1A6A60. Compares the requested mission (+0x4C type, +0x50 object, +0x40 position), not +// the accepted one isSameMission reads. +bool SquadCoordinator::isSameRequest(BotSquad::OrderType type, const Vec3& position, IAIObject* object) +{ + bool same = false; + if (m_i76 == static_cast(type) && m_requestedObject == object) + { + const float epsilon = 1.1920929e-07f; + if (std::fabs(m_v64.x - position.x) <= epsilon && std::fabs(m_v64.y - position.y) <= epsilon) + same = std::fabs(m_v64.z - position.z) <= epsilon; + } + return same; +} + +// ELF 0x1A7940. +SquadMember* SquadCoordinator::getBotInSquad() +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + if (m_squadMembers[index]->isBot()) + return m_squadMembers[index]; + return 0; +} + +// ELF 0x1A7E70: by value. +std::list SquadCoordinator::getListOfAreaNavPoints() +{ + return m_list104; +} + +// ELF 0x1A8580. +void SquadCoordinator::getSquadIgnoreList(std::vector& ignore) +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + { + IAIObject* const vehicle = m_squadMembers[index]->getPlayer()->getCurrentVehicle(); // +0x54 + if (vehicle != 0) + ignore.push_back(vehicle); + } +} + +// ELF 0x1A8680. +bool SquadCoordinator::squadHasHumanPlayer() +{ + for (unsigned int index = 0; index < m_squadMembers.size(); ++index) + if (!m_squadMembers[index]->isBot()) + return true; + return false; +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h index d05604461..b8ef1cc05 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h @@ -10,6 +10,7 @@ #include #include "../../../../Math/Vec3.h" +#include "BotSquad.h" // BotSquad::OrderType namespace dice { namespace hfe { @@ -20,29 +21,33 @@ class SquadFormation; class SquadMember; class IAIPlayer; class AIStrategicArea; +class AIStrategicObject; +class Bot; +class IAIObject; enum StrategicStrengthType : int; // Attested type name; enum labels remain unrecovered. class SquadCoordinator { public: // attested nested type name: `std::list` insert/erase/clear - // are instantiated. on the ELF (`shotsFired` allocates 0x44), four Vec3s zeroed by - // the allocation; the scalar members are written field by field. Roles come from shotsFired - // (, ), removeSquadMemberFire and updateShotsFired; names are [INFERRED]. - // Nothing in this tree allocates one yet, so the list stays empty on every exercised path. + // are instantiated. on the ELF (`shotsFired(int, const Vec3&)`, ELF 0x1A5F00, allocates 0x44), + // four Vec3s zeroed by the allocation; the scalar members are written field by field. Roles + // come from shotsFired, getFiringDir, removeSquadMemberFire and updateShotsFired; names are + // [INFERRED]. struct SquadMemberFire { /* +0x00 */ double m_time; // expiry: game time + 10 s, restamped on each shot - /* +0x08 */ Vec3 m_v8; // the shotsFired Vec3 argument [UNRESOLVED role] - /* +0x14 */ Vec3 m_v20; // seeded from it too; refreshed conditionally [UNRESOLVED] + /* +0x08 */ Vec3 m_v8; // the latest shot's direction; getFiringDir answers it + /* +0x14 */ Vec3 m_v20; // the direction at the last re-path (turns past dot 0.1) /* +0x20 */ int m_playerId; // the shotsFired int; the search/removal key /* +0x24 */ SquadMember* m_member; // getSquadMember(playerId, index), borrowed - /* +0x28 */ Vec3 m_v40; // shooter position at the latest shot [UNRESOLVED role] + /* +0x28 */ Vec3 m_v40; // shooter position at the latest shot /* +0x34 */ Vec3 m_position; // shooter position at the first shot; the 5 m anchor - /* +0x40 */ int m_i64; // 1, or the shooting bot's slot +0x80 answer [UNRESOLVED] + /* +0x40 */ int m_i64; // the shooting bot's firing target (Bot +0x80), else -1 }; SquadCoordinator(int side, int squadIndex); + ~SquadCoordinator(); // ELF 0x1A3270 (D1) void update(double time); // complete order void updateSquadPosition(); // complete @@ -52,7 +57,9 @@ class SquadCoordinator void updateIncomingMessages(); // radio-enqueue seam bool isSquadTakingFlag(); // complete void updateSquadManeuver(); // selected maneuver seams - int chooseSquadManeuver(); // integer payload, enum spelling unresolved + int chooseSquadManeuver(); // ELF 0x1A56A0: 0 none, 1 alternate fire, 2 static flank + void squadManeuverAlternateFire(); // ELF 0x1A4E90 + void squadManeuverStaticFlank(); // ELF 0x1A4060 void updateSquadPaths(); // complete invalidation loop int getSide(); int getMissionStatus(); // integer payload, enum spelling unresolved @@ -71,9 +78,79 @@ class SquadCoordinator SquadMember* getSquadMember(int index); SquadMember* getSquadMember(int playerId, int& index); bool hasMemberWithKit(KitType type); + // ELF 0x1A86D0: a member's pending request is (handle, action) (SquadMember::RequestAction). + bool isAnySquadMemberRespondingToRequest(unsigned int handle, int action); + // ELF 0x1A8730: how much `member` should answer the request (handle, action); see the .cpp. + float requestResponseModifier(SquadMember* member, unsigned int handle, int action); bool isSquadAssignedToAnyArea(); AIStrategicArea* getSquadStrategicAreaAssignment(); // borrowed void resetNeedOrderMessageTimer(double now); + void reset(); // ELF 0x1A3790 + void removeSquadMemberFire(SquadMember* member); // ELF 0x1A64B0 + bool isSquadCloseToNonOwnedTarget(); // ELF 0x1A6EC0 + bool squadHasMission(); // ELF 0x1A6B00: +0x78 == 2 + bool isSquadAvailable(); // ELF 0x1A7FA0: +0x78 == 0 + void removeAll(); // ELF 0x1A3930 + void destroySquadMember(int index); // ELF 0x1A83C0 + bool getValidSaPos(SquadMember* member, Vec3& position); // ELF 0x1A7BC0 + // [CHOSEN, not recovered] declaration placement; added by ai-w1-e-fire for + // BBPFireInfantery::createPlanInternal (coord/ai-requests.md 2026-11-01). ELF 0x1A5D90. + void shotsFired(int playerId, unsigned int target); + bool getValidSaPos(SquadMember* member, AIStrategicArea* area, Vec3& position); // ELF 0x1A7D30 + bool isValidPosition(SquadMember* member, const Vec3& position); // ELF 0x1A6B60 + // The requested-mission record (+60..+95), copied out by value by getMissionRequest. Its + // twin at +24..+59 is the accepted mission. [INFERRED] names. + struct MissionRequest + { + /* +0x00 */ AIStrategicArea* m_area; + /* +0x04 */ Vec3 m_position; + /* +0x10 */ int m_type; // BotSquad::OrderType, 4 = none + /* +0x14 */ IAIObject* m_object; + /* +0x18 */ double m_time; // requestMission: the update time + 10 s lives at +132 instead + /* +0x20 */ bool m_commander; // the order came from the commander + }; + MissionRequest getMissionRequest(); // ELF 0x1A3A40 + void requestRepair(const Vec3& position); // ELF 0x1A4950 + bool acceptMission(SquadMember* member); // ELF 0x1A7160 + bool isPosOnWater(SquadMember* member, Vec3& position); // ELF 0x1A4DC0 + bool getSquadMissionTargetPos(Vec3& position); // ELF 0x1A6B20 + bool getRandomValidPosition(SquadMember* member, Vec3& position, float radius); // ELF 0x1A79C0 + void requestMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object, bool commander); // ELF 0x1A6F30 + // ELF 0x1A69C0: the accepted order (+40 type, +44 object, +28 position within FLT_EPSILON per axis). + bool isSameMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object); + const Vec3& getSquadLeaderGotoPos() { return m_v200; } // ELF 0x1A7FE0: this + 0xC8 + int getSquadLeaderIndex() { return m_i96; } // ELF 0x1A5D70: +0x60 + bool isRepairRequested() { return m_b172; } // ELF 0x1A49F0: movzbl +0xAC + Vec3& getRepairRequestPos() { return m_v176; } // ELF 0x1A4A00: this + 0xB0 + void setRogerThatPositionMessage(bool roger) { m_b220 = roger; } // ELF 0x1A39F0: +0xDC + bool getRogerThatPositionMessage() { return m_b220; } // ELF 0x1A3A10: +0xDC + bool isSquadRequestedToArea(int areaIndex); // ELF 0x1A7F60 + void removeSquadMember(int index); // ELF 0x1A82E0 + void removeSquadMember(SquadMember* member); // ELF 0x1A84F0 + + // Dynamic flanking (no caller in libaidll.so), its line-of-sight and position helpers. + void squadManeuverDynamicFlank(); // ELF 0x1A4250 + bool canSeePos(const Vec3& from, const Vec3& to); // ELF 0x1A4A10 + void getFlankingCoords(std::vector& coords); // ELF 0x1A4B10 + bool haveFlankingCoords() { return m_b156; } // ELF 0x1A4B50 + bool getRandomValidFlankPos(SquadMember* member, float radius, Vec3& position); // ELF 0x1A4B60 + int getSquadManeuver() { return m_i148; } // ELF 0x1A5690 + // Fire records: shotsFired(int, const Vec3&) is SquadManager::shotsFired's per-squad half. + void shotsFired(int playerId, const Vec3& direction); // ELF 0x1A5F00 + bool anyFiring(); // ELF 0x1A6570 + bool isFiring(int playerId); // ELF 0x1A65B0 + SquadMember* getClosestFiringMember(SquadMember* member, float& distanceSquared); + Vec3 getFiringDir(SquadMember* member); // ELF 0x1A6820 + // Repair confirmation (BBPBridgeRepair). + void confirmRepairRequested() { m_b196 = true; } // ELF 0x1A49D0 + bool haveConfirmedRepairRequest() { return m_b196; } // ELF 0x1A49E0 + // The requested (not the accepted) mission is (type, position within FLT_EPSILON, object). + bool isSameRequest(BotSquad::OrderType type, const Vec3& position, IAIObject* object); // ELF 0x1A6A60 + SquadMember* getBotInSquad(); // ELF 0x1A7940: the first bot member, or null + std::list getListOfAreaNavPoints(); // ELF 0x1A7E70: a copy + // Appends every member's current vehicle (IAIPlayer +0x54) that is not null. + void getSquadIgnoreList(std::vector& ignore); // ELF 0x1A8580 + bool squadHasHumanPlayer(); // ELF 0x1A8680: any member that is not a bot // layout, on the ELF, read store by store out of the constructor // The [UNRESOLVED] gaps hold position and claim nothing; the constructor never writes them. @@ -84,19 +161,22 @@ class SquadCoordinator /* +24 */ AIStrategicArea* m_strategicAreaAssignment; // [INFERRED] name; ELF +0x18 / PE +0x28, borrowed; initially null /* +28 */ Vec3 m_v28; // zeroed [UNRESOLVED] /* +40 */ int m_i40; // = 4 [UNRESOLVED] - /* +44 */ int m_i44; // = 0 [UNRESOLVED] - /* +48 */ double m_d48; // = -20.0 a "never happened" sentinel, not a time - /* +56 */ char m_gap56[4]; // never written by the constructor - /* +60 */ int m_i60; // = 0 [UNRESOLVED] + /* +44 */ IAIObject* m_i44; // = 0; acceptMission: the request's object + /* +48 */ double m_d48; // = -20.0 a "never happened" sentinel; acceptMission: the game time + /* +56 */ bool m_b56; // never written by the constructor; acceptMission: the request's commander flag + // isSquadRequestedToArea (ELF 0x1A7F60) compares the area index at +0xF0 of this pointer. + /* +60 */ AIStrategicArea* m_requestedArea; // = 0 [CHOSEN] name /* +64 */ Vec3 m_v64; // zeroed [UNRESOLVED] /* +76 */ int m_i76; // = 4 [UNRESOLVED] - the twin of m_i40 - /* +80 */ int m_i80; // = 0 [UNRESOLVED] - /* +84 */ char m_gap84[12]; // never written by the constructor + /* +80 */ IAIObject* m_requestedObject; // = 0; requestMission's object [INFERRED] name + /* +84 */ double m_d84; // never written by the constructor; getMissionRequest copies it + /* +92 */ bool m_b92; // requestMission: the order came from the commander /* +96 */ int m_i96; // leader member index, initially -1 /* +100 */ SquadFormation* m_formation; // new SquadFormation(this) - /* +104 */ std::list m_list104; // header only; 4-byte element [UNRESOLVED] + /* +104 */ std::list m_list104; // the area nav points; getListOfAreaNavPoints copies it /* +108 */ Vec3 m_v108; // zeroed twice - once before the formation, once after - /* +120 */ int m_i120; // = 0 [UNRESOLVED] + // 0 = available (isSquadAvailable, ELF 0x1A7FA0), 2 = has a mission (squadHasMission). + /* +120 */ int m_i120; // = 0 /* +124 */ double m_d124; // = 0.0 [UNRESOLVED] /* +132 */ double m_d132; // = 0.0 [UNRESOLVED] /* +140 */ double m_d140; // = 0.0 [UNRESOLVED] @@ -111,9 +191,9 @@ class SquadCoordinator /* +176 */ Vec3 m_v176; // zeroed; getRepairRequestPos returns its address /* +188 */ double m_d188; // request deadline; the constructor never writes it /* +196 */ bool m_b196; // = false; haveConfirmedRepairRequest - /* +200 */ Vec3 m_v200; // zeroed twice, like m_v108 + /* +200 */ Vec3 m_v200; // zeroed twice, like m_v108; getSquadLeaderGotoPos /* +212 */ double m_needOrderMessageTimer; // = IBFTimer::getGameTime at construction - /* +220 */ bool m_b220; // = false [UNRESOLVED] + /* +220 */ bool m_b220; // = false; get/setRogerThatPositionMessage }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp index a146ef12f..a75eb158d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp @@ -1,16 +1,27 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadFormation operations. #include "SquadFormation.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1ACBB0, __tcf_0 0x1ACC10, _GLOBAL__I 0x1ACC40). +#include + +#include + #include #include "SquadCoordinator.h" #include "SquadMember.h" #include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" +#include "../Main/AIRandom.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::getCurrentVehicle #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getMaxNumberOfSquadMembers #include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" namespace dice { namespace hfe { @@ -243,21 +254,37 @@ void SquadFormation::selectFormation() m_formation = FormationLine; } -// Updates the formation direction from its anchor member. An empty anchor returns immediately. -// [FRONTIER] The occupied-anchor path requires the remaining information queries. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SquadFormation operation. +// ELF 0x1AB470: the anchor's (slot 0) vehicle speed (IAIPlayer +0x54 getCurrentVehicle, its +// information for side m_side + 1, Information +0x38 IPIMobile +0x1C getSpeed, copied) sets the +// forward vector when its squared length exceeds 0.25f (0x49CE84): vec3ToVec2XZ into m_forward, +// then the inlined Vec2 normalisation (left alone within 1.1920929e-07f (0x49CC7C) of unit length, +// zeroed below 1.4210855e-14f (0x49CCA4), else scaled by 1 / sqrt). An empty anchor returns. void SquadFormation::updateFormationForwardVector() { - Vec3 speed = {}; Slot* const anchor = m_slots[0]; if (!anchor->m_occupied) return; IAIPlayer* const player = m_coordinator->getSquadMember(anchor->m_memberIndex)->getPlayer(); IAIObject* const vehicle = player->getCurrentVehicle(); - (void)speed; - (void)vehicle; - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateFormationForwardVector (IAIObject information query)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + const Vec3 speed = info->getMobile()->getSpeed(); + if (!(speed.x * speed.x + speed.y * speed.y + speed.z * speed.z > 0.25f)) + return; + + vec3ToVec2XZ(speed, m_forward); + const float lengthSq = m_forward.x * m_forward.x + m_forward.y * m_forward.y; + if (std::fabs(lengthSq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSq) < 1.4210855e-14f) + { + m_forward.x = 0.0f; + m_forward.y = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSq); + m_forward.y = m_forward.y * inverse; + m_forward.x = m_forward.x * inverse; } // Adds a trail position when the anchor moves more than six metres from the last position. @@ -356,6 +383,125 @@ void SquadFormation::joinSquadLeader() updateMovementFlag(true); } +// ELF 0x1AC550 (1248 bytes). The world position of `memberIndex`'s slot: the squad position plus +// the slot offset rotated by the forward vector (normalised when not unit length; the angle is +// acos(y), negated for x > 0). Slot 0 (the leader's) is always taken; another slot only when the +// position is valid for its member and not on water (its trailing fallback is then released), +// otherwise its trailing position - claiming the first free one, and failing that the mission +// target (only for a mission without an object) or the slot-0 member's position. Without a squad +// position the leader's position is used. +bool SquadFormation::getSlotWorldPos(int memberIndex, Vec3& position) +{ + bool found = true; + Vec3 squad = {}; + m_coordinator->getSquadPosition(squad); + if ((0.0f - squad.x) * (0.0f - squad.x) + (0.0f - squad.y) * (0.0f - squad.y) + + (0.0f - squad.z) * (0.0f - squad.z) < 0.001f) + { + found = false; + if (m_coordinator->getSquadLeader()->getPosition(position)) + found = true; + return found; + } + float fx = m_forward.x; + float fy = m_forward.y; + for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + { + Slot* const slot = m_slots[i]; + if (slot->m_memberIndex != memberIndex) + continue; + const Vec3 offset = slot->m_offset; + const float lengthSq = fx * fx + fy * fy; + if (1.1920929e-07f <= std::fabs(lengthSq - 1.0f)) + { + if (1.4210855e-14f <= std::fabs(lengthSq)) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + fx = fx * inverse; + fy = inverse * fy; + } + else + { + fx = 0.0f; + fy = 0.0f; + } + } + float clamped = -1.0f; + if (-1.0f <= fy) + { + clamped = 1.0f; + if (fy <= 1.0f) + clamped = fy; + } + float angle = std::acos(clamped); + if (0.0f < fx) + angle = -angle; + const float s = std::sin(angle); + position.x = squad.x + (offset.x * fy - offset.z * s); + position.y = offset.y + squad.y; + position.z = squad.z + offset.x * s + offset.z * fy; + if (i == 0) + return true; + SquadMember* member = m_coordinator->getSquadMember(slot->m_memberIndex); + if (m_coordinator->isValidPosition(member, position) && !m_coordinator->isPosOnWater(member, position)) + { + slot->m_i20 = -1; + return true; + } + int trail = slot->m_i20; + if (trail == -1) + { + trail = getFirstFreeTrailingSlot(member); + if (trail == -1) + { + if (m_coordinator->squadHasMission()) + return m_coordinator->getSquadMissionTargetPos(position); + member = m_coordinator->getSquadMember(getSquadMemberIndexAtSlot(0)); + if (!member) + return false; + return member->getPosition(position); + } + slot->m_i20 = trail; + } + position = m_slotTargets[trail].second; + return true; + } + return found; +} + +// ELF 0x1ACA30 (320 bytes). The first trailing position that is set, unclaimed by any slot and +// valid for `member`; -1 when none. (The image also computes, and drops, the distance to it.) +int SquadFormation::getFirstFreeTrailingSlot(SquadMember* member) +{ + for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + { + const bool assigned = isTrailPosAssigned(static_cast(i)); + const bool valid = m_coordinator->isValidPosition(member, m_slotTargets[i].second); + if (m_slotTargets[i].first && !assigned && valid) + return static_cast(i); + } + return -1; +} + +// ELF 0x1ACB70: whether any slot falls back to trailing position `trailIndex`. +bool SquadFormation::isTrailPosAssigned(int trailIndex) +{ + for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + { + if (m_slots[i]->m_i20 == trailIndex) + return true; + } + return false; +} + +// ELF 0x1AB640: the formation leaves the squad leader (+84 set, +85 cleared). +void SquadFormation::leaveSquadLeader() +{ + m_b85 = false; + m_b84 = true; + updateMovementFlag(true); +} + // [INFERRED] void result. No slot-vector, leader or member null guards exist. void SquadFormation::updateFormation() { @@ -464,24 +610,67 @@ void SquadFormation::updateFormation() } } -// [INFERRED] void result. The first slot is deliberately excluded from this scan. +// ELF 0x1AAFC0. m_b36 (shouldSquadMoveOut) starts true; every occupied slot but the first is +// checked. A slot stops waiting (+0x18 = false, +0x1C = 0.0f) for the squad leader while the +// formation leaves it (m_b84), for a bot, for a member without a position, outside an estimated +// arrival of (150, 1500) (0x49CF9C / 0x49CF98), or when the member is no farther from the squad's +// goto position than the squad itself (both squared distances). Otherwise the squad waits +// (m_b36 = false): a waiting slot whose deadline (float)time has passed stops waiting (and the +// squad moves out unless another slot holds it); a slot without a deadline (< 0.01f, 0x49CB30) +// starts waiting until (float)time + 10 + 10 * random (0x49CC88; AIRandom inlined, 2^-32). void SquadFormation::updateWaitForSquadMembers(double time) { m_b36 = true; Vec3 memberPosition = {}; Vec3 squadPosition = {}; - (void)memberPosition; - (void)squadPosition; - (void)time; for (unsigned int index = 1; index < m_maxSquadMembers; ++index) { Slot* const slot = m_slots[index]; - if (slot->m_occupied) + if (!slot->m_occupied) + continue; + + SquadMember* const member = m_coordinator->getSquadMember(slot->m_memberIndex); + bool wait = false; + if (!(m_b84 && slot->m_memberIndex == m_coordinator->getSquadLeaderIndex()) && !member->isBot()) + { + const float arrival = m_coordinator->getSquadMember(slot->m_memberIndex)->getEstimatedArrival(); + const bool hasPosition = member->getPosition(memberPosition); + m_coordinator->getSquadPosition(squadPosition); + if (hasPosition && 1500.0f > arrival && arrival > 150.0f) + { + const Vec3& goal = m_coordinator->getSquadGotoPos(); + const float mx = memberPosition.x - goal.x; + const float my = memberPosition.y - goal.y; + const float mz = memberPosition.z - goal.z; + const float memberDistanceSq = mx * mx + my * my + mz * mz; + const Vec3& goal2 = m_coordinator->getSquadGotoPos(); + const float sx = squadPosition.x - goal2.x; + const float sy = squadPosition.y - goal2.y; + const float sz = squadPosition.z - goal2.z; + wait = memberDistanceSq > sx * sx + sy * sy + sz * sz; + } + } + + if (!wait) + { + slot->m_b24 = false; + slot->m_i28 = 0.0f; + continue; + } + + if (slot->m_b24) + { + if (static_cast(time) > slot->m_i28) + slot->m_b24 = false; + else + m_b36 = false; + } + else if (0.01f > slot->m_i28) { - // The real member lookup begins an occupied-slot timing policy with - // platform-specific time/RNG precision; no deadline or wait is invented. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateWaitForSquadMembers (occupied slot timing)"); + m_b36 = false; + slot->m_b24 = true; + const double draw = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10; + slot->m_i28 = static_cast(static_cast(static_cast(time)) + (draw * 10.0 + 10.0)); } } } @@ -686,19 +875,33 @@ void SquadFormation::updateClosestSlots() } } -// The slot/member read precedes -// the first getSlotWorldPos call; no argument or null guard is added. +// ELF 0x1AAE70 (336 bytes). The occupied slot (1..) whose member stands closest to the world +// position of `slotIndex`'s slot; -1 when that position is unknown or no member qualifies. int SquadFormation::getClosestSlotIndex(int slotIndex) { int best = -1; float minimum = 3.402823466e+38F; Vec3 target = {}; Vec3 position = {}; - const int memberIndex = m_slots[slotIndex]->m_memberIndex; - (void)best; (void)minimum; (void)target; (void)position; (void)memberIndex; - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // The bool getSlotWorldPos(int,Vec3&) movement/position chain remains unwritten. - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::getClosestSlotIndex (getSlotWorldPos)"); + if (!getSlotWorldPos(m_slots[slotIndex]->m_memberIndex, target)) + return best; + for (unsigned int i = 1; i < m_maxSquadMembers; ++i) + { + if (!m_slots[i]->m_occupied) + continue; + if (!m_coordinator->getSquadMember(m_slots[i]->m_memberIndex)->getPosition(position)) + continue; + const float dx = target.x - position.x; + const float dy = target.y - position.y; + const float dz = target.z - position.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + if (minimum > distanceSq) + { + minimum = distanceSq; + best = static_cast(i); + } + } + return best; } // Keep the real allocation and captured pointers; @@ -726,8 +929,7 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) : m_slots() , m_coordinator(coordinator) , m_formation(0) - , m_i48(0) - , m_f52(0.0f) + , m_forward() , m_i88(0) , m_d92(0.0) , m_slotTargets() @@ -768,8 +970,8 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) setFormation(); m_b36 = false; - m_i48 = 0; - m_f52 = 1.0f; + m_forward.x = 0.0f; + m_forward.y = 1.0f; m_v60.x = 0.0f; m_v60.y = 0.0f; m_v60.z = 0.0f; @@ -841,16 +1043,11 @@ void SquadFormation::updateMovementFlag(bool force) } } -// Preserve both guards. -// The positioned-squad arm calls getSlotWorldPos(getSquadMemberIndexAtSlot(0), m_v72). -// Its navigation/position dependencies are not recovered here. -// [FRONTIER, narrow] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// Preserve both guards (inlined in the image): the positioned squad's slot-zero world position. void SquadFormation::updateSlotZeroPos() { if (m_slots[0]->m_occupied && m_coordinator->squadHasPosition()) - { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateSlotZeroPos (getSlotWorldPos)"); - } + getSlotWorldPos(getSquadMemberIndexAtSlot(0), m_v72); } // Only the target-valid flags and slot indices are @@ -867,8 +1064,12 @@ void SquadFormation::resetTrailingPositions() } } -// Sets the formation speed from the slowest occupied slot, adjusted for crowding. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SquadFormation operation. +// ELF 0x1AB310: the formation speed is the slowest occupied slot's vehicle speed, scaled by 0.9 +// (0x49CFA0) when more than one slot is occupied, 5.0f (0x49CDAC) when none is. Per occupied slot: +// getSquadMember(slot +4)->getPlayer()->getCurrentVehicle() (IAIPlayer +0x54), its information +// handle for side m_side + 1 (IAIObject +0xB8), the informationManager lookup (inlined: generation +// check, null on mismatch) and Information +0x38 IPIMobile::getMaxSpeed; `flds 0x28; fucompi` keeps +// the smaller value. The image dereferences the looked-up information unchecked. void SquadFormation::updateFormationMaxSpeed() { int occupied = 0; @@ -882,8 +1083,12 @@ void SquadFormation::updateFormationMaxSpeed() if (slot->m_occupied) { ++occupied; - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::updateFormationMaxSpeed" - " - the per-member IPIMobile::getMaxSpeed lookup"); + IAIObject* const vehicle = + m_coordinator->getSquadMember(slot->m_memberIndex)->getPlayer()->getCurrentVehicle(); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + const float speed = info->getMobile()->getMaxSpeed(); + if (m_formationMaxSpeed > speed) + m_formationMaxSpeed = speed; } } @@ -942,8 +1147,7 @@ void SquadFormation::setFormation() } } -// Places slot zero at the origin and alternates subsequent formation slots on either side. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x1AB830: slot zero at the origin, later slots alternate +/- direction.x on either side. void SquadFormation::setLineFormation() { const float spacing = 1.0f; @@ -979,25 +1183,185 @@ void SquadFormation::setLineFormation() slot->m_offset.y = 0.0f; slot->m_offset.z = 0.0f; + // ELF 0x1AB920: an occupied slot is spread by both vehicles' radii, measured from its + // reference slot: offset = reference offset + offset * (3 * own radius + 3 * reference + // radius) (0x49CC90 = 3.0f; the image rounds the first product to float, keeps the x + // product's sum in x87 precision). if (slot->m_occupied) { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::setLineFormation" - " - the occupied-slot vehicle-radius spread"); + const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); + Slot* const reference = m_slots[slot->m_referenceSlot]; + const float spread = 3.0f * m_coordinator->getSquadMember(reference->m_memberIndex)->getVehicleRadius() + own; + slot->m_offset.x = slot->m_offset.x * spread + reference->m_offset.x; + slot->m_offset.y = slot->m_offset.y * spread + reference->m_offset.y; + slot->m_offset.z = slot->m_offset.z * spread + reference->m_offset.z; } } } -// [FRONTIER] Wedge and echelon layouts selected by changeFormation remain unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stops when their layout behavior is recovered. +// ELF 0x1ABA10: the line's alternating walk, but the offset also steps 1.0f * direction.z +// along z on both sides (+x / -x); the image's Vec3 temporary keeps the last (x, z) between +// slots (slot 0 is the origin). Occupied slots are spread as in setLineFormation. void SquadFormation::setWedgeFormation() { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::setWedgeFormation"); + const float spacing = 1.0f; + + bool positiveSide = true; + Vec3 offset = {}; + int referenceSlot = 0; + + for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + { + Slot* const slot = m_slots[i]; + + if (i) + { + if (positiveSide) + { + offset.x = spacing * m_direction.x; + offset.z = spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot; + positiveSide = false; + + if (i >= 3) + ++referenceSlot; + } + else + { + offset.x = -spacing * m_direction.x; + offset.z = spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot++; + positiveSide = true; + } + } + + slot->m_offset = offset; + + if (slot->m_occupied) + { + const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); + Slot* const reference = m_slots[slot->m_referenceSlot]; + const float spread = 3.0f * m_coordinator->getSquadMember(reference->m_memberIndex)->getVehicleRadius() + own; + slot->m_offset.x = slot->m_offset.x * spread + reference->m_offset.x; + slot->m_offset.y = slot->m_offset.y * spread + reference->m_offset.y; + slot->m_offset.z = slot->m_offset.z * spread + reference->m_offset.z; + } + } } +// ELF 0x1ABBF0: as the wedge, with z mirrored per side: (+x, -z) then (-x, +z). void SquadFormation::setEchelonFormation() { - BF2_AI_FRONTIER("dice::hfe::ai::SquadFormation::setEchelonFormation"); + const float spacing = 1.0f; + + bool positiveSide = true; + Vec3 offset = {}; + int referenceSlot = 0; + + for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + { + Slot* const slot = m_slots[i]; + + if (i) + { + if (positiveSide) + { + offset.x = spacing * m_direction.x; + offset.z = -spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot; + positiveSide = false; + + if (i >= 3) + ++referenceSlot; + } + else + { + offset.x = -spacing * m_direction.x; + offset.z = spacing * m_direction.z; + slot->m_referenceSlot = referenceSlot++; + positiveSide = true; + } + } + + slot->m_offset = offset; + + if (slot->m_occupied) + { + const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); + Slot* const reference = m_slots[slot->m_referenceSlot]; + const float spread = 3.0f * m_coordinator->getSquadMember(reference->m_memberIndex)->getVehicleRadius() + own; + slot->m_offset.x = slot->m_offset.x * spread + reference->m_offset.x; + slot->m_offset.y = slot->m_offset.y * spread + reference->m_offset.y; + slot->m_offset.z = slot->m_offset.z * spread + reference->m_offset.z; + } + } +} + +// ELF 0x1AC370: every slot is reset, then the first min(members, slots - 1) members that are +// allowed in formation take consecutive slots (occupied, their member index). When there are at +// least as many members as slots, the last slot is left free. +void SquadFormation::reassignSlots() +{ + for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + resetSlot(static_cast(i)); + unsigned int count = static_cast(m_coordinator->getNumberOfSquadMembers()); + if (count >= m_maxSquadMembers) + count = m_maxSquadMembers - 1; + unsigned int next = 0; + for (unsigned int i = 0; i < count; ++i) + { + SquadMember* const member = m_coordinator->getSquadMember(static_cast(i)); + if (!member->isAllowedInFormation()) + continue; + Slot* const slot = m_slots[next++]; + slot->m_occupied = true; + slot->m_memberIndex = member->getMemberIndex(); + } +} + +// ELF 0x1A9E10 (D1, 240 B; recovered on the client track, docs/macos-c-singleplayer.md). Clears +// the coordinator back-pointer, deletes the first m_maxSquadMembers slots (the bound is the +// member count fixed at construction, not the vector's size), then empties both vectors. +SquadFormation::~SquadFormation() +{ + m_coordinator = 0; + for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + delete m_slots[i]; + m_slots.erase(m_slots.begin(), m_slots.end()); + m_slotTargets.erase(m_slotTargets.begin(), m_slotTargets.end()); +} + +// ELF 0x1A9FB0. Shipped defect: the gap-checking loop has no checks left in this image. +void SquadFormation::debugCheckNoFormationSlotGaps() +{ + unsigned int last = m_maxSquadMembers - 1; + while (last && !m_slots[last]->m_occupied) + --last; + if (last) + for (unsigned int index = 0; index <= last; ++index) {} +} + +// ELF 0x1AA7E0. +bool SquadFormation::hasFormationMoved() { return m_b56; } + +// ELF 0x1ABDE0. +void SquadFormation::changeFormation(Formations formation) +{ + m_formation = formation; + setFormation(); +} + +// ELF 0x1AC440: both ray endpoints are raised by one metre; the input vectors are untouched. +bool SquadFormation::haveLineOfSightBetween(Vec3& from, Vec3& to) +{ + std::vector ignore; + m_coordinator->getSquadIgnoreList(ignore); + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + const Vec3 raisedFrom = {from.x, from.y + 1.0f, from.z}; + const Vec3 raisedTo = {to.x, to.y + 1.0f, to.z}; + bool hit; + return !environment->collideLineWithWorld(raisedFrom, raisedTo, ignore, false, 0.0f, true, hit); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h index bfe15fb34..a44309c19 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h @@ -15,6 +15,7 @@ namespace hfe { namespace ai { class SquadCoordinator; +class SquadMember; class SquadFormation { @@ -46,7 +47,7 @@ class SquadFormation /* +0 */ bool m_occupied; // the flag every deep branch in this class is guarded by /* +4 */ int m_memberIndex; // = -1; indexes the coordinator's squad-member vector /* +8 */ Vec3 m_offset; // the position the formation setters compute - /* +20 */ int m_i20; // = -1 [UNRESOLVED] + /* +20 */ int m_i20; // = -1; the trailing position (m_slotTargets) this slot falls back to /* +24 */ bool m_b24; // = false [UNRESOLVED] /* +28 */ float m_i28; // legacy inferred name; float proved by leaveFormation's x87 loads/stores /* +32 */ int m_referenceSlot; // the slot this one is measured from [INFERRED] @@ -63,28 +64,41 @@ class SquadFormation }; explicit SquadFormation(SquadCoordinator* coordinator); + ~SquadFormation(); // ELF 0x1A9E10 (D1) void update(double time); // complete scheduler void updateFormation(); // leader/anchor reassignment - void updateWaitForSquadMembers(double time); // occupied timing seam - void updateFormationForwardVector(); // occupied owner-query seam + void updateWaitForSquadMembers(double time); // ELF 0x1AAFC0 + void updateFormationForwardVector(); // ELF 0x1AB470 void updateTrailingPositions(); // complete void updateTrailingSlots(); // complete void selectFormation(); // / PE inlined at int getSquadMemberIndexAtSlot(int slotIndex); // no occupied test + // ELF 0x1AB6C0: the first slot is occupied (no empty-vector guard). + bool hasSquadMembers() { return m_slots[0]->m_occupied; } + bool getSlotWorldPos(int memberIndex, Vec3& position); // ELF 0x1AC550 + int getFirstFreeTrailingSlot(SquadMember* member); // ELF 0x1ACA30 + bool isTrailPosAssigned(int trailIndex); // ELF 0x1ACB70 bool shouldLeaveSquadLeader(); // returns m_b84 void joinSquadLeader(); // (inlines the movement update) + void leaveSquadLeader(); // ELF 0x1AB640 float getFormationMaxSpeed(); + bool shouldSquadMoveOut() { return m_b36; } // ELF 0x1AB6F0: +0x24 void updateFormationMaxSpeed(); void setFormation(); + void changeFormation(Formations formation); + bool hasFormationMoved(); + bool haveLineOfSightBetween(Vec3& from, Vec3& to); + void debugCheckNoFormationSlotGaps(); void setLineFormation(); - void setWedgeFormation(); // [FRONTIER] - void setEchelonFormation(); // [FRONTIER] + void setWedgeFormation(); // ELF 0x1ABA10 + void setEchelonFormation(); // ELF 0x1ABBF0 void joinFormation(int memberIndex); bool isInFormation(int memberIndex); // ignores occupied flag void leaveFormation(int memberIndex); void resetSlot(int slotIndex); // inlined + void reassignSlots(); // ELF 0x1AC370 void updateClosestSlots(); int getClosestSlotIndex(int slotIndex); // world-position seam void swapSlots(int first, int second); // three payload fields only @@ -101,13 +115,10 @@ class SquadFormation /* +36 */ bool m_b36; // = false; shouldSquadMoveOut returns it /* +40 */ float m_formationMaxSpeed; // FLT_MAX, then 5.0f - see the header note /* +44 */ int m_side; // = the coordinator's side - // ELF +0x30 / PE +0x34 is one `Vec2` - the formation's XZ forward vector, born (0, 1). The - // Vec2 type is attested by the forward-vector update passing this address to - // `vec3ToVec2XZ(const Vec3&, Vec2&)`; getSlotWorldPos is the only other reader. The split - // below predates that evidence and stays until the occupied projection lands, so that the - // retyping and its first writer arrive together. - /* +48 */ int m_i48; // = 0 Vec2 x (0.0f bits) - /* +52 */ float m_f52; // = 1.0f Vec2 y + // ELF +0x30 / PE +0x34: the formation's XZ forward vector, born (0, 1). Attested as one Vec2 + // by the forward-vector update passing its address to `vec3ToVec2XZ(const Vec3&, Vec2&)`; + // getSlotWorldPos (ELF 0x1AC550) reads it as two floats. + /* +48 */ Vec2 m_forward; /* +56 */ bool m_b56; // = false; hasFormationMoved returns it /* +60 */ Vec3 m_v60; // zeroed; anchor position at the last movement stamp /* +72 */ Vec3 m_v72; // zeroed; slot-zero world position (updateSlotZeroPos) diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp index b7fac1e72..63233d26e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp @@ -2,11 +2,23 @@ // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadManager operations. #include "SquadManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B0FE0, __tcf_0 0x1B1040, _GLOBAL__I 0x1B1070). +#include +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] #include "SquadCoordinator.h" // the constructor builds two per squad #include "BotMain.h" #include "BotSquad.h" +#include "SquadMember.h" #include "../Main/AIDllFrontier.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" #include "../Main/IBotManager.h" #include "../Main/AIMain.h" #include "../Main/CommonSingletonServer.h" @@ -19,6 +31,16 @@ #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../../Core/SettingsRepostitory.h" #include "../../../../Core/StringUtil.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/Information.h" +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include namespace dice { namespace hfe { @@ -144,6 +166,22 @@ void SquadManager::setPlayerOnValidPosition(IAIPlayer* player, bool valid, doubl m_playerValidPositions.insert(std::make_pair(id, time)); } +// ELF 0x1AE5B0 (listing). Whether a human (not getIsAIPlayer, +0x88) of `side` (getSide, +0x6C) +// is among the factory's players (IAIPlayerFactory +0x2C, copied); null entries are skipped. +// The manager itself is not read. +bool SquadManager::haveHumanPlayerOnOwnSide(int side) +{ + const std::vector players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (std::vector::const_iterator i = players.begin(); i != players.end(); ++i) + { + IAIPlayer* const player = *i; + if (player && !player->getIsAIPlayer() && player->getSide() == side) + return true; + } + return false; +} + // Copy the borrowed factory // vector before callbacks. Preserve the repeated AI-player query even when the first one // returned true. A live, non-downed human with a vehicle next needs IAIObject::getInformation @@ -157,17 +195,27 @@ void SquadManager::updateHumanPlayers(double time) IAIPlayer* player = *i; if (!player) continue; - if (!player->getIsAIPlayer() && player->getIsAlive() && !player->isManDown()) + // ELF 0x1AE1D0: a human in an object with mobile information is on a valid position + // unless pathfinding rejects it (IAIPathfinding +0x2C, vehicle number, equipment type). + bool valid = true; + IAIObject* vehicle = 0; + if (!player->getIsAIPlayer() && player->getIsAlive() && !player->isManDown() + && (vehicle = player->getCurrentVehicle()) != 0) { - if (player->getCurrentVehicle()) + Information* const info = informationManager->getInformation(vehicle->getInformation(player->getSide())); + if (info) { - player->getSide(); - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadManager::updateHumanPlayers (IAIObject::getInformation)"); + const Vec3 position = info->getPosition(); + if (IPIMobile* const mobile = info->getMobile()) + { + const int type = info->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->isValidPosition(mobile->getVehicleNumber(), type, position, false)) + valid = false; + } } } if (!player->getIsAIPlayer()) - setPlayerOnValidPosition(player, true, time); + setPlayerOnValidPosition(player, valid, time); } for (std::map::iterator i = m_playerValidPositions.begin(); i != m_playerValidPositions.end(); ) @@ -276,11 +324,25 @@ void SquadManager::addSquadMember(int playerId, int side) best = selected->getNumberOfSquadMembers(); if (best >= splitAt) { - // The old member is fetched before removal. Its removal/formation reindexing - // engine exit/rejoin and subsequent deletion remain unrecovered as a chain. - selected->getSquadMember(best - 1); - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadManager::addSquadMember (SquadCoordinator::removeSquadMember)"); + // ELF 0x1AF21A: the last member moves to the next (empty) squad: it is unlinked, + // the old squad re-elects its leader, the engine squad is left (IBFSquad +0x10 + // exitSquad), the member's player joins the next coordinator - a bot through its + // BotSquad, a human through IBFSquad +0x0C joinSquad - and the record is deleted. + // The new player then joins that next squad too. + SquadMember* const moved = selected->getSquadMember(best - 1); + selected->removeSquadMember(best - 1); + selected->updateSquadLeader(); + IBFSquad* const squads = static_cast(CommonSingletonServer::m_iBFSquad); + squads->exitSquad(selected->getSquadId() + 1, moved->getPlayer()); + selected = coordinators[selected->getSquadId() + 1]; + selected->addSquadMember(moved->getPlayer()); + if (moved->isBot()) + IBotManager::instance->getBotFromPlayerId(moved->getPlayerId())->getBotSquad() + ->joinSquad(selected->getSquadId() + 1); + else + squads->joinSquad(selected->getSquadId() + 1, moved->getPlayer()); + selected->updateSquadLeader(); + delete moved; } } @@ -337,6 +399,90 @@ SquadCoordinator* SquadManager::getSquadFromPlayer(int playerId, int side) return 0; } +// ELF 0x1AF6A0: the player's squad on side 1, else on side 2; returns the side searched last. +int SquadManager::getSquadFromPlayer(int playerId, SquadCoordinator*& squad) +{ + squad = getSquadFromPlayer(playerId, 1); + if (squad) + return 1; + squad = getSquadFromPlayer(playerId, 2); + return 2; +} + +// ELF 0x1AF720: one-based squad id and side, no range checks. +SquadCoordinator* SquadManager::getSquadFromId(int squadId, int side) +{ + return m_coordinators[side - 1][squadId - 1]; +} + +// ELF 0x1AF860 (256 bytes). An order received by the player's squad: the order position comes +// from the engine (IBFSquad +0x50 getCommanderOrder for a commander order, +0x54 getSquadOrder +// for the squad leader's), then a repair order (type 3) becomes a repair request and anything +// else a mission request without a target object. +void SquadManager::setSquadReceivedOrder(BotSquad::OrderType type, int playerId, bool commander) +{ + SquadCoordinator* squad; + const int side = getSquadFromPlayer(playerId, squad); + if (!squad) + return; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + if (commander) + engine->getCommanderOrder(side, squad->getSquadId() + 1, position, 0); + else + engine->getSquadOrder(side, squad->getSquadId() + 1, position, 0); + if (type == 3) + squad->requestRepair(position); + else + squad->requestMission(type, position, 0, commander); +} + +// ELF 0x1AF960 (320 bytes). Without a player commander, a squad with a mission state whose request +// came from the (AI) commander gets that order again: attack (type 0) or defend, through the side's +// CommanderInterface, and a commander message (0 attack / 1 defend) due in 2 s. +void SquadManager::repeatOrder(int side, int squadId) +{ + ISAI* const sai = IAIMain::m_instance->getSAI(side); + SquadCoordinator* const squad = getSquadFromId(squadId, side); + if (!squad || sai->isPlayerCommander()) + return; + if (squad->getMissionStatus() == 0) + return; + const SquadCoordinator::MissionRequest request = squad->getMissionRequest(); + if (!request.m_commander) + return; + if (request.m_type == 0) + { + sai->getCommanderInterface()->giveAttackOrder(request.m_position, squad); + enqueueCommanderMessage(side - 1, squadId - 1, static_cast(0), 2.0f); + } + else + { + sai->getCommanderInterface()->giveDefendOrder(request.m_position, squad); + enqueueCommanderMessage(side - 1, squadId - 1, static_cast(1), 2.0f); + } +} + +// ELF 0x1AE970 (276 bytes). A message for the same (side index, squad index) already queued +// keeps its place; otherwise a new one (zeroed, 20 bytes) goes to the back. +void SquadManager::enqueueCommanderMessage(int sideIndex, int squadIndex, CommanderMessageType type, double delay) +{ + for (std::list::iterator it = m_commanderMessages.begin(); it != m_commanderMessages.end(); ++it) + { + if ((*it)->m_sideIndex == sideIndex && (*it)->m_squadIndex == squadIndex) + return; + } + CommanderMessage* const message = new CommanderMessage(); + message->m_dueTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime() + delay; + message->m_type = type; + message->m_sideIndex = sideIndex; + message->m_squadIndex = squadIndex; + m_commanderMessages.push_back(message); +} + // Squad zero is ignored. An existing member anywhere on the // side also returns immediately: a bot's engine join notification must not insert it twice. // On a miss, retain the unchecked coordinator/player lookups, add, then update the leader. @@ -354,6 +500,538 @@ void SquadManager::playerJoinsSquad(int playerId, int squadId, int side) coordinator->updateSquadLeader(); } +// ELF 0x1AF800: every coordinator of the one-based side drops its strategic-area assignment. +void SquadManager::unAssignSquads(int side) +{ + std::vector& coordinators = m_coordinators[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + coordinators[i]->unAssignSquad(); +} + +// ELF 0x1AE100: both sides unassigned, queued commander messages and player positions cleared, +// the artillery flags of both side blocks and the update cursors reset, then every coordinator +// of side 0 and then side 1 resets. +// ELF 0x1ADD70 (D1, 467 B; recovered on the client track, docs/macos-c-singleplayer.md). Each +// side's coordinators are deleted (nonvirtual SquadCoordinator D1 + operator delete) and the +// vector emptied, then the commander messages and valid positions are cleared and the singleton +// pointer zeroed unconditionally. The members go afterwards in reverse declaration order. +SquadManager::~SquadManager() +{ + for (int side = 0; side < 2; ++side) + { + for (unsigned int i = 0; i < m_coordinators[side].size(); ++i) + delete m_coordinators[side][i]; + m_coordinators[side].erase(m_coordinators[side].begin(), m_coordinators[side].end()); + } + clearCommanderMessages(); + clearPlayerValidPositions(); + m_instance = 0; +} + +void SquadManager::reset() +{ + unAssignSquads(1); + unAssignSquads(2); + clearCommanderMessages(); + clearPlayerValidPositions(); + m_sideBlock0.m_b0 = false; + m_sideBlock1.m_b0 = false; + m_squadCursor = 0; + m_sideCursor = 1; + for (int side = 0; side < 2; ++side) + for (unsigned int i = 0; i < m_coordinators[side].size(); ++i) + m_coordinators[side][i]->reset(); +} + +// ELF 0x1B0180: squad 0 (no squad) is ignored. Otherwise the player's member record is unlinked +// from coordinator [side - 1][squadId - 1], which re-elects its leader. The record itself is not +// deleted on this path, as shipped. +void SquadManager::playerRemovedFromSquad(int playerId, int squadId, int side) +{ + if (!squadId) + return; + SquadMember* const member = getSquadMember(playerId, side); + if (!member) + return; + SquadCoordinator* const coordinator = m_coordinators[side - 1][squadId - 1]; + coordinator->removeSquadMember(member); + coordinator->updateSquadLeader(); +} + +// ELF 0x1AF750: the side's squads assigned to the area are released, except those already close to +// their non-owned target; answers how many were released. +int SquadManager::unAssignSquads(int areaIndex, int side) +{ + int released = 0; + std::vector& coordinators = m_coordinators[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + if (coordinators[i]->isSquadCloseToNonOwnedTarget()) + continue; + if (coordinators[i]->isSquadAssignedToArea(areaIndex)) + { + coordinators[i]->unAssignSquad(); + ++released; + } + } + return released; +} + +// ELF 0x1B0610 (466 bytes). An enemy human whose valid position (m_playerValidPositions) is +// more than 60 s old and who sits in an object with information for its side is camping; its +// position's x and z are returned. +bool SquadManager::haveCampingHumans(int side, Vec2& position) +{ + const int enemy = side == 1 ? 2 : 1; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + IAIPlayerFactory* const factory = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + for (std::map::iterator it = m_playerValidPositions.begin(); + it != m_playerValidPositions.end(); ++it) + { + IAIPlayer* const player = factory->getPlayerFromId(it->first); + if (!player || player->getSide() != enemy || !(it->second + 60.0 < now)) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const info = informationManager->getInformation(vehicle->getInformation(player->getSide())); + if (info) + { + const Vec3& p = info->getPosition(); + position.x = p.x; + position.y = p.z; + return true; + } + } + return false; +} + +// ELF 0x1AFD30. The nearest available squad with members whose strategic strength (type +// !attack) is positive; a squad requested to this very area counts only while its leader is a +// bot. strength receives twice the chosen squad's strength (0 if none). +SquadCoordinator* SquadManager::getClosestAvailableSquad(AIStrategicArea* area, const Vec3& position, + int side, bool attack, int& strength) +{ + SquadCoordinator* closest = 0; + float best = 3.4028235e+38f; + Vec3 squadPosition = { 0.0f, 0.0f, 0.0f }; + std::vector& coordinators = m_coordinators[side - 1]; + strength = 0; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + if (!squad->isSquadAvailable() || squad->getNumberOfSquadMembers() <= 0) + continue; + if (squad->isSquadRequestedToArea(area->getIndex()) && !squad->getSquadLeader()->isBot()) + continue; + const int value = squad->getStrategicStrength(static_cast(!attack)) * 2; + if (value <= 0) + continue; + squad->getSquadPosition(squadPosition); + const float dx = position.x - squadPosition.x; + const float dy = position.y - squadPosition.y; + const float dz = position.z - squadPosition.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + { + strength = value; + closest = squad; + best = distance; + } + } + return closest; +} + +// ELF 0x1AFAA0: distance to the nearest squad leader with a valid position (FLT_MAX's root +// when there is none). +float SquadManager::getDistanceToClosestSquad(const Vec3& position, int side) +{ + float best = 3.4028235e+38f; + Vec3 leader = { 0.0f, 0.0f, 0.0f }; + const std::vector& coordinators = m_coordinators[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + if (squad->getNumberOfSquadMembers() <= 0) + continue; + if (squad->getSquadLeader()->getPosition(leader)) + { + const float dx = position.x - leader.x; + const float dy = position.y - leader.y; + const float dz = position.z - leader.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + best = distance; + } + } + return std::sqrt(best); +} + +// ELF 0x1AEE60: the float at +0x98 (+152, m_float152, 40.0f at construction). +float SquadManager::getArtillerySafeDistance() +{ + return m_float152; +} + +// ELF 0x1B07F0 (427 bytes): is any player of the side within radius in an object that is a +// soldier (type flag 0x20) or not vehicle-flagged (0x10)? +bool SquadManager::friendliesCloseTo(Vec3 position, float radius, int side) +{ + std::vector ids; + bool found = false; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment)->getWorldPlayerIds(ids); + IAIPlayerFactory* const factory = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + for (std::vector::iterator it = ids.begin(); it != ids.end(); ++it) + { + IAIPlayer* const player = factory->getPlayerFromId(*it); + if (!player || player->getSide() != side) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const info = informationManager->getInformation(vehicle->getInformation(side)); + if (!info) + continue; + const unsigned int flags = info->getObjectTypeFlags(); + if ((flags & 0x20) == 0 && (flags & 0x10) != 0) + continue; + const Vec3& p = info->getPosition(); + const float dx = p.x - position.x; + const float dy = p.y - position.y; + const float dz = p.z - position.z; + if (dx * dx + dy * dy + dz * dz < radius * radius) + { + found = true; + break; + } + } + return found; +} + +// ELF 0x1B09A0 (339 bytes). Marks the side's artillery warning with the time and impact point +// and a random delay in [d/2, d) for d = m_double156; both sides' flee positions become invalid. +// The sum is x87 extended in the ELF (fildll, fmuls, fmul, faddp); bf2x87::Real keeps that. +void SquadManager::incomingArtillery(Vec3 position, int side) +{ + SideBlock& block = side - 1 == 0 ? m_sideBlock0 : m_sideBlock1; + SideBlock& other = side - 1 == 0 ? m_sideBlock1 : m_sideBlock0; + const double half = 0.5 * m_double156; + block.m_b0 = true; + block.m_artilleryStartTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + block.m_artilleryPosition = position; + const unsigned int r = AIRandom::m_instance->next(); + block.m_validFlee0 = false; + block.m_validFlee1 = false; + const bf2x87::Real halfX = bf2x87::Real(half); + const bf2x87::Real delay = halfX + (bf2x87::Real(static_cast(r)) * bf2x87::Real(2.3283064e-10f)) * halfX; + block.m_artilleryDelay = static_cast(delay); + other.m_validFlee0 = false; + other.m_validFlee1 = false; +} + +// ELF 0x1B0B00 (574 bytes). Inside the safe distance (+152) of the side's own pending strike, +// or of the other side's strike once its delay has passed: sinceStart = now - start and +// artillerySide = the striking side. Otherwise -1.0 and 0. +bool SquadManager::isInArtilleryDangerZone(Vec3 position, int side, double& sinceStart, int& artillerySide) +{ + SideBlock& own = side - 1 == 0 ? m_sideBlock0 : m_sideBlock1; + SideBlock& other = side - 1 == 0 ? m_sideBlock1 : m_sideBlock0; + const int otherSide = side - 1 == 0 ? 2 : 1; + bool danger = false; + sinceStart = -1.0; + artillerySide = 0; + const bf2x87::Real now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float safe = m_float152 * m_float152; + const auto distanceSq = [&position](const SideBlock& block) { + const float dx = block.m_artilleryPosition.x - position.x; + const float dy = block.m_artilleryPosition.y - position.y; + const float dz = block.m_artilleryPosition.z - position.z; + return dx * dx + dy * dy + dz * dz; + }; + if (own.m_b0 && distanceSq(own) < safe) + { + danger = true; + sinceStart = static_cast(now - bf2x87::Real(own.m_artilleryStartTime)); + artillerySide = side; + } + else if (other.m_b0 && distanceSq(other) < safe + && bf2x87::Real(other.m_artilleryStartTime) + bf2x87::Real(other.m_artilleryDelay) < now) + { + danger = true; + sinceStart = static_cast(now - bf2x87::Real(other.m_artilleryStartTime)); + artillerySide = otherSide; + } + return danger; +} + +// ELF 0x1AFF20: the first coordinator of the side that holds the player drops it, tells the +// engine squad (IBFSquad::exitSquad, squad id + 1) and re-elects its leader. +void SquadManager::removeSquadMember(int playerId, int side) +{ + std::vector& coordinators = m_coordinators[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + int index = 0; + SquadMember* const member = squad->getSquadMember(playerId, index); + if (!member) + continue; + squad->removeSquadMember(index); + IAIPlayer* const player = member->getPlayer(); + static_cast(CommonSingletonServer::m_iBFSquad)->exitSquad(squad->getSquadId() + 1, player); + squad->updateSquadLeader(); + return; + } +} + +// ELF 0x1AE000: both sides' squads are emptied, then every active bot is added again. +void SquadManager::removeAllSquads() +{ + for (unsigned int i = 0; i < m_coordinators[0].size(); ++i) + m_coordinators[0][i]->removeAll(); + for (unsigned int i = 0; i < m_coordinators[1].size(); ++i) + m_coordinators[1][i]->removeAll(); + IBotManager* const manager = IBotManager::instance; + if (!manager) + return; + const unsigned int count = manager->getBotCount(); + for (unsigned int i = 0; i < count; ++i) + { + Bot* const bot = manager->getBot(i); + if (!bot->isDeactivated()) + { + const int side = bot->getSide(); + addSquadMember(bot->getPlayerId(), side); + } + } +} + +// ELF 0x1B0010: removeSquadMember's search, but the coordinator destroys the member record. +void SquadManager::destroySquadMember(int playerId, int side) +{ + std::vector& coordinators = m_coordinators[side - 1]; + for (unsigned int i = 0; i < coordinators.size(); ++i) + { + SquadCoordinator* const squad = coordinators[i]; + int index = 0; + SquadMember* const member = squad->getSquadMember(playerId, index); + if (!member) + continue; + IAIPlayer* const player = member->getPlayer(); + squad->destroySquadMember(index); + static_cast(CommonSingletonServer::m_iBFSquad)->exitSquad(squad->getSquadId() + 1, player); + squad->updateSquadLeader(); + return; + } +} + +// ELF 0x1AF600: the object's occupying player selects the squad. +SquadCoordinator* SquadManager::getSquadFromPlayer(unsigned int handle, int side) +{ + Information* const information = informationManager->getInformation(handle); + if (!information) + return 0; + IPIUnit* const unit = information->getUnit(); + if (!unit) + return 0; + const int playerId = unit->getOccupyingPlayerId(side); + return playerId == -1 ? 0 : getSquadFromPlayer(playerId, side); +} + +// ELF 0x1B0210: both lookups run even when the first player has no squad. +bool SquadManager::isInSameSquad(int firstPlayer, int secondPlayer, int side) +{ + SquadCoordinator* const first = getSquadFromPlayer(firstPlayer, side); + SquadCoordinator* const second = getSquadFromPlayer(secondPlayer, side); + if (!first || !second) + return false; + const int firstId = first->getSquadId(); + return firstId == second->getSquadId(); +} + +// ELF 0x1B02A0. +bool SquadManager::isInAnySquad(int playerId, int side) +{ + return getSquadFromPlayer(playerId, side) != 0; +} + +// ELF 0x1B0510: only a type-zero active weapon publishes a firing direction. +void SquadManager::shotsFired(int playerId, int side, const Vec3& direction) +{ + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + IAIObject* const vehicle = player->getCurrentVehicle(); + InformationManager* const manager = informationManager; + Information* const information = manager->getInformation(vehicle->getInformation(side)); + // Shipped defect: information is dereferenced without checking the pool lookup. + IPIArmament* const armament = information->getArmament(); + if (!armament) + return; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + if (weapon && weapon->getWeaponType() == 0) + { + SquadCoordinator* const squad = getSquadFromPlayer(playerId, side); + if (squad) + squad->shotsFired(playerId, direction); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B04B0, added by ai-w1-e-fire (createPlanInternal 0x2672BF reports every new fire plan): +// forwards to the shooter's squad, when he has one. +void SquadManager::shotsFired(int playerId, int side, unsigned int target) +{ + if (SquadCoordinator* const squad = getSquadFromPlayer(playerId, side)) + squad->shotsFired(playerId, target); +} + +// ELF 0x1AFBC0: over both sides' squads (stride 12), the positioned leader of a non-empty squad +// with the smallest squared distance (strictly smaller than FLT_MAX, then than the best so far). +SquadMember* SquadManager::getSquadLeaderClosestTo(const Vec3& position) +{ + float best = 3.4028235e+38f; + SquadMember* closest = 0; + Vec3 leaderPosition = {}; + for (unsigned int side = 0; side < 2; ++side) + { + std::vector& squads = m_coordinators[side]; + for (unsigned int i = 0; i < squads.size(); ++i) + { + if (squads[i]->getNumberOfSquadMembers() <= 0) + continue; + SquadMember* const leader = squads[i]->getSquadLeader(); + if (!leader->getPosition(leaderPosition)) + continue; + const float dx = position.x - leaderPosition.x; + const float dy = position.y - leaderPosition.y; + const float dz = position.z - leaderPosition.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + if (distanceSq < best) + { + best = distanceSq; + closest = leader; + } + } + } + return closest; +} + +// ELF 0x1AF480. +SquadMember* SquadManager::getSquadMember(unsigned int handle, int side) +{ + Information* const info = informationManager->getInformation(handle); + if (info && info->getUnit()) + { + const int playerId = info->getUnit()->getOccupyingPlayerId(side); + if (playerId != -1) + return getSquadMember(playerId, side); + } + return 0; +} + +// ELF 0x1B0440. +bool SquadManager::isAnySquadMemberRespondingToRequest(unsigned int handle, int action, int side) +{ + const std::vector& squads = m_coordinators[side - 1]; + for (unsigned int i = 0; i < squads.size(); ++i) + { + if (squads[i]->isAnySquadMemberRespondingToRequest(handle, action)) + return true; + } + return false; +} + +// ELF 0x1B0390. +float SquadManager::requestResponseModifier(SquadMember* member, unsigned int handle, int action, int side) +{ + float modifier = 0.0f; + SquadCoordinator* const squad = getSquadFromPlayer(member->getPlayerId(), side); + if (squad) + { + if (member->isSameRequest(handle, action)) + modifier = 1.0f; + else + modifier = squad->requestResponseModifier(member, handle, action); + } + return modifier; +} + +// ELF 0x1B0D40. +Vec3 SquadManager::getArtilleryTargetPos(int side) +{ + SideBlock* const blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + return blocks[side - 1]->m_artilleryPosition; +} + +namespace { + +// The member's current vehicle's information for its side, with a unit; null otherwise. +Information* fleeInformation(SquadMember* member, int side) +{ + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + if (!vehicle) + return 0; + Information* const info = informationManager->getInformation(vehicle->getInformation(side)); + if (!info || !info->getUnit()) + return 0; + return info; +} + +} // namespace + +// ELF 0x1B0D80. +bool SquadManager::haveValidArtilleryFleePos(SquadMember* member, Vec3& position) +{ + const int side = member->getSide(); + SideBlock* const blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + SideBlock* const block = blocks[side - 1]; + Information* const info = fleeInformation(member, side); + if (!info) + return false; + if ((info->getObjectTypeFlags() & 0x00200000u) == 0) + { + if (!block->m_validFlee1) + return false; + position = block->m_fleePos1; + } + else + { + if (!block->m_validFlee0) + return false; + position = block->m_fleePos0; + } + return true; +} + +// ELF 0x1B0EC0. +void SquadManager::setValidArtilleryFleePos(SquadMember* member, Vec3 position) +{ + const int side = member->getSide(); + SideBlock* const blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + SideBlock* const block = blocks[side - 1]; + Information* const info = fleeInformation(member, side); + if (!info) + return; + if ((info->getObjectTypeFlags() & 0x00200000u) == 0) + { + block->m_validFlee1 = true; + block->m_fleePos1 = position; + } + else + { + block->m_validFlee0 = true; + block->m_fleePos0 = position; + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h index ebb791d87..41993e001 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h @@ -8,12 +8,14 @@ #include #include #include "../../../../Math/Vec3.h" +#include "BotSquad.h" // BotSquad::OrderType namespace dice { namespace hfe { namespace ai { class SquadCoordinator; // (`operator new(0xE0)`); held only by pointer here +class AIStrategicArea; class SquadMember; class IAIPlayer; // Attested enum name in both squad-strength ELF manglings. Enumerator names are not recovered. @@ -23,6 +25,7 @@ class SquadManager { public: SquadManager(); + ~SquadManager(); // ELF 0x1ADD70 (D1) // Direct AIMain scheduling call, double by value; neither image materializes a result. void update(double time); @@ -42,18 +45,62 @@ class SquadManager void newSquadLeader(int side, int squadId); void playerJoinsSquad(int playerId, int squadId, int side); SquadMember* getSquadMember(int playerId, int side); + // ELF 0x1AF480: the member occupying the object (IPIUnit::getOccupyingPlayerId(side)), or null. + SquadMember* getSquadMember(unsigned int handle, int side); + // ELF 0x1B0440: any squad of the side has a member with this pending request. + bool isAnySquadMemberRespondingToRequest(unsigned int handle, int action, int side); + // ELF 0x1B0390: 0 without a squad, 1 when `member` already has this request, else the squad's + // SquadCoordinator::requestResponseModifier. `action` is SquadMember::RequestAction. + float requestResponseModifier(SquadMember* member, unsigned int handle, int action, int side); + // [CHOSEN, not recovered] declaration placement; added by ai-w1-e-fire for + // BBPFireInfantery::createPlanInternal (coord/ai-requests.md 2026-11-01). ELF 0x1B04B0. + void shotsFired(int playerId, int side, unsigned int target); + void shotsFired(int playerId, int side, const Vec3& direction); SquadCoordinator* getSquadFromPlayer(int playerId, int side); + SquadCoordinator* getSquadFromPlayer(unsigned int handle, int side); + bool isInSameSquad(int firstPlayer, int secondPlayer, int side); + bool isInAnySquad(int playerId, int side); + int getSquadFromPlayer(int playerId, SquadCoordinator*& squad); // ELF 0x1AF6A0: the side found + SquadMember* getSquadLeaderClosestTo(const Vec3& position); // ELF 0x1AFBC0 + SquadCoordinator* getSquadFromId(int squadId, int side); // ELF 0x1AF720, unchecked + void setSquadReceivedOrder(BotSquad::OrderType type, int playerId, bool commander); // ELF 0x1AF860 + void repeatOrder(int side, int squadId); // ELF 0x1AF960 int getSquadStrengths(int side, int areaIndex, StrategicStrengthType type); // Clears messages and position records by erasing each container node individually. void clearCommanderMessages(); void clearPlayerValidPositions(); + void unAssignSquads(int side); // ELF 0x1AF800 + int unAssignSquads(int areaIndex, int side); // ELF 0x1AF750 + // [FRONTIER] declared by ai-strategic for SAI::checkCommanderUseArtillery; owner ai-bot + // (coord/ai-requests.md). getArtillerySafeDistance is recovered (ELF 0x1AEE60: +0x98). + bool haveCampingHumans(int side, Vec2& position); // ELF 0x1B0610 + bool haveHumanPlayerOnOwnSide(int side); // ELF 0x1AE5B0 + float getArtillerySafeDistance(); // ELF 0x1AEE60 + float getDistanceToClosestSquad(const Vec3& position, int side); // ELF symbol; requested from ai-bot + SquadCoordinator* getClosestAvailableSquad(AIStrategicArea* area, const Vec3& position, int side, + bool attack, int& strength); // ELF symbol; requested from ai-bot + bool friendliesCloseTo(Vec3 position, float radius, int side); // ELF 0x1B07F0 + void removeAllSquads(); // ELF 0x1AE000 + void destroySquadMember(int playerId, int side); // ELF 0x1B0010 + void removeSquadMember(int playerId, int side); // ELF 0x1AFF20 + bool isInArtilleryDangerZone(Vec3 position, int side, double& sinceStart, int& artillerySide); // ELF 0x1B0B00 + Vec3 getArtilleryTargetPos(int side); // ELF 0x1B0D40 + // ELF 0x1B0D80 / 0x1B0EC0: the side's remembered flee position, one for soldiers, one for + // vehicles (the member's current vehicle's information flag 0x200000). + bool haveValidArtilleryFleePos(SquadMember* member, Vec3& position); + void setValidArtilleryFleePos(SquadMember* member, Vec3 position); + void incomingArtillery(Vec3 position, int side); // ELF 0x1B09A0 + void reset(); // ELF 0x1AE100 + void playerRemovedFromSquad(int playerId, int squadId, int side); // ELF 0x1B0180 static SquadManager* m_instance; // Queued commander message. Field and enumerator names are inferred. // Native dueTime offset/record size: ELF +0xC/20 bytes, PE +0x10/24 bytes. enum CommanderMessageType : int; + // ELF 0x1AE970: queued once per (side index, squad index), due after `delay` s of game time. + void enqueueCommanderMessage(int sideIndex, int squadIndex, CommanderMessageType type, double delay); class CommanderMessage { public: diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp index 7e60395ce..975e072f0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp @@ -2,6 +2,10 @@ // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadMember operations. #include "SquadMember.h" +#include +#include +// static init: ELF 0x1B56E0, 0x1B5740, 0x1B5770: iostream Init only. +#include "../AIStrategicEntity/AIStrategicArea.h" #include "../Main/AIDllFrontier.h" #include "../Main/IBotManager.h" @@ -10,6 +14,25 @@ #include "SquadFormation.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "SquadManager.h" +#include "WaypointList.h" +#include "../../../AIInterface/BFKnowledge/BFSquad.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategic/SAI.h" +#include "../Main/AIMain.h" +#include "CommunicationAgent.h" +#include "WPAltitudeMoveTo.h" +#include "WPMoveTo.h" +#include "../Main/AIRandom.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" namespace dice { @@ -126,7 +149,7 @@ SquadMember::SquadMember(SquadCoordinator* squad, IAIPlayer* player, m_havePath = false; m_request = new RequestState(); m_request->m_action = 0; - m_int38 = 0; + m_assistMember = 0; m_position = {0.0f, 0.0f, 0.0f}; m_positionValid = false; m_flag49 = false; @@ -193,12 +216,22 @@ void SquadMember::update(double time) } else if (m_bot && getPosition(position)) { + // ELF 0x1B1ED0: WaypointList::getUrgency (vtable +8) at this position, no null + // guard. Below 0.5 the path is dropped; so it is when an unmoved member is more than + // 4 m from its path goal (+0x60). WaypointList* const waypoints = m_bot->getWaypoints(); - (void)waypoints; - // ELF +0x08 / PE +0x04 takes this position and the freshly read Bot. - // Its complete owner interface is not known. The time store is later. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (WaypointList position query)"); + if (waypoints->getUrgency(position, m_bot) < 0.5f) + { + setHavePath(false); + } + else if (!m_moved) + { + const float dx = m_vector60.x - position.x; + const float dy = m_vector60.y - position.y; + const float dz = m_vector60.z - position.z; + if (dx * dx + dy * dy + dz * dz > 16.0f) + setHavePath(false); + } } m_time24 = time; } @@ -208,12 +241,14 @@ void SquadMember::update(double time) Vec3 position = {}; if (getPosition(position)) { - if (isMobile()) + double sinceArtillery = 0.0; + int artillerySide = 0; + if (isMobile() + && SquadManager::m_instance->isInArtilleryDangerZone(position, m_side + 1, sinceArtillery, artillerySide)) { - // The bool danger query and subsequent avoidArtillery body remain - // unrecovered, not replaced by a fabricated no-danger decision. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (SquadManager::isInArtilleryDangerZone)"); + // A member that runs from artillery does nothing else this tick. + if (avoidArtillery(position, sinceArtillery, artillerySide)) + return; } else { @@ -234,13 +269,53 @@ void SquadMember::update(double time) const unsigned int handle = m_bot->getCurrentEquipment(); Information* const information = manager->getInformation(handle); #endif - if (information && (information->getObjectTypeFlags() & 0x200000u) && - information->hasArmament()) + IPIArmament* const armament = information ? information->getArmament() : 0; + if (information && (information->getObjectTypeFlags() & 0x200000u) && armament + && armament->getActiveWeapon() != -1) { - // The next call is the armament's selected-index query, ELF +0x14 - // PE +0x10. Keep the full missing owner/WeaponInfo chain explicit. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (IPIArmament selected weapon)"); + // ELF 0x1B1ED0: a soldier who is not firing switches to weapon slot 2 (activation + // input, inlined Input::setInput(float) = 1) unless he should keep the active one: + // a medic (kit 5) with weapon type 1 at no more than 95 % health, an engineer + // (kit 3) with type 2 while his other ammunition is at most 90 % (product of + // current/max over the remaining weapons), or a non-type-1/2 weapon while firing. + WeaponInfo* const active = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (active) + { + IPIPhysical* const physical = information->getPhysical(); + bool keep = false; + if (m_player->getSpawnKit() == 5 && active->getWeaponType() == 1 + && !(physical->getHealth() > 0.95f)) + { + keep = true; + } + else + { + if (m_player->getSpawnKit() == 3 && active->getWeaponType() == 2) + { + const std::vector weapons = armament->getWeapons(); + float ratio = 1.0f; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() != 1 && weapon->getWeaponType() != 2 + && weapon->getAmmo() != -1 && weapon->getMaxAmmo() != 0) + { + ratio = (static_cast(weapon->getCurrentAmmo()) + / static_cast(weapon->getMaxAmmo())) * ratio; + } + } + keep = ratio <= 0.9f; + } + if (!keep && active->getWeaponType() != 1 && active->getWeaponType() != 2 + && m_bot->isFiring()) + keep = true; + } + WeaponInfo* const primary = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(2)); + if (primary && !keep && active != primary) + m_bot->m_playerInput->setInput( + static_cast(primary->getWeaponActivate()), 1.0f); + } } } @@ -255,16 +330,19 @@ void SquadMember::update(double time) } if (member) { - // The selected member goes to acceptMission before the engine's - // accept/decline courier. Neither response is fabricated here. - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::update (SquadCoordinator::acceptMission)"); + // ELF 0x1B20AB: the selected member goes to acceptMission, then this member's player + // accepts (IBFSquad +0x2C) or declines (+0x30) the squad order. + IBFSquad* const engine = static_cast(CommonSingletonServer::m_iBFSquad); + if (m_squad->acceptMission(member)) + engine->acceptSquadOrder(m_squadIndex + 1, m_player); + else + engine->declineSquadOrder(m_squadIndex + 1, m_player); } } // Formation remains the entry capture; member index is fresh after callbacks. const bool inFormation = formation->isInFormation(m_memberIndex); - m_int38 = 0; + m_assistMember = 0; if (inFormation) moveWithFormation(); else @@ -305,27 +383,41 @@ bool SquadMember::isMoving() return m_moved; } -// These are the complete refusal paths before vehicle information. -// The remaining body queries the vehicle at ELF +0xB8 / PE +0xB4 with m_side+1, checks its -// information/type/physical records, then compares the squad destination distance if assigned. -// IAIObject is still forward-only, so its slot signature must be recovered before crossing here. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B5380 (432 bytes). A live, not man-down member whose object is a soldier +// (type flag 0x200000) with unit and mobile information; on a mission to an assigned area it +// leaves the formation once within m_formationDistanceSq of the valid area position. bool SquadMember::isAllowedInFormation() { - if (!m_player->getIsAlive()) - return false; - if (m_player->isManDown()) + bool allowed = false; + if (!m_player->getIsAlive() || m_player->isManDown()) return false; - if (!m_player->getCurrentVehicle()) + IAIObject* const vehicle = m_player->getCurrentVehicle(); + if (!vehicle) return false; - - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::isAllowedInFormation (IAIObject information handle)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + if (info && info->getUnit() && (info->getObjectTypeFlags() & 0x00200000) != 0 && info->getMobile()) + { + allowed = true; + Vec3 goal = m_squad->getSquadGotoPos(); + Vec3 position = { 0.0f, 0.0f, 0.0f }; + if (m_squad->getMissionStatus() == 2 && m_squad->isSquadAssignedToAnyArea()) + { + m_squad->getValidSaPos(this, goal); + if (getPosition(position)) + { + const float dz = goal.z - position.z; + const float dx = goal.x - position.x; + const float dy = goal.y - position.y; + if (dz * dz + dx * dx + dy * dy < m_formationDistanceSq) + allowed = false; + } + } + } + return allowed; } -// The getter occurs before either flag is cleared. A null current -// vehicle leaves the prior position untouched. The nonnull arm needs the same unknown IAIObject -// slot, Information::getPrimaryObject(side+1), and the primary object's position/physics record. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B1A70 (371 bytes). The position is the primary object's (with physical information) +// for the member's side; it counts as moved beyond 0.1 m. void SquadMember::updateMemberPos() { IAIObject* const vehicle = m_player->getCurrentVehicle(); @@ -333,13 +425,24 @@ void SquadMember::updateMemberPos() m_moved = false; if (!vehicle) return; - - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::updateMemberPos (IAIObject information handle)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + Information* const primary = informationManager->getInformation(info->getPrimaryObject(m_side + 1)); + if (primary && primary->getUnit()) + { + const float oldY = m_position.y; + const float oldX = m_position.x; + const float oldZ = m_position.z; + m_position = primary->getPosition(); + m_positionValid = true; + const float dz = oldZ - m_position.z; + const float dx = oldX - m_position.x; + const float dy = oldY - m_position.y; + if (dz * dz + dx * dx + dy * dy > 0.01f) + m_moved = true; + } } -// Retain -// the vehicle before testing the freshly read player's alive/man-down state. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B5560 (188 bytes): a live member in an object with unit and mobile information. bool SquadMember::isMobile() { IAIObject* const vehicle = m_player->getCurrentVehicle(); @@ -349,27 +452,112 @@ bool SquadMember::isMobile() return false; if (m_player->isManDown()) return false; - - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::isMobile (IAIObject information handle)"); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + return info && info->getUnit() && info->getMobile(); } -// Position validity is deliberately ignored before the formation-world-position query. -// [INFERRED] void return: callers discard it and exits materialize no common value. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B3AC0 (864 bytes). The member's slot position (SquadFormation::getSlotWorldPos); with it, +// the maximum speed and the estimated arrival (squared distance / speed, as in the image) are +// refreshed from the vehicle's mobile information (no null checks). A bot member: within +// sqrt(10) of the slot it counts as arrived (+0x30; arriving clears the path flag). The slot-0 +// member leads: on a mission once the formation moves out, at the formation's speed, towards the +// goal (snapped to the area order position) unless it has a path or is within sqrt(8); otherwise +// only with a player commander and no path. Everyone else moves to the slot while +0x49 / +0x4A +// ask for it (+0x4A is consumed). void SquadMember::moveWithFormation() { SquadFormation* const formation = m_squad->getSquadFormation(); Vec3 position = {}; getPosition(position); Vec3 slotPosition = {}; - (void)formation; (void)slotPosition; - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::moveWithFormation (SquadFormation::getSlotWorldPos)"); + if (!formation->getSlotWorldPos(m_memberIndex, slotPosition)) + return; + const float dx = slotPosition.x - position.x; + const float dy = slotPosition.y - position.y; + const float dz = slotPosition.z - position.z; + const float distanceSq = dy * dy + dx * dx + dz * dz; + Information* const info = + informationManager->getInformation(m_player->getCurrentVehicle()->getInformation(m_side + 1)); + const float maxSpeed = info->getMobile()->getMaxSpeed(); + m_maxSpeed = maxSpeed; + m_estimatedArrival = static_cast(static_cast(distanceSq) / maxSpeed); + if (!m_bot) + return; + if (distanceSq <= 10.0f) + { + if (!m_flag30) + m_havePath = false; + m_flag30 = true; + } + else + { + m_flag30 = false; + } + if (formation->getSquadMemberIndexAtSlot(0) == m_memberIndex) + { + if (m_squad->getMissionStatus() == 2 && formation->shouldSquadMoveOut()) + { + m_maxSpeed = formation->getFormationMaxSpeed(); + Vec3 goal = m_squad->getSquadGotoPos(); + if (m_squad->isSquadAssignedToAnyArea()) + m_squad->getValidSaPos(this, goal); + if (m_havePath) + return; + const float gx = goal.x - position.x; + const float gy = goal.y - position.y; + const float gz = goal.z - position.z; + if (gz * gz + gx * gx + gy * gy <= 8.0f) + return; + } + else + { + if (m_havePath) + return; + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + return; + } + moveToGoalPos(info); + } + else if (m_flag49 || m_flag4A) + { + m_flag4A = false; + moveToSlotPos(slotPosition, info); + } } -// The no-bot and dead-player returns are shipped. The alive branch ignores position -// validity, copies the goal and queries the fresh player; no null vehicle guard follows. -// [INFERRED] void return, as above. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x1B3FF0 (592 bytes). A path to the slot: a one-goal WPMoveTo(0, 60, 2) on the ground, or a +// WPAltitudeMoveTo for aircraft as in moveToGoalPos - except that here the image samples the +// terrain at (x, y) of the slot, not (x, z). +void SquadMember::moveToSlotPos(const Vec3& position, Information* information) +{ + m_havePath = true; + m_vector60 = position; + if (!(information->getObjectTypeFlags() & 0x10u)) + { + WPMoveTo::GoalList goals; + goals.push_back(std::make_pair(position, -1)); + m_bot->setWaypoints(new WPMoveTo(0.0f, 60.0f, 2, goals)); + return; + } + float altitude = 70.0f; + float radius = 30.0f; + if (information->getObjectTypeFlags() & 0x20u) + { + radius = 5.0f; + altitude = 20.0f; + } + std::list positions; + Vec3 raised = position; + raised.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(position.x, position.y) + + altitude; + positions.push_back(raised); + m_bot->setWaypoints(new WPAltitudeMoveTo(radius, radius, altitude, 2, positions)); +} + +// ELF 0x1B3E20 (464 bytes). A live bot member refreshes its maximum speed from its vehicle's +// mobile information (no null check on the information) and moves to the goal while it has no +// path: on a mission (status 2) when farther than sqrt(8) from the squad's goto position; +// otherwise only while its side's SAI has a player commander. void SquadMember::moveWithoutFormation() { if (!m_bot) @@ -380,16 +568,537 @@ void SquadMember::moveWithoutFormation() Vec3 position = {}; getPosition(position); const Vec3 goal = m_squad->getSquadGotoPos(); - IAIObject* const vehicle = m_player->getCurrentVehicle(); - (void)goal; (void)vehicle; - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::moveWithoutFormation (IAIObject information handle)"); + Information* const info = + informationManager->getInformation(m_player->getCurrentVehicle()->getInformation(m_side + 1)); + if (info->getMobile()) + m_maxSpeed = info->getMobile()->getMaxSpeed(); + if (m_squad->getMissionStatus() == 2) + { + if (m_havePath) + return; + const float dz = goal.z - position.z; + const float dx = goal.x - position.x; + const float dy = goal.y - position.y; + if (8.0f < dz * dz + dx * dx + dy * dy) + { + moveToGoalPos(info); + return; + } + } + else if (m_havePath) + { + return; + } + if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + return; + moveToGoalPos(info); } -// [FRONTIER] Returns the member's vehicle radius once the information query chain is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SquadMember operation. +namespace { + +// The acknowledgement after a move order: a bot member tells the squad (radio message 6 when +// it moves, 7 when the position is unreachable; channel 3, priority 3, delay 2 s) once per +// order, as the coordinator's roger-that flag allows. +void acknowledgePosition(SquadMember* member, SquadCoordinator* squad, int message) +{ + if (!squad->getRogerThatPositionMessage() || !member->isBot()) + return; + member->getBot()->getCommunicationAgent()->enqueueRadioMessage( + static_cast(message), static_cast(3), 3, 2.0f, 0); + squad->setRogerThatPositionMessage(false); +} + +} // namespace + +// ELF 0x1B4240 (3802 bytes). Only for a mobile member of a squad on a mission (status 2). +// * Ground units (no type flag 0x10) follow the squad leader while the formation says so and the +// squad is not close to a non-owned target: to the leader's goto position, unless it lies in +// the assigned area; without an area directly, otherwise snapped to the order position of the +// strategic area containing it. A reachable goal becomes a one-goal WPMoveTo(0, 60, 2); +// an unreachable one is acknowledged with message 7 and falls through to the squad goal. +// * The squad goal: the goto position, snapped to the assigned area's order position. Aircraft +// (flag 0x10; helicopters 0x20 too) get a WPAltitudeMoveTo at terrain height + 70 (20) with +// radius 30 (5). Otherwise an unreachable goal is acknowledged with 7; a reachable one without +// an area becomes a WPMoveTo (set only when it differs from the current waypoints); with an +// area, the strategic route from the bot's current object to the area: no route gives a +// WPMoveTo as before (no acknowledgement), a route is handed to orderNormalBot, dropping its +// first object when the bot is closer to the goal than that object is. +// The ordered goal is kept at +0x60 (for a route: the area's height marker m_f148 as y). +void SquadMember::moveToGoalPos(Information* information) +{ + if (!information->getMobile()) + return; + if (m_squad->getMissionStatus() != 2) + return; + Vec3 goal = m_squad->getSquadGotoPos(); + AIStrategicArea* area = m_squad->getSquadStrategicAreaAssignment(); + const int side = m_side + 1; + + if (!(information->getObjectTypeFlags() & 0x10u) + && m_squad->getSquadFormation()->shouldLeaveSquadLeader() + && !m_squad->isSquadCloseToNonOwnedTarget()) + { + goal = m_squad->getSquadLeaderGotoPos(); + bool follow = false; + if (!area) + { + follow = true; + } + else if (!area->isInside(goal)) + { + AIStrategicArea* const closest = static_cast( + AIStrategicObjectManager::getInstance()->getClosestObject(goal, side)); + if (closest && closest->isInside(goal)) + m_squad->getValidSaPos(this, closest, goal); + follow = true; + } + if (follow) + { + if (m_squad->isValidPosition(this, goal)) + { + m_havePath = true; + WPMoveTo::GoalList goals; + goals.push_back(std::make_pair(goal, -1)); + m_bot->setWaypoints(new WPMoveTo(0.0f, 60.0f, 2, goals)); + m_vector60 = goal; + acknowledgePosition(this, m_squad, 6); + return; + } + acknowledgePosition(this, m_squad, 7); + } + } + + goal = m_squad->getSquadGotoPos(); + if (m_squad->isSquadAssignedToAnyArea()) + m_squad->getValidSaPos(this, goal); + if (information->getObjectTypeFlags() & 0x10u) + { + float altitude = 70.0f; + float radius = 30.0f; + if (information->getObjectTypeFlags() & 0x20u) + { + radius = 5.0f; + altitude = 20.0f; + } + std::list positions; + Vec3 raised = goal; + raised.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(goal.x, goal.z) + + altitude; + positions.push_back(raised); + m_bot->setWaypoints(new WPAltitudeMoveTo(radius, radius, altitude, 2, positions)); + m_vector60 = goal; + acknowledgePosition(this, m_squad, 6); + return; + } + if (!m_squad->isValidPosition(this, goal)) + { + acknowledgePosition(this, m_squad, 7); + return; + } + m_havePath = true; + WPMoveTo::GoalList goals; + if (!m_squad->isSquadAssignedToAnyArea()) + { + goals.push_back(std::make_pair(goal, -1)); + WPMoveTo* const waypoints = new WPMoveTo(0.0f, 60.0f, 2, goals); + if (!isSameWaypointList(m_bot->getWaypoints(), waypoints)) + { + m_bot->setWaypoints(waypoints); + m_vector60 = goal; + acknowledgePosition(this, m_squad, 6); + } + else + { + delete waypoints; + } + return; + } + + std::list route; + const int botId = static_cast(m_bot->getBotId()); + AIStrategicArea* const from = static_cast(AIStrategicObjectManager::getInstance()->getStrategicObject( + IAIMain::m_instance->getSAI(side)->getBotCurrentPos(botId))); + if (!m_squad->getSquadStrategicAreaAssignment()->getRouteList(side, from, route)) + { + goals.push_back(std::make_pair(goal, -1)); + WPMoveTo* const waypoints = new WPMoveTo(0.0f, 60.0f, 2, goals); + if (!isSameWaypointList(m_bot->getWaypoints(), waypoints)) + { + m_bot->setWaypoints(waypoints); + m_vector60 = goal; + } + else + { + delete waypoints; + } + return; + } + if (1 < route.size()) + { + Vec3 position = {}; + getPosition(position); + const float dx = goal.x - position.x; + const float dz = goal.z - position.z; + const Vec2& first = route.front()->getPosition(side); + const float fx = goal.x - first.x; + const float fz = goal.z - first.y; + if (dx * dx + dz * dz < fz * fz + fx * fx) + route.erase(route.begin()); + } + goal.y = m_squad->getSquadStrategicAreaAssignment()->m_f148; + m_vector60 = goal; + ISAI* const sai = IAIMain::m_instance->getSAI(side); + m_squad->getSquadStrategicAreaAssignment()->orderNormalBot(side, route, static_cast(m_bot->getBotId()), sai); + acknowledgePosition(this, m_squad, 6); +} + +// ELF 0x1B5120 (539 bytes). Only a current WPMoveTo (type word +0xC == 0) can match: both goal +// lists must have the same length and each pair of goals lie within 10 m (squared <= 100). +bool SquadMember::isSameWaypointList(WaypointList* current, WaypointList* candidate) +{ + if (static_cast(current)->m_int0C != 0) + return false; + std::list a; + std::list b; + static_cast(current)->getCoords(a); + static_cast(candidate)->getCoords(b); + if (a.empty() || b.empty()) + return false; + std::list::const_iterator i = a.begin(); + std::list::const_iterator j = b.begin(); + while (i != a.end()) + { + const float dx = j->x - i->x; + const float dy = j->y - i->y; + const float dz = j->z - i->z; + if (dx * dx + dy * dy + dz * dz > 100.0f) + return false; + ++i; + ++j; + if (i == a.end()) + return j == b.end(); + if (j == b.end()) + return false; + } + return false; +} + +// ELF 0x1B3A10: IPIPhysical::getRadius of the member's object information; no null guards. float SquadMember::getVehicleRadius() { - BF2_AI_FRONTIER("dice::hfe::ai::SquadMember::getVehicleRadius"); + IAIObject* const vehicle = m_player->getCurrentVehicle(); + Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); + return info->getPhysical()->getRadius(); +} + +// ELF 0x1B1930: the per-round state - the position flags (+0x48..+0x4B: invalid, 49/4A set, +// 4B clear), the path reconsideration time (+0x24) and the two Vec3s at +0x54/+0x60 zeroed. +void SquadMember::reset() +{ + m_positionValid = false; + m_flag49 = true; + m_flag4A = true; + m_flag4B = false; + m_time24 = 0.0; + m_vector54.x = m_vector54.y = m_vector54.z = 0.0f; + m_vector60.x = m_vector60.y = m_vector60.z = 0.0f; +} + +void SquadMember::setMemberIndex(int index) +{ + m_memberIndex = index; +} + +// ELF 0x1B1BF0: only with a mission, an area assignment whose status for this member's side is +// non-zero and a valid position: true when the squad's goto position lies inside the formation +// distance (squared distance below +0x4C). +bool SquadMember::isCloseToNonOwnedTarget() const +{ + if (!m_squad->squadHasMission()) + return false; + if (!m_squad->isSquadAssignedToAnyArea()) + return false; + if (!m_squad->getSquadStrategicAreaAssignment()->m_status[m_side]) + return false; + if (!m_positionValid) + return false; + const Vec3& target = m_squad->getSquadGotoPos(); + const double dx = static_cast(target.x) - m_position.x; + const double dy = static_cast(target.y) - m_position.y; + const double dz = static_cast(target.z) - m_position.z; + return m_formationDistanceSq > dx * dx + dy * dy + dz * dz; +} + +// ELF 0x1B1D10: status 1 uses the second threshold; other nonzero statuses use the first. +bool SquadMember::isCloseToNonOwnedTarget(float otherDistanceSq, float statusOneDistanceSq) const +{ + if (!m_squad->squadHasMission()) + return false; + if (!m_squad->isSquadAssignedToAnyArea()) + return false; + const int status = m_squad->getSquadStrategicAreaAssignment()->m_status[m_side]; + if (!status) + return false; + const float distanceSq = status == 1 ? statusOneDistanceSq : otherDistanceSq; + if (!m_positionValid) + return false; + Vec2 target = {0.0f, 0.0f}; + Vec2 position = {0.0f, 0.0f}; + vec3ToVec2XZ(m_squad->getSquadGotoPos(), target); + vec3ToVec2XZ(m_position, position); + const float dx = position.x - target.x; + const float dy = position.y - target.y; + return distanceSq > dx * dx + dy * dy; +} + +// ELF 0x1B2840 (1609 bytes). Already avoiding: true. Otherwise up to five candidates at the +// safe distance + 5 m from the artillery target, starting away from it through `position` and +// swinging round (the angle goes 0 -> +x, -(a) - x, 3a + x, ..., x in [0.6, 0.8)); a valid one, or +// else the side's remembered flee position, becomes a one-goal WPMoveTo (0, 60, flags 2) and the +// member avoids artillery (+0x31, +0x4B). A found candidate is remembered for the side. +bool SquadMember::avoidArtillery(Vec3 position, double /*sinceStart*/, int side) +{ + if (m_flag4B) + return true; + SquadManager* const manager = SquadManager::m_instance; + const Vec3 target = manager->getArtilleryTargetPos(side); + Vec3 away; + away.x = position.x - target.x; + away.y = position.y - target.y; + away.z = position.z - target.z; + const float safe = manager->getArtillerySafeDistance(); + const float lengthSq = away.z * away.z + away.x * away.x + away.y * away.y; + if (std::fabs(lengthSq - 1.0f) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.1920929e-07f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + away.x = away.x * inverse; + away.y = away.y * inverse; + away.z = inverse * away.z; + } + else + { + away.x = 0.0f; + away.y = 0.0f; + away.z = 0.0f; + } + } + const float radius = safe + 5.0f; + Vec3 direction = away; + Vec3 candidate; + candidate.x = 0.0f; + candidate.y = 0.0f; + candidate.z = 0.0f; + float angle = 0.0f; + bool found = false; + for (int tries = 0; tries <= 4;) + { + candidate.x = radius * direction.x + target.x; + candidate.y = radius * direction.y + target.y; + candidate.z = radius * direction.z + target.z; + if (m_squad->isValidPosition(this, candidate)) + { + found = true; + break; + } + ++tries; + if (0.0f < angle) + angle = (angle - (angle + angle)) - (AIRandom::m_instance->nextFloat() * 0.2f + 0.6f); + else + angle = (angle + angle + angle) + (AIRandom::m_instance->nextFloat() * 0.2f + 0.6f); + rotateXZ(away, direction, angle); + } + if (!found && !manager->haveValidArtilleryFleePos(this, candidate)) + return false; + m_havePath = true; + m_flag4B = true; + std::list > goals; + goals.push_back(std::make_pair(candidate, -1)); + m_bot->setWaypoints(new WPMoveTo(0.0f, 60.0f, 2, goals)); + if (found) + manager->setValidArtilleryFleePos(this, candidate); + return true; +} + +// ELF 0x1B1E60: a killed member leaves its formation slot. +void SquadMember::squadMemberKilled() +{ + SquadFormation* const formation = m_squad->getSquadFormation(); + if (formation->isInFormation(m_memberIndex)) + formation->leaveFormation(m_memberIndex); +} + +// ELF 0x1B1990: frees the request record (operator delete); the pointer is left as is. +void SquadMember::removeRequest() +{ + ::operator delete(m_request); +} + +// ELF 0x1B3810: the member stands on its squad's assigned area's control point: it has a +// position, the area exists and its status for the member's side (+0x70 + 4 * (side + 1)) is +// non-zero, the area has a control point, the player is alive (IAIPlayer +0x24) and not man-down +// (+0x2C), and the squared distance is below radius^2 + 5 (0x49CDAC). +bool SquadMember::isTakingFlag() +{ + bool taking = false; + AIStrategicArea* const area = m_squad->getSquadStrategicAreaAssignment(); + Vec3 position = {}; + if (getPosition(position) && area && static_cast(area->getStatus(m_side + 1)) != 0) + { + Vec3 point = {}; + float radius; + if (area->getControlPointPosAndRadius(point, radius)) + { + radius = radius * radius; + if (m_player->getIsAlive() && !m_player->isManDown()) + { + const float dx = position.x - point.x; + const float dy = position.y - point.y; + const float dz = position.z - point.z; + if (dx * dx + dy * dy + dz * dz < radius + 5.0f) + taking = true; + } + } + } + return taking; +} + +// ELF 0x1B1E50. +void SquadMember::setForcePathUpdate(bool force) { m_flag4A = force; } + +// ELF 0x1B2EA0: the assisted member's equipment supplies the movement dimensions. +void SquadMember::moveToAssistSquadMember(SquadMember* member, const Vec3& position) +{ + if (m_havePath) + return; + IAIObject* const vehicle = member->getPlayer()->getCurrentVehicle(); + InformationManager* const manager = informationManager; + Information* const information = manager->getInformation(vehicle->getInformation(m_side + 1)); + moveToSlotPos(position, information); +} + +// ELF 0x1B2F40: ten attempts; failure returns the zero vector. +Vec3 SquadMember::getRandomAssistPos(SquadMember* member, const Vec3& position, const Vec3& direction) +{ + Vec3 result = {}; + const Vec2 normal = {direction.z, -direction.x}; + const float radius = member->getVehicleRadius(); + const float diameter = radius + radius; + const float selfRadius = getVehicleRadius(); + const float range = selfRadius + selfRadius + diameter; + Vec3 selfPosition = {}; + if (!getPosition(selfPosition)) + return result; + for (int attempt = 0; attempt < 10; ++attempt) + { + float angle = AIRandom::m_instance->nextFloat() * 0.785398006f + 0.436329991f; + Vec2 toward = {selfPosition.x - position.x, selfPosition.z - position.z}; + const float squared = toward.x * toward.x + toward.y * toward.y; + if (!(std::fabs(squared - 1.0f) < 1.1920928955078125e-7f)) + { + if (!(std::fabs(squared) < 1.4210854715202004e-14f)) + { + const float inverse = 1.0f / std::sqrt(squared); + toward.x *= inverse; + toward.y *= inverse; + } + else + { + toward.x = 0.0f; + toward.y = 0.0f; + } + } + if (toward.x * normal.x + toward.y * normal.y > 0.0f) + angle = -angle; + Vec3 rotated = {}; + rotateXZ(direction, rotated, angle); + const Vec3 base = {radius * rotated.x * 4.0f + position.x, + radius * rotated.y * 4.0f + position.y, + radius * rotated.z * 4.0f + position.z}; + const float random = AIRandom::m_instance->nextFloat(); + const Vec3 candidate = {rotated.x * random * range + base.x, + rotated.y * random * range + base.y, + random * rotated.z * range + base.z}; + if (m_squad->isValidPosition(this, candidate)) + return candidate; + } + return result; +} + +// ELF 0x1B3450: only a different shooter within 75 metres can be assisted. +SquadMember* SquadMember::getAssistFiringSquadMember(Vec3& position) +{ + Vec3 memberPosition = {}; + if (!m_squad->anyFiring() || m_squad->isFiring(m_playerId)) + return 0; + float distanceSquared; + SquadMember* const member = m_squad->getClosestFiringMember(this, distanceSquared); + if (!member || !(distanceSquared < 5625.0f)) + return 0; + if (m_assistMember != member) + m_havePath = false; + m_assistMember = member; + if (member->getPosition(memberPosition)) + { + const Vec3 direction = m_squad->getFiringDir(member); + position = getRandomAssistPos(member, memberPosition, direction); + if (!(position.x * position.x + position.y * position.y + position.z * position.z < 0.001f)) + return member; + } + m_assistMember = 0; + return 0; +} + +// ELF 0x1B35B0: missing data normally permits damage; man-down and insufficient strength refuse it. +bool SquadMember::canDamageTarget(unsigned int target) +{ + if (!m_bot || target == 0xFFFFFFFFu) + return true; + if (m_bot->getManDown()) + return false; + Information* const targetInformation = informationManager->getInformation(target); + if (!targetInformation) + return true; + Vec3 position = {}; + IPIPhysical* const targetPhysical = targetInformation->getPhysical(); + if (!targetPhysical || !getPosition(position)) + return true; + InformationManager* const manager = informationManager; + Information* const equipment = manager->getInformation(m_bot->getCurrentEquipment()); + if (!equipment) + return true; + IPIArmament* const armament = equipment->getArmament(); + if (!armament) + return true; + const std::vector& weapons = armament->getWeapons(); + const Vec3& targetPosition = targetInformation->getPosition(); + const float dx = m_position.x - targetPosition.x; + const float dy = m_position.y - targetPosition.y; + const float dz = m_position.z - targetPosition.z; + (void)std::sqrt(dx * dx + dy * dy + dz * dz); + float strength = 0.0f; + if (armament->isAntiAircraft() || !(targetInformation->getObjectTypeFlags() & 0x10u)) + { + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 0) + { + const float candidate = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + if (candidate > strength) + strength = candidate; + } + } + } + return strength > 0.1f; +} + +// ELF 0x1B39A0: action is written before the handle is re-read from the request. +void SquadMember::getCurrentRequestAction(RequestAction& action, unsigned int& handle) +{ + action = static_cast(m_request->m_action); + handle = m_request->m_handle; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h index c5e9582ff..4e92fddff 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h @@ -14,6 +14,8 @@ namespace ai { class IAIPlayer; class Bot; class SquadCoordinator; +class Information; +class WaypointList; class SquadMember { @@ -26,21 +28,59 @@ class SquadMember SquadCoordinator* getSquad(); int getPlayerId(); bool isBot(); + float getEstimatedArrival() { return m_estimatedArrival; } // ELF 0x1B5550: flds +0x20 + bool isAtFormationSlot() { return m_flag30; } // ELF 0x1B5540: movzbl +0x30 + int getSide() { return m_side + 1; } // ELF 0x1B5680: +0x1C, incl + bool isTakingFlag(); // ELF 0x1B3810 Bot* getBot(); // borrowed int getMemberIndex(); + void setMemberIndex(int index); // ELF 0x1B56C0: +0x04 + bool isCloseToNonOwnedTarget() const; // ELF 0x1B1BF0 + bool isCloseToNonOwnedTarget(float, float) const; // ELF 0x1B1D10, squared horizontal thresholds void setIsSquadLeader(bool leader); bool isSquadLeader(); bool isMoving(); // returns m_moved + void setIsIdle(bool idle) { m_flag49 = idle; } // ELF 0x1B3950: +0x49 + bool getIsIdle() { return m_flag49; } // ELF 0x1B3960 + bool isAvoidingArtillery() { return m_flag4B; } // ELF 0x1B2E90: +0x4B void setHavePath(bool havePath); + void setForcePathUpdate(bool force); + void moveToAssistSquadMember(SquadMember* member, const Vec3& position); + Vec3 getRandomAssistPos(SquadMember* member, const Vec3& position, const Vec3& direction); + SquadMember* getAssistFiringSquadMember(Vec3& position); + bool canDamageTarget(unsigned int target); void update(double time); // bounded dependent calls void updateFormationStatus(); + void reset(); // ELF 0x1B1930 + void removeRequest(); // ELF 0x1B1990 + void squadMemberKilled(); // ELF 0x1B1E60 + bool avoidArtillery(Vec3 position, double sinceStart, int side); // ELF 0x1B2840 [FRONTIER] bool getPosition(Vec3& position); // copies even if invalid bool isAllowedInFormation(); // nonnull vehicle [FRONTIER] void updateMemberPos(); // nonnull vehicle [FRONTIER] bool isMobile(); // owner query [FRONTIER] - void moveWithFormation(); // world-position [FRONTIER] - void moveWithoutFormation(); // alive owner query [FRONTIER] - float getVehicleRadius(); // [FRONTIER] + void moveWithFormation(); // ELF 0x1B3AC0 + void moveToSlotPos(const Vec3& position, Information* information); // ELF 0x1B3FF0 + void moveWithoutFormation(); // ELF 0x1B3E20 + void moveToGoalPos(Information* information); // ELF 0x1B4240 + bool isSameWaypointList(WaypointList* current, WaypointList* candidate); // ELF 0x1B5120 + float getVehicleRadius(); + + // ELF 0x1B5620: +0x2C. + float getMaxSpeed() { return m_maxSpeed; } + // ELF 0x1B39C0: the request (+0x34) back to action 0, handle -1. + void clearRequestAction() { m_request->m_action = 0; m_request->m_handle = 0xFFFFFFFFu; } + // ELF 0x1B3980: the pending request (+0x34) becomes this action (+0) and handle (+4). The image + // takes the SquadMember::RequestAction enum; the tree keeps it as int like isSameRequest. + void setCurrentRequestAction(int action, unsigned int handle) + { m_request->m_action = action; m_request->m_handle = handle; } + enum RequestAction : int; + void getCurrentRequestAction(RequestAction& action, unsigned int& handle); + // ELF 0x1B39E0: the pending request (+0x34) has this handle (+4) and action (+0). + bool isSameRequest(unsigned int handle, int action) + { return m_request->m_handle == handle && m_request->m_action == action; } + // ELF 0x1B56B0: +0. + int getSquadId() const { return m_squadIndex; } // [INFERRED] carrier name. The two fields are attested by setCurrentRequestAction // its first parameter is the RequestAction enum, its second unsigned int. @@ -62,19 +102,19 @@ class SquadMember /* +0x20 */ float m_estimatedArrival; // getEstimatedArrival /* +0x24 */ double m_time24; // last path reconsideration time; initialized to zero /* +0x2C */ float m_maxSpeed; // getMaxSpeed - /* +0x30 */ bool m_flag30; // [UNRESOLVED] + /* +0x30 */ bool m_flag30; // moveWithFormation: within sqrt(10) of the slot [INFERRED] /* +0x31 */ bool m_havePath; /* +0x34 */ RequestState* m_request; - /* +0x38 */ int m_int38; // [UNRESOLVED] + /* +0x38 */ SquadMember* m_assistMember; // [INFERRED] member currently being assisted /* +0x3C */ Vec3 m_position; /* +0x48 */ bool m_positionValid; - /* +0x49 */ bool m_flag49; // [UNRESOLVED] + /* +0x49 */ bool m_flag49; // set/getIsIdle; moveWithFormation moves an idle member to its slot /* +0x4A */ bool m_flag4A; // setHavePath writes the inverse of its argument - /* +0x4B */ bool m_flag4B; // [UNRESOLVED] + /* +0x4B */ bool m_flag4B; // isAvoidingArtillery /* +0x4C */ float m_formationDistanceSq; // [INFERRED] name, starts at 900.0 /* +0x50 */ bool m_moved; /* +0x54 */ Vec3 m_vector54; // [UNRESOLVED] - /* +0x60 */ Vec3 m_vector60; // [UNRESOLVED] + /* +0x60 */ Vec3 m_vector60; // the last goal moveToGoalPos ordered [INFERRED] meaning }; #if defined(_MSC_VER) diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp new file mode 100644 index 000000000..4082668bc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp @@ -0,0 +1,82 @@ +// A flight waypoint list that closes in on an object. Evidence: libaidll.so 1.5.3153 (ia-32), see +// WPAltitudeCloseTo.h. + +#include "WPAltitudeCloseTo.h" + +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B60D0, __tcf_0 0x1B6130, _GLOBAL__I 0x1B6160). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B5E40 (C1; C2 0x1B5DE0): the base fields (+8 = -1.0f), the arguments, then +0xC = 3. +WPAltitudeCloseTo::WPAltitudeCloseTo(unsigned int target, float radius, float second, float third) +{ + m_target = target; + m_radius = radius; + m_second = second; + m_int0C = 3; + m_third = third; +} + +// ELF 0x1B5EC0 (D1; D2 0x1B5EA0, D0 0x1B5EE0): the base vptr only. +WPAltitudeCloseTo::~WPAltitudeCloseTo() +{ +} + +// ELF 0x1B5F20. A missing target sets +5 and yields 0. Otherwise the waypoint is reached (+4 set, +// urgency 0) when radius^2 > dx^2 * dz^2 and position.y is below +0x18; every other case yields 1. +// The XZ test multiplies the squared components (`fmulp` at 0x1B5FEF) where a distance would add +// them; that shipped defect is kept. Unordered compares fall through to 1, as here. +// [PLATFORM] retail keeps the differences and products in x87 extended precision; native builds +// round each to float. +float WPAltitudeCloseTo::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + + // The image zeroes two Vec3 temporaries (the difference and a copy of it) before the lookup; + // only their components below are read. + Information* const target = informationManager->getInformation(m_target); + if (!target) + { + m_flag5 = true; + return 0.0f; + } + + const Vec3& targetPosition = target->getPosition(); + const Vec3 from = position; + const float dx = targetPosition.x - from.x; + const float dz = targetPosition.z - from.z; + if (m_radius * m_radius > dx * dx * (dz * dz) && m_second > from.y) + { + m_flag4 = true; + return 0.0f; + } + return 1.0f; +} + +// ELF 0x1B6040: the target's position, false when the handle is stale. +bool WPAltitudeCloseTo::getGoalPoint(Vec3& out) +{ + Information* const target = informationManager->getInformation(m_target); + if (!target) + return false; + out = target->getPosition(); + return true; +} + +// ELF 0x1B60C0: `flds 0x14(this)`. +float WPAltitudeCloseTo::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h new file mode 100644 index 000000000..319b25a0f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.h @@ -0,0 +1,39 @@ +// A flight waypoint list that closes in on an object at an altitude. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPAltitudeCloseTo.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B6EE0; constructors 0x1B5DE0 / 0x1B5E40; +// destructors 0x1B5EA0 / 0x1B5EC0 / 0x1B5EE0; getUrgency 0x1B5F20; getGoalPoint 0x1B6040; +// getWayPointRadius 0x1B60C0; getId 0x1B6220. No call site in the image constructs it. + +#ifndef AI_AIDLL_AI_AIBOT_WPALTITUDECLOSETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPALTITUDECLOSETO_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPAltitudeCloseTo : public WaypointList +{ +public: + // ELF 0x1B5E40: base fields (+8 = -1.0f), the arguments at +0x10..+0x1C, +0xC = 3. + WPAltitudeCloseTo(unsigned int target, float radius, float second, float third); + virtual ~WPAltitudeCloseTo(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B5F20 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B6040: the target's position + virtual int getId() { return 5; } // ELF 0x1B6220 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B60C0: +0x14 + + /* +0x0C */ int m_int0C; // ctor 3 [UNRESOLVED] meaning + /* +0x10 */ unsigned int m_target; // information handle (getGoalPoint) + /* +0x14 */ float m_radius; // getWayPointRadius; the arrival radius in getUrgency + /* +0x18 */ float m_second; // getUrgency: arrival needs position.y below it + /* +0x1C */ float m_third; // BBPGotoWaypoint3d: BAPAMoveTo3dObject's distance argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPALTITUDECLOSETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp new file mode 100644 index 000000000..a9dadc3b3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp @@ -0,0 +1,111 @@ +// A flight waypoint list. Evidence: libaidll.so 1.5.3153 (ia-32), see WPAltitudeMoveTo.h. + +#include "WPAltitudeMoveTo.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B6CC0, __tcf_0 0x1B6D20, _GLOBAL__I 0x1B6D50). +#include + +#include "BotMain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B6230 (C1; C2 0x1B6420): base fields, +8 = -1.0f, the arguments, +0x18 = 1e9f +// (0x4E6E6B28), the empty list, +0xC = 4, a clear and the copy. +WPAltitudeMoveTo::WPAltitudeMoveTo(float first, float second, float third, unsigned int flags, + std::list& positions) +{ + m_first = first; + m_second = second; + m_float18 = 1e9f; + m_third = third; + m_flags = flags; + m_int0C = 4; + m_positions.clear(); + for (std::list::iterator it = positions.begin(); it != positions.end(); ++it) + m_positions.push_back(*it); +} + +// ELF 0x1B6560: the list, then the base vptr. +WPAltitudeMoveTo::~WPAltitudeMoveTo() +{ +} + +// ELF 0x1B6690. f2 = m_first^2, s2 = m_second^2, d = distXZSqr(position, front), dy2 = the squared +// height difference to the front position. With several positions the front is dropped (+4 set) +// when f2 > d and s2 > dy2, or when d grew beyond the last stored distance (+0x18), which then +// takes d; the urgency is (d + dy2) / (f2 + s2) when f2 > d and dy2 > s2 (the height test is +// reversed against the drop test, as compiled), else 1. With one position nothing is dropped: the +// urgency is 0 inside 50 m (2500) for an airborne bot, else (d + dy2) / (f2 + s2) when f2 > d +// and s2 > dy2, else 1; that arm also formats the values into a stringstream that is never read +// (the image's dead debug output). No positions: +5 set, urgency 0. Unordered compares answer 1. +// [PLATFORM] retail keeps dy2 and the sums in x87 extended precision (dy2 is rounded to float only +// on the drop path). +float WPAltitudeMoveTo::getUrgency(const Vec3& position, Bot* bot) +{ + if (m_wayPointError) + return 0.0f; + if (m_positions.empty()) + { + m_flag5 = true; + return 0.0f; + } + + const float firstSqr = m_first * m_first; + const float secondSqr = m_second * m_second; + const float distanceSqr = distXZSqr(position, m_positions.front()); + const float dy = position.y - m_positions.front().y; + const float heightSqr = dy * dy; + if (m_positions.size() == 1) + { + float urgency; + if (2500.0f > distanceSqr && bot->isAirBorn()) + urgency = 0.0f; + else if (firstSqr > distanceSqr && secondSqr > heightSqr) + urgency = (distanceSqr + heightSqr) / (firstSqr + secondSqr); + else + urgency = 1.0f; + std::stringstream debug; + debug << "distLeftSquare: " << distanceSqr << ", MinDist: " << m_first << ", Urg: " << urgency; + return urgency; + } + + if ((firstSqr > distanceSqr && secondSqr > heightSqr) || distanceSqr > m_float18) + { + m_positions.erase(m_positions.begin()); + m_flag4 = true; + } + m_float18 = distanceSqr; + if (firstSqr > distanceSqr && heightSqr > secondSqr) + return (distanceSqr + heightSqr) / (firstSqr + secondSqr); + return 1.0f; +} + +// ELF 0x1B6C40: the first position when there is one. +bool WPAltitudeMoveTo::getGoalPoint(Vec3& out) +{ + const bool any = !m_positions.empty(); + if (any) + out = m_positions.front(); + return any; +} + +// ELF 0x1B6C80: `out = positions` (std::list::operator=). +void WPAltitudeMoveTo::getCoords(std::list& out) const +{ + out = m_positions; +} + +// ELF 0x1B6CB0: `flds 0x10(this)`. +float WPAltitudeMoveTo::getWayPointRadius() const +{ + return m_first; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h new file mode 100644 index 000000000..30c96f0ee --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.h @@ -0,0 +1,48 @@ +// A flight waypoint list: positions an air bot flies through at an altitude. +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/WPAltitudeMoveTo.cpp (FILE symbol +// beside 0x1B6CC0); vtable 0x4B70A0; constructors 0x1B6230 / 0x1B6420; destructors 0x1B6560 / +// 0x1B65C0 / 0x1B6620; getUrgency 0x1B6690; getGoalPoint 0x1B6C40; getCoords 0x1B6C80; +// getWayPointRadius 0x1B6CB0; getId 0x1B6F90. Size 0x28 (`operator new(0x28)` in +// AIStrategicArea::orderAirBot, which passes (altitude, 120.0f, 50.0f, 2, path)). + +#ifndef AI_AIDLL_AI_AIBOT_WPALTITUDEMOVETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPALTITUDEMOVETO_H + +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPAltitudeMoveTo : public WaypointList +{ +public: + // ELF 0x1B6230. Note the list is taken by non-const reference (mangled `RSt4list`). + WPAltitudeMoveTo(float first, float second, float third, unsigned int flags, std::list& positions); + virtual ~WPAltitudeMoveTo(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B6690 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B6C40: the first position + virtual int getId() { return 6; } // ELF 0x1B6F90 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B6CB0: +0x10 + + void getCoords(std::list& out) const; // ELF 0x1B6C80: list assignment + + // [INFERRED] names; the stores are attested. + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ int m_int0C; // ctor 4 + /* +0x10 */ float m_first; // the first argument; getWayPointRadius + /* +0x14 */ float m_second; + /* +0x18 */ float m_float18; // ctor 1e9f; getUrgency's last front distance + /* +0x1C */ float m_third; + /* +0x20 */ unsigned int m_flags; + /* +0x24 */ std::list m_positions; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPALTITUDEMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp new file mode 100644 index 000000000..6a7c0a0a6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp @@ -0,0 +1,82 @@ +// A flight patrol loop. Evidence: libaidll.so 1.5.3153 (ia-32), see WPAltitudePatrol.h. + +#include "WPAltitudePatrol.h" + +#include + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B8220, __tcf_0 0x1B8280, _GLOBAL__I 0x1B82B0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B7E60 (C1; C2 0x1B7CB0): the base fields (+8 = -1.0f), the arguments, the empty list, +// +0xC = 5, a clear, then each position appended. +WPAltitudePatrol::WPAltitudePatrol(float first, float second, float third, unsigned int flags, + std::list& positions) +{ + m_first = first; + m_second = second; + m_third = third; + m_flags = flags; + m_int0C = 5; + m_positions.clear(); + for (std::list::iterator it = positions.begin(); it != positions.end(); ++it) + m_positions.insert(m_positions.end(), *it); +} + +// ELF 0x1B7FC0 (D1; D2 0x1B7F60, D0 0x1B8020): the list, then the base vptr. +WPAltitudePatrol::~WPAltitudePatrol() +{ +} + +// ELF 0x1B8090. The front position is reached when m_first^2 > dx^2 + dz^2 and |dy| < m_second +// (differences position - front); it is then re-inserted at the end before the front is erased +// and +4 is set. The urgency is 1 either way, 0 on a waypoint error. +// [PLATFORM] retail keeps the XZ sum in x87 extended precision and takes |dy| through SSE +// (`andnps` with the sign mask); native builds round each step to float. +float WPAltitudePatrol::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + + const float radiusSqr = m_first * m_first; + const float dx = position.x - m_positions.front().x; + const float dz = position.z - m_positions.front().z; + if (radiusSqr > dx * dx + dz * dz) + { + const float dy = std::fabs(position.y - m_positions.front().y); + if (m_second > dy) + { + m_positions.insert(m_positions.end(), m_positions.front()); + m_positions.erase(m_positions.begin()); + m_flag4 = true; + } + } + return 1.0f; +} + +// ELF 0x1B81A0: the front position (no empty check). +bool WPAltitudePatrol::getGoalPoint(Vec3& out) +{ + out = m_positions.front(); + return true; +} + +// ELF 0x1B81E0: list assignment. +void WPAltitudePatrol::getCoords(std::list& out) const +{ + out = m_positions; +} + +// ELF 0x1B8210: `flds 0x10(this)`. +float WPAltitudePatrol::getWayPointRadius() const +{ + return m_first; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h new file mode 100644 index 000000000..9533899d4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudePatrol.h @@ -0,0 +1,46 @@ +// A flight waypoint list that patrols positions at an altitude. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPAltitudePatrol.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B7260; constructors 0x1B7CB0 / 0x1B7E60; +// destructors 0x1B7F60 / 0x1B7FC0 / 0x1B8020; getUrgency 0x1B8090; getGoalPoint 0x1B81A0; +// getCoords 0x1B81E0; getWayPointRadius 0x1B8210; getId 0x1B82D0. Constructed only by +// AIConsole::botSetWaypoints_Patrol3d (0x3921D0, call at 0x3922B9). + +#ifndef AI_AIDLL_AI_AIBOT_WPALTITUDEPATROL_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPALTITUDEPATROL_H + +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPAltitudePatrol : public WaypointList +{ +public: + // ELF 0x1B7E60: base fields (+8 = -1.0f), the arguments at +0x10..+0x1C, the empty list, + // +0xC = 5, a clear and the copy. The list is taken by non-const reference (mangled `RSt4list`). + WPAltitudePatrol(float first, float second, float third, unsigned int flags, std::list& positions); + virtual ~WPAltitudePatrol(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B8090 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B81A0: the first position + virtual int getId() { return 7; } // ELF 0x1B82D0 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B8210 + + void getCoords(std::list& out) const; // ELF 0x1B81E0 + + /* +0x0C */ int m_int0C; // ctor 5 [UNRESOLVED] meaning + /* +0x10 */ float m_first; // getWayPointRadius; the XZ arrival radius + /* +0x14 */ float m_second; // getUrgency: the |dy| arrival tolerance + /* +0x18 */ float m_third; // BBPGotoWaypoint3d: BAPAMoveTo3d's distance argument + /* +0x1C */ unsigned int m_flags; + /* +0x20 */ std::list m_positions; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPALTITUDEPATROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp new file mode 100644 index 000000000..9a282e437 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp @@ -0,0 +1,95 @@ +// A boat waypoint list for beach landings. Evidence: libaidll.so 1.5.3153 (ia-32), see +// WPBeachLanding.h. + +#include "WPBeachLanding.h" + +#include "BotMain.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../AIStrategicEntity/AILandingZoneManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B86C0, __tcf_0 0x1B8720, _GLOBAL__I 0x1B8750). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B8370 (C1; C2 0x1B82E0): the base fields (+8 = -1.0f), the arguments, the zone by index, +// +0xC = 6, then the zone into BotMain +0xE8 through the Bot pointer. +WPBeachLanding::WPBeachLanding(int zoneIndex, float value, int map, int approachType, Bot* bot) +{ + m_map = map; + m_inside = false; + m_approachType = approachType; + m_value = value; + m_zone = AILandingZoneManager::m_instance->getAILandingZone(zoneIndex); + m_int0C = 6; + static_cast(bot)->m_ptr232 = m_zone; +} + +// ELF 0x1B8470 (C1; C2 0x1B8400): as above with the zone given. +WPBeachLanding::WPBeachLanding(AILandingZone* zone, float value, int map, int approachType, Bot* bot) +{ + m_map = map; + m_inside = false; + m_approachType = approachType; + m_zone = zone; + m_int0C = 6; + m_value = value; + static_cast(bot)->m_ptr232 = zone; +} + +void WPBeachLanding::storeLandingZone(Bot* bot, AILandingZone* zone) +{ + static_cast(bot)->m_ptr232 = zone; +} + +// ELF 0x1B8500 (D1; D2 0x1B84E0, D0 0x1B8520): the base vptr only. +WPBeachLanding::~WPBeachLanding() +{ +} + +// ELF 0x1B8560. Inside means a squared zone distance of exactly 0 (unordered is outside); outside, +// the distance is queried a second time for the store. +4 is set when inside changes. +float WPBeachLanding::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + + const bool wasInside = m_inside; + m_inside = m_zone->getDistanceSqr(position) == 0.0f; + m_distanceSqr = m_inside ? 0.0f : m_zone->getDistanceSqr(position); + m_flag4 = m_inside != wasInside; + return 1.0f; +} + +// ELF 0x1B8600: the beach position inside the zone, the approach position (10 m) outside it. +bool WPBeachLanding::getGoalPoint(Vec3& out) +{ + if (m_inside) + return m_zone->getBeachPosition(m_map, out); + return m_zone->getApproachPosition(m_map, m_approachType, out, 10.0f); +} + +// ELF 0x1B8670 +bool WPBeachLanding::insideZone() +{ + return m_inside; +} + +// ELF 0x1B8680: distance^2 >= the last squared zone distance; unordered is false. +bool WPBeachLanding::closeToZone(float distance) +{ + return distance * distance >= m_distanceSqr; +} + +// ELF 0x1B86A0: a constant 10. +float WPBeachLanding::getWayPointRadius() const +{ + return 10.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h new file mode 100644 index 000000000..5d3f484fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.h @@ -0,0 +1,57 @@ +// A boat waypoint list: approach a landing zone, then run onto its beach. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPBeachLanding.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B72A0 (D1, D0, getUrgency, getGoalPoint, +// getId, then WaypointList's setWayPointError / getWayPointError, then getWayPointRadius). +// Constructors 0x1B82E0 / 0x1B8370 (zone index) and 0x1B8400 / 0x1B8470 (zone); destructors +// 0x1B84E0 / 0x1B8500 / 0x1B8520. No call site in the image constructs it, so the size is not +// attested; BBPGotoWaypointBoat::createPlan reads it through getId 3. + +#ifndef AI_AIDLL_AI_AIBOT_WPBEACHLANDING_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPBEACHLANDING_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class AILandingZone; + +class WPBeachLanding : public WaypointList +{ +public: + // Both forms also store the zone into the bot (BotMain +0xE8). + WPBeachLanding(int zoneIndex, float value, int map, int approachType, Bot* bot); + WPBeachLanding(AILandingZone* zone, float value, int map, int approachType, Bot* bot); + virtual ~WPBeachLanding(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B8560 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B8600 + virtual int getId() { return 3; } // ELF 0x1B8770 (weak) + virtual float getWayPointRadius() const; // ELF 0x1B86A0: 10 + + bool insideZone(); // ELF 0x1B8670 + bool closeToZone(float distance); // ELF 0x1B8680 + + // [CHOSEN, not recovered] packaging: the BotMain +0xE8 store both beach-landing waypoint + // lists' constructors make inline (WPMoveToBeachLanding 0x1BA42E too). It lives here because + // WPBeachLanding is BotMain's friend; [RETIRE-WHEN: wpmovetobeach-friend] BotMain.h also + // befriends WPMoveToBeachLanding, which then stores the zone itself. + static void storeLandingZone(Bot* bot, AILandingZone* zone); + + // [INFERRED] names; the stores are attested. + /* +0x0C */ int m_int0C; // ctor 6 [UNRESOLVED] meaning + /* +0x10 */ int m_map; // getBeachPosition / getApproachPosition first argument + /* +0x14 */ int m_approachType; // getApproachPosition second argument + /* +0x18 */ bool m_inside; // getUrgency: distance 0 to the zone + /* +0x1C */ float m_value; // ctor float argument; no reader in this TU + /* +0x20 */ float m_distanceSqr; // getUrgency; not initialised by the constructors + /* +0x24 */ int m_unknown24; // [UNRESOLVED] never stored or read in this TU + /* +0x28 */ AILandingZone* m_zone; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPBEACHLANDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp new file mode 100644 index 000000000..1526a9a7a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp @@ -0,0 +1,151 @@ +// A waypoint list that closes in on one object. Evidence: libaidll.so 1.5.3153 (ia-32), see +// WPCloseTo.h. + +#include "WPCloseTo.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B8F90, __tcf_0 0x1B8FF0, _GLOBAL__I 0x1B9020). +#include + +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// Inlined in the constructor and getUrgency: without a physical plug-in the object's position, +// else the sphere's local offset rotated by the transformation (rows 0..2) plus the position. +Vec3 closeToPosition(Information* info) +{ + IPIPhysical* const physical = info->getPhysical(); + if (!physical) + return info->getPosition(); + const Mat4& m = info->getTransformation(); + const Vec3 offset = physical->getSphereLocalOffset(); + const float* const r = m.m; + Vec3 point; + point.x = r[8] * offset.z + r[0] * offset.x + r[4] * offset.y; + point.y = r[1] * offset.x + r[5] * offset.y + r[9] * offset.z; + point.z = offset.x * r[2] + offset.y * r[6] + offset.z * r[10]; + const Vec3& position = info->getPosition(); + point.x = position.x + point.x; + point.y = position.y + point.y; + point.z = position.z + point.z; + return point; +} +} // namespace + +// ELF 0x1B8780: the radius is at least 5.0f, and with a physical plug-in at least twice its +// smallest radius (x87 compare against 2r, stored as float). +WPCloseTo::WPCloseTo(unsigned int target, float radius) + : m_int12(2) + , m_target(target) + , m_radius(radius <= 5.0f ? 5.0f : radius) + , m_distanceSq(25.0f) +{ + m_flag4 = true; + m_flag5 = false; + m_wayPointError = false; + m_goal.x = 0.0f; + m_goal.y = 0.0f; + m_goal.z = 0.0f; + Information* const info = informationManager->getInformation(target); + if (!info) + return; + if (IPIPhysical* const physical = info->getPhysical()) + { + const float smallest = physical->getSmallestRadius(); + const float twice = smallest + smallest; + if (m_radius <= twice) + m_radius = twice; + } + m_goal = closeToPosition(info); +} + +WPCloseTo::~WPCloseTo() +{ +} + +// ELF 0x1B8BA0. 0 after a waypoint error, or (marking +5) when the object is gone. Otherwise the +// squared distance d from `position` to the object is kept (+0x18) and the urgency is +// min(1, d / (4 r^2)); inside r^2 the list is marked (+4) and the urgency is 0; outside, a goal +// that moved more than r (squared distances) is refreshed and the list marked. +float WPCloseTo::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + Information* const info = informationManager->getInformation(m_target); + if (!info) + { + m_flag5 = true; + return 0.0f; + } + const Vec3 point = closeToPosition(info); + const float dx = point.x - position.x; + const float dy = point.y - position.y; + const float dz = point.z - position.z; + const float distanceSq = dx * dx + dy * dy + dz * dz; + m_distanceSq = distanceSq; + const float radiusSq = m_radius * m_radius; + float urgency = distanceSq / (radiusSq * 4.0f); + if (1.0f < urgency) + urgency = 1.0f; + if (radiusSq <= distanceSq) + { + const float gx = m_goal.x - point.x; + const float gy = m_goal.y - point.y; + const float gz = m_goal.z - point.z; + if (radiusSq < gx * gx + gy * gy + gz * gz) + { + m_goal = point; + m_flag4 = true; + } + return urgency; + } + m_flag4 = true; + return 0.0f; +} + +// ELF 0x1B8F00: the goal while the object exists. +bool WPCloseTo::getGoalPoint(Vec3& out) +{ + if (!informationManager->getInformation(m_target)) + return false; + out = m_goal; + return true; +} + +// ELF 0x1B8E30. Without the object the speed stands. Without a mobile plug-in: 0 once the radius +// reaches the kept distance (+0x14 against +0x18 as stored), else the speed. With one: within +// that, at most the object's speed magnitude (IPIMobile +0x24); beyond twice the distance the +// speed stands; in between at most magnitude * 1.33 (0x49D240) * d / r. +float WPCloseTo::modifyMaxSpeed(float speed) +{ + Information* const info = informationManager->getInformation(m_target); + if (!info) + return speed; + IPIMobile* const mobile = info->getMobile(); + if (!mobile) + return m_radius < m_distanceSq ? speed : 0.0f; + float limit; + if (m_radius >= m_distanceSq) + { + limit = mobile->getSpeedMagnitude(); + } + else + { + if (m_radius < m_distanceSq + m_distanceSq) + return speed; + limit = mobile->getSpeedMagnitude() * 1.33f * m_distanceSq / m_radius; + } + return limit > speed ? speed : limit; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h new file mode 100644 index 000000000..7415b6856 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.h @@ -0,0 +1,42 @@ +// A waypoint list that closes in on one object (by information handle). Evidence: libaidll.so +// 1.5.3153 (ia-32): vtable 0x4B72E0 (D1, D0, getUrgency 0x1B8BA0, getGoalPoint 0x1B8F00, getId +// 0x1B9040 (weak, 0), WaypointList's error pair, getWayPointRadius 0x1B8F80); constructors +// 0x1B8780 / 0x1B8950; destructors 0x1B8B20 / 0x1B8B40 / 0x1B8B60; modifyMaxSpeed 0x1B8E30. + +#ifndef AI_AIDLL_AI_AIBOT_WPCLOSETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPCLOSETO_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPCloseTo : public WaypointList +{ +public: + WPCloseTo(unsigned int target, float radius); // ELF 0x1B8780 + virtual ~WPCloseTo(); // ELF 0x1B8B20 + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B8BA0 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B8F00 + virtual int getId() { return 0; } // ELF 0x1B9040 (weak) + virtual float getWayPointRadius() const { return m_radius; } // ELF 0x1B8F80: flds +0x14 + + float modifyMaxSpeed(float speed); // ELF 0x1B8E30 + unsigned int getTarget() const { return m_target; } // [INFERRED] reader of +0x10 + + // [INFERRED] names; the stores are attested (constructor 0x1B8780). + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ unsigned int m_int12; // 2 [UNRESOLVED] (WPEmpty 1) + /* +0x10 */ unsigned int m_target; // the object's information handle + /* +0x14 */ float m_radius; // at least 5, at least twice the target's smallest radius + /* +0x18 */ float m_distanceSq; // 25.0f, then getUrgency's squared distance to the goal + /* +0x1C */ Vec3 m_goal; // the target's (sphere centre) position when last moved +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPCLOSETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp new file mode 100644 index 000000000..8e8641e92 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.cpp @@ -0,0 +1,45 @@ +// The "no waypoints" list. Evidence: libaidll.so 1.5.3153 (ia-32), see WPEmpty.h. + +#include "WPEmpty.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1B9230, __tcf_0 0x1B9290, _GLOBAL__I 0x1B92C0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B9050. +WPEmpty::WPEmpty(const Vec3& position) + : m_int12(1) + , m_position(position) +{ + m_flag4 = true; + m_flag5 = false; + m_wayPointError = false; +} + +// ELF 0x1B9130. +WPEmpty::~WPEmpty() +{ +} + +// ELF 0x1B91B0: marks the list (+4) and follows the bot's position; urgency 0. +float WPEmpty::getUrgency(const Vec3& position, Bot*) +{ + m_flag4 = true; + m_position = position; + return 0.0f; +} + +// ELF 0x1B9200. +bool WPEmpty::getGoalPoint(Vec3& out) +{ + out = m_position; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h new file mode 100644 index 000000000..72b6a1cc2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPEmpty.h @@ -0,0 +1,36 @@ +// The "no waypoints" list: holds one position (the bot's own at creation) and reports it as the +// goal. Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/WPEmpty.cpp (FILE symbol +// beside 0x1B9230); vtable 0x4B7320 (D1, D0, getUrgency, getGoalPoint, getId; the rest are +// WaypointList's); constructors 0x1B9050 / 0x1B90C0; destructors 0x1B9130 / 0x1B9150 / 0x1B9170. +// Size 0x1C (`operator new(0x1c)` in BotMain::updateBot 0x18BF50). + +#ifndef AI_AIDLL_AI_AIBOT_WPEMPTY_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPEMPTY_H + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPEmpty : public WaypointList +{ +public: + explicit WPEmpty(const Vec3& position); // ELF 0x1B9050 + virtual ~WPEmpty(); // ELF 0x1B9130 + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B91B0 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B9200: always true + virtual int getId() { return 8; } // ELF 0x1B92E0 (weak) + + // [INFERRED] names; the stores are attested (constructor 0x1B9050). + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ unsigned int m_int12; // 1 [UNRESOLVED] + /* +0x10 */ Vec3 m_position; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPEMPTY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp new file mode 100644 index 000000000..66d2aafbb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp @@ -0,0 +1,203 @@ +// A walk-through waypoint list. Evidence: libaidll.so 1.5.3153 (ia-32), see WPMoveTo.h. + +#include "WPMoveTo.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BA040, __tcf_0 0x1BA0A0, _GLOBAL__I 0x1BA0D0). +#include + +#include "../Main/AIDllFrontier.h" +#include "BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1B96C0 (C1; C2 0x1B97E0). The base fields (+4 true, +5 / +6 false), then +8 = -1.0f, +// the clamp, +0x10..+0x18, the empty list, +0x20 = false, +0xC = 0, a clear, and the copy. +WPMoveTo::WPMoveTo(float radius, float stepRadius, unsigned int flags, const GoalList& goals) +{ + if (stepRadius <= 1.0f) + stepRadius = 1.0f; + m_radius = radius; + m_stepRadius = stepRadius; + m_flags = flags; + m_flag20 = false; + m_int0C = 0; + m_goals.clear(); + for (GoalList::const_iterator it = goals.begin(); it != goals.end(); ++it) + m_goals.push_back(*it); +} + +// ELF 0x1B92F0 (C1; C2 0x1B9530). As above with a clamp at 2.0; every position is paired with -1 +// and the last goal then takes `lastArea`. +WPMoveTo::WPMoveTo(float radius, float stepRadius, unsigned int flags, const std::list& positions, int lastArea) +{ + if (stepRadius <= 2.0f) + stepRadius = 2.0f; + m_radius = radius; + m_stepRadius = stepRadius; + m_flags = flags; + m_flag20 = false; + m_int0C = 0; + m_goals.clear(); + for (std::list::const_iterator it = positions.begin(); it != positions.end(); ++it) + m_goals.push_back(std::make_pair(*it, -1)); + if (!m_goals.empty()) + m_goals.back().second = lastArea; +} + +// ELF 0x1B9900: the list, then the base vptr. +WPMoveTo::~WPMoveTo() +{ +} + +// ELF 0x1B9A30 (1344 bytes). r is max(ceil(radius), the equipment's smallest radius) for the last +// goal; max(ceil(step radius), smallest radius) for an intermediate goal, or max(smallest radius, 10) +// for one without an area. d^2 is the squared distance from `position` to the front goal. +// * No goals: done (+5), 0. +// * The last goal within r: done (+5), +6 cleared, 0. Beyond r: clamp(d^2 / (1.5 r^2), 0.1, 1) times +// 2 for an area the side holds (status != 0), 0 inside an area it does not hold (d^2 = 0), else 1 +// with d^2 reduced by the side's area radius squared; without an area 1, or 0 when +6 is set. +// A set +6 moves the goal inside the area (randomizePos(side, 0.9)) and is cleared. +5 = d^2 < 1.5 r^2. +// * An intermediate goal is popped (+4 set, +6 cleared) within r, or beyond it when the bot is +// inside the goal's area, or with +6 set and no area; with +6 set outside the area it is moved +// instead. Always 1. +float WPMoveTo::getUrgency(const Vec3& position, Bot* bot) +{ + if (m_goals.empty()) + { + m_flag5 = true; + return 0.0f; + } + IPIPhysical* const physical = + informationManager->getInformation(bot->getCurrentEquipment())->getPhysical(); + const Vec3& goal = m_goals.front().first; + const float dx = goal.x - position.x; + const float dy = goal.y - position.y; + const float dz = goal.z - position.z; + float distanceSq = dz * dz + dy * dy + dx * dx; + + if (m_goals.size() == 1) + { + float radius = static_cast(std::ceil(static_cast(m_radius))); + const float smallest = physical->getSmallestRadius(); + if (radius < smallest) + radius = smallest; + const float radiusSq = radius * radius; + if (!(radiusSq <= distanceSq)) + { + m_flag5 = true; + m_wayPointError = false; + return 0.0f; + } + float factor; + AIStrategicArea* const area = + AIStrategicObjectManager::getInstance()->getStrategicArea(m_goals.front().second); + if (!area) + { + factor = m_wayPointError ? 0.0f : 1.0f; + } + else + { + const int side = bot->getSide(); + if (static_cast(area->getStatus(side)) == 0) + { + if (!area->isInside(position)) + { + // +0x98 + 4 * side: m_size[side]. + const float sideRadius = area->m_size[bot->getSide()]; + distanceSq = distanceSq - sideRadius * sideRadius; + factor = 1.0f; + } + else + { + factor = 0.0f; + distanceSq = 0.0f; + } + } + else + { + factor = 2.0f; + } + if (m_wayPointError) + { + area->randomizePos(bot->getSide(), 0.9f, m_goals.front().first); + m_wayPointError = false; + } + } + const float scaled = radiusSq * 1.5f; + float urgency = distanceSq / scaled; + m_flag5 = !(scaled <= distanceSq); + if (1.0f < urgency) + urgency = 1.0f; + if (!(0.1f <= urgency)) + urgency = 0.1f; + return urgency * factor; + } + + float radius = static_cast(std::ceil(static_cast(m_stepRadius))); + float smallest = physical->getSmallestRadius(); + if (radius < smallest) + radius = smallest; + if (m_goals.front().second == -1) + { + radius = physical->getSmallestRadius(); + if (radius <= 10.0f) + radius = 10.0f; + } + if (radius * radius <= distanceSq) + { + AIStrategicArea* const area = + AIStrategicObjectManager::getInstance()->getStrategicArea(m_goals.front().second); + if (!area) + { + if (!m_wayPointError) + return 1.0f; + } + else if (!area->isInside(position)) + { + if (!m_wayPointError) + return 1.0f; + area->randomizePos(bot->getSide(), 0.9f, m_goals.front().first); + m_wayPointError = false; + return 1.0f; + } + } + m_goals.erase(m_goals.begin()); + m_flag4 = true; + m_wayPointError = false; + return 1.0f; +} + +// ELF 0x1B9F70: the first goal's position when there is one. +bool WPMoveTo::getGoalPoint(Vec3& out) +{ + const bool any = !m_goals.empty(); + if (any) + out = m_goals.front().first; + return any; +} + +// ELF 0x1B9FB0: each goal position appended to `out`. +void WPMoveTo::getCoords(std::list& out) const +{ + for (GoalList::const_iterator it = m_goals.begin(); it != m_goals.end(); ++it) + out.push_back(it->first); +} + +// ELF 0x1BA030: `flds 0x10(this)`. +float WPMoveTo::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h new file mode 100644 index 000000000..72f65181d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.h @@ -0,0 +1,53 @@ +// A waypoint list of (position, strategic area id) goals a bot walks through in order. +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/WPMoveTo.cpp (FILE symbol beside +// 0x1BA040); vtable 0x4B7360; constructors 0x1B92F0 / 0x1B9530 (Vec3 list + last area) and +// 0x1B96C0 / 0x1B97E0 (pair list); destructors 0x1B9900 / 0x1B9960 / 0x1B99C0; getUrgency +// 0x1B9A30; getGoalPoint 0x1B9F70; getCoords 0x1B9FB0; getWayPointRadius 0x1BA030; getId 0x1BA140. +// Size 0x24 (`operator new(0x24)` in AIStrategicArea::orderNormalBot). + +#ifndef AI_AIDLL_AI_AIBOT_WPMOVETO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPMOVETO_H + +#include +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPMoveTo : public WaypointList +{ +public: + typedef std::list > GoalList; + + // ELF 0x1B96C0: the goals as given; the second distance is at least 1. + WPMoveTo(float radius, float stepRadius, unsigned int flags, const GoalList& goals); + // ELF 0x1B92F0: each position with area -1, the last one with `lastArea`; the second distance is + // at least 2. + WPMoveTo(float radius, float stepRadius, unsigned int flags, const std::list& positions, int lastArea); + virtual ~WPMoveTo(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1B9A30 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1B9F70: the first goal + virtual int getId() { return 1; } // ELF 0x1BA140 (weak) + virtual float getWayPointRadius() const; // ELF 0x1BA030: +0x10 + + void getCoords(std::list& out) const; // ELF 0x1B9FB0: appends the positions + + // [INFERRED] names; the stores are attested. + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ int m_int0C; // ctor 0 (WPAltitudeMoveTo writes 4) + /* +0x10 */ float m_radius; // the goal radius; getWayPointRadius + /* +0x14 */ float m_stepRadius; // the radius for intermediate goals + /* +0x18 */ unsigned int m_flags; // the third argument ([UNRESOLVED] meaning) + /* +0x1C */ GoalList m_goals; + /* +0x20 */ bool m_flag20; // ctor false +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp new file mode 100644 index 000000000..c01eacbfb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp @@ -0,0 +1,178 @@ +// A boat waypoint list for beach landings through waypoints. Evidence: libaidll.so 1.5.3153 +// (ia-32), see WPMoveToBeachLanding.h. + +#include "WPMoveToBeachLanding.h" + +#include + +#include "BotMain.h" +#include "WPBeachLanding.h" // storeLandingZone +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../AIStrategicEntity/AILandingZoneManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BAB80, __tcf_0 0x1BABE0, _GLOBAL__I 0x1BAC10). +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The radius the constructors keep: the argument when above 5, else 5 (unordered gives 5). +float atLeastFive(float radius) +{ + return radius > 5.0f ? radius : 5.0f; +} + +} // anonymous namespace + +// ELF 0x1BA320 (C1; C2 0x1BA150): the base fields, the arguments, the zone by index, the +// waypoints copy-constructed, +0xC = 7, then the zone into BotMain +0xE8 through the Bot pointer. +WPMoveToBeachLanding::WPMoveToBeachLanding(int zoneIndex, float radius, int map, int approachType, + int value24, + std::list >& waypoints, Bot* bot) + : m_map(map) + , m_approachType(approachType) + , m_inside(false) + , m_radius(atLeastFive(radius)) + , m_int24(value24) + , m_zone(AILandingZoneManager::m_instance->getAILandingZone(zoneIndex)) + , m_waypoints(waypoints) +{ + m_int0C = 7; + WPBeachLanding::storeLandingZone(bot, m_zone); // BotMain +0xE8 +} + +// ELF 0x1BA560 (C1; C2 0x1BA450): as above with the zone given. +WPMoveToBeachLanding::WPMoveToBeachLanding(AILandingZone* zone, float radius, int map, + int approachType, int value24, + std::list >& waypoints, Bot* bot) + : m_map(map) + , m_approachType(approachType) + , m_inside(false) + , m_radius(atLeastFive(radius)) + , m_int24(value24) + , m_zone(zone) + , m_waypoints(waypoints) +{ + m_int0C = 7; + WPBeachLanding::storeLandingZone(bot, m_zone); // BotMain +0xE8 +} + +// ELF 0x1BA6D0 (D1; D2 0x1BA670, D0 0x1BA730): the waypoint list. +WPMoveToBeachLanding::~WPMoveToBeachLanding() +{ +} + +// ELF 0x1BA7A0. While waypoints remain, the first is dropped when reached - within the larger of +// the ceil'd radius and the bot's equipment's smallest radius (IPIPhysical +13), in XZ - or when +// the bot is inside its strategic area; dropping sets +4 and clears the error. A waypoint whose +// area does not exist is dropped only on a waypoint error; one whose area the bot is outside of +// is re-randomised within the area (0.9) on an error, which clears it. The equipment's record +// and physical plug-in are not null-tested. Without waypoints, the zone as WPBeachLanding but +// "inside" is a squared distance below 10. Always 1. +float WPMoveToBeachLanding::getUrgency(const Vec3& position, Bot* bot) +{ + if (!m_waypoints.empty()) + { + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); // +0xD8 + IPIPhysical* const physical = equipment->getPhysical(); + const float radius = static_cast(std::ceil(static_cast(m_radius))); + const float smallest = physical->getSmallestRadius(); + float reach = radius > smallest ? radius : smallest; + reach = reach * reach; + const std::pair& front = m_waypoints.front(); + const float dx = position.x - front.first.x; + const float dz = position.z - front.first.z; + if (reach > dx * dx + dz * dz) + { + m_waypoints.erase(m_waypoints.begin()); + m_flag4 = true; + m_wayPointError = false; + } + else + { + AIStrategicArea* const area = + AIStrategicObjectManager::getInstance()->getStrategicArea(front.second); + if (area) + { + if (area->isInside(position)) + { + m_waypoints.erase(m_waypoints.begin()); + m_flag4 = true; + m_wayPointError = false; + } + else if (m_wayPointError) + { + area->randomizePos(bot->getSide(), 0.9f, m_waypoints.front().first); // +0xE0 + m_wayPointError = false; + } + } + else if (m_wayPointError) + { + m_waypoints.erase(m_waypoints.begin()); + m_flag4 = true; + m_wayPointError = false; + } + } + } + if (!m_waypoints.empty()) + return 1.0f; + + const bool wasInside = m_inside; + m_inside = 10.0f > m_zone->getDistanceSqr(position); + m_flag4 = m_inside != wasInside; + m_distanceSqr = m_inside ? 0.0f : m_zone->getDistanceSqr(position); + return 1.0f; +} + +// ELF 0x1BAA20: the first waypoint while any remain; then the beach position inside the zone, +// the approach position (10 m) outside it. +bool WPMoveToBeachLanding::getGoalPoint(Vec3& out) +{ + if (!m_waypoints.empty()) + { + out = m_waypoints.front().first; + return true; + } + if (m_inside) + return m_zone->getBeachPosition(m_map, out); + return m_zone->getApproachPosition(m_map, m_approachType, out, 10.0f); +} + +// ELF 0x1BAAC0 +bool WPMoveToBeachLanding::insideZone() +{ + return m_inside; +} + +// ELF 0x1BAAD0: distance^2 >= the last squared zone distance; unordered is false. +bool WPMoveToBeachLanding::closeToZone(float distance) +{ + return distance * distance >= m_distanceSqr; +} + +// ELF 0x1BAAF0 +void WPMoveToBeachLanding::getCoords(std::list& out) const +{ + for (std::list >::const_iterator it = m_waypoints.begin(); + it != m_waypoints.end(); ++it) + out.push_back(it->first); +} + +// ELF 0x1BAB70: the constructor's radius. +float WPMoveToBeachLanding::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h new file mode 100644 index 000000000..546b14fe6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.h @@ -0,0 +1,61 @@ +// A boat waypoint list that first runs through a list of (position, strategic area) waypoints and +// then approaches a landing zone and its beach, as WPBeachLanding does. +// Evidence: libaidll.so 1.5.3153 (ia-32). File WPMoveToBeachLanding.cpp (FILE symbol; the AIBot +// directory is [INFERRED] from its neighbours); vtable 0x4B73A0 (D1, D0, getUrgency, +// getGoalPoint, getId, WaypointList's setWayPointError / getWayPointError, getWayPointRadius). +// Constructors 0x1BA150 / 0x1BA320 (zone index) and 0x1BA450 / 0x1BA560 (zone); destructors +// 0x1BA670 / 0x1BA6D0 / 0x1BA730. No call site in the image constructs it, so the size is not +// attested; getId answers 4. + +#ifndef AI_AIDLL_AI_AIBOT_WPMOVETOBEACHLANDING_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPMOVETOBEACHLANDING_H + +#include +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class AILandingZone; + +class WPMoveToBeachLanding : public WaypointList +{ +public: + // `waypoints` is copied: each a position and the index of the strategic area it lies in. The + // radius is `radius`, at least 5. Both forms also store the zone into the bot (BotMain +0xE8). + WPMoveToBeachLanding(int zoneIndex, float radius, int map, int approachType, int value24, + std::list >& waypoints, Bot* bot); + WPMoveToBeachLanding(AILandingZone* zone, float radius, int map, int approachType, int value24, + std::list >& waypoints, Bot* bot); + virtual ~WPMoveToBeachLanding(); + + virtual float getUrgency(const Vec3& position, Bot* bot); // ELF 0x1BA7A0 + virtual bool getGoalPoint(Vec3& out); // ELF 0x1BAA20 + virtual int getId() { return 4; } // ELF 0x1BAC30 (weak) + virtual float getWayPointRadius() const; // ELF 0x1BAB70 + + bool insideZone(); // ELF 0x1BAAC0 + bool closeToZone(float distance); // ELF 0x1BAAD0 + // Appends the remaining waypoint positions to `out`. + void getCoords(std::list& out) const; // ELF 0x1BAAF0 + + // [INFERRED] names; the stores are attested. + /* +0x0C */ int m_int0C; // ctor 7 [UNRESOLVED] meaning (WPBeachLanding: 6) + /* +0x10 */ int m_map; // getBeachPosition / getApproachPosition first argument + /* +0x14 */ int m_approachType; // getApproachPosition second argument + /* +0x18 */ bool m_inside; // getUrgency: squared zone distance below 10 + /* +0x1C */ float m_radius; // waypoint reach radius (ceil'd) and getWayPointRadius + /* +0x20 */ float m_distanceSqr; // getUrgency; not initialised by the constructors + /* +0x24 */ int m_int24; // ctor argument [UNRESOLVED]; no reader in this TU + /* +0x28 */ AILandingZone* m_zone; + /* +0x2C */ std::list > m_waypoints; // (position, strategic area index) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPMOVETOBEACHLANDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp new file mode 100644 index 000000000..d4fa76218 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.cpp @@ -0,0 +1,82 @@ +// A closed patrol loop. Evidence: libaidll.so 1.5.3153 (ia-32), see WPPatrol.h. + +#include "WPPatrol.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1BB370, __tcf_0 0x1BB3D0, _GLOBAL__I 0x1BB400). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1BAC40 (C2; C1 0x1BADF0). The base fields, +8 = -1.0f, the clamp, +0x10 / +0x14, the empty +// list, +0xC = 8, a clear, then each point appended. +WPPatrol::WPPatrol(float radius, unsigned int flags, std::list& points) +{ + if (radius <= 5.0f) + radius = 5.0f; + m_radius = radius; + m_flags = flags; + m_int0C = 8; + m_points.clear(); + for (std::list::iterator it = points.begin(); it != points.end(); ++it) + m_points.insert(m_points.end(), *it); +} + +// ELF 0x1BAEF0 (C2; C1 0x1BAFD0). As above, from a vector. +WPPatrol::WPPatrol(float radius, unsigned int flags, std::vector& points) +{ + if (radius <= 5.0f) + radius = 5.0f; + m_radius = radius; + m_flags = flags; + m_int0C = 8; + m_points.clear(); + for (std::vector::iterator it = points.begin(); it != points.end(); ++it) + m_points.insert(m_points.end(), *it); +} + +// ELF 0x1BB0B0 (D2; D1 0x1BB110, D0 0x1BB170): the list, then the base vptr. +WPPatrol::~WPPatrol() +{ +} + +// ELF 0x1BB1E0. The test is radius^2 > distXZSqr(position, front); the front point is re-inserted +// at the end before the front is erased. +float WPPatrol::getUrgency(const Vec3& position, Bot*) +{ + if (m_wayPointError) + return 0.0f; + const float radiusSqr = m_radius * m_radius; + if (radiusSqr > distXZSqr(position, m_points.front())) + { + m_points.insert(m_points.end(), m_points.front()); + m_points.erase(m_points.begin()); + m_flag4 = true; + } + return 1.0f; +} + +// ELF 0x1BB2F0. +bool WPPatrol::getGoalPoint(Vec3& out) +{ + out = m_points.front(); + return true; +} + +// ELF 0x1BB330: list assignment. +void WPPatrol::getCoords(std::list& out) const +{ + out = m_points; +} + +// ELF 0x1BB360. +float WPPatrol::getWayPointRadius() const +{ + return m_radius; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h new file mode 100644 index 000000000..9c870302d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPPatrol.h @@ -0,0 +1,53 @@ +// A closed patrol loop: the bot walks to the front point; once within the radius the point is moved +// to the back of the list, so the loop repeats forever. +// Evidence: libaidll.so 1.5.3153 (ia-32). Placement AIBot/WPPatrol.cpp [INFERRED] from the +// neighbouring WPMoveTo / WPMoveToBeachLanding TUs (the static-init symbol names the WPPatrol +// constructor); vtable 0x4B73E0 (D1, D0, getUrgency, getGoalPoint, getId, then WaypointList's +// setWayPointError / getWayPointError, then getWayPointRadius); constructors 0x1BAC40 / 0x1BADF0 +// (list) and 0x1BAEF0 / 0x1BAFD0 (vector); destructors 0x1BB0B0 / 0x1BB110 / 0x1BB170. +// Size 0x1C (`operator new(0x1c)` in PatrolPath::botIsAlive 0x350BF0). + +#ifndef AI_AIDLL_AI_AIBOT_WPPATROL_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WPPATROL_H + +#include +#include + +#include "WaypointList.h" + +namespace dice { +namespace hfe { +namespace ai { + +class WPPatrol : public WaypointList +{ +public: + // Both constructors clamp the radius to at least 5 and copy the points in order. + WPPatrol(float radius, unsigned int flags, std::list& points); + WPPatrol(float radius, unsigned int flags, std::vector& points); + virtual ~WPPatrol(); + + // 0 with the waypoint error set; otherwise 1, after cycling the front point to the back when + // `position` is within the radius of it (XZ plane) and marking the step (+4). + virtual float getUrgency(const Vec3& position, Bot* bot); + // The front point; always true (an empty list is not checked). + virtual bool getGoalPoint(Vec3& out); + virtual int getId() { return 2; } // ELF 0x1BB420 (weak) + virtual float getWayPointRadius() const; + + // Replaces `out` with the patrol points. + void getCoords(std::list& out) const; + + // [INFERRED] names, as in WPMoveTo; the stores are attested. + // +0x08: WaypointList::m_float8 (base constructor: -1.0f) + /* +0x0C */ int m_int0C; // ctor 8 [UNRESOLVED] meaning + /* +0x10 */ float m_radius; + /* +0x14 */ unsigned int m_flags; // the second argument (PatrolPath passes 5) [UNRESOLVED] meaning + /* +0x18 */ std::list m_points; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WPPATROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h b/Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h new file mode 100644 index 000000000..123277c70 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WaypointList.h @@ -0,0 +1,54 @@ +// Abstract waypoint target a bot follows (WPMoveTo, WPEmpty, WPPatrol, ... derive from it). +// [INFERRED] Source placement; the class is inline in the ELF (weak symbols only). + +#ifndef AI_AIDLL_AI_AIBOT_WAYPOINTLIST_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIBOT_WAYPOINTLIST_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Bot; + +// vtable ELF 0x4b6f20: D1 0x1B6180 (vptr store only), D0 0x1B61A0, three pure slots (WPMoveTo +// 0x4b7360 names them getUrgency / getGoalPoint / getId), then the three accessors below. +// The base constructor is inlined into every subclass (WPEmpty::WPEmpty 0x1B9050 stores +// +4 = 1, +5 = 0, +6 = 0 before its own fields). +class WaypointList +{ +public: + WaypointList() + : m_flag4(true) + , m_flag5(false) + , m_wayPointError(false) + , m_float8(-1.0f) + { + } + virtual ~WaypointList() {} + + virtual float getUrgency(const Vec3& position, Bot* bot) = 0; // +0x08 [INFERRED] return type + virtual bool getGoalPoint(Vec3& out) = 0; // +0x0C bool: WPMoveTo 0x1B9F70 returns "not empty" + virtual int getId() = 0; // +0x10 WPMoveTo 1, WPEmpty 8 + // ELF 0x1B61E0 / 0x1B61F0: the byte at +6. + virtual void setWayPointError(bool error) { m_wayPointError = error; } // +0x14 + virtual bool getWayPointError() const { return m_wayPointError; } // +0x18 + // ELF 0x1B6200: the base radius is 0. + virtual float getWayPointRadius() const { return 0.0f; } // +0x1C + + // [UNRESOLVED] meaning of +4 and +5; SAI::updateBotPositions reads +5 inline. + /* 4 */ bool m_flag4; // base ctor: true + /* 5 */ bool m_flag5; // base ctor: false + /* 6 */ bool m_wayPointError; // base ctor: false + // Every subclass constructor stores -1.0f here before its own vptr store (the inlined base + // constructor); PatrolPath::botIsAlive stores the patrol speed. BBPGotoWaypoint3d::createPlan + // (0x27F7F6) reads it through the base pointer as the speed, the vehicle's maximum when < 0. + /* 8 */ float m_float8; // base ctor: -1.0f [INFERRED] meaning (speed override) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_WAYPOINTLIST_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp new file mode 100644 index 000000000..6f00113d8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp @@ -0,0 +1,99 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1CDA60 (__tcf_0 0x1CDAC0, _GLOBAL__I 0x1CDAF0): 's Init object only. +#include + +#include "BAPAAimAt.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSubObjects.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CD6E0 (C1; C2 0x1CD600). Vec3 members zeroed, the Aimer default-constructed, the ring +// cleared; +0x80..+0xA0 and +0x140/+0x144 are left alone. +BAPAAimAt::BAPAAimAt() +{ + m_offset.x = m_offset.y = m_offset.z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec20[i].x = m_vec20[i].y = m_vec20[i].z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec50[i].x = m_vec50[i].y = m_vec50[i].z = 0.0f; + m_pitchIndex = 0; + m_int148 = 0; + m_overrideValid = 0; + m_overrideAim = 0; + m_lastYawError = 0.0f; + for (int i = 0; i < 10; ++i) + m_pitchErrors[i] = 0.0f; +} + +// ELF 0x1CD8E0 (C1; C2 0x1CD7E0) +BAPAAimAt::BAPAAimAt(BAPVariable* overrideValid, BAPVariable* overrideAim) +{ + m_offset.x = m_offset.y = m_offset.z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec20[i].x = m_vec20[i].y = m_vec20[i].z = 0.0f; + for (int i = 0; i < 4; ++i) + m_vec50[i].x = m_vec50[i].y = m_vec50[i].z = 0.0f; + m_pitchIndex = 0; + m_lastYawError = 0.0f; + m_int148 = 0; + m_overrideValid = overrideValid; + m_overrideAim = overrideAim; + for (int i = 0; i < 10; ++i) + m_pitchErrors[i] = 0.0f; +} + +// ELF 0x1CDB40 (D1; D0 0x1CDBA0): the Aimer and the base only; the end condition belongs to the +// subclasses. +BAPAAimAt::~BAPAAimAt() +{ +} + +// ELF 0x1CD5C0: never executed directly (the plan interpreter's entry does the aiming). +bool BAPAAimAt::execute(Bot*, bool& ok, bool& done) +{ + ok = false; + done = true; + return false; +} + +// ELF 0x1CDB20 +BAPStatementType BAPAAimAt::getId() const +{ + return BAPSTAimAt; // 6 +} + +// ELF 0x1CDB30 +bool BAPAAimAt::hasDefault() +{ + return false; +} + +// ELF 0x1CD9E0: mean of the ten ring entries (x87 sum, then * 0.1). +float BAPAAimAt::getAveragePitchAngle() +{ + double sum = 0.0; + for (int i = 0; i < 10; ++i) + sum += m_pitchErrors[i]; + return static_cast(sum * static_cast(0.1f)); // fmuls: the float constant +} + +// ELF 0x1CDA20: `mov 0xb4(bot)` = BotMain::m_fireCorrection; zeroes its +0x2C Vec3 and returns it +// (`lea 0x2c(%edx), %eax`). The aim actions add it to the relative target position and subtract +// it from the prediction. +Vec3& BAPAAimAt::correctAim(Bot* bot) +{ + Vec3& correction = static_cast(bot)->getFireCorrection()->m_vec44; + correction.x = 0.0f; + correction.y = 0.0f; + correction.z = 0.0f; + return correction; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h new file mode 100644 index 000000000..470637754 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h @@ -0,0 +1,73 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "../AIBot/Aimer.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7780 (17 words), package C-actions. +// Layout from the constructors 0x1CD6E0 / 0x1CD8E0 and the subclasses (BAPAAimAtObject 0x1CE650, +// BAPAAimAtPoint 0x1CFE90); sizeof 0x154. Fields are public: B's EntryMouseTurretAimAt (0x2B9700) +// reads/writes +0xA0, +0x110, +0x114 and +0x13C inline. +class BAPAAimAt : public BAPAction +{ +public: + BAPAAimAt(); // 0x1CD6E0 + BAPAAimAt(BAPVariable*, BAPVariable*); // 0x1CD8E0 + virtual ~BAPAAimAt(); // 0x1CDB40 + + virtual bool execute(Bot*, bool&, bool&); // 0x1CD5C0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1CDB20, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1CDB30, slot +0x14; from the base declaration + virtual int getAimAtType() = 0; // no body, slot +0x20; Object 1, Point 0 + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool, Bot*) = 0; // no body, slot +0x24 + virtual bool getVectorToTarget(const Vec3&, Vec3&) const = 0; // no body, slot +0x28; ELF bool (EntryMouseTurretAimAt 0x2B9985 tests al) + virtual const Mat4* getAimerTransform() const = 0; // no body, slot +0x2C; `lea 0x174(this)` + virtual bool isAimingValid() const = 0; // no body, slot +0x30 + virtual bool getLastAimVec(Vec3&) const = 0; // no body, slot +0x34 + virtual bool getPredictedPosition(Vec3&) const = 0; // no body, slot +0x38 + virtual bool getImpactTime(double&) const = 0; // no body, slot +0x3C + virtual bool getImpactPosition(Vec3&, double) const = 0; // no body, slot +0x40; Aimer::getImpactPosition's bool + + float getAveragePitchAngle(); // 0x1CD9E0 + Vec3& correctAim(Bot*); // 0x1CDA20: zeroes and returns FireCorrectionData +0x2C + + /* +0x14 */ Vec3 m_offset; // = 0; the subclasses store their aim offset + /* +0x20 */ Vec3 m_vec20[4]; // = 0; [UNRESOLVED] not read by C's bodies + /* +0x50 */ Vec3 m_vec50[4]; // = 0; [UNRESOLVED] not read by C's bodies + /* +0x80 */ char m_gap80[0x18]; // [UNRESOLVED] not written by any constructor + /* +0x98 */ double m_double98; // subclasses: -5e9; [UNRESOLVED] not read by C's bodies + /* +0xA0 */ BAPCondition* m_endCondition; // owned by the subclasses (their destructors delete it) + /* +0xA4 */ Aimer m_aimer; + /* +0x110 */ float m_lastYawError; // = 0; EntryMouseTurretAimAt writes pi when idle + /* +0x114 */ float m_pitchErrors[10]; // = 0; ring, getAveragePitchAngle averages it + /* +0x13C */ int m_pitchIndex; // = 0; ring index + /* +0x140 */ int m_int140; // subclasses: 0; [UNRESOLVED] + /* +0x144 */ int m_unwritten144; // [UNRESOLVED] not written + /* +0x148 */ int m_int148; // = 0; [UNRESOLVED] + /* +0x14C */ BAPVariable* m_overrideValid; // with m_overrideAim: BAPAAimAtObject::getAimVec takes them + /* +0x150 */ BAPVariable* m_overrideAim; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp new file mode 100644 index 000000000..b4be9a034 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp @@ -0,0 +1,147 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1CE1D0 (__tcf_0 0x1CE230, _GLOBAL__I 0x1CE260): 's Init object only. +#include + +#include "BAPAAimAt3d.h" + +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The weapon transform's third and fourth rows (+0xEC forward, +0xFC position), passed by address. +// [CHOSEN, not recovered] spelling of the image's `this + 0xEC` / `this + 0xFC`. +const Vec3& forwardOf(const Mat4& transform) +{ + return *reinterpret_cast(&transform.m[8]); +} + +const Vec3& positionOf(const Mat4& transform) +{ + return *reinterpret_cast(&transform.m[12]); +} + +void addTo(Vec3& v, const Vec3& add) +{ + v.x = add.x + v.x; + v.y = add.y + v.y; + v.z = add.z + v.z; +} + +} // namespace + +// ELF 0x1CDE70 (C1; C2 0x1CDC90). m_condition, m_impactTime and the subclass members are left +// to the subclass constructors, as compiled. +BAPAAimAt3d::BAPAAimAt3d() +{ + m_offset = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vec24 = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_vec30 = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_vec3C = bapinline::vec3(0.0f, 1.0f, 0.0f); + for (int i = 0; i < 4; ++i) + m_vecs48[i] = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 4; ++i) + m_vecs78[i] = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vecA8 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_lastAimVec = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_predictedPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 16; ++i) + m_aimerTransform.m[i] = 0.0f; + m_aimerTransform.m[0] = m_aimerTransform.m[5] = m_aimerTransform.m[10] = m_aimerTransform.m[15] = 1.0f; + m_aimVecValid = false; + m_int1C4 = 0; + for (int i = 0; i < 4; ++i) + m_floats1AC[i] = 0.0f; + m_vec1C8 = bapinline::vec3(0.0f, 0.0f, 1.0f); +} + +// ELF 0x1CE360 (weak; D0 0x1CE3C0): the Aimer member, then BAPStatement's destructor. +BAPAAimAt3d::~BAPAAimAt3d() +{ +} + +// ELF 0x1CDC70. Only an interpreter entry (EntryHeliAimAt, ...) can execute an aim: on its own +// the statement fails at once. +bool BAPAAimAt3d::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1CE280 (weak) +BAPStatementType BAPAAimAt3d::getId() const +{ + return BAPSTAimAt; +} + +// ELF 0x1CE290 (weak) +bool BAPAAimAt3d::hasDefault() +{ + return false; +} + +// ELF 0x1CE2A0 (weak) +const Mat4& BAPAAimAt3d::getAimerTransform() const +{ + return m_aimerTransform; +} + +// ELF 0x1CE2B0 (weak) +bool BAPAAimAt3d::isAimVecValid() const +{ + return m_aimVecValid; +} + +// ELF 0x1CE2C0 (weak) +bool BAPAAimAt3d::getLastAimVec(Vec3& aimVec) +{ + aimVec = m_lastAimVec; + return m_aimVecValid; +} + +// ELF 0x1CE300 (weak) +bool BAPAAimAt3d::getPredictedPosition(Vec3& position) const +{ + position = m_predictedPosition; + return m_aimVecValid; +} + +// ELF 0x1CE340 (weak) +bool BAPAAimAt3d::getImpactTime(double& time) const +{ + time = m_impactTime; + return m_aimVecValid; +} + +// ELF 0x1CE050. The impact point `time` seconds after firing along the weapon's forward axis, in +// world space. +bool BAPAAimAt3d::getImpactPosition(Vec3& position, double time) const +{ + const bool result = m_aimer.getImpactPosition(position, forwardOf(m_aimerTransform), static_cast(time)); + addTo(position, positionOf(m_aimerTransform)); + return result; +} + +// ELF 0x1CE0D0. The point of the forward-axis trajectory nearest the target, in world space. +bool BAPAAimAt3d::getNearestImpactPosition(Vec3& position, double& time) const +{ + const bool result = m_aimer.getNearestImpactPoint(forwardOf(m_aimerTransform), position, time); + addTo(position, positionOf(m_aimerTransform)); + return result; +} + +// ELF 0x1CE150. The target's predicted position `time` seconds from now, in world space. +void BAPAAimAt3d::getPredictedPosition(double time, Vec3& position) const +{ + m_aimer.getPredictedTargetPosition(bapinline::gameTime() + time, position); + addTo(position, positionOf(m_aimerTransform)); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h new file mode 100644 index 000000000..299764dcc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h @@ -0,0 +1,88 @@ +// Base of the 3d aim actions (aircraft and helicopter weapons): the plan statement the vehicle aim +// entries (EntryHeliAimAt, ...) execute. It keeps the aimer's ballistic state for the precision +// conditions (BAPCConPrecision3d, BAPCConBombPrecision3d). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT3D_H + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/Aimer.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7800 (19 words), package G-vehicles. Object size 0x1D4 (the subclasses add from +// +0x1D4). Member names are [INFERRED]; members only the entries use are [UNRESOLVED] by meaning +// and carry their constructed values. +class BAPAAimAt3d : public BAPAction +{ +public: + BAPAAimAt3d(); // 0x1CDE70 + virtual ~BAPAAimAt3d(); // 0x1CE360 (weak) + + virtual bool execute(Bot*, bool&, bool&); // 0x1CDC70, slot +0x00 + virtual BAPStatementType getId() const; // 0x1CE280, slot +0x10 (weak): AimAt + virtual bool hasDefault(); // 0x1CE290, slot +0x14 (weak): false + virtual int getAimAtType() = 0; // no body, slot +0x20: 1 object, 0 point + // Target position minus `from`; false when the target has no information. + virtual bool getVectorToTarget(const Vec3& from, Vec3& vector) const = 0; // no body, slot +0x24 + // Feeds the aimer with the weapon transform and velocities and solves the firing direction + // (Aimer::getFiringDirection); returns, and stores, whether it found one. + virtual bool getAimVec(const Mat4& transform, const Vec3& shooterVelocity, Vec3& direction, float accuracy, + float drag, float speed, float gravityScale, bool highArc) = 0; // no body, slot +0x28 + // The return types of the slots below follow their bodies (this + 0xCC, the +0x114 flag, the + // Aimer results); the skeleton's int/void were wrong. + virtual const Mat4& getAimerTransform() const; // 0x1CE2A0, slot +0x2C (weak); [INFERRED] reference + virtual bool isAimVecValid() const; // 0x1CE2B0, slot +0x30 (weak) + virtual bool getLastAimVec(Vec3&); // 0x1CE2C0, slot +0x34 (weak) + virtual bool getPredictedPosition(Vec3&) const; // 0x1CE300, slot +0x38 (weak) + virtual bool getImpactTime(double&) const; // 0x1CE340, slot +0x3C (weak) + virtual bool getImpactPosition(Vec3&, double) const; // 0x1CE050, slot +0x40 + virtual bool getNearestImpactPosition(Vec3&, double&) const; // 0x1CE0D0, slot +0x44 + virtual void getPredictedPosition(double, Vec3&) const; // 0x1CE150, slot +0x48 + +protected: + // [INFERRED] friendship: EntryHeliAimAt reads/writes +0x14/+0x24..+0x3C/+0xA8/+0x1A4..+0x1D0 inline (ELF 0x2B5420). + friend class EntryHeliAimAt; + // [INFERRED] friendship: EntryPlaneAimAt reads/writes +0x14/+0x24..+0x3C/+0xA8/+0x1A4..+0x1B8 inline (ELF 0x2BFC70). + friend class EntryPlaneAimAt; + /* +0x014 */ BAPCondition* m_condition; // the subclass constructors' condition; deleted by them + /* +0x018 */ Vec3 m_offset; // aim offset (subclass constructors) + /* +0x024 */ Vec3 m_vec24; // [INFERRED] equipment facing; EntryHeliAimAt + /* +0x030 */ Vec3 m_vec30; // [INFERRED] equipment right axis; EntryHeliAimAt + /* +0x03C */ Vec3 m_vec3C; // [INFERRED] equipment up axis; EntryHeliAimAt + /* +0x048 */ Vec3 m_vecs48[4]; // [UNRESOLVED] constructed zero + /* +0x078 */ Vec3 m_vecs78[4]; // [UNRESOLVED] constructed zero + /* +0x0A8 */ Vec3 m_vecA8; // [INFERRED] previous velocity sample; EntryHeliAimAt + /* +0x0B4 */ Vec3 m_lastAimVec; // getAimVec's direction + /* +0x0C0 */ Vec3 m_predictedPosition; // getFiringDirection's target, in world space + /* +0x0CC */ Mat4 m_aimerTransform; // the weapon transform of the last getAimVec; identity + /* +0x10C */ double m_impactTime; // getFiringDirection's impact time (not constructed) + /* +0x114 */ bool m_aimVecValid; // getAimVec's result + /* +0x118 */ Aimer m_aimer; + /* +0x184 */ char m_unknown184[0x18]; // [UNRESOLVED] not touched by the AimAt3d family + /* +0x19C */ double m_double19C; // [UNRESOLVED] subclass constructors: -5e9 + /* +0x1A4 */ float m_float1A4; // [UNRESOLVED] the subclass constructors' first float + /* +0x1A8 */ float m_float1A8; // [UNRESOLVED] their second float + /* +0x1AC */ float m_floats1AC[4]; // [INFERRED] yaw error, pitch error, unresolved, equipment height; EntryHeliAimAt + /* +0x1BC */ int m_int1BC; // [UNRESOLVED] subclass constructors: 0 + /* +0x1C0 */ int m_unknown1C0; // [UNRESOLVED] not constructed + /* +0x1C4 */ int m_int1C4; // [UNRESOLVED] constructed 0 (again by the subclasses) + /* +0x1C8 */ Vec3 m_vec1C8; // [INFERRED] previous steering direction; EntryHeliAimAt +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMAT3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp new file mode 100644 index 000000000..19ef27cb7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp @@ -0,0 +1,205 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1CF280 (__tcf_0 0x1CF2E0, _GLOBAL__I 0x1CF310): 's Init object only. +#include + +#include "BAPAAimAtObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CE650 (C1; C2 0x1CE3B0). The isPrimary/getPrimaryObject pairs on the bot's equipment and +// on the target are evaluated and their answers dropped, as in the image (neither information is +// null-checked there). +BAPAAimAtObject::BAPAAimAtObject(Bot* bot, unsigned int target, const Vec3& offset, BAPCondition* endCondition, + unsigned long long controls, int patternId, bool useCenter, + BAPVariable* overrideValid, BAPVariable* overrideAim) + : BAPAAimAt(overrideValid, overrideAim) +{ + m_bot = bot; + m_target = target; + m_lastAim = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 16; ++i) + m_aimerTransform.m[i] = 0.0f; + m_aimerTransform.m[15] = 1.0f; + m_aimerTransform.m[10] = 1.0f; + m_aimerTransform.m[5] = 1.0f; + m_aimerTransform.m[0] = 1.0f; + m_valid = false; + m_useCenter = useCenter; + + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self->isPrimary()) + self->getPrimaryObject(bot->getSide()); + Information* info = bapinline::info(target); + if (!info->isPrimary()) + info->getPrimaryObject(bot->getSide()); + + m_offset = offset; + m_endCondition = endCondition; + endCondition->setOwner(this); + m_patternId = patternId; + m_int140 = 0; + m_controls = controls; + m_int148 = 0; + m_double98 = -5000000000.0; +} + +// ELF 0x1CE8F0 (D1; D0 0x1CE970): deletes the end condition (virtual destructor, slot +0x10). +BAPAAimAtObject::~BAPAAimAtObject() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1CF330 +int BAPAAimAtObject::getAimAtType() +{ + return 1; +} + +// ELF 0x1CEA00. With both override variables set their values win. Otherwise the target point is +// the sensed hit point (Bot slot +0x94 getSensedObjectFromHandle, +0x04, through the target's +// transformation) or, when the target is not sensed and m_useCenter is set, its position; not +// sensed without m_useCenter, or no target information: false. The Aimer gets the drag, speed and +// scaled gravity, the target relative to the weapon origin (plus the offset and the bot's fire +// correction) and the target's velocity (its own mobile, else its primary object's). +bool BAPAAimAtObject::getAimVec(const Mat4& origin, const Vec3& ownSpeed, Vec3& dir, float accuracy, float drag, + float speed, float gravityModifier, bool highArc, Bot* bot) +{ + if (m_overrideValid && m_overrideAim) { + dir = m_overrideAim->m_value; + m_lastAim = dir; + m_valid = m_overrideValid->m_value; + return m_overrideValid->m_value; + } + + Vec3 rel = bapinline::vec3(0.0f, 0.0f, 0.0f); + const Vec3& correction = correctAim(bot); + Information* target = bapinline::info(m_target); + if (!target) + return false; + m_bot->getCurrentEquipment(); // answer dropped (0x1CEB5x) + m_aimerTransform = origin; + + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + Vec3 point; + SensedObject* sensed = m_bot->getSensedObjectFromHandle(m_target); + if (!sensed) { + if (!m_useCenter) + return false; + point = target->getPosition(); + } else { + const Mat4& t = target->getAIObject()->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + point.x = t.m[0] * l.x + t.m[4] * l.y + t.m[8] * l.z + t.m[12]; // 0x1CECE8..0x1CED09 + point.y = t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13]; + point.z = l.x * t.m[2] + l.y * t.m[6] + l.z * t.m[10] + t.m[14]; + } + + const float ox = m_aimerTransform.m[12]; + const float oy = m_aimerTransform.m[13]; + const float oz = m_aimerTransform.m[14]; + rel.x = (point.x - ox) + m_offset.x + correction.x; + rel.y = (point.y - oy) + m_offset.y + correction.y; + rel.z = (point.z - oz) + m_offset.z + correction.z; + + Vec3 velocity; + IPIMobile* mobile = target->getMobile(); + if (!mobile && !target->isPrimary()) { + Information* primary = bapinline::info(target->getPrimaryObject(m_bot->getSide())); + if (primary) + mobile = primary->getMobile(); + } + if (mobile) + velocity = mobile->getSpeed(); + else + velocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + + m_aimer.setTargetData(rel, velocity, ownSpeed, &m_aimerTransform, bapinline::gameTime()); + m_valid = m_aimer.getFiringDirection(bapinline::gameTime(), accuracy, highArc, m_lastAim, m_predicted, + &m_impactTime); + // Back to world space; the correction comes off again. + m_predicted.x = (m_aimerTransform.m[12] + m_predicted.x) - correction.x; + m_predicted.y = (m_aimerTransform.m[13] + m_predicted.y) - correction.y; + m_predicted.z = (m_aimerTransform.m[14] + m_predicted.z) - correction.z; + dir = m_lastAim; + return m_valid; +} + +// ELF 0x1CF060: target position - from; false (out untouched) without the target information. +bool BAPAAimAtObject::getVectorToTarget(const Vec3& from, Vec3& out) const +{ + Information* target = bapinline::info(m_target); + if (target) + out = bapinline::sub(target->getPosition(), from); + return target != 0; +} + +// ELF 0x1CF1F0 +const Mat4* BAPAAimAtObject::getAimerTransform() const +{ + return &m_aimerTransform; +} + +// ELF 0x1CF130 +bool BAPAAimAtObject::isAimingValid() const +{ + return m_valid; +} + +// ELF 0x1CF140 +bool BAPAAimAtObject::getLastAimVec(Vec3& out) const +{ + if (m_valid) + out = m_lastAim; + return m_valid; +} + +// ELF 0x1CF180 +bool BAPAAimAtObject::getPredictedPosition(Vec3& out) const +{ + if (m_valid) + out = m_predicted; + return m_valid; +} + +// ELF 0x1CF1C0 +bool BAPAAimAtObject::getImpactTime(double& out) const +{ + if (m_valid) + out = m_impactTime; + return m_valid; +} + +// ELF 0x1CF200: the Aimer's impact position along the transform's row 2 (+0x194), made absolute. +bool BAPAAimAtObject::getImpactPosition(Vec3& out, double time) const +{ + Vec3 forward = bapinline::vec3(m_aimerTransform.m[8], m_aimerTransform.m[9], m_aimerTransform.m[10]); + const bool result = m_aimer.getImpactPosition(out, forward, static_cast(time)); + out.x = m_aimerTransform.m[12] + out.x; + out.y = m_aimerTransform.m[13] + out.y; + out.z = m_aimerTransform.m[14] + out.z; + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.h new file mode 100644 index 000000000..1af38e483 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.h @@ -0,0 +1,54 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7860 (17 words), package C-actions. +class BAPAAimAtObject : public BAPAAimAt +{ +public: + BAPAAimAtObject(Bot*, unsigned int, const Vec3&, BAPCondition*, unsigned long long, int, bool, BAPVariable*, BAPVariable*); // 0x1CE650 + virtual ~BAPAAimAtObject(); // 0x1CE8F0 + + virtual int getAimAtType(); // 0x1CF330, slot +0x20; from the base declaration + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool, Bot*); // 0x1CEA00, slot +0x24; from the base declaration + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1CF060, slot +0x28; from the base declaration + virtual const Mat4* getAimerTransform() const; // 0x1CF1F0, slot +0x2C; from the base declaration + virtual bool isAimingValid() const; // 0x1CF130, slot +0x30; from the base declaration + virtual bool getLastAimVec(Vec3&) const; // 0x1CF140, slot +0x34; from the base declaration + virtual bool getPredictedPosition(Vec3&) const; // 0x1CF180, slot +0x38; from the base declaration + virtual bool getImpactTime(double&) const; // 0x1CF1C0, slot +0x3C; from the base declaration + virtual bool getImpactPosition(Vec3&, double) const; // 0x1CF200, slot +0x40; from the base declaration + + /* +0x154 */ Bot* m_bot; + /* +0x158 */ unsigned int m_target; // information handle + /* +0x15C */ Vec3 m_lastAim; // getFiringDirection's direction + /* +0x168 */ Vec3 m_predicted; // getFiringDirection's target, made absolute + /* +0x174 */ Mat4 m_aimerTransform; // = identity; getAimVec copies the weapon's origin + /* +0x1B4 */ double m_impactTime; + /* +0x1BC */ bool m_valid; // = false; getFiringDirection's answer + /* +0x1BD */ bool m_useCenter; // ctor bool: no sensed hit point, aim at the position +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp new file mode 100644 index 000000000..051a0956d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp @@ -0,0 +1,119 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1CFC90 (__tcf_0 0x1CFCF0, _GLOBAL__I 0x1CFD20): 's Init object only. +#include + +#include "BAPAAimAtObject3d.h" + +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CF410 (C1; C2 0x1CF340). The condition's owner is set without a null test, as compiled. +BAPAAimAtObject3d::BAPAAimAtObject3d(Bot* bot, unsigned int target, const Vec3& offset, BAPCondition* condition, + unsigned long long controls, int patternId, float float1A4, float float1A8) +{ + m_bot = bot; + m_target = target; + m_float1A4 = float1A4; + m_float1A8 = float1A8; + m_offset = offset; + m_condition = condition; + condition->setOwner(this); + m_patternId = patternId; + m_int1BC = 0; + m_controls = controls; + m_int1C4 = 0; + m_double19C = static_cast(-5000000000.0f); +} + +// ELF 0x1CF560 (D1 0x1CF4E0, D0 0x1CF5E0) +BAPAAimAtObject3d::~BAPAAimAtObject3d() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1CFD40 +int BAPAAimAtObject3d::getAimAtType() +{ + return 1; +} + +// ELF 0x1CFBC0 +bool BAPAAimAtObject3d::getVectorToTarget(const Vec3& from, Vec3& vector) const +{ + Information* const target = bapinline::info(m_target); + if (target) + vector = bapinline::sub(target->getPosition(), from); + return target != 0; +} + +// ELF 0x1CF660. Refuses a slow projectile (speed at most 0.1) from a nearly resting shooter. The +// target point is the bot's sensed point on the object, in the object's current transformation, +// or else the object's position; its velocity is the object's IPIMobile speed, or that of its +// primary object for the bot's side, or zero. +bool BAPAAimAtObject3d::getAimVec(const Mat4& transform, const Vec3& shooterVelocity, Vec3& direction, + float accuracy, float drag, float speed, float gravityScale, bool highArc) +{ + if (speed <= 0.1f && bapinline::lengthSqr(shooterVelocity) <= 0.01f) + return false; + Bot* const bot = m_bot; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + Information* const target = bapinline::info(m_target); + if (!target) + return false; + + m_aimerTransform = transform; + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity() * gravityScale; + + Vec3 targetPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (SensedObject* const sensed = bot->getSensedObjectFromHandle(m_target)) + { + const Mat4& t = target->getAIObject()->getTransformation(); + const Vec3& p = sensed->m_seenPosition; + targetPosition.x = t.m[0] * p.x + t.m[4] * p.y + t.m[8] * p.z + t.m[12]; + targetPosition.y = t.m[1] * p.x + t.m[5] * p.y + t.m[9] * p.z + t.m[13]; + targetPosition.z = t.m[2] * p.x + t.m[6] * p.y + t.m[10] * p.z + t.m[14]; + } + else + { + targetPosition = target->getPosition(); + } + const Vec3 relative = bapinline::sub(targetPosition, *reinterpret_cast(&m_aimerTransform.m[12])); + + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + IPIMobile* mobile = target->getMobile(); + if (!mobile && !target->isPrimary()) + { + if (Information* const primary = bapinline::info(target->getPrimaryObject(m_bot->getSide()))) + mobile = primary->getMobile(); + } + if (mobile) + targetVelocity = mobile->getSpeed(); + + m_aimer.setTargetData(relative, targetVelocity, shooterVelocity, &transform, timer->getGameTime()); + m_aimVecValid = m_aimer.getFiringDirection(timer->getGameTime(), accuracy, highArc, direction, + m_predictedPosition, &m_impactTime); + m_lastAimVec = direction; + m_predictedPosition.x = m_aimerTransform.m[12] + m_predictedPosition.x; + m_predictedPosition.y = m_aimerTransform.m[13] + m_predictedPosition.y; + m_predictedPosition.z = m_aimerTransform.m[14] + m_predictedPosition.z; + return m_aimVecValid; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.h new file mode 100644 index 000000000..8d272f1b8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.h @@ -0,0 +1,45 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT3D_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt3d.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7900 (19 words), package G-vehicles. +// Aims at an information object: its position, or the bot's sensed point on it, with its velocity +// (or its primary object's). +class BAPAAimAtObject3d : public BAPAAimAt3d +{ +public: + BAPAAimAtObject3d(Bot*, unsigned int, const Vec3&, BAPCondition*, unsigned long long, int, float, float); // 0x1CF410 + virtual ~BAPAAimAtObject3d(); // 0x1CF560 + + virtual int getAimAtType(); // 0x1CFD40, slot +0x20 + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1CFBC0, slot +0x24 + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool); // 0x1CF660, slot +0x28 + +private: + // [INFERRED] friendship: EntryHeliAimAt reads +0x1D8 inline (ELF 0x2B5420). + friend class EntryHeliAimAt; + // [INFERRED] friendship: EntryPlaneAimAt reads +0x1D8 inline (ELF 0x2BFC70). + friend class EntryPlaneAimAt; + /* +0x1D4 */ Bot* m_bot; + /* +0x1D8 */ unsigned int m_target; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATOBJECT3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp new file mode 100644 index 000000000..c9f583910 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp @@ -0,0 +1,148 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D06B0 (__tcf_0 0x1D0710, _GLOBAL__I 0x1D0740): 's Init object only. +#include + +#include "BAPAAimAtPoint.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CFE90 (C1; C2 0x1CFC50) +BAPAAimAtPoint::BAPAAimAtPoint(Bot* bot, BAPVariable* point, const Vec3& offset, BAPCondition* endCondition, + unsigned long long controls, int patternId, BAPVariable* overrideValid, + BAPVariable* overrideAim) + : BAPAAimAt(overrideValid, overrideAim) +{ + m_point = point; + m_lastAim = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_bot = bot; + m_predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 16; ++i) + m_aimerTransform.m[i] = 0.0f; + m_aimerTransform.m[15] = 1.0f; + m_aimerTransform.m[10] = 1.0f; + m_aimerTransform.m[5] = 1.0f; + m_aimerTransform.m[0] = 1.0f; + m_valid = false; + m_offset = offset; + m_endCondition = endCondition; + endCondition->setOwner(this); + m_patternId = patternId; + m_double98 = -5000000000.0; + m_controls = controls; + m_int140 = 0; + m_int148 = 0; +} + +// ELF 0x1D0050 (D1; D0 0x1D00D0): deletes the end condition. +BAPAAimAtPoint::~BAPAAimAtPoint() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D0760 +int BAPAAimAtPoint::getAimAtType() +{ + return 0; +} + +// ELF 0x1D0160. Like BAPAAimAtObject::getAimVec for the point variable, without the override +// variables, with a zero target velocity and the caller's origin matrix (not the copy) handed to +// setTargetData. The bot's equipment is read and dropped first, as in the image. +bool BAPAAimAtPoint::getAimVec(const Mat4& origin, const Vec3& ownSpeed, Vec3& dir, float accuracy, float drag, + float speed, float gravityModifier, bool highArc, Bot* bot) +{ + Vec3 rel = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_bot->getCurrentEquipment(); // answer dropped + const Vec3& correction = correctAim(bot); + m_aimerTransform = origin; + + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag == 0.0f ? 0.0f : 1.0f / drag; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + const Vec3& p = m_point->m_value; + rel.x = (p.x - m_aimerTransform.m[12]) + m_offset.x + correction.x; + rel.y = (p.y - m_aimerTransform.m[13]) + m_offset.y + correction.y; + rel.z = (p.z - m_aimerTransform.m[14]) + m_offset.z + correction.z; + + const double now = bapinline::gameTime(); + const Vec3 velocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aimer.setTargetData(rel, velocity, ownSpeed, &origin, now); + m_valid = m_aimer.getFiringDirection(bapinline::gameTime(), accuracy, highArc, m_lastAim, m_predicted, + &m_impactTime); + m_predicted.x = (m_aimerTransform.m[12] + m_predicted.x) - correction.x; + m_predicted.y = (m_aimerTransform.m[13] + m_predicted.y) - correction.y; + m_predicted.z = (m_aimerTransform.m[14] + m_predicted.z) - correction.z; + dir = m_lastAim; + return m_valid; +} + +// ELF 0x1D04E0: always true. +bool BAPAAimAtPoint::getVectorToTarget(const Vec3& from, Vec3& out) const +{ + out = bapinline::sub(m_point->m_value, from); + return true; +} + +// ELF 0x1D0620 +const Mat4* BAPAAimAtPoint::getAimerTransform() const +{ + return &m_aimerTransform; +} + +// ELF 0x1D0560 +bool BAPAAimAtPoint::isAimingValid() const +{ + return m_valid; +} + +// ELF 0x1D0570 +bool BAPAAimAtPoint::getLastAimVec(Vec3& out) const +{ + if (m_valid) + out = m_lastAim; + return m_valid; +} + +// ELF 0x1D05B0 +bool BAPAAimAtPoint::getPredictedPosition(Vec3& out) const +{ + if (m_valid) + out = m_predicted; + return m_valid; +} + +// ELF 0x1D05F0 +bool BAPAAimAtPoint::getImpactTime(double& out) const +{ + if (m_valid) + out = m_impactTime; + return m_valid; +} + +// ELF 0x1D0630: as BAPAAimAtObject::getImpactPosition. +bool BAPAAimAtPoint::getImpactPosition(Vec3& out, double time) const +{ + Vec3 forward = bapinline::vec3(m_aimerTransform.m[8], m_aimerTransform.m[9], m_aimerTransform.m[10]); + const bool result = m_aimer.getImpactPosition(out, forward, static_cast(time)); + out.x = m_aimerTransform.m[12] + out.x; + out.y = m_aimerTransform.m[13] + out.y; + out.z = m_aimerTransform.m[14] + out.z; + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h new file mode 100644 index 000000000..769ae5790 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B79A0 (17 words), package C-actions. +class BAPAAimAtPoint : public BAPAAimAt +{ +public: + BAPAAimAtPoint(Bot*, BAPVariable*, const Vec3&, BAPCondition*, unsigned long long, int, BAPVariable*, BAPVariable*); // 0x1CFE90 + virtual ~BAPAAimAtPoint(); // 0x1D0050 + + virtual int getAimAtType(); // 0x1D0760, slot +0x20; from the base declaration + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool, Bot*); // 0x1D0160, slot +0x24; from the base declaration + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1D04E0, slot +0x28; from the base declaration + virtual const Mat4* getAimerTransform() const; // 0x1D0620, slot +0x2C; from the base declaration + virtual bool isAimingValid() const; // 0x1D0560, slot +0x30; from the base declaration + virtual bool getLastAimVec(Vec3&) const; // 0x1D0570, slot +0x34; from the base declaration + virtual bool getPredictedPosition(Vec3&) const; // 0x1D05B0, slot +0x38; from the base declaration + virtual bool getImpactTime(double&) const; // 0x1D05F0, slot +0x3C; from the base declaration + virtual bool getImpactPosition(Vec3&, double) const; // 0x1D0630, slot +0x40; from the base declaration + + /* +0x154 */ BAPVariable* m_point; + /* +0x158 */ Bot* m_bot; + /* +0x15C */ Vec3 m_lastAim; + /* +0x168 */ Vec3 m_predicted; + /* +0x174 */ Mat4 m_aimerTransform; // = identity + /* +0x1B4 */ double m_impactTime; + /* +0x1BC */ bool m_valid; // = false +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp new file mode 100644 index 000000000..41b38631d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp @@ -0,0 +1,84 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1D0D50 (__tcf_0 0x1D0DB0, _GLOBAL__I 0x1D0DE0): 's Init object only. +#include + +#include "BAPAAimAtPoint3d.h" + +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "BAPActionInline.h" +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D0870 (C1; C2 0x1D0770). The condition's owner is set without a null test, as compiled. +BAPAAimAtPoint3d::BAPAAimAtPoint3d(Vec3& point, Vec3& offset, BAPCondition* condition, unsigned long long controls, + int patternId, float float1A4, float float1A8) +{ + m_point = bapinline::vec3(offset.x + point.x, offset.y + point.y, offset.z + point.z); + m_float1A4 = float1A4; + m_float1A8 = float1A8; + m_offset = offset; + m_condition = condition; + condition->setOwner(this); + m_patternId = patternId; + m_int1BC = 0; + m_controls = controls; + m_int1C4 = 0; + m_double19C = static_cast(-5000000000.0f); +} + +// ELF 0x1D09F0 (D1 0x1D0970, D0 0x1D0A70) +BAPAAimAtPoint3d::~BAPAAimAtPoint3d() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D0E00 +int BAPAAimAtPoint3d::getAimAtType() +{ + return 0; +} + +// ELF 0x1D0D00 +bool BAPAAimAtPoint3d::getVectorToTarget(const Vec3& from, Vec3& vector) const +{ + vector = bapinline::sub(m_point, from); + return true; +} + +// ELF 0x1D0AF0. A resting target: the relative position is the point (plus the offset once more) +// from the transformation's position; unlike the object aim, the transformation is not stored, so +// the predicted position is offset by the previous aim's weapon position. +bool BAPAAimAtPoint3d::getAimVec(const Mat4& transform, const Vec3& shooterVelocity, Vec3& direction, + float accuracy, float drag, float speed, float gravityScale, bool highArc) +{ + Vec3 relative = bapinline::vec3(0.0f, 0.0f, 0.0f); + const Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); // stored, never read + (void)targetVelocity; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = speed; + m_aimer.m_gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity() * gravityScale; + + const Vec3 position = bapinline::vec3(transform.m[12], transform.m[13], transform.m[14]); + const Vec3 toPoint = bapinline::sub(m_point, position); + relative = bapinline::add(toPoint, m_offset); + const Vec3 resting = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aimer.setTargetData(relative, resting, shooterVelocity, &transform, timer->getGameTime()); + m_aimVecValid = m_aimer.getFiringDirection(timer->getGameTime(), accuracy, highArc, m_lastAimVec, + m_predictedPosition, &m_impactTime); + direction = m_lastAimVec; + m_predictedPosition.x = m_aimerTransform.m[12] + m_predictedPosition.x; + m_predictedPosition.y = m_aimerTransform.m[13] + m_predictedPosition.y; + m_predictedPosition.z = m_aimerTransform.m[14] + m_predictedPosition.z; + return m_aimVecValid; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.h new file mode 100644 index 000000000..75c0d9ab3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.h @@ -0,0 +1,39 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT3D_H + +#include "../../../../Math/Vec3.h" +#include "BAPAAimAt3d.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace ai { + +class BAPCondition; + +// ELF: vtable 0x4B7A00 (19 words), package G-vehicles. +// Aims at a fixed point. The constructor adds the offset to the point and keeps it in m_offset, +// so getAimVec applies it twice, as shipped. +class BAPAAimAtPoint3d : public BAPAAimAt3d +{ +public: + BAPAAimAtPoint3d(Vec3&, Vec3&, BAPCondition*, unsigned long long, int, float, float); // 0x1D0870 + virtual ~BAPAAimAtPoint3d(); // 0x1D09F0 + + virtual int getAimAtType(); // 0x1D0E00, slot +0x20 + virtual bool getVectorToTarget(const Vec3&, Vec3&) const; // 0x1D0D00, slot +0x24 + virtual bool getAimVec(const Mat4&, const Vec3&, Vec3&, float, float, float, float, bool); // 0x1D0AF0, slot +0x28 + +private: + /* +0x1D4 */ Vec3 m_point; // the constructor's point plus offset +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAAIMATPOINT3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp new file mode 100644 index 000000000..979809760 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp @@ -0,0 +1,87 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D1450 (__tcf_0 0x1D14B0, _GLOBAL__I 0x1D14E0): 's Init object only. +#include + +#include "BAPAChangeWeapon.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D0F00 (C1): the weapon is resolved now; controls = the 64-bit `1 << getWeaponActivate()`. +// Neither the information nor the weapon is null-checked. +BAPAChangeWeapon::BAPAChangeWeapon(Bot* bot, int weaponIndex, int patternId) +{ + m_bot = bot; + m_weaponIndex = weaponIndex; + m_patternId = patternId; + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + m_weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weaponIndex)); + m_controls = 1ULL << (static_cast(m_weapon->getWeaponActivate()) & 63u); +} + +// ELF 0x1D1030 (D0 0x1D1070) +BAPAChangeWeapon::~BAPAChangeWeapon() +{ +} + +// ELF 0x1D10C0. Soldiers: while another slot is active, release fire / alt fire / reload and +// press the activation input (ok, not failed); once it is active, release them all (done). +// Vehicles: press the activation input (Input::setInput inlined with its range check) and finish. +bool BAPAChangeWeapon::execute(Bot* bot, bool& ok, bool& failed) +{ + Information* info = bapinline::info(bot->getCurrentEquipment()); + if (!info) { + ok = false; + failed = true; + return true; + } + io::PlayerInput* input = bot->getInput(); + if (info->getObjectTypeFlags() & 0x200000u) { + if (info->getArmament()->getActiveWeapon() != m_weaponIndex) { + input->setInput(io::PIFire, 0.0f); + input->setInput(io::PIAltFire, 0.0f); + input->setInput(io::PIReload, 0.0f); + input->setInput(static_cast(m_weapon->getWeaponActivate()), 1.0f); + ok = true; + failed = false; + return true; + } + input->setInput(static_cast(m_weapon->getWeaponActivate()), 0.0f); + input->setInput(io::PIFire, 0.0f); + input->setInput(io::PIAltFire, 0.0f); + input->setInput(io::PIReload, 0.0f); + ok = true; + failed = true; + return true; + } + input->setInput(static_cast(m_weapon->getWeaponActivate()), 1.0f); + ok = true; + failed = true; + return true; +} + +// ELF 0x1D1430 +BAPStatementType BAPAChangeWeapon::getId() const +{ + return BAPSTChangeWeapon; // 28 +} + +// ELF 0x1D1440 +bool BAPAChangeWeapon::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.h new file mode 100644 index 000000000..79e48078d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.h @@ -0,0 +1,44 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACHANGEWEAPON_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACHANGEWEAPON_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B7AA0 (8 words), operator new 0x20, package C-actions. +// Selects a weapon slot of the bot's current vehicle/soldier by pressing its activation +// input (controls = 1 << that input). +class BAPAChangeWeapon : public BAPAction +{ +public: + BAPAChangeWeapon(Bot*, int, int); // 0x1D0F00 + virtual ~BAPAChangeWeapon(); // 0x1D1030 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D10C0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D1430, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D1440, slot +0x14; from the base declaration + +private: + /* +0x14 */ Bot* m_bot; + /* +0x18 */ int m_weaponIndex; // armament slot + /* +0x1C */ WeaponInfo* m_weapon; // resolved at construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACHANGEWEAPON_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp new file mode 100644 index 000000000..a59cd3abc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp @@ -0,0 +1,199 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D1BE0 (__tcf_0 0x1D1C40, _GLOBAL__I 0x1D1C70): 's Init object only. +#include + +#include "BAPAComponentSoldierPose.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/AIRandom.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D1620 (C1; C2 0x1D1500 region). The fire threshold gets the inline Mersenne-Twister +// draw: `t5 = t * 5` is stored as float, then `rnd * 2^-32 * t5 + t` in x87 precision +// (double here) and stored as float. +BAPAComponentSoldierPose::BAPAComponentSoldierPose(SoldierPose normal, SoldierPose incommingFire, + float fireObjectsThreshold, SoldierPose danger, + float controlThreshold, unsigned int object, + float timeDuration) +{ + m_normalPose = normal; + m_incommingFirePose = incommingFire; + const float t5 = fireObjectsThreshold * 5.0f; + const unsigned int r = AIRandom::m_instance->next(); + m_fireObjectsThreshold = static_cast(static_cast(r) * static_cast(2.3283064e-10f) * t5 + + fireObjectsThreshold); + m_dangerPose = danger; + m_currentPose = normal; + // The ordered comparisons leave a NaN unchanged. + float c = controlThreshold; + if (-1.0f > c) + c = -1.0f; + else if (c > 1.0f) + c = 1.0f; + m_controlThreshold = c; + m_timeDuration = timeDuration; + m_lastChangeTime = -static_cast(FLT_MAX); + m_object = object; +} + +// ELF 0x1D1760 (D1; D0 0x1D1780) +BAPAComponentSoldierPose::~BAPAComponentSoldierPose() +{ +} + +// ELF 0x1D17C0 +void BAPAComponentSoldierPose::setNormalPose(SoldierPose pose) +{ + m_normalPose = pose; +} + +// ELF 0x1D17D0 +void BAPAComponentSoldierPose::setIncommingFirePose(SoldierPose pose) +{ + m_incommingFirePose = pose; +} + +// ELF 0x1D17E0 +void BAPAComponentSoldierPose::setFireObjectsThreshold(float threshold) +{ + m_fireObjectsThreshold = threshold; +} + +// ELF 0x1D17F0 +void BAPAComponentSoldierPose::setDangerPose(SoldierPose pose) +{ + m_dangerPose = pose; +} + +// ELF 0x1D1800 +void BAPAComponentSoldierPose::setControlThreshold(float threshold) +{ + m_controlThreshold = threshold; +} + +// ELF 0x1D1810 +void BAPAComponentSoldierPose::setTimeDuration(float duration) +{ + m_timeDuration = duration; +} + +// Inline in both 0x1D1820 and 0x1D1940: `info->m_objectTypeFlags & 0x200000` (byte +6 bit 5), +// `m_iaiPlayerFactory->getPlayerFromId(info->getPlayerId())` (+0x20), `player->getSoldier()` +// (+0x4C) non-null, and `info->getSoldierPose() != SPStanding`. +bool BAPAComponentSoldierPose::objectForcesCrouch() const +{ + if (m_object == 0xFFFFFFFFu) + return false; + Information* info = bapinline::info(m_object); + if (!info || !(info->getObjectTypeFlags() & 0x200000u)) + return false; + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(info->getPlayerId()); + return player && player->getSoldier() && info->getSoldierPose() != SPStanding; +} + +// ELF 0x1D1820 +SoldierPose BAPAComponentSoldierPose::getNormalPose() +{ + if (objectForcesCrouch()) + return SPCrouching; + return m_normalPose; +} + +// ELF 0x1D18E0 +SoldierPose BAPAComponentSoldierPose::getIncommingFirePose() const +{ + return m_incommingFirePose; +} + +// ELF 0x1D18F0 +float BAPAComponentSoldierPose::getFireObjectsThreshold() const +{ + return m_fireObjectsThreshold; +} + +// ELF 0x1D1900 +SoldierPose BAPAComponentSoldierPose::getDangerPose() const +{ + return m_dangerPose; +} + +// ELF 0x1D1910 +float BAPAComponentSoldierPose::getControlThreshold() const +{ + return m_controlThreshold; +} + +// ELF 0x1D1920 +float BAPAComponentSoldierPose::getTimeDuration() const +{ + return m_timeDuration; +} + +// ELF 0x1D1930 +SoldierPose BAPAComponentSoldierPose::getCurrentPose() const +{ + return m_currentPose; +} + +// ELF 0x1D1940. Swimming wins; otherwise the pose is re-chosen at most every m_timeDuration: +// crouch next to a non-standing followed soldier; incoming fire above the threshold picks the +// incoming-fire pose, else control below the threshold picks the danger pose, else the normal +// pose; "lying" (3) needs kit 1 or 3, otherwise crouch. Then water: deeper than 0.4 stands, +// any water turns lying into crouching. +SoldierPose BAPAComponentSoldierPose::computeCurrentPose(float incommingFire, float control, double time, + Bot* bot, const Vec3& position) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return m_currentPose; + if (self->getSoldierPose() == SPSwimming) { + m_currentPose = SPSwimming; + return SPSwimming; + } + if (time - m_lastChangeTime < static_cast(m_timeDuration)) + return m_currentPose; + m_lastChangeTime = time; + if (objectForcesCrouch()) { + m_currentPose = SPCrouching; + return SPCrouching; + } + + SoldierPose pose; + if (incommingFire <= m_fireObjectsThreshold) + pose = (m_controlThreshold <= control) ? m_normalPose : m_dangerPose; + else + pose = m_incommingFirePose; + if (pose == SPLying && self->getKitType() != 1 && self->getKitType() != 3) + pose = SPCrouching; + m_currentPose = pose; + + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float water = terrain->getWaterLevel(position.x, position.z); + const float depth = water - terrain->getHeight(position.x, position.z); + if (0.4f < depth) { + m_currentPose = SPStanding; + return SPStanding; + } + if (0.0f < depth && m_currentPose == SPLying) { + m_currentPose = SPCrouching; + return SPCrouching; + } + return m_currentPose; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.h new file mode 100644 index 000000000..21f9591e8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.h @@ -0,0 +1,64 @@ +// Soldier-pose chooser shared by pose and move actions. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACOMPONENTSOLDIERPOSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACOMPONENTSOLDIERPOSE_H + +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7AE0 (16 words), package C-actions. +// Soldier-pose chooser mixed into BAPAMoveTo and BAPASoldierPose (secondary base, size 0x2C). +// Setters return nothing (no eax write); the float getters return through x87. +class BAPAComponentSoldierPose +{ +public: + BAPAComponentSoldierPose(SoldierPose normal, SoldierPose incommingFire, float fireObjectsThreshold, + SoldierPose danger, float controlThreshold, unsigned int object, + float timeDuration); // 0x1D1620 + virtual ~BAPAComponentSoldierPose(); // 0x1D1760 + + virtual void setNormalPose(SoldierPose); // 0x1D17C0, slot +0x08 + virtual void setIncommingFirePose(SoldierPose); // 0x1D17D0, slot +0x0C + virtual void setFireObjectsThreshold(float); // 0x1D17E0, slot +0x10 + virtual void setDangerPose(SoldierPose); // 0x1D17F0, slot +0x14 + virtual void setControlThreshold(float); // 0x1D1800, slot +0x18 + virtual void setTimeDuration(float); // 0x1D1810, slot +0x1C + virtual SoldierPose getNormalPose(); // 0x1D1820, slot +0x20 + virtual SoldierPose getIncommingFirePose() const; // 0x1D18E0, slot +0x24 + virtual float getFireObjectsThreshold() const; // 0x1D18F0, slot +0x28 + virtual SoldierPose getDangerPose() const; // 0x1D1900, slot +0x2C + virtual float getControlThreshold() const; // 0x1D1910, slot +0x30 + virtual float getTimeDuration() const; // 0x1D1920, slot +0x34 + virtual SoldierPose getCurrentPose() const; // 0x1D1930, slot +0x38 + virtual SoldierPose computeCurrentPose(float incommingFire, float control, double time, Bot*, + const Vec3& position); // 0x1D1940, slot +0x3C + +private: + // True when m_object is a soldier-type information (flags bit 21) whose player has a soldier + // that is not standing: the inline test getNormalPose and computeCurrentPose both spell out. + bool objectForcesCrouch() const; + + /* +0x04 */ SoldierPose m_normalPose; + /* +0x08 */ SoldierPose m_incommingFirePose; + /* +0x0C */ float m_fireObjectsThreshold; // randomised: t + rnd * t * 5 + /* +0x10 */ SoldierPose m_dangerPose; + /* +0x14 */ SoldierPose m_currentPose; // = normal + /* +0x18 */ float m_controlThreshold; // clamped to [-1, 1] + /* +0x1C */ float m_timeDuration; + /* +0x20 */ double m_lastChangeTime; // = -FLT_MAX + /* +0x28 */ unsigned int m_object; // information handle, -1 = none + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACOMPONENTSOLDIERPOSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp new file mode 100644 index 000000000..141780932 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp @@ -0,0 +1,61 @@ +// A completed debug marker whose integer value appears in plan dumps. + +// static init: ELF 0x1FB8F0 (__tcf_0 0x1FB950, _GLOBAL__I 0x1FB980): 's Init object only. +#include + +#include "BAPADebug.h" + +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FB6F0 (C1; C2 0x1FB6A0) +BAPADebug::BAPADebug(int value) : BAPAction(UninitializedPatternId()), m_value(value) +{ +} + +// ELF 0x1FB780 (D1; D2 0x1FB740, D0 0x1FB7C0) +BAPADebug::~BAPADebug() +{ +} + +// ELF 0x1FB810 +bool BAPADebug::execute(Bot*, bool& success, bool& finished) +{ + success = true; + finished = true; + return true; +} + +// ELF 0x1FB9A0 +unsigned long long BAPADebug::getControls() +{ + return m_controls; +} + +// ELF 0x1FB9B0 +BAPStatementType BAPADebug::getId() const +{ + return BAPSTDebug; +} + +// ELF 0x1FB9C0 +bool BAPADebug::hasDefault() +{ + return false; +} + +// ELF 0x1FB830 +void BAPADebug::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << getId() << "(" << m_value << ")" << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h new file mode 100644 index 000000000..8db452904 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPADebug.h @@ -0,0 +1,37 @@ +// A completed debug marker whose integer value appears in plan dumps. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPADEBUG_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPADEBUG_H + +#include +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA540 (8 words), package H-deferred. +class BAPADebug : public BAPAction +{ +public: + explicit BAPADebug(int); // 0x1FB6F0 + virtual ~BAPADebug(); // 0x1FB780 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FB810, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1FB9A0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1FB9B0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FB9C0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1FB830, slot +0x1C; from the base declaration +private: + /* +0x14 */ int m_value; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPADEBUG_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp new file mode 100644 index 000000000..82bdd7e8b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp @@ -0,0 +1,47 @@ +// Expression statement; neither shipped image constructs an expression object. + +#include "BAPAEvaluate.h" + +#include "BAPExpression.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D1CF0 (C1; C2 0x1D1C90). +BAPAEvaluate::BAPAEvaluate(BAPExpression* expression) + : BAPStatement(UninitializedPatternId{}), m_expression(expression) +{ +} + +// ELF 0x1D1DB0 (D1; D2 0x1D1D50, D0 0x1D1E10). +BAPAEvaluate::~BAPAEvaluate() +{ + if (m_expression) + delete m_expression; +} + +// ELF 0x1D1E80 +bool BAPAEvaluate::execute(Bot*, bool& ok, bool& done) +{ + m_expression->unimplementedExpressionSlot2(); + ok = true; + done = true; + return true; +} + +// ELF 0x1D1EB0 +BAPStatementType BAPAEvaluate::getId() const +{ + return BAPSTEvaluate; +} + +// ELF 0x1D1EC0 +bool BAPAEvaluate::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h new file mode 100644 index 000000000..39ab3f73e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.h @@ -0,0 +1,36 @@ +// Owns an expression, invokes its pure operation and finishes successfully. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATE_H + +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPExpression; +class Bot; + +// ELF: vtable 0x4B7B40 (8 words), package H-deferred. +class BAPAEvaluate : public BAPStatement +{ +public: + explicit BAPAEvaluate(BAPExpression*); // 0x1D1CF0 + virtual ~BAPAEvaluate(); // 0x1D1DB0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D1E80, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D1EB0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D1EC0, slot +0x14; from the base declaration + +private: + /* +0x14 */ BAPExpression* m_expression; // owned; constructor leaves the inherited pattern id unwritten +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp new file mode 100644 index 000000000..bdfe5cf2d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp @@ -0,0 +1,72 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D2220 (__tcf_0 0x1D2280, _GLOBAL__I 0x1D22B0): 's Init object only. +#include + +#include "BAPAEvaluateCondition.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D1F40 (C1) +BAPAEvaluateCondition::BAPAEvaluateCondition(BAPCondition* condition, int patternId) +{ + m_condition = condition; + m_patternId = patternId; + condition->setOwner(this); +} + +// ELF 0x1D2020 (D0 0x1D2090): deletes the condition. +BAPAEvaluateCondition::~BAPAEvaluateCondition() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D2100 +bool BAPAEvaluateCondition::execute(Bot* bot, bool& ok, bool& failed) +{ + m_result = m_condition->evaluate(bot); + ok = true; + failed = true; + return true; +} + +// ELF 0x1D2140: no controls. +unsigned long long BAPAEvaluateCondition::getControls() +{ + return 0; +} + +// ELF 0x1D22D0 +BAPStatementType BAPAEvaluateCondition::getId() const +{ + return BAPSTEvaluateCondition; // 43 +} + +// ELF 0x1D2150 +bool BAPAEvaluateCondition::hasDefault() +{ + return true; +} + +// ELF 0x1D2160 +void BAPAEvaluateCondition::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + bapinline::streamType(out, getId()) << "("; + out << (m_result ? "[true]" : "[false]"); + out << *m_condition; + out << ")" << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.h new file mode 100644 index 000000000..d2aea5c40 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATECONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATECONDITION_H + +#include +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7BC0 (8 words), operator new 0x1C, package C-actions. +// Evaluates a condition once and remembers the answer (+0x18, printed by streamSelf). +class BAPAEvaluateCondition : public BAPStatement +{ +public: + BAPAEvaluateCondition(BAPCondition*, int); // 0x1D1F40 + virtual ~BAPAEvaluateCondition(); // 0x1D2020 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2100, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D2140, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D22D0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2150, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1D2160, slot +0x1C; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; // owned + /* +0x18 */ bool m_result; // not initialised by the ctor +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAEVALUATECONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp new file mode 100644 index 000000000..c97137fd1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp @@ -0,0 +1,50 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D24C0 (__tcf_0 0x1D2520, _GLOBAL__I 0x1D2550): 's Init object only. +#include + +#include "BAPAForgetTarget.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSenses.h" +#include "../AIBot/SensingAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D2330 (C1) +BAPAForgetTarget::BAPAForgetTarget(unsigned int target) +{ + m_target = target; +} + +// ELF 0x1D23C0 (D0 0x1D2400) +BAPAForgetTarget::~BAPAForgetTarget() +{ +} + +// ELF 0x1D2450: `bot->getSensingAgent()->+0x68` (getSenses) ->forgetObject(target). +bool BAPAForgetTarget::execute(Bot* bot, bool& ok, bool& failed) +{ + bot->getSensingAgent()->getSenses()->forgetObject(m_target); + ok = true; + failed = true; + return true; +} + +// ELF 0x1D24A0 +BAPStatementType BAPAForgetTarget::getId() const +{ + return BAPSTForgetTarget; // 39 +} + +// ELF 0x1D24B0 +bool BAPAForgetTarget::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.h new file mode 100644 index 000000000..bfd50db16 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAFORGETTARGET_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAFORGETTARGET_H + +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7C40 (8 words), operator new 0x18, package C-actions. +// Makes the bot's senses forget one object (BotSenses::forgetObject). +class BAPAForgetTarget : public BAPStatement +{ +public: + explicit BAPAForgetTarget(unsigned int); // 0x1D2330 + virtual ~BAPAForgetTarget(); // 0x1D23C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2450, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D24A0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D24B0, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_target; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAFORGETTARGET_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp new file mode 100644 index 000000000..e9d410f90 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp @@ -0,0 +1,52 @@ +// Requests a horn notification for one information handle; execution returns false as shipped. + +// static init: ELF 0x1D2780 (__tcf_0 0x1D27E0, _GLOBAL__I 0x1D2810): 's Init object only. +#include + +#include "BAPAHonkHorn.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D25D0 (C1; C2 0x1D2570) +BAPAHonkHorn::BAPAHonkHorn(unsigned int object, int tag) : BAPAction(UninitializedPatternId()) +{ + m_patternId = tag; + m_object = object; +} + +// ELF 0x1D2670 (D1; D2 0x1D2630, D0 0x1D26B0) +BAPAHonkHorn::~BAPAHonkHorn() +{ +} + +// ELF 0x1D2700 +bool BAPAHonkHorn::execute(Bot* bot, bool& success, bool& finished) +{ + Information* object = bapinline::info(m_object); + bot->getCommunicationAgent()->honkHorn(object); + success = false; + finished = true; + return false; +} + +// ELF 0x1D2830 +BAPStatementType BAPAHonkHorn::getId() const +{ + return BAPSTHonkHorn; +} + +// ELF 0x1D2840 +bool BAPAHonkHorn::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h new file mode 100644 index 000000000..c350899c4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.h @@ -0,0 +1,34 @@ +// Requests a horn notification for one information handle; execution returns false as shipped. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAHONKHORN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAHONKHORN_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7C80 (8 words), operator new 0x18, package G-vehicles. +class BAPAHonkHorn : public BAPAction +{ +public: + BAPAHonkHorn(unsigned int, int); // 0x1D25D0 + virtual ~BAPAHonkHorn(); // 0x1D2670 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2700, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D2830, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2840, slot +0x14; from the base declaration +private: + /* +0x14 */ unsigned int m_object; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAHONKHORN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp new file mode 100644 index 000000000..c75d75b15 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp @@ -0,0 +1,63 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPAIdle.h" + +#include "BAPCondition.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D28C0 (C1; C2 0x1D2810 region): the condition's owner is set unconditionally. +BAPAIdle::BAPAIdle(BAPCondition* condition, unsigned long long controls, int patternId) +{ + m_condition = condition; + condition->setOwner(this); + m_patternId = patternId; + m_controls = controls; +} + +// ELF 0x1D2990 (D0 0x1D29F0): deletes the condition. +BAPAIdle::~BAPAIdle() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D2A60 +bool BAPAIdle::execute(Bot* bot, bool& ok, bool& failed) +{ + ok = true; + failed = m_condition->evaluate(bot); + return true; +} + +// ELF 0x1D2AA0 +unsigned long long BAPAIdle::getControls() +{ + return m_controls; +} + +// ELF 0x1D2B10 (weak) +BAPStatementType BAPAIdle::getId() const +{ + return BAPSTIdle; // 13 +} + +// ELF 0x1D2AB0 +bool BAPAIdle::hasDefault() +{ + return true; +} + +// ELF 0x1D2AC0: every level. +void BAPAIdle::debug(BotScriptDebugger::DebugLevel, std::string& text) +{ + text = "Idling..."; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h new file mode 100644 index 000000000..d303f5a9a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAIDLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAIDLE_H + +#include +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7CC0 (8 words), package C-actions. +// Idles until the condition holds (ok = true, failed = condition). +class BAPAIdle : public BAPAction +{ +public: + BAPAIdle(BAPCondition*, unsigned long long, int); // 0x1D28C0 + virtual ~BAPAIdle(); // 0x1D2990 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2A60, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D2AA0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D2B10, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2AB0, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1D2AC0, slot +0x18; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; // owned +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp new file mode 100644 index 000000000..d09700c04 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp @@ -0,0 +1,55 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D2D10 (__tcf_0 0x1D2D70, _GLOBAL__I 0x1D2DA0): 's Init object only. +#include + +#include "BAPALook.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D2BA0 (C1; C2 0x1D2B20 identical). The inline BAPStatement base clears +0x04/+0x08 and +// counts `news`; then +0x14 = cond, +0x18 = speed, +0x1C..+0x2C = 0, +0x08 = controls, +0x10 = tag. +// The condition's owner is set by the derived constructors, not here. +BAPALook::BAPALook(float lookSpeed, BAPCondition* endCondition, unsigned long long controls, int tag) +{ + m_endCondition = endCondition; + m_lookSpeed = lookSpeed; + m_deviation = 0.0f; + m_lastControl = 0.0f; + m_cameraForward.x = 0.0f; + m_cameraForward.y = 0.0f; + m_cameraForward.z = 0.0f; + m_controls = controls; + m_patternId = tag; +} + +// ELF 0x1D2C60 (D1; D2 0x1D2C20, D0 0x1D2CA0): only the inline base destructor (`destroys`). +BAPALook::~BAPALook() +{ +} + +// ELF 0x1D2CF0: a look never runs by itself (the entries do the work): ok = false, failed = true. +bool BAPALook::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1D2DC0 +BAPStatementType BAPALook::getId() const +{ + return BAPSTLookAt; // 23 +} + +// ELF 0x1D2DD0 +bool BAPALook::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.h new file mode 100644 index 000000000..1748effc7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALook.h @@ -0,0 +1,50 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOK_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOK_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7D00 (9 words), package C-actions. Size 0x30 (derived data starts at +0x30). +// Look statement base: the infantry/turret look entries steer the camera towards +// getLookDirection() and keep their regulator state in the public fields below. +class BAPALook : public BAPAction +{ +public: + BAPALook(float, BAPCondition*, unsigned long long, int); // 0x1D2BA0 + virtual ~BAPALook(); // 0x1D2C60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D2CF0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D2DC0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D2DD0, slot +0x14; from the base declaration + virtual Vec3 getLookDirection(bool&) = 0; // no body, slot +0x20; ELF sret (BAPALookInDir 0x1D3D40 `ret $4`) + + // Read and written inline by EntryMouseTurretLookAt::execute (0x2B9E90) and the other look + // entries, so public. [INFERRED] names from that use. + /* +0x14 */ BAPCondition* m_endCondition; // evaluated first by the entries: true ends the look. + // The derived classes own and delete it (base dtor does not). + /* +0x18 */ float m_lookSpeed; // the ctor's float; passed to mouseControlLookAtDirection + /* +0x1C */ float m_deviation; // = 0; regulator out/in (angle to target); entries store pi (0x40490FDB) when idle + /* +0x20 */ float m_lastControl; // = 0; regulator out/in (previous control value) + /* +0x24 */ Vec3 m_cameraForward; // = 0; entries copy camera matrix row 2 (+0x20) here +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOK_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp new file mode 100644 index 000000000..037b9940c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp @@ -0,0 +1,49 @@ +// Look statement that keeps the view along the vehicle's facing. Recovered from libaidll.so +// 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPALookAhead.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1D3070, __tcf_0 0x1D30D0, _GLOBAL__I 0x1D3100). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D2E60 (C1; C2 0x1D2DE0): the base, the bot's current equipment at +0x30, then the end +// condition's owner (not null-checked). +BAPALookAhead::BAPALookAhead(Bot* bot, float lookSpeed, BAPCondition* endCondition, unsigned long long controls, + int tag) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_equipment = bot->getCurrentEquipment(); + m_endCondition->setOwner(this); +} + +// ELF 0x1D2F30 (D1; D2 0x1D2EE0, D0 0x1D2F80): deletes the end condition. +BAPALookAhead::~BAPALookAhead() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D2FE0: the equipment's facing; ok reports whether its information still exists, and a +// stale handle yields (0, 0, 0). +Vec3 BAPALookAhead::getLookDirection(bool& ok) +{ + Information* const equipment = bapinline::info(m_equipment); + ok = equipment != 0; + if (!ok) + return bapinline::vec3(0.0f, 0.0f, 0.0f); + return equipment->getFaceing(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.h new file mode 100644 index 000000000..e6504868e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.h @@ -0,0 +1,36 @@ +// Look statement along the facing of the bot's vehicle. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKAHEAD_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKAHEAD_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7D40 (9 words), package G-vehicles. Looks along the facing of the bot's equipment +// at construction time. +class BAPALookAhead : public BAPALook +{ +public: + BAPALookAhead(Bot*, float, BAPCondition*, unsigned long long, int); // 0x1D2E60 + virtual ~BAPALookAhead(); // 0x1D2F30 + + virtual Vec3 getLookDirection(bool&); // 0x1D2FE0, slot +0x20; from the base declaration + + /* +0x30 */ unsigned int m_equipment; // the bot's current equipment handle at construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKAHEAD_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp new file mode 100644 index 000000000..d0d0a2fce --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp @@ -0,0 +1,65 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D3580 (__tcf_0 0x1D35E0, _GLOBAL__I 0x1D3610): 's Init object only. +#include + +#include "BAPALookAtObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/Information.h" +#include "../Main/AIDllFrontier.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D31A0 (C1; C2 0x1D3120) +BAPALookAtObject::BAPALookAtObject(Bot* bot, unsigned int target, float lookSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag, BAPVariable* targetPosition, + float heightOffset) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_bot = bot; + m_target = target; + m_targetPosition = targetPosition; + m_heightOffset = heightOffset; + m_endCondition->setOwner(this); +} + +// ELF 0x1D3270 (D1; D2 0x1D3220, D0 0x1D32C0): deletes the end condition. +BAPALookAtObject::~BAPALookAtObject() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D3320: from the camera position of the bot's current vehicle/soldier to the target +// (or the override variable's point), raised by m_heightOffset, normalised. No target +// information: ok = false and (1, 0, 0). +Vec3 BAPALookAtObject::getLookDirection(bool& ok) +{ + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + Information* target = bapinline::info(m_target); + ok = target != 0; + if (!ok) + return bapinline::vec3(1.0f, 0.0f, 0.0f); + + // The camera transform is fetched before the target point (0x1D33D9; the bot's equipment + // information is not null-checked). Its row 3 (+0x30) is the camera position. + const Mat4& camera = self->getControlInfo()->getCameraTransformation(); + Vec3 p; + if (m_targetPosition) + p = m_targetPosition->m_value; + else + p = target->getPosition(); + Vec3 dir = bapinline::vec3(p.x - camera.m[12], (m_heightOffset + p.y) - camera.m[13], p.z - camera.m[14]); + bapinline::normalize(dir); + return dir; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.h new file mode 100644 index 000000000..7db18c041 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7DC0 (9 words), package C-actions. +class BAPALookAtObject : public BAPALook +{ +public: + BAPALookAtObject(Bot*, unsigned int, float, BAPCondition*, unsigned long long, int, BAPVariable*, float); // 0x1D31A0 + virtual ~BAPALookAtObject(); // 0x1D3270 + + virtual Vec3 getLookDirection(bool&); // 0x1D3320, slot +0x20; from the base declaration + +private: + /* +0x30 */ Bot* m_bot; + /* +0x34 */ unsigned int m_target; // information handle + /* +0x38 */ BAPVariable* m_targetPosition; // optional override of the target's position + /* +0x3C */ float m_heightOffset; // added to the target point's y +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp new file mode 100644 index 000000000..32da64221 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp @@ -0,0 +1,48 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D39C0 (__tcf_0 0x1D3A20, _GLOBAL__I 0x1D3A50): 's Init object only. +#include + +#include "BAPALookAtPoint.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D36C0 (C1; C2 0x1D3630). Unlike the other looks it neither sets the condition's owner +// nor deletes the condition. +BAPALookAtPoint::BAPALookAtPoint(const Vec3& point, Bot* bot, float lookSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_point = point; + m_bot = bot; +} + +// ELF 0x1D3940 (D1; D2 0x1D38F0 region, D0 0x1D3990): base only. +BAPALookAtPoint::~BAPALookAtPoint() +{ +} + +// ELF 0x1D3750: from the bot's current vehicle/soldier position to the point, normalised; no +// information: ok = false and a zero vector. +Vec3 BAPALookAtPoint::getLookDirection(bool& ok) +{ + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + if (!self) { + ok = false; + return bapinline::vec3(0.0f, 0.0f, 0.0f); + } + ok = true; + Vec3 dir = bapinline::sub(m_point, self->getPosition()); + bapinline::normalize(dir); + return dir; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.h new file mode 100644 index 000000000..9042808e6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.h @@ -0,0 +1,39 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATPOINT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATPOINT_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7E00 (9 words), package C-actions. +class BAPALookAtPoint : public BAPALook +{ +public: + BAPALookAtPoint(const Vec3&, Bot*, float, BAPCondition*, unsigned long long, int); // 0x1D36C0 + virtual ~BAPALookAtPoint(); // 0x1D3940 + + virtual Vec3 getLookDirection(bool&); // 0x1D3750, slot +0x20; from the base declaration + +private: + /* +0x30 */ Vec3 m_point; + /* +0x3C */ Bot* m_bot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKATPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp new file mode 100644 index 000000000..e08927448 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp @@ -0,0 +1,40 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D3C90 (__tcf_0 0x1D3CF0, _GLOBAL__I 0x1D3D20): 's Init object only. +#include + +#include "BAPALookInDir.h" + +#include "../AIBotActionPlan/BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D3B00 (C1; C2 0x1D3A70 identical): direction copied to +0x30, then the end condition's +// owner (+0x04) is pointed at this statement. +BAPALookInDir::BAPALookInDir(const Vec3& direction, float lookSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag) + : BAPALook(lookSpeed, endCondition, controls, tag) +{ + m_direction = direction; + endCondition->setOwner(this); +} + +// ELF 0x1D3BE0 (D1; D2 0x1D3B90, D0 0x1D3C30): deletes the end condition (virtual D0, slot +0x10). +BAPALookInDir::~BAPALookInDir() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D3D40: always valid, the stored direction. +Vec3 BAPALookInDir::getLookDirection(bool& ok) +{ + ok = true; + return m_direction; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.h new file mode 100644 index 000000000..e0f972c16 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKINDIR_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKINDIR_H + +#include "../../../../Math/Vec3.h" +#include "BAPALook.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; + +// ELF: vtable 0x4B7E40 (9 words), package C-actions. +class BAPALookInDir : public BAPALook +{ +public: + BAPALookInDir(const Vec3&, float, BAPCondition*, unsigned long long, int); // 0x1D3B00 + virtual ~BAPALookInDir(); // 0x1D3BE0 + + virtual Vec3 getLookDirection(bool&); // 0x1D3D40, slot +0x20; from the base declaration + +private: + /* +0x30 */ Vec3 m_direction; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPALOOKINDIR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp new file mode 100644 index 000000000..230039410 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp @@ -0,0 +1,192 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D4BA0 (__tcf_0 0x1D4C00, _GLOBAL__I 0x1D4C30): 's Init object only. +#include + +#include "BAPAMergeSoldierInputs.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIPlanInterpreter/MouseControl.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Game/Objects/IObject.h" +#include "../../../../Game/Objects/ObjectLayoutAccess.h" +#include "../../../../Physics/IPhysicsNode.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The function-static `lookAheadFrames` of execute (ELF .data 0x4B7EA4). +int lookAheadFrames = 3; + +float signedSqrtClamped(float v) +{ + const float sign = v <= 0.0f ? (0.0f <= v ? 0.0f : -1.0f) : 1.0f; + const float r = std::sqrt(std::fabs(v)) * sign; + if (r < -1.0f) + return -1.0f; + if (1.0f < r) + return 1.0f; + return r; +} + +} // namespace + +// ELF 0x1D3DD0 (C1; C2 0x1D3D40) +BAPAMergeSoldierInputs::BAPAMergeSoldierInputs(int patternId) +{ + m_lastYawError = 0.0f; + m_lastPitchError = 0.0f; + m_patternId = patternId; +} + +// ELF 0x1D3E70 (D1; D0 0x1D3EB0): base only. +BAPAMergeSoldierInputs::~BAPAMergeSoldierInputs() +{ +} + +// ELF 0x1D3F00. Turns the sensing agent's move direction (+0x50) into soldier inputs. +// Walking (no sprint input, not swimming): the direction is split onto the soldier's forward and +// right axes (XZ, normalised, turned ahead by the body's yaw rate over lookAheadFrames frames), +// each as a clamped signed square root, scaled by |throttle|; sprint released. +// Sprinting or swimming: the mouse turns the camera to the direction; throttle is pressed while +// the yaw error is small (< 5 deg) or the sprint focus (+0x58 point, or the +0x64 target's +// position) is at least 4 m away (1 m for a human-occupied vehicle within 3 m); sprint is kept +// while the error is below 40 deg and the focus is beyond that distance. A larger error releases +// the throttle input directly. Always ok and done. +bool BAPAMergeSoldierInputs::execute(Bot* bot, bool& ok, bool& done) +{ + io::PlayerInput* input = bot->getInput(); + SensingAgent* sensing = bot->getSensingAgent(); + const Vec2 move = sensing->getMoveDirection(); + Information* self = bapinline::info(bot->getCurrentEquipment()); // not null-checked + const Mat4& t = self->getTransformation(); + IPIControlInfo* controlInfo = self->getControlInfo(); + float pitchError = 0.0f; + float yawError = 0.0f; + const SoldierPose pose = self->getSoldierPose(); + const bool sprint = bapinline::mappedInput(input, io::PISprint) != 0.0f; + + io::PlayerInputMap lastInput; + float lastValue; + if (!sprint && pose != SPSwimming) { + Vec2 forward; + forward.x = 0.0f; + forward.y = 0.0f; + Vec2 right; + right.x = 0.0f; + right.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&t.m[8]), forward); + vec3ToVec2XZ(*reinterpret_cast(&t.m[0]), right); + bapinline::normalize(forward); + bapinline::normalize(right); + IAIObject* object = self->getAIObject(); + if (object) { + world::IPhysicsNode* node = static_cast( + world::object_detail::LayoutAccess::physicsNode(object->getObject())); + if (node) { + const float step = static_cast(lookAheadFrames) + * static_cast(bapinline::timeIncrease()); + const float rate = node->getRotationalSpeed().y * 0.017453292f; + if (rate != 0.0f) { + // A 2D rotation by -angle (rows (c, -s), (s, c)) applied as v' = (c*x + s*y, + // -s*x + c*y) to both axes (0x1D48B8..0x1D4AA0). + const float angle = rate * step; + const float c = std::cos(angle); + const float s = std::sin(angle); + const Vec2 f = forward; + forward.x = c * f.x + s * f.y; + forward.y = f.x * -s + f.y * c; + const Vec2 r = right; + right.y = -s * r.x + c * r.y; + right.x = s * r.y + c * r.x; + } + } + } + const float throttle = bapinline::mappedInput(input, io::PIThrottle); + const float f = signedSqrtClamped(forward.x * move.x + forward.y * move.y); + const float r = signedSqrtClamped(right.x * move.x + move.y * right.y); + input->setInput(io::PIThrottle, f * std::fabs(throttle)); + input->setInput(io::PIYaw, std::fabs(throttle) * r); + lastInput = io::PISprint; + lastValue = 0.0f; + } else { + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + vec2ToVec3XZ(move, dir); + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + mouseControlLookAtDirection(bot, dir, camera, pitchError, m_lastPitchError, yawError, m_lastYawError, 0.0f, + controlInfo, input, 0.0f, 0.0f, 0.0f); + bool humanVehicle = false; + float focusDistSqr = 0.0f; + if (sprint) { + const Vec3 pos = bapinline::vec3(t.m[12], t.m[13], t.m[14]); + Vec3 focus = bapinline::vec3(0.0f, 0.0f, 0.0f); + const unsigned int handle = bot->getSensingAgent()->getSprintFocusTarget(); + Information* focusInfo = handle == 0xFFFFFFFFu ? 0 : bapinline::info(handle); + if (!focusInfo) { + const Vec3& p = bot->getSensingAgent()->getSprintFocus(); + focus.x = p.x; + focus.z = p.z; + } else { + focus = focusInfo->getPosition(); + humanVehicle = focusInfo->getAIObject() && !IBotManager::instance->getBot(focusInfo->getAIObject()) + && focusInfo->getUnit() && focusInfo->getUnit()->isOccupied(); + } + const float dx = pos.x - focus.x; + const float dz = pos.z - focus.z; + focusDistSqr = dx * dx + 0.0f + dz * dz; + } + const bool close = bot->getSensingAgent()->getSprintFocusTarget() != 0xFFFFFFFFu && focusDistSqr < 9.0f + && humanVehicle; + const float limit = close ? 1.0f : 16.0f; + if (limit <= focusDistSqr || close || std::fabs(yawError) <= 0.08726646f) { + if ((std::fabs(yawError) < 0.6981317f || close) && limit < focusDistSqr) { + if (sprint) + input->setInput(io::PISprint, 1.0f); + lastInput = io::PIThrottle; + lastValue = 1.0f; + } else { + input->setInput(io::PIThrottle, 1.0f); + lastInput = io::PISprint; + lastValue = 0.0f; + } + } else { + if ((input->mappingFlags >> 3) & 1ULL) + input->inputs[io::PIThrottle] = 0.0f; // Input::setInput inlined (0x1D4180) + lastInput = io::PISprint; + lastValue = 0.0f; + } + } + input->setInput(lastInput, lastValue); + m_lastPitchError = pitchError; + m_lastYawError = yawError; + ok = true; + done = true; + return true; +} + +// ELF 0x1D4C50 +BAPStatementType BAPAMergeSoldierInputs::getId() const +{ + return BAPSTMergeSoldierInputs; // 36 +} + +// ELF 0x1D4B90 +bool BAPAMergeSoldierInputs::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.h new file mode 100644 index 000000000..60a3e0d19 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMERGESOLDIERINPUTS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMERGESOLDIERINPUTS_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7EC0 (8 words), operator new 0x1C, package C-actions. +class BAPAMergeSoldierInputs : public BAPAction +{ +public: + explicit BAPAMergeSoldierInputs(int); // 0x1D3DD0 + virtual ~BAPAMergeSoldierInputs(); // 0x1D3E70 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D3F00, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1D4C50, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D4B90, slot +0x14; from the base declaration + +private: + /* +0x14 */ float m_lastYawError; // = 0; mouseControlLookAtDirection's yaw in/out + /* +0x18 */ float m_lastPitchError; // = 0; its pitch in/out +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMERGESOLDIERINPUTS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp new file mode 100644 index 000000000..2a1d78639 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp @@ -0,0 +1,92 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1D5030 (__tcf_0 0x1D5090, _GLOBAL__I 0x1D50C0): 's Init object only. +#include + +#include "BAPAMoveAwayFrom3dObject.h" + +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D4D50 (C1; C2 0x1D4C60) +BAPAMoveAwayFrom3dObject::BAPAMoveAwayFrom3dObject(unsigned int object, float distance, BAPCondition* condition, + unsigned long long controls, int patternId) +{ + m_condition = condition; + m_point = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_object = object; + m_vec30 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_distance = distance; + m_patternId = patternId; + m_controls = controls; + if (condition) + condition->setOwner(this); + if (Information* const info = bapinline::info(m_object)) + m_mobile = info->getMobile() != 0; + m_vec30 = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D4EA0 (D1 0x1D4E40, D0 0x1D4F00) +BAPAMoveAwayFrom3dObject::~BAPAMoveAwayFrom3dObject() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1D4F70. Only a vehicle move entry executes it: on its own it fails at once. +bool BAPAMoveAwayFrom3dObject::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1D4F90. Without information the previous point is returned unchanged. +Vec3* BAPAMoveAwayFrom3dObject::getFirstPoint() +{ + if (Information* const info = bapinline::info(m_object)) + { + if (!m_mobile) + m_point = info->getPosition(); + else + info->getMobile()->getPositionEstimate(m_point); + } + return &m_point; +} + +// ELF 0x1D50E0 (weak) +unsigned long long BAPAMoveAwayFrom3dObject::getControls() +{ + return m_controls; +} + +// ELF 0x1D50F0 (weak) +BAPStatementType BAPAMoveAwayFrom3dObject::getId() const +{ + return BAPSTMoveAwayFromObject; +} + +// ELF 0x1D5100 (weak) +bool BAPAMoveAwayFrom3dObject::hasDefault() +{ + return false; +} + +// ELF 0x1D5110 (weak) +bool BAPAMoveAwayFrom3dObject::isFinished(Bot* bot) +{ + bool finished = false; + if (m_condition) + finished = m_condition->evaluate(bot); + return finished; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.h new file mode 100644 index 000000000..f598ce02f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.h @@ -0,0 +1,51 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVEAWAYFROM3DOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVEAWAYFROM3DOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B7F00 (9 words), package G-vehicles. +// Flies away from an information object until the condition holds; the vehicle move entries +// execute it (on its own it fails) and read the object's point from getFirstPoint. +class BAPAMoveAwayFrom3dObject : public BAPAction +{ +public: + BAPAMoveAwayFrom3dObject(unsigned int, float, BAPCondition*, unsigned long long, int); // 0x1D4D50 + virtual ~BAPAMoveAwayFrom3dObject(); // 0x1D4EA0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D4F70, slot +0x00 + virtual unsigned long long getControls(); // 0x1D50E0, slot +0x0C + virtual BAPStatementType getId() const; // 0x1D50F0, slot +0x10 + virtual bool hasDefault(); // 0x1D5100, slot +0x14 + virtual bool isFinished(Bot*); // 0x1D5110, slot +0x20: the condition, false without one + + Vec3* getFirstPoint(); // 0x1D4F90; refreshes and returns this + 0x1C (was [INFERRED] int) + +private: + // [INFERRED] friendship: EntryHeliMoveAwayFromObject reads +0x14/+0x2C/+0x30 inline (ELF 0x2B6580). + friend class EntryHeliMoveAwayFromObject; + /* +0x14 */ unsigned int m_object; + /* +0x18 */ BAPCondition* m_condition; // deleted by the destructor + /* +0x1C */ Vec3 m_point; // getFirstPoint: the object's position or position estimate + /* +0x28 */ bool m_mobile; // the object had an IPIMobile at construction (else not set) + /* +0x2C */ float m_distance; // [INFERRED] name: callers pass 150 + /* +0x30 */ Vec3 m_vec30; // [INFERRED] previous velocity sample; EntryHeliMoveAwayFromObject +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVEAWAYFROM3DOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp new file mode 100644 index 000000000..7f6e023e3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp @@ -0,0 +1,356 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D6700 (__tcf_0 0x1D6760, _GLOBAL__I 0x1D6790): 's Init object only. +#include + +#include "BAPAMoveTo.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIPlanInterpreter/InfanteryControl.h" +#include "../Main/AIRandom.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SensingAgent.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The constructor's fire threshold: `rnd * 2^-32 * 14 + 1` in x87 precision, stored as float. +float randomFireThreshold() +{ + const unsigned int r = AIRandom::m_instance->next(); + return static_cast(static_cast(r) * static_cast(2.3283064e-10f) * 14.0 + 1.0); +} + +inline float length2(float x, float y) +{ + return std::sqrt(x * x + y * y); +} + +} // namespace + +// ELF 0x1D5310 (C1; C2 0x1D5150). Pose chooser: stand, lie under incoming fire above a random +// threshold in [1, 15), crouch in danger, no control threshold, no object, 10 s between changes. +// Ends with BotMain::setMoveToStatus(0) (Bot vtable +0x244). +BAPAMoveTo::BAPAMoveTo(Bot* bot) + : BAPAction(UninitializedPatternId()), + BAPAComponentSoldierPose(SPStanding, SPLying, randomFireThreshold(), SPCrouching, 0.0f, 0xFFFFFFFFu, 10.0f) +{ + m_coordinate = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_isSprinting = false; + m_previousSpeed = 0.0f; + m_currentPoint.x = 0.0f; + m_currentPoint.y = 0.0f; + m_vec74.x = 0.0f; + m_vec74.y = 0.0f; + m_avoidPoint.x = 0.0f; + m_avoidPoint.y = 0.0f; + m_obstaclePosition.x = 0.0f; + m_obstaclePosition.y = 0.0f; + m_cachedDir.x = 0.0f; + m_cachedDir.y = 0.0f; + m_obstacle = 0xFFFFFFFFu; + m_nextDirTime = -1000.0; + m_previousHeading.y = 0.0f; + m_previousHeading.x = 1.0f; + static_cast(bot)->setMoveToStatus(0); +} + +// ELF 0x1D5550 (D1; D2 0x1D54D0, D0 0x1D55D0, thunk 0x1D67D0): deletes the end condition. +BAPAMoveTo::~BAPAMoveTo() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1D5650 +unsigned long long BAPAMoveTo::getControls() +{ + return m_controls; +} + +// ELF 0x1D5710 +BAPStatementType BAPAMoveTo::getId() const +{ + return BAPSTMoveTo; // 7 +} + +// ELF 0x1D5720 +bool BAPAMoveTo::hasDefault() +{ + return false; +} + +// ELF 0x1D5700 +bool BAPAMoveTo::getIsSprinting() +{ + return m_isSprinting; +} + +// ELF 0x1D6880 +bool BAPAMoveTo::getIsMovingAway() +{ + return false; +} + +// ELF 0x1D6890 +Vec2& BAPAMoveTo::getCurrentPoint() +{ + return m_currentPoint; +} + +// ELF 0x1D68A0 +int BAPAMoveTo::update(Vec2&, bool&, bool&, float) +{ + return 0; +} + +// ELF 0x1D68B0: only the end condition. +bool BAPAMoveTo::isFinished(Bot* bot) +{ + bool finished = false; + if (m_endCondition) + finished = m_endCondition->evaluate(bot); + return finished; +} + +// ELF 0x1D68F0 +bool BAPAMoveTo::getSecondPoint(Vec2&) +{ + return false; +} + +// ELF 0x1D6900 +bool BAPAMoveTo::getLargestAngleDiff(float&) +{ + return false; +} + +// ELF 0x1D6910 +float BAPAMoveTo::getTargetDistance() +{ + return 0.0f; +} + +// ELF 0x1D6930 +unsigned int BAPAMoveTo::getObject() +{ + return 0xFFFFFFFFu; +} + +// ELF 0x1D5760: distance from the bot's current vehicle/soldier to the goal (x87 sum z, x, y). +float BAPAMoveTo::getSimpleTargetDistance(Bot* bot) +{ + return std::sqrt(BAPAMoveTo::getSimpleTargetDistanceSqr(bot)); // inline in the image (no virtual call) +} + +// ELF 0x1D5810 (the information is not null-checked) +float BAPAMoveTo::getSimpleTargetDistanceSqr(Bot* bot) +{ + const Vec3& p = bapinline::info(bot->getCurrentEquipment())->getPosition(); + const double dz = static_cast(p.z) - m_coordinate.z; + const double dx = static_cast(p.x) - m_coordinate.x; + const double dy = static_cast(p.y) - m_coordinate.y; + return static_cast(dz * dz + dx * dx + dy * dy); +} + +// ELF 0x1D6940 +bool BAPAMoveTo::isStuck() +{ + return false; +} + +// ELF 0x1D5660: sprinting looks at a point (target -1) or at an object (the point is zeroed). +void BAPAMoveTo::setIsSprinting(Bot* bot, bool sprinting, const Vec3& point, unsigned int target) +{ + m_isSprinting = sprinting; + if (!sprinting) + return; + if (target == 0xFFFFFFFFu) { + bot->getSensingAgent()->setSprintFocus(point); + } else { + bot->getSensingAgent()->setSprintFocusTarget(target); + bot->getSensingAgent()->setSprintFocus(bapinline::vec3(0.0f, 0.0f, 0.0f)); + } +} + +// ELF 0x1D5730 +Vec3& BAPAMoveTo::getCoordinate() +{ + return m_coordinate; +} + +// ELF 0x1D5740 +float BAPAMoveTo::getMaxSpeed() +{ + return m_maxSpeed; +} + +// ELF 0x1D5750 +float BAPAMoveTo::getMaxArriveSpeed() +{ + return m_maxArriveSpeed; +} + +// ELF 0x1D58B0. The XZ direction to walk towards `target`, normalised into `dir`, steering round +// one obstacle (m_obstacle) that updateInfantryMoveToPosWithObstacles picked. The answer is +// cached until m_nextDirTime (always "now", so every call recomputes). Returns true when the +// obstacle code took over (dir untouched) or the bot keeps walking straight past the obstacle. +bool BAPAMoveTo::getTargetDir(Bot* bot, Vec2 target, Vec2& dir, Information* targetInfo, bool flag) +{ + const double now = bapinline::gameTime(); + if (now < m_nextDirTime) { + dir = m_cachedDir; + return m_cachedResult; + } + m_cachedResult = true; + m_nextDirTime = now + 0.0; + + Vec2 pos; + pos.x = 0.0f; + pos.y = 0.0f; + vec3ToVec2XZ(bapinline::info(bot->getCurrentEquipment())->getPosition(), pos); + + if (usesPathfinding() + && (m_obstacle == 0xFFFFFFFFu || needsUpdate(m_avoidPoint, m_obstacle, m_obstacleRadius))) { + Vec2 ahead; + ahead.x = 0.0f; + ahead.y = 0.0f; + bot->getBotNavigation()->getFirstPointBeyondDist(pos, 10.0f, ahead); + if (updateInfantryMoveToPosWithObstacles(bot, ahead, m_coordinate, getObject(), m_avoidPoint, m_obstacle, + m_avoidDistance, m_obstaclePosition, m_obstacleRadius, m_avoiding, + targetInfo, flag)) + return true; + } + + dir.x = target.x - pos.x; + dir.y = target.y - pos.y; + const float distSqr = dir.y * dir.y + dir.x * dir.x; + float dist = std::sqrt(distSqr); + bool passing = false; + + Information* obstacle = bapinline::info(m_obstacle); + if (!obstacle) { + m_obstacle = 0xFFFFFFFFu; + } else { + const float toObsX = m_obstaclePosition.x - pos.x; + const float toObsY = m_obstaclePosition.y - pos.y; + const float fromObsX = pos.x - m_obstaclePosition.x; + const float fromObsY = pos.y - m_obstaclePosition.y; + unsigned int current = m_obstacle; + // -0xE8(%ebp): also the left side of the "(r + 1)^2" test below (0x1D6535), not the target + // distance (audit 2026-11-01). + const float obsDistSqr = fromObsY * fromObsY + fromObsX * fromObsX; + if ((m_obstacleRadius + 1.0f) * (m_obstacleRadius + 1.0f) < obsDistSqr) { + current = 0xFFFFFFFFu; + m_obstacle = 0xFFFFFFFFu; + } + bool isOwnTarget = false; + if (current != 0xFFFFFFFFu) { + unsigned int change = bot->getChangeTarget(); + Information* ci = bapinline::info(change); + if (ci && !ci->isPrimary()) + change = ci->getPrimaryObject(bot->getSide()); + unsigned int repair = bot->getRepairTarget(); + Information* ri = bapinline::info(repair); + if (ri && !ri->isPrimary()) + repair = ri->getPrimaryObject(bot->getSide()); + current = m_obstacle; + isOwnTarget = current == repair || current == change; + } + passing = isOwnTarget; + if (current != 0xFFFFFFFFu) { + if (!isOwnTarget && !m_avoiding) { + passing = toObsY * dir.y + toObsX * dir.x < 0.0f; + if (!passing && targetInfo && dist * dist <= toObsX * toObsX + toObsY * toObsY) + passing = true; + } + Vec2 obsPos; + obsPos.x = 0.0f; + obsPos.y = 0.0f; + vec3ToVec2XZ(obstacle->getPosition(), obsPos); + const float driftX = m_obstaclePosition.x - obsPos.x; + const float driftY = m_obstaclePosition.y - obsPos.y; + if (driftY * driftY + driftX * driftX < 0.25f) { + Vec2 goal; + goal.x = 0.0f; + goal.y = 0.0f; + vec3ToVec2XZ(m_coordinate, goal); + const float toGoalX = goal.x - pos.x; + const float toGoalY = goal.y - pos.y; + const float goalToObs = length2(obsPos.x - goal.x, obsPos.y - goal.y); + const float r = m_obstacleRadius; + const float reach = (r - goalToObs) + 0.8f; + const bool goalClose = toGoalY * toGoalY + toGoalX * toGoalX < reach * reach; + if ((m_avoiding && goalToObs <= r + && (goalClose || (m_avoidDistance < r && obsDistSqr <= (r + 1.0f) * (r + 1.0f)))) + || ((!passing || isOwnTarget) && goalToObs <= r && goalClose)) { + m_cachedDir = dir; + return true; + } + target = m_avoidPoint; + dir.x = target.x - pos.x; + dir.y = target.y - pos.y; + dist = length2(dir.x, dir.y); + } else { + m_obstacle = 0xFFFFFFFFu; + } + } + } + + if (getIsSprinting() && 1.1920929e-07f < std::fabs(target.y - 0.0f) + std::fabs(target.x - 0.0f)) + setIsSprinting(bot, true, bapinline::vec3(target.x, 0.0f, target.y), 0xFFFFFFFFu); + + bool straight = true; + if (m_obstacle != 0xFFFFFFFFu) { + if (dist < 0.3f) + m_obstacle = 0xFFFFFFFFu; + if (m_obstacle != 0xFFFFFFFFu && !passing && 0.5f < dist) { + straight = false; + Vec2 toAvoid; + toAvoid.x = m_avoidPoint.x - pos.x; + toAvoid.y = m_avoidPoint.y - pos.y; + bapinline::normalize(toAvoid); + Vec2 toObs; + toObs.x = m_obstaclePosition.x - pos.x; + toObs.y = m_obstaclePosition.y - pos.y; + bapinline::normalize(toObs); + if (toAvoid.y * toObs.y + toAvoid.x * toObs.x <= 0.05f) { + dir.x *= 1.0f / dist; + dir.y = (1.0f / dist) * dir.y; + } else { + // Step round the obstacle: from its centre through the point one unit towards the + // avoid point, out to m_avoidDistance. + Vec2 out; + out.x = (pos.x + toAvoid.x) - m_obstaclePosition.x; + out.y = (pos.y + toAvoid.y) - m_obstaclePosition.y; + bapinline::normalize(out); + dir.x = (out.x * m_avoidDistance + m_obstaclePosition.x) - pos.x; + dir.y = (m_avoidDistance * out.y + m_obstaclePosition.y) - pos.y; + bapinline::normalize(dir); + } + } + } + if (straight) { + if (0.001f < dist) { + dir.x *= 1.0f / dist; + dir.y = (1.0f / dist) * dir.y; + } else { + dir.x = 1.0f; + dir.y = 0.0f; + } + } + m_cachedDir = dir; + m_cachedResult = false; + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h new file mode 100644 index 000000000..9c462a1c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.h @@ -0,0 +1,83 @@ +// Move statement base with soldier-pose and obstacle-avoidance state. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO_H + +#include "../../../../Math/Vec3.h" +#include "BAPAComponentSoldierPose.h" +#include "BAPAction.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; + +// ELF: vtable 0x4B7F40 (40 words), package C-actions. +// Size 0xB4. Move statement base: the move entries call getTargetDir/update and read the public +// fields below inline. The BAPAComponentSoldierPose part sits at +0x14 (vtable 0x4B7FA8). +class BAPAMoveTo : public BAPAction, public BAPAComponentSoldierPose +{ +public: + explicit BAPAMoveTo(Bot*); // 0x1D5310 + virtual ~BAPAMoveTo(); // 0x1D5550 + + virtual unsigned long long getControls(); // 0x1D5650, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D5710, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D5720, slot +0x14; from the base declaration + virtual bool getIsSprinting(); // 0x1D5700, slot +0x20; [INFERRED] ELF bool + virtual bool getIsMovingAway(); // 0x1D6880, slot +0x24 + virtual Vec2& getCurrentPoint(); // 0x1D6890, slot +0x28 (+0x6C) + virtual int update(Vec2&, bool&, bool&, float); // 0x1D68A0, slot +0x2C; ELF bool (`al`), kept int: F's BAPAMoveToDirect overrides it as int + virtual bool isFinished(Bot*); // 0x1D68B0, slot +0x30 + virtual bool getSecondPoint(Vec2&); // 0x1D68F0, slot +0x34 + virtual bool getLargestAngleDiff(float&); // 0x1D6900, slot +0x38 + virtual float getTargetDistance(); // 0x1D6910, slot +0x3C + virtual unsigned int getObject(); // 0x1D6930, slot +0x40 (information handle, -1 = none) + virtual float getSimpleTargetDistance(Bot*); // 0x1D5760, slot +0x44 + virtual float getSimpleTargetDistanceSqr(Bot*); // 0x1D5810, slot +0x48 + virtual int usesPathfinding() = 0; // no body, slot +0x4C (ELF bool; kept int for F/H overrides) + virtual int withinDistance() = 0; // no body, slot +0x50 (ELF bool; kept int for F overrides) + virtual bool isStuck(); // 0x1D6940, slot +0x54 + + void setIsSprinting(Bot*, bool, const Vec3&, unsigned int); // 0x1D5660 + Vec3& getCoordinate(); // 0x1D5730 (+0x44) + float getMaxSpeed(); // 0x1D5740 + float getMaxArriveSpeed(); // 0x1D5750 + bool getTargetDir(Bot*, Vec2, Vec2&, Information*, bool); // 0x1D58B0 + + // Read and written inline by the move entries and the subclasses. [INFERRED] names. + /* +0x40 */ bool m_isSprinting; + /* +0x44 */ Vec3 m_coordinate; // the goal + /* +0x50 */ float m_maxSpeed; + /* +0x54 */ float m_maxArriveSpeed; + /* +0x58 */ BAPCondition* m_endCondition; // owned; isFinished evaluates it + /* +0x5C */ bool m_pathValid; // initPathfinding's answer (BAPAMoveToFinding) + // BoatControl::speedControl (ELF 0x2AA759, 0x2AA802..0x2AA814) reads/writes these samples. + /* +0x60 */ float m_previousSpeed; // = 0 + /* +0x64 */ Vec2 m_previousHeading; // = (1, 0) + /* +0x6C */ Vec2 m_currentPoint; // = 0; updatePath's next point + /* +0x74 */ Vec2 m_vec74; // = 0; [UNRESOLVED] + /* +0x7C */ int m_unwritten7C; // [UNRESOLVED] not written by the constructor + // Obstacle avoidance state of getTargetDir / updateInfantryMoveToPosWithObstacles. + /* +0x80 */ unsigned int m_obstacle; // information handle, -1 = none + /* +0x84 */ Vec2 m_avoidPoint; + /* +0x8C */ float m_obstacleRadius; + /* +0x90 */ float m_avoidDistance; + /* +0x94 */ Vec2 m_obstaclePosition; + /* +0x9C */ bool m_avoiding; + /* +0xA0 */ double m_nextDirTime; // = -1000.0 + /* +0xA8 */ Vec2 m_cachedDir; + /* +0xB0 */ bool m_cachedResult; + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp new file mode 100644 index 000000000..e531732b5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp @@ -0,0 +1,126 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D6F80 (__tcf_0 0x1D6FE0, _GLOBAL__I 0x1D7010): 's Init object only. +#include + +#include "BAPAMoveTo3d.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +Vec3 row(const Mat4& m, int r) +{ + return bapinline::vec3(m.m[r * 4], m.m[r * 4 + 1], m.m[r * 4 + 2]); +} +} // namespace + +// ELF 0x1D6B90 (C1; C2 0x1D6950). Store order of the image: +0x14 = 0, speeds, condition, point, +// +0x3C = 0, +0x4C/+0x58 = 0, +0x48 distance, the rest 0; then the bot's current equipment (no null +// test): +0x10 pattern id, condition +4 = this, +0x54 = getAltitude (vfn +0x38) of its +// IPIMobile::getSpeed (vfn +0x1C), +8 controls, +0x58/+0x64/+0x70 = transformation rows 2/1/0, +// +0x3C = 0 again. +BAPAMoveTo3d::BAPAMoveTo3d(Bot* bot, const Vec3& point, float maxSpeed, float maxArriveSpeed, + BAPCondition* breakCondition, unsigned long long controls, float distance, int patternId) +{ + m_vec14 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_breakCondition = breakCondition; + m_point = point; + m_vec3C = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_int4C = 0; + m_distance = distance; + m_int50 = 0; + m_forward = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_up = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 0.0f); + Information* equipment = bapinline::info(bot->getCurrentEquipment()); + m_patternId = patternId; + if (m_breakCondition) + m_breakCondition->setOwner(this); + m_altitude = equipment->getAltitude(equipment->getMobile()->getSpeed()); + m_controls = controls; + m_forward = row(equipment->getTransformation(), 2); + m_right = row(equipment->getTransformation(), 0); + m_up = row(equipment->getTransformation(), 1); + m_vec3C = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D6E30 (D0 0x1D6E90): deletes the condition (vfn +0x10). +BAPAMoveTo3d::~BAPAMoveTo3d() +{ + if (m_breakCondition) + delete m_breakCondition; +} + +// ELF 0x1D6F00: the entry drives the move; executed directly it answers ok = false, finished = true. +bool BAPAMoveTo3d::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1D6F20 +unsigned long long BAPAMoveTo3d::getControls() +{ + return m_controls; +} + +// ELF 0x1D7030 +BAPStatementType BAPAMoveTo3d::getId() const +{ + return BAPSTMoveTo; // 7 +} + +// ELF 0x1D6F30 +bool BAPAMoveTo3d::hasDefault() +{ + return false; +} + +// ELF 0x1D7040: the break condition's evaluate (vfn +0), false without one. +bool BAPAMoveTo3d::isFinished(Bot* bot) +{ + bool finished = false; + if (m_breakCondition) + finished = m_breakCondition->evaluate(bot); + return finished; +} + +// ELF 0x1D6F40 +float BAPAMoveTo3d::getMaxSpeed() +{ + return m_maxSpeed; +} + +// ELF 0x1D6F50 +float BAPAMoveTo3d::getMaxArriveSpeed() +{ + return m_maxArriveSpeed; +} + +// ELF 0x1D6F60 +BAPCondition* BAPAMoveTo3d::getBreakCondition() +{ + return m_breakCondition; +} + +// ELF 0x1D6F70 +Vec3* BAPAMoveTo3d::getFirstPoint() +{ + return &m_point; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h new file mode 100644 index 000000000..d5b213107 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.h @@ -0,0 +1,64 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3D_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8080 (9 words), package F-infantry. +// 3d (air) move to a point, driven by its plan entry; execute itself answers false/finished. +// operator new 0x7C (BBPChange::createPlan). +class BAPAMoveTo3d : public BAPAction +{ +public: + BAPAMoveTo3d(Bot*, const Vec3&, float, float, BAPCondition*, unsigned long long, float, int); // 0x1D6B90 + virtual ~BAPAMoveTo3d(); // 0x1D6E30 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D6F00, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D6F20, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D7030, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D6F30, slot +0x14; from the base declaration + virtual bool isFinished(Bot*); // 0x1D7040, slot +0x20; [INFERRED] ELF int + + float getMaxSpeed(); // 0x1D6F40; x87 load of +0x20 + float getMaxArriveSpeed(); // 0x1D6F50; x87 load of +0x24 + BAPCondition* getBreakCondition(); // 0x1D6F60; returns +0x28 (was [INFERRED] int) + Vec3* getFirstPoint(); // 0x1D6F70; returns this + 0x2C (was [INFERRED] int) + +private: + // [INFERRED] friendship: EntryHeliMoveTo reads +0x3C/+0x48 inline (ELF 0x2B69B0). + friend class EntryHeliMoveTo; + // [INFERRED] friendship: EntryPlaneMoveTo reads/writes +0x48/+0x4C/+0x58..+0x78 inline (ELF 0x2C0C80). + friend class EntryPlaneMoveTo; + /* +0x14 */ Vec3 m_vec14; // = 0 [UNRESOLVED] + /* +0x20 */ float m_maxSpeed; + /* +0x24 */ float m_maxArriveSpeed; + /* +0x28 */ BAPCondition* m_breakCondition; // owned (deleted by the destructor), owner = this + /* +0x2C */ Vec3 m_point; // the goal + /* +0x38 */ int m_unwritten38; // not written by the constructor + /* +0x3C */ Vec3 m_vec3C; // [INFERRED] previous velocity sample; EntryHeliMoveTo + /* +0x48 */ float m_distance; // the constructor's 7th argument (createPlan: 25.0) + /* +0x4C */ float m_int4C; // [INFERRED] previous equipment height; EntryPlaneMoveTo + /* +0x50 */ int m_int50; // = 0 [UNRESOLVED] + /* +0x54 */ float m_altitude; // current equipment's getAltitude(its IPIMobile::getSpeed()) + /* +0x58 */ Vec3 m_forward; // current equipment's transformation row 2 + /* +0x64 */ Vec3 m_up; // row 1 + /* +0x70 */ Vec3 m_right; // row 0 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp new file mode 100644 index 000000000..3b087da5d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp @@ -0,0 +1,107 @@ +// Three-dimensional direction move recovered from libaidll.so. +// static init: ELF 0x1D7900 (__tcf_0 0x1D7960, _GLOBAL__I 0x1D7990): 's Init object only. +#include +#include "BAPAMoveTo3dDirection.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D71F0 (C1; C2 0x1D7080) +BAPAMoveTo3dDirection::BAPAMoveTo3dDirection(const Vec3& target, float maxSpeed, + float maxArriveSpeed, const Vec3& direction, BAPCondition* condition, + unsigned long long controls, float altitude, int patternId) + : BAPAction(UninitializedPatternId()), m_maxSpeed(maxSpeed), m_maxArriveSpeed(maxArriveSpeed), + m_altitude(altitude), m_vector24(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_target(target), m_direction(direction), m_forward(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_up(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_right(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_endCondition(condition), m_vector70(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_vector7C(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_state(0), m_initialize(false) +{ + m_patternId = patternId; + m_controls = controls; + if (condition) + condition->setOwner(this); + m_forward = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_up = bapinline::vec3(0.0f, 1.0f, 0.0f); + m_vector24 = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D74A0 (C1; C2 0x1D7360) +BAPAMoveTo3dDirection::BAPAMoveTo3dDirection(float distance, float maxSpeed, + float maxArriveSpeed, BAPCondition* condition, unsigned long long controls, + float altitude, int patternId) + : BAPAction(UninitializedPatternId()), m_maxSpeed(maxSpeed), m_maxArriveSpeed(maxArriveSpeed), + m_altitude(altitude), m_vector24(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_target(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_direction(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_forward(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_up(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_right(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_endCondition(condition), + m_vector70(bapinline::vec3(0.0f, 0.0f, 0.0f)), m_vector7C(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_state(0), m_distance(distance), m_initialize(true) +{ + m_patternId = patternId; + m_controls = controls; + if (condition) + condition->setOwner(this); + m_forward = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_up = bapinline::vec3(0.0f, 1.0f, 0.0f); +} + +// ELF 0x1D7640 (D1; D2 0x1D75E0, D0 0x1D76A0) +BAPAMoveTo3dDirection::~BAPAMoveTo3dDirection() +{ + delete m_endCondition; +} + +// ELF 0x1D7710 +bool BAPAMoveTo3dDirection::execute(Bot* bot, bool& success, bool& finished) +{ + success = false; + finished = true; + if (m_initialize) { + m_initialize = false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + const Mat4& transform = self->getTransformation(); + m_target = bapinline::vec3(m_distance * transform.m[8] + transform.m[12], + m_distance * transform.m[9] + transform.m[13], + m_distance * transform.m[10] + transform.m[14]); + m_target.y = m_altitude; + Vec3 direction = bapinline::vec3(transform.m[8], 0.0f, transform.m[10]); + bapinline::normalize(direction); + m_direction = direction; + } + return false; +} + +// ELF 0x1D78E0 +unsigned long long BAPAMoveTo3dDirection::getControls() +{ + return m_controls; +} + +// ELF 0x1D79F0 +BAPStatementType BAPAMoveTo3dDirection::getId() const +{ + return BAPSTMoveToDirection; +} + +// ELF 0x1D78F0 +bool BAPAMoveTo3dDirection::hasDefault() +{ + return false; +} + +// ELF 0x1D79B0 +bool BAPAMoveTo3dDirection::isFinished(Bot* bot) +{ + return m_endCondition && m_endCondition->evaluate(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.h new file mode 100644 index 000000000..4107b0bb5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.h @@ -0,0 +1,54 @@ +// Three-dimensional direction move with optional first-execution target initialization. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DDIRECTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DDIRECTION_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B80C0 (9 words), package H-deferred. +class BAPAMoveTo3dDirection : public BAPAction +{ +public: + BAPAMoveTo3dDirection(const Vec3&, float, float, const Vec3&, BAPCondition*, unsigned long long, float, int); // 0x1D71F0 + BAPAMoveTo3dDirection(float, float, float, BAPCondition*, unsigned long long, float, int); // 0x1D74A0 + virtual ~BAPAMoveTo3dDirection(); // 0x1D7640 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D7710, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D78E0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D79F0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D78F0, slot +0x14; from the base declaration + virtual bool isFinished(Bot*); // 0x1D79B0, slot +0x20; [INFERRED] ELF int + // [INFERRED] names; plane-interpreter readers distinguish scalar and vector state. + /* +0x14 */ float m_maxSpeed; + /* +0x18 */ float m_maxArriveSpeed; + /* +0x1C */ float m_currentAltitude; // left uninitialized by both constructors + /* +0x20 */ float m_altitude; + /* +0x24 */ Vec3 m_vector24; // [INFERRED] previous velocity sample; EntryHeliMoveToDirection (ELF 0x2B6D30) + /* +0x30 */ Vec3 m_target; + /* +0x3C */ Vec3 m_direction; + /* +0x48 */ Vec3 m_forward; + /* +0x54 */ Vec3 m_up; + /* +0x60 */ Vec3 m_right; + /* +0x6C */ BAPCondition* m_endCondition; + /* +0x70 */ Vec3 m_vector70; + /* +0x7C */ Vec3 m_vector7C; + /* +0x88 */ int m_state; + /* +0x8C */ float m_distance; // first constructor leaves this uninitialized + /* +0x90 */ bool m_initialize; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DDIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp new file mode 100644 index 000000000..37b6b33a9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp @@ -0,0 +1,109 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1D7EF0 (__tcf_0 0x1D7F50, _GLOBAL__I 0x1D7F80): 's Init object only. +#include + +#include "BAPAMoveTo3dObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D7B80 (C1; C2 0x1D7A00). Zeroes +0x28..+0x7C and +0x84, stores the arguments, condition +// +4 = this, +0x80 = object has an IPIMobile (only when the information exists), then the three +// axes (+0x74 (1,0,0), +0x68 (0,0,1), +0x5C (0,1,0)) and +0x34 = 0. +BAPAMoveTo3dObject::BAPAMoveTo3dObject(unsigned int object, float f18, float maxSpeed, float maxArriveSpeed, + float distance, BAPCondition* breakCondition, unsigned long long controls, + int patternId) +{ + m_object = object; + m_float18 = f18; + m_maxSpeed = maxSpeed; + m_breakCondition = breakCondition; + m_point = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_maxArriveSpeed = maxArriveSpeed; + m_vec34 = bapinline::vec3(0.0f, 0.0f, 0.0f); + for (int i = 0; i < 4; ++i) + m_int40[i] = 0; + m_distance = distance; + m_up = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_forward = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_int84 = 0; + m_patternId = patternId; + m_controls = controls; + if (breakCondition) + breakCondition->setOwner(this); + Information* info = bapinline::info(m_object); + if (info) + m_objectMobile = info->getMobile() != 0; + m_right = bapinline::vec3(1.0f, 0.0f, 0.0f); + m_forward = bapinline::vec3(0.0f, 0.0f, 1.0f); + m_up = bapinline::vec3(0.0f, 1.0f, 0.0f); + m_vec34 = bapinline::vec3(0.0f, 0.0f, 0.0f); +} + +// ELF 0x1D7D60 (D0 0x1D7DC0): deletes the condition (vfn +0x10). +BAPAMoveTo3dObject::~BAPAMoveTo3dObject() +{ + if (m_breakCondition) + delete m_breakCondition; +} + +// ELF 0x1D7E30: as BAPAMoveTo3d::execute. +bool BAPAMoveTo3dObject::execute(Bot*, bool& ok, bool& finished) +{ + ok = false; + finished = true; + return false; +} + +// ELF 0x1D7FA0 +unsigned long long BAPAMoveTo3dObject::getControls() +{ + return m_controls; +} + +// ELF 0x1D7FB0 +BAPStatementType BAPAMoveTo3dObject::getId() const +{ + return BAPSTMoveToObject; // 9 +} + +// ELF 0x1D7FC0 +bool BAPAMoveTo3dObject::hasDefault() +{ + return false; +} + +// ELF 0x1D7FD0 +bool BAPAMoveTo3dObject::isFinished(Bot* bot) +{ + bool finished = false; + if (m_breakCondition) + finished = m_breakCondition->evaluate(bot); + return finished; +} + +// ELF 0x1D7E50: refresh +0x28 from the object (getPosition vfn +0x30, or with +0x80 the IPIMobile +// position estimate vfn +0x2C) when it still exists; return it. +Vec3* BAPAMoveTo3dObject::getFirstPoint() +{ + Information* info = bapinline::info(m_object); + if (info) { + if (!m_objectMobile) + m_point = info->getPosition(); + else + info->getMobile()->getPositionEstimate(m_point); + } + return &m_point; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.h new file mode 100644 index 000000000..9ec7a282d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.h @@ -0,0 +1,62 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8100 (9 words), package F-infantry. +// 3d (air) move to an object, driven by its plan entry; execute itself answers false/finished. +// operator new 0x88 (BBPChange::createPlan). +class BAPAMoveTo3dObject : public BAPAction +{ +public: + BAPAMoveTo3dObject(unsigned int, float, float, float, float, BAPCondition*, unsigned long long, int); // 0x1D7B80 + virtual ~BAPAMoveTo3dObject(); // 0x1D7D60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D7E30, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1D7FA0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D7FB0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D7FC0, slot +0x14; from the base declaration + virtual bool isFinished(Bot*); // 0x1D7FD0, slot +0x20; [INFERRED] ELF int + + Vec3* getFirstPoint(); // 0x1D7E50; refreshes and returns this + 0x28 (was [INFERRED] int) + +private: + // [INFERRED] friendship: EntryHeliMoveToObject reads +0x34/+0x50 inline (ELF 0x2B73E0). + friend class EntryHeliMoveToObject; + // [INFERRED] friendship: EntryPlaneMoveToObject reads/writes +0x14..+0x20/+0x40/+0x50/+0x5C..+0x84 inline (ELF 0x2C2AD0). + friend class EntryPlaneMoveToObject; + /* +0x14 */ unsigned int m_object; // information handle + /* +0x18 */ float m_float18; // createPlan: 0.5 [UNRESOLVED] + /* +0x1C */ float m_maxSpeed; + /* +0x20 */ float m_maxArriveSpeed; + /* +0x24 */ BAPCondition* m_breakCondition; // owned, owner = this + /* +0x28 */ Vec3 m_point; // getFirstPoint: the object's position or position estimate + /* +0x34 */ Vec3 m_vec34; // [INFERRED] previous velocity sample; EntryHeliMoveToObject + /* +0x40 */ float m_int40[4]; // [INFERRED] first element: previous speed magnitude; others [UNRESOLVED] + /* +0x50 */ float m_distance; // createPlan: 25.0 + /* +0x54 */ int m_unwritten54[2]; // not written by the constructor + /* +0x5C */ Vec3 m_up; // (0, 1, 0) + /* +0x68 */ Vec3 m_forward; // (0, 0, 1) + /* +0x74 */ Vec3 m_right; // (1, 0, 0) + /* +0x80 */ bool m_objectMobile; // the object has an IPIMobile (+0x38); only set when it exists + /* +0x84 */ float m_int84; // [INFERRED] previous equipment height; EntryPlaneMoveToObject +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETO3DOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp new file mode 100644 index 000000000..6bde413cf --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp @@ -0,0 +1,62 @@ +// Direct move statement (no pathfinding). Recovered from libaidll.so 1.5.3153 (ia-32); ELF +// addresses on every body. + +#include "BAPAMoveToDirect.h" + +#include "BAPCondition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1D8330, __tcf_0 0x1D8390, _GLOBAL__I 0x1D83C0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D8110 (C1; C2 0x1D8010): the base, +0xB4 = (0, 0), the arguments, the end condition's +// owner when there is one, +0x60 = 0, +0x5C = true, the goal in XZ, then the controls. +BAPAMoveToDirect::BAPAMoveToDirect(Bot* bot, const Vec3& coordinate, float maxSpeed, float maxArriveSpeed, + BAPCondition* endCondition, unsigned long long controls, int patternId) + : BAPAMoveTo(bot) +{ + m_goal2d.x = 0.0f; + m_goal2d.y = 0.0f; + m_bot = bot; + m_patternId = patternId; + m_coordinate = coordinate; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_previousSpeed = 0.0f; + m_pathValid = true; + vec3ToVec2XZ(coordinate, m_goal2d); + m_controls = controls; +} + +// ELF 0x1D8250 (D1; D2 0x1D8210, D0 0x1D8290, thunks 0x1D83E0 / 0x1D8400): base only. +BAPAMoveToDirect::~BAPAMoveToDirect() +{ +} + +// ELF 0x1D82E0: runs only through the move entries. +bool BAPAMoveToDirect::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1D8300: always the goal; neither flag is raised. +int BAPAMoveToDirect::update(Vec2& point, bool& reached, bool& done, float) +{ + point = m_goal2d; + reached = false; + done = false; + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.h new file mode 100644 index 000000000..bcccaa652 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.h @@ -0,0 +1,40 @@ +// Move statement that steers straight at its goal. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAMoveTo.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8140 (40 words), package F-infantry. Steers straight at the goal without +// pathfinding; size 0xC0 (`operator new(0xc0)` in BBPGotoWaypointBoat::createPlan). +class BAPAMoveToDirect : public BAPAMoveTo +{ +public: + BAPAMoveToDirect(Bot*, const Vec3&, float, float, BAPCondition*, unsigned long long, int); // 0x1D8110 + virtual ~BAPAMoveToDirect(); // 0x1D8250 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D82E0, slot +0x00; from the base declaration + virtual int update(Vec2&, bool&, bool&, float); // 0x1D8300, slot +0x2C; from the base declaration + virtual int usesPathfinding() { return 0; } // 0x1D8420 (weak), slot +0x4C + virtual int withinDistance() { return 0; } // 0x1D8430 (weak), slot +0x50 + + /* +0xB4 */ Vec2 m_goal2d; // the goal in XZ; update hands it out + /* +0xBC */ Bot* m_bot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp new file mode 100644 index 000000000..7d7e49c53 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp @@ -0,0 +1,61 @@ +// Direction-move base recovered from libaidll.so. +// static init: ELF 0x1D8600 (__tcf_0 0x1D8660, _GLOBAL__I 0x1D8690): 's Init object only. +#include +#include "BAPAMoveToDirection.h" +#include "BAPCondition.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D8520 (C1; C2 0x1D8440) +BAPAMoveToDirection::BAPAMoveToDirection() + : BAPAction(UninitializedPatternId()), + BAPAComponentSoldierPose(SPStanding, SPLying, 1.0f, SPCrouching, 0.0f, 0xFFFFFFFFu, 5.0f), + m_point(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_direction(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_state68(bapinline::vec3(0.0f, 0.0f, 0.0f)) +{ +} + +// ELF 0x1D8740 (D1; D0 0x1D87D0) +BAPAMoveToDirection::~BAPAMoveToDirection() +{ +} + +// ELF 0x1D86B0 +unsigned long long BAPAMoveToDirection::getControls() +{ + return m_controls; +} + +// ELF 0x1D86C0 +BAPStatementType BAPAMoveToDirection::getId() const +{ + return BAPSTMoveToDirection; +} + +// ELF 0x1D86D0 +bool BAPAMoveToDirection::hasDefault() +{ + return false; +} + +// ELF 0x1D86E0: the Boolean reference is deliberately untouched. +int BAPAMoveToDirection::update(Vec2& point, bool&) +{ + point.x = m_point.x; + point.y = m_point.z; + return 1; +} + +// ELF 0x1D8700 +bool BAPAMoveToDirection::isFinished(Bot* bot) +{ + return m_endCondition && m_endCondition->evaluate(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.h new file mode 100644 index 000000000..c3935816c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.h @@ -0,0 +1,55 @@ +// Direction-move state shared by the direct and finding variants; derived classes own its conditions. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTION_H + +#include "../../../../Math/Vec3.h" +#include "BAPAComponentSoldierPose.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BAPCondition; + +// ELF: vtable 0x4B8200 (32 words). +class BAPAMoveToDirection : public BAPAction, public BAPAComponentSoldierPose +{ +public: + BAPAMoveToDirection(); // 0x1D8520 + virtual ~BAPAMoveToDirection(); // 0x1D8740 + + virtual unsigned long long getControls(); // 0x1D86B0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1D86C0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1D86D0, slot +0x14; from the base declaration + virtual int update(Vec2&, bool&); // 0x1D86E0, slot +0x20; [INFERRED] ELF int + virtual bool isFinished(Bot*); // 0x1D8700, slot +0x24; [INFERRED] ELF int + // [CHOSEN, not recovered] Names and integer types under AGENTS.md's unimplemented-slot exception. + // Pure in base/Direct/Finding: ia-32 vtables 0x4B8200/0x4B82C0/0x4B8360, + // amd-64 0x614D80/0x614EE0/0x615000, primary slots 10/11 (+0x28/+0x2C; +0x50/+0x58). + // EntryBoatMoveToDirection calls 0x2B2DFA / amd-64 0x2FF5CA pass only this; + // dec eax compares the full 32-bit result with 1, so a byte/bool return is insufficient. + virtual int unimplementedDirectionSlot10() = 0; + // Calls 0x2B2E5C (also reached from 0x2B30D7) / amd-64 0x2FF78D/0x2FF7A9: + // stack this,int 1|2 / rdi=this,esi=1|2; no caller consumes the result. + virtual void unimplementedDirectionSlot11(int) = 0; + // [INFERRED] names; constructors and interpreter readers attest the member sequence. + /* +0x40 */ Vec3 m_point; + /* +0x4C */ float m_maxSpeed; + /* +0x50 */ float m_maxArriveSpeed; + /* +0x54 */ Vec3 m_direction; + /* +0x60 */ BAPCondition* m_endCondition; + /* +0x64 */ BAPCondition* m_condition64; + /* +0x68 */ Vec3 m_state68; // [INFERRED] previous signed speed, then XZ facing; EntryTankMoveToDirection (ELF 0x2C4800) + /* +0x74 */ bool m_flag74; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp new file mode 100644 index 000000000..63116c3a6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp @@ -0,0 +1,67 @@ +// Direct direction move recovered from libaidll.so. +// static init: ELF 0x1D8E30 (__tcf_0 0x1D8E90, _GLOBAL__I 0x1D8EC0): 's Init object only. +#include +#include "BAPAMoveToDirectionDirect.h" +#include "BAPCondition.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D8A30 (C1; C2 0x1D8860) +BAPAMoveToDirectionDirect::BAPAMoveToDirectionDirect(Bot*, Vec3& point, Vec3& direction, + float maxSpeed, float maxArriveSpeed, BAPCondition* condition, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveToDirection() +{ + m_firstPoint.x = 0.0f; + m_firstPoint.y = 0.0f; + m_condition64 = condition; + condition->setOwner(this); + m_patternId = patternId; + m_point = point; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_state68.x = 0.0f; + m_flag74 = true; + m_direction = direction; + bapinline::normalize(m_direction); + vec3ToVec2XZ(point, m_firstPoint); + m_controls = controls; +} + +// ELF 0x1D8CA0 (D1; D2 0x1D8C00, D0 0x1D8D40) +BAPAMoveToDirectionDirect::~BAPAMoveToDirectionDirect() +{ + delete m_endCondition; + delete m_condition64; +} + +// ELF 0x1D8DE0 +bool BAPAMoveToDirectionDirect::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1D8E00 +Vec2* BAPAMoveToDirectionDirect::getFirstPoint() +{ + return &m_firstPoint; +} + +// ELF 0x1D8E10 +Vec2* BAPAMoveToDirectionDirect::getSecondPoint(bool& flag) +{ + flag = m_flag74; + return &m_firstPoint; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.h new file mode 100644 index 000000000..188a95347 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.h @@ -0,0 +1,36 @@ +// Direct direction move with two owned conditions. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONDIRECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONDIRECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPAMoveToDirection.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B82C0 (30 words), package H-deferred. +class BAPAMoveToDirectionDirect : public BAPAMoveToDirection +{ +public: + BAPAMoveToDirectionDirect(Bot*, Vec3&, Vec3&, float, float, BAPCondition*, BAPCondition*, unsigned long long, int); // 0x1D8A30 + virtual ~BAPAMoveToDirectionDirect(); // 0x1D8CA0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D8DE0, slot +0x00; from the base declaration + + Vec2* getFirstPoint(); // ELF 0x1D8E00; [INFERRED] pointer spelling; returns the member address + Vec2* getSecondPoint(bool&); // ELF 0x1D8E10; [INFERRED] pointer spelling + + /* +0x78 */ Vec2 m_firstPoint; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONDIRECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp new file mode 100644 index 000000000..03afb9709 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp @@ -0,0 +1,74 @@ +// Finding direction move recovered from libaidll.so. +// static init: ELF 0x1D95F0 (__tcf_0 0x1D9650, _GLOBAL__I 0x1D9680): 's Init object only. +#include +#include "BAPAMoveToDirectionFinding.h" +#include "BAPCondition.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D9170 (C1; C2 0x1D8F20) +BAPAMoveToDirectionFinding::BAPAMoveToDirectionFinding(Bot* bot, Vec3& point, Vec3& direction, + float maxSpeed, float maxArriveSpeed, BAPCondition* condition, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveToDirection() +{ + m_firstPoint.x = m_firstPoint.y = 0.0f; + m_secondPoint.x = m_secondPoint.y = 0.0f; + Vec2 position = {0.0f, 0.0f}; + Information* self = bapinline::info(bot->getCurrentEquipment()); + m_condition64 = condition; + condition->setOwner(this); + m_patternId = patternId; + m_point = point; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_flag74 = true; + m_state68.x = 0.0f; + m_direction = direction; + bapinline::normalize(m_direction); + self->getMobile()->getVehicleNumber(); + // Shipped calls discard both results; neither stored path point is updated. + vec3ToVec2XZ(self->getPosition(), position); + m_controls = controls; +} + +// ELF 0x1D9460 (D1; D2 0x1D93C0, D0 0x1D9500) +BAPAMoveToDirectionFinding::~BAPAMoveToDirectionFinding() +{ + delete m_endCondition; + delete m_condition64; +} + +// ELF 0x1D95A0 +bool BAPAMoveToDirectionFinding::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1D95C0 +Vec2* BAPAMoveToDirectionFinding::getFirstPoint() +{ + return &m_firstPoint; +} + +// ELF 0x1D95D0 +Vec2* BAPAMoveToDirectionFinding::getSecondPoint(bool& flag) +{ + flag = m_flag74; + return &m_secondPoint; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.h new file mode 100644 index 000000000..30ff2a0f5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.h @@ -0,0 +1,37 @@ +// Direction move retaining the shipped zero-valued path points. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONFINDING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONFINDING_H + +#include "../../../../Math/Vec3.h" +#include "BAPAMoveToDirection.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8360 (30 words), package H-deferred. +class BAPAMoveToDirectionFinding : public BAPAMoveToDirection +{ +public: + BAPAMoveToDirectionFinding(Bot*, Vec3&, Vec3&, float, float, BAPCondition*, BAPCondition*, unsigned long long, int); // 0x1D9170 + virtual ~BAPAMoveToDirectionFinding(); // 0x1D9460 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D95A0, slot +0x00; from the base declaration + + Vec2* getFirstPoint(); // ELF 0x1D95C0; [INFERRED] pointer spelling + Vec2* getSecondPoint(bool&); // ELF 0x1D95D0; [INFERRED] pointer spelling + + /* +0x78 */ Vec2 m_firstPoint; // [INFERRED] names + /* +0x80 */ Vec2 m_secondPoint; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETODIRECTIONFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp new file mode 100644 index 000000000..dc5b89571 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp @@ -0,0 +1,231 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DA4D0 (__tcf_0 0x1DA530, _GLOBAL__I 0x1DA560): 's Init object only. +#include + +#include "BAPAMoveToFinding.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../AIBot/SquadMember.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1D9880 (C1; C2 0x1D96E0). The bot's getCurrentEquipment() result is discarded. +BAPAMoveToFinding::BAPAMoveToFinding(Bot* bot, const Vec3& coordinate, float maxSpeed, float maxArriveSpeed, + BAPCondition* endCondition, unsigned long long controls, int patternId, + float maxDistance, float minDistance) + : BAPAMoveTo(bot) +{ + m_flagD4 = false; + m_flagD5 = false; + m_intD8 = 1; + for (int i = 0; i < 8; ++i) + m_zeroB4[i] = 0; + m_bot = bot; + m_maxDistance = maxDistance; + m_minDistance = minDistance; + m_maxDistanceSqr = maxDistance * maxDistance; + m_minDistanceSqr = minDistance * minDistance; + m_pathDone = false; + bot->getCurrentEquipment(); + m_patternId = patternId; + m_coordinate = coordinate; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); + m_previousSpeed = 0.0f; + m_pathValid = true; + m_pathStarted = false; + m_controls = controls; + m_alternative.x = 0.0f; + m_alternative.y = 0.0f; +} + +// ELF 0x1D9A60 (D0 0x1D9AA0, thunk 0x1DA5A0): base only. +BAPAMoveToFinding::~BAPAMoveToFinding() +{ +} + +// ELF 0x1D9AF0: runs only through the move entries. +bool BAPAMoveToFinding::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1DA420 +void BAPAMoveToFinding::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << "MoveToFinding(" << static_cast(m_minDistance) << ", " << static_cast(m_maxDistance) + << ")" << std::endl; +} + +// ELF 0x1D9B10. Next path point into `point`; `reached`/`done` as the entries expect (the float +// argument is not read). A bot that waits for repairs, or whose vehicle is in the air but not in +// water, stops (reached = false, done = true). Pathfinding restarts when the goal moved or the +// search is not running; inside the ring [min + 1] round the goal a valid ring point is searched +// in 0.5 rad steps. Finally artillery: a target point in a danger zone the bot is not in stops +// the move; a soldier in a danger zone whose squad member avoids artillery sprints. +int BAPAMoveToFinding::update(Vec2& point, bool& reached, bool& done, float) +{ + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + if (static_cast(m_bot)->getShouldWaitForRepairs() + || (self->getPhysical()->isInAir() && !self->getPhysical()->isInWater())) { + reached = false; + done = true; + return 1; + } + + bool restart = !m_pathStarted; + if (!restart) { + BotNavigation* nav = m_bot->getBotNavigation(); + const Vec3& goal = nav->getGoal(); + const bool sameGoal = std::fabs(m_coordinate.x - goal.x) <= 1.1920929e-07f + && std::fabs(m_coordinate.y - goal.y) <= 1.1920929e-07f + && std::fabs(m_coordinate.z - goal.z) <= 1.1920929e-07f; + restart = !sameGoal || !m_bot->getBotNavigation()->isSearchActive(); + } + if (restart) { + m_pathStarted = true; + m_pathValid = m_bot->getBotNavigation()->initPathfinding(m_coordinate, 0.0f, m_maxDistance); + } + + bool result = false; + if (m_pathValid + && m_bot->getBotNavigation()->updatePath(m_currentPoint, m_pathDone, done, 0.0f)) { + result = true; + point = m_currentPoint; + reached = m_pathDone; + } + + const float distance = getSimpleTargetDistance(m_bot); + if (!(m_minDistance + 1.0f > distance) || !(m_minDistance > 1.0f)) { // 0x1D9C57 / 0x1D9C61 jbe + if (done) + goto finish; + if (isFinished(m_bot)) { + m_pathValid = true; + reached = true; + m_pathDone = true; + point = m_currentPoint; + result = true; + } + } else { + if (1.1920929e-07f < std::fabs(m_alternative.y - 0.0f) + std::fabs(m_alternative.x - 0.0f)) { + IPIMobile* mobile = self->getMobile(); + const int equipment = self->getUnit()->getEquipmentType(); + float angle = 0.0f; + bool valid; + do { + const float s = std::sin(angle); + const float c = std::cos(angle); + const float r = m_minDistance + 1.0f; + Vec3 p = bapinline::vec3(s * r + m_coordinate.x, r * 0.0f + m_coordinate.y, r * c + m_coordinate.z); + valid = IAIPathfinding::instance->isValidPosition(mobile->getVehicleNumber(), equipment, p, true); + if (valid) + vec3ToVec2XZ(p, m_alternative); + angle += 0.5f; + if (6.2831855f <= angle) { + if (!valid) + return 0; + break; + } + } while (!valid); + } + point = m_alternative; + } + + if (!done) { + const Vec3 target = bapinline::vec3(point.x, self->getPosition().y, point.y); + double sinceStart; + int artillerySide; + if (!(self->getObjectTypeFlags() & 0x10u)) { + const int side = m_bot->getSide(); + if (SquadManager::m_instance->isInArtilleryDangerZone(target, side, sinceStart, artillerySide) + && !SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), m_bot->getSide(), + sinceStart, artillerySide)) { + done = true; + goto finish; + } + } + if (self->getObjectTypeFlags() & 0x200000u) { + SquadMember* member; + if (SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), m_bot->getSide(), sinceStart, + artillerySide) + && (member = m_bot->getSquadMember()) != 0 && member->isAvoidingArtillery()) + setIsSprinting(m_bot, true, target, 0xFFFFFFFFu); + } + } + +finish: + if (!result) + m_pathStarted = false; + return result; +} + +// ELF 0x1DA3B0: end condition or within distance; then BotNavigation::clearProgress. +bool BAPAMoveToFinding::isFinished(Bot* bot) +{ + if ((!m_endCondition || !m_endCondition->evaluate(bot)) && !withinDistance()) + return false; + bot->getBotNavigation()->clearProgress(); + return true; +} + +// ELF 0x1DA260 +bool BAPAMoveToFinding::getSecondPoint(Vec2& point) +{ + return m_bot->getBotNavigation()->getSecondPoint(point); +} + +// ELF 0x1DA2B0 +bool BAPAMoveToFinding::getLargestAngleDiff(float& angle) +{ + return m_bot->getBotNavigation()->getLargestAngleDiff(angle); +} + +// ELF 0x1DA300: BotNavigation +0xBC. +float BAPAMoveToFinding::getTargetDistance() +{ + return m_bot->getBotNavigation()->getTargetDistance(); +} + +// ELF 0x1DA5C0 +int BAPAMoveToFinding::usesPathfinding() +{ + return 1; +} + +// ELF 0x1DA360: min^2 <= d^2 <= max^2. +int BAPAMoveToFinding::withinDistance() +{ + const float d = getSimpleTargetDistanceSqr(m_bot); + return (d <= m_maxDistanceSqr && m_minDistanceSqr <= d) ? 1 : 0; +} + +// ELF 0x1DA330: BotNavigation +0xC0. +bool BAPAMoveToFinding::isStuck() +{ + return m_bot->getBotNavigation()->getIsStuck(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.h new file mode 100644 index 000000000..67ddbc371 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.h @@ -0,0 +1,61 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOFINDING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOFINDING_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPAMoveTo.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8440 (40 words), package C-actions. +// Moves to a point with the bot's pathfinding (BotNavigation), finishing between the +// minimum and maximum distance. +class BAPAMoveToFinding : public BAPAMoveTo +{ +public: + BAPAMoveToFinding(Bot*, const Vec3&, float, float, BAPCondition*, unsigned long long, int, float, float); // 0x1D9880 + virtual ~BAPAMoveToFinding(); // 0x1D9A60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1D9AF0, slot +0x00; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1DA420, slot +0x1C; from the base declaration + virtual int update(Vec2&, bool&, bool&, float); // 0x1D9B10, slot +0x2C; from the base declaration + virtual bool isFinished(Bot*); // 0x1DA3B0, slot +0x30; from the base declaration + virtual bool getSecondPoint(Vec2&); // 0x1DA260, slot +0x34; from the base declaration + virtual bool getLargestAngleDiff(float&); // 0x1DA2B0, slot +0x38; from the base declaration + virtual float getTargetDistance(); // 0x1DA300, slot +0x3C; from the base declaration + virtual int usesPathfinding(); // 0x1DA5C0, slot +0x4C; from the base declaration + virtual int withinDistance(); // 0x1DA360, slot +0x50; from the base declaration + virtual bool isStuck(); // 0x1DA330, slot +0x54; from the base declaration + +private: + /* +0xB4 */ int m_zeroB4[8]; // +0xB4..+0xD0 = 0; [UNRESOLVED] + /* +0xD4 */ bool m_flagD4; // = false; [UNRESOLVED] + /* +0xD5 */ bool m_flagD5; // = false; [UNRESOLVED] + /* +0xD8 */ int m_intD8; // = 1; [UNRESOLVED] + /* +0xDC */ Bot* m_bot; + /* +0xE0 */ float m_maxDistance; // last-but-one ctor float; initPathfinding's radius + /* +0xE4 */ float m_minDistance; // last ctor float + /* +0xE8 */ float m_maxDistanceSqr; + /* +0xEC */ float m_minDistanceSqr; + /* +0xF0 */ Vec2 m_alternative; // valid point on the ring round the goal + /* +0xF8 */ bool m_pathDone; // updatePath's flag + /* +0xF9 */ bool m_pathStarted; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp new file mode 100644 index 000000000..5d9b558de --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp @@ -0,0 +1,111 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DAA60 (__tcf_0 0x1DAAC0, _GLOBAL__I 0x1DAAF0): 's Init object only. +#include + +#include "BAPAMoveToObject.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IBotManager.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DA690 (C1; C2 0x1DA5D0) +BAPAMoveToObject::BAPAMoveToObject(Bot* bot, unsigned int object, float distance, float maxSpeed, + float maxArriveSpeed, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveTo(bot) +{ + m_object = object; + m_distance = distance; + m_distanceSqr = distance * distance; + m_maxSpeed = maxSpeed; + m_maxArriveSpeed = maxArriveSpeed; + m_controls = controls; + m_patternId = patternId; + m_endCondition = endCondition; + if (endCondition) + endCondition->setOwner(this); +} + +// ELF 0x1DAB50 (D0 0x1DABB0, thunk 0x1DAC00): base only. +BAPAMoveToObject::~BAPAMoveToObject() +{ +} + +// ELF 0x1DA7D0: runs only through the move entries. +bool BAPAMoveToObject::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1DAB10 +unsigned long long BAPAMoveToObject::getControls() +{ + return m_controls; +} + +// ELF 0x1DAB20 +BAPStatementType BAPAMoveToObject::getId() const +{ + return BAPSTMoveToObject; // 9 +} + +// ELF 0x1DAB30 +bool BAPAMoveToObject::hasDefault() +{ + return false; +} + +// ELF 0x1DA9A0: the id is printed as a number here (this TU has no operator<< for the enum). +void BAPAMoveToObject::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << static_cast(getId()) << "(" << static_cast(m_distance) << ")" << std::endl; +} + +// ELF 0x1DA750: end condition or within m_distance; then BotNavigation::clearProgress. +bool BAPAMoveToObject::isFinished(Bot* bot) +{ + if ((!m_endCondition || !m_endCondition->evaluate(bot)) && m_distanceSqr <= getSimpleTargetDistanceSqr(bot)) + return false; + bot->getBotNavigation()->clearProgress(); + return true; +} + +// ELF 0x1DAB40 +unsigned int BAPAMoveToObject::getObject() +{ + return m_object; +} + +// ELF 0x1DA7F0 +float BAPAMoveToObject::getSimpleTargetDistance(Bot* bot) +{ + return std::sqrt(BAPAMoveToObject::getSimpleTargetDistanceSqr(bot)); // inline in the image (no virtual call) +} + +// ELF 0x1DA8E0: neither information is null-checked. +float BAPAMoveToObject::getSimpleTargetDistanceSqr(Bot* bot) +{ + const Vec3& a = bapinline::info(bot->getCurrentEquipment())->getPosition(); + const Vec3& b = bapinline::info(m_object)->getPosition(); + const double dz = static_cast(a.z) - b.z; + const double dx = static_cast(a.x) - b.x; + const double dy = static_cast(a.y) - b.y; + return static_cast(dz * dz + dx * dx + dy * dy); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.h new file mode 100644 index 000000000..26b98bfca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.h @@ -0,0 +1,48 @@ +// Object-targeted move base; owns its optional end condition through BAPAMoveTo. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECT_H + +#include +#include "BAPAMoveTo.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8500 (40 words), package C-actions. +// Moves to an object until within m_distance (or the end condition holds). +class BAPAMoveToObject : public BAPAMoveTo +{ +public: + BAPAMoveToObject(Bot*, unsigned int, float, float, float, BAPCondition*, unsigned long long, int); // 0x1DA690 + virtual ~BAPAMoveToObject(); // 0x1DAB50 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DA7D0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1DAB10, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1DAB20, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DAB30, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1DA9A0, slot +0x1C; from the base declaration + virtual bool isFinished(Bot*); // 0x1DA750, slot +0x30; from the base declaration + virtual unsigned int getObject(); // 0x1DAB40, slot +0x40; from the base declaration + virtual float getSimpleTargetDistance(Bot*); // 0x1DA7F0, slot +0x44; from the base declaration + virtual float getSimpleTargetDistanceSqr(Bot*); // 0x1DA8E0, slot +0x48; from the base declaration + + + /* +0xB4 */ unsigned int m_object; // information handle + /* +0xB8 */ float m_distance; + /* +0xBC */ float m_distanceSqr; + /* +0xC0 */ bool m_pathValid2; // not written here; BAPAMoveToObjectFinding sets it (initPathfinding's answer); [UNRESOLVED] name + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp new file mode 100644 index 000000000..05d0acb84 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp @@ -0,0 +1,52 @@ +// Direct object-move point source recovered from libaidll.so. +// static init: ELF 0x1DAF30 (__tcf_0 0x1DAF90, _GLOBAL__I 0x1DAFC0): 's Init object only. +#include +#include "BAPAMoveToObjectDirect.h" +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DACE0 (C1; C2 0x1DAC20) +BAPAMoveToObjectDirect::BAPAMoveToObjectDirect(Bot* bot, unsigned int object, + float distance, float maxSpeed, float maxArriveSpeed, BAPCondition* endCondition, + unsigned long long controls, int patternId) + : BAPAMoveToObject(bot, object, distance, maxSpeed, maxArriveSpeed, endCondition, + controls, patternId) +{ + m_isMobile = bapinline::info(object)->getMobile() != 0; +} + +// ELF 0x1DADE0 (D1; D2 0x1DADA0, D0 0x1DAE20) +BAPAMoveToObjectDirect::~BAPAMoveToObjectDirect() +{ +} + +// ELF 0x1DAE70 +Vec2& BAPAMoveToObjectDirect::getCurrentPoint() +{ + Information* object = bapinline::info(m_object); + if (object) { + if (m_isMobile) { + Vec3 position = bapinline::vec3(0.0f, 0.0f, 0.0f); + object->getMobile()->getPositionEstimate(position); + vec3ToVec2XZ(position, m_currentPoint); + } else { + vec3ToVec2XZ(object->getPosition(), m_currentPoint); + } + } + return m_currentPoint; +} + +// ELF 0x1DB020 +int BAPAMoveToObjectDirect::usesPathfinding() +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.h new file mode 100644 index 000000000..e9c0c9427 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.h @@ -0,0 +1,36 @@ +// Direct object-move point source; mobile availability is captured at construction. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTDIRECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTDIRECT_H + +#include "BAPAMoveToObject.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B85C0 (40 words), package H-deferred. +class BAPAMoveToObjectDirect : public BAPAMoveToObject +{ +public: + BAPAMoveToObjectDirect(Bot*, unsigned int, float, float, float, BAPCondition*, unsigned long long, int); // 0x1DACE0 + virtual ~BAPAMoveToObjectDirect(); // 0x1DADE0 + + virtual Vec2& getCurrentPoint(); // 0x1DAE70, slot +0x28; from the base declaration + virtual int usesPathfinding(); // 0x1DB020, slot +0x4C; from the base declaration +private: + // [UNRESOLVED] Unaccessed bytes before the mobile flag. Both images leave the span unwritten; + // retain its extent without assigning a semantic member type (ia-32 +0xC1..+0xC7). + unsigned char m_unwrittenC1[7]; + /* +0xC8 */ bool m_isMobile; // [INFERRED] name; amd-64 +0xE8 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTDIRECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp new file mode 100644 index 000000000..d82dc2a2a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp @@ -0,0 +1,500 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DD560 (__tcf_0 0x1DD5C0, _GLOBAL__I 0x1DD5F0): 's Init object only. +#include + +#include "BAPAMoveToObjectFinding.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIKnowledge/Information.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DB1A0 (C1; C2 0x1DB030) +BAPAMoveToObjectFinding::BAPAMoveToObjectFinding(Bot* bot, unsigned int object, float distance, float maxSpeed, + float maxArriveSpeed, BAPCondition* endCondition, + unsigned long long controls, int patternId, + BAPCondition* replanCondition, float minDistance, int index) + : BAPAMoveToObject(bot, object, distance, maxSpeed, maxArriveSpeed, endCondition, controls, patternId) +{ + m_flagE9 = false; + m_intEC = 1; + m_bot = bot; + for (int i = 0; i < 8; ++i) + m_zeroC8[i] = 0; + m_flagF8 = true; + m_replanCondition = replanCondition; + m_pathDone = false; + m_movingAway = false; + m_pathStarted = false; + m_minDistance = minDistance; + m_minDistanceSqr = minDistance * minDistance; + m_index = index; + m_lastInitTime = -1.0; + if (m_distance < minDistance) { + m_minDistance = m_distance; + m_minDistanceSqr = m_distanceSqr; + } + if (m_replanCondition) + m_replanCondition->setOwner(this); + m_flag107 = false; + m_pathValid2 = true; +} + +// ELF 0x1DC0C0 (D1; D0 0x1DC140, thunk 0x1DD630): deletes the replan condition. +BAPAMoveToObjectFinding::~BAPAMoveToObjectFinding() +{ + if (m_replanCondition) + delete m_replanCondition; +} + +// ELF 0x1DD430 +void BAPAMoveToObjectFinding::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << "MoveToObjectFinding"; + if (m_index != -1) + out << "[" << m_index << "]"; + out << "(" << static_cast(m_minDistance) << ", " << static_cast(m_distance) << ")" << std::endl; +} + +// ELF 0x1DD660 +bool BAPAMoveToObjectFinding::getIsMovingAway() +{ + return m_movingAway; +} + +namespace { + +bool sameVec3(const Vec3& a, const Vec3& b) +{ + return std::fabs(a.x - b.x) <= 1.1920929e-07f && std::fabs(a.y - b.y) <= 1.1920929e-07f + && std::fabs(a.z - b.z) <= 1.1920929e-07f; +} + +} // namespace + +// ELF 0x1DC1C0. Path to the object's last valid position. Fails (m_pathValid2 = false, 0) without +// the bot's or the object's information, the object's primary mobile, a valid position for the +// object, or (soldier, close in height) an active weapon; a bot without a valid position is +// marked stuck. A bot waiting for repairs or airborne out of water: reached = false, done, 1. +// Re-plans (initObjectFinding) when: the object is sensed only indirectly and its last valid +// position moved (once, m_flag107, and not while flanking with the path unfinished); the +// navigation goal is not m_coordinate; every second, when closer than m_minDistance and not +// flanking, or flanking with the target within m_minDistance of the goal and the path done, or +// with the path done, not within distance and the target moved; the search is not running +// (a fresh start: zero direction/origin, flag true); or every second when the re-plan condition +// holds (after it was false, or with the path done). Then updatePath (the float is passed on); +// a target point inside an artillery zone the bot is not in stops the move (done). A soldier +// chasing (not flanking) within 2 m of height sprints at the object while the path is shorter +// than its physical's radius + 25 (unless firing a weapon with range > 5 that is not type 4), +// otherwise stops sprinting; in an artillery zone with an avoiding squad member it sprints at +// the point. isFinished then completes the move. +int BAPAMoveToObjectFinding::update(Vec2& point, bool& reached, bool& done, float distance) +{ + BotMain* bot = static_cast(m_bot); + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self || !m_pathValid2) { + m_pathValid2 = false; + return 0; + } + if (bot->getShouldWaitForRepairs() || (self->getPhysical()->isInAir() && !self->getPhysical()->isInWater())) { + reached = false; + done = true; + return 1; + } + Information* target = bapinline::info(m_object); + if (!target) { + m_pathValid2 = false; + return 0; + } + IPIMobile* mobile = self->getMobile(); + const IPIMobile::ValidPos& own = mobile->getLastValidPosition(mobile->getVehicleNumber()); + Information* primary = bapinline::info(target->getPrimaryObject(self->getSide())); + if (!primary || !primary->getMobile()) { + m_pathValid2 = false; + return 0; + } + const IPIMobile::ValidPos& goal = primary->getMobile()->getLastValidPosition(mobile->getVehicleNumber()); + if (own.polygon == 0xFFFFFFFFu) { + bot->getBotNavigation()->setIsStuck(true); + m_pathValid2 = false; + return 0; + } + if (goal.polygon == 0xFFFFFFFFu) { + m_pathValid2 = false; + return 0; + } + Vec3 dir = bapinline::sub(goal.position, own.position); + float dist = std::sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); + if (0.0001f < dist) { + const float inv = 1.0f / dist; + dir.x *= inv; + dir.y *= inv; + dir.z = inv * dir.z; + } + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + const bool indirect = sensed ? (sensed->m_flags & 8u) != 0 : true; + if (!indirect) + m_flag107 = false; + const bool within = withinDistance() != 0; + const bool pathDone = m_pathDone; + const bool replanDue = 1.0 < bapinline::gameTime() - m_lastInitTime; + + // 0: no re-plan; 1: towards the target (dist, dir, own position, false); 2: fresh start. + int replan = 0; + bool checkNavigation = true; + if (indirect) { + if (!sameVec3(m_coordinate, goal.position) && !m_flag107 && !(m_movingAway && !pathDone)) { + m_flag107 = true; + replan = 1; + checkNavigation = false; + } + } + if (checkNavigation) { + bool searchCheck = true; + if (!sameVec3(m_coordinate, bot->getBotNavigation()->getGoal())) { + replan = 1; + searchCheck = false; + } else if (replanDue) { + if (m_movingAway || !(m_minDistance > dist)) { // 0x1DCCAB ja + if (m_movingAway) { + const Vec3 d = bapinline::sub(goal.position, m_coordinate); + if (d.x * d.x + d.y * d.y + d.z * d.z < m_minDistance * m_minDistance && pathDone) { + replan = 1; + searchCheck = false; + } + } + if (searchCheck && pathDone && !within && !sameVec3(m_coordinate, goal.position)) { + replan = 1; + searchCheck = false; + } + } else { + replan = 1; + searchCheck = false; + } + } + if (searchCheck) { + if (!m_pathStarted || !bot->getBotNavigation()->isSearchActive()) { + replan = 2; + } else if (replanDue && m_replanCondition && m_replanCondition->evaluate(m_bot)) { + if (!m_flagF8 || m_pathDone) { + m_flagF8 = true; + replan = 1; + } + } else { + m_flagF8 = false; + } + } + } + if (replan == 1) { + initObjectFinding(dist, dir, own.position, goal.quadTree, goal.polygon, goal.position, false); + } else if (replan == 2) { + const Vec3 zero = bapinline::vec3(0.0f, 0.0f, 0.0f); + initObjectFinding(0.0f, zero, zero, goal.quadTree, goal.polygon, goal.position, true); + } + + m_pathStarted = true; + if (!m_pathValid2) + return 0; + if (!m_movingAway) + bot->getBotNavigation()->updateLastPoint(primary); + const bool got = bot->getBotNavigation()->updatePath(m_currentPoint, m_pathDone, done, distance); + bool stopped = false; + const Vec3 target3 = bapinline::vec3(m_currentPoint.x, self->getPosition().y, m_currentPoint.y); + double sinceStart; + int artillerySide; + if (got) { + point = m_currentPoint; + reached = m_pathDone; + if (!(self->getObjectTypeFlags() & 0x10u) + && SquadManager::m_instance->isInArtilleryDangerZone(target3, bot->getSide(), sinceStart, artillerySide) + && !SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), bot->getSide(), sinceStart, + artillerySide)) { + done = true; + stopped = true; + } + } + if (!done) { + const bool soldier = (self->getObjectTypeFlags() & 0x200000u) != 0; + bool artilleryCheck = true; + if (!stopped && !m_movingAway && soldier + && std::fabs(target->getPosition().y - self->getPosition().y) < 2.0f) { + artilleryCheck = false; + const float pathLeft = bot->getBotNavigation()->getTargetDistance(); + IPIPhysical* physical = target->getPhysical(); + IPIArmament* armament = self->getArmament(); + if (!armament || armament->getActiveWeapon() == -1) { + m_pathValid2 = false; + return 0; + } + WeaponInfo* weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) { + m_pathValid2 = false; + return 0; + } + const Vec3 zero = bapinline::vec3(0.0f, 0.0f, 0.0f); + if ((!bot->isFiring() || !(weapon->getMaxRange() > 5.0f) || /* 0x1DCAB4 jbe */ weapon->getWeaponType() == 4) + && pathLeft < physical->getRadius() + 25.0f) + setIsSprinting(m_bot, true, zero, m_object); + else + setIsSprinting(m_bot, false, zero, 0xFFFFFFFFu); + } + if (artilleryCheck && soldier + && SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), bot->getSide(), sinceStart, + artillerySide)) { + SquadMember* member = bot->getSquadMember(); + if (member && member->isAvoidingArtillery()) + setIsSprinting(m_bot, true, target3, 0xFFFFFFFFu); + } + if (!done && isFinished(m_bot)) { + m_pathValid2 = true; + reached = true; + m_pathDone = true; + point = m_currentPoint; + return 1; + } + } + if (!got) { + m_pathStarted = false; + return 0; + } + return 1; +} + +// ELF 0x1DD340: end condition, or (when moving away) path done and within distance, or +// (otherwise) within distance; then BotNavigation::clearProgress. +bool BAPAMoveToObjectFinding::isFinished(Bot* bot) +{ + bool ended = false; + if (m_endCondition && m_endCondition->evaluate(bot)) + ended = true; + bool finished; + if (!m_movingAway) + finished = ended || withinDistance(); + else + finished = ended || (m_pathDone && withinDistance()); + if (finished) + bot->getBotNavigation()->clearProgress(); + return finished; +} + +// ELF 0x1DD200 +bool BAPAMoveToObjectFinding::getLargestAngleDiff(float& angle) +{ + return m_bot->getBotNavigation()->getLargestAngleDiff(angle); +} + +// ELF 0x1DD1D0: BotNavigation +0xBC. +float BAPAMoveToObjectFinding::getTargetDistance() +{ + return m_bot->getBotNavigation()->getTargetDistance(); +} + +// ELF 0x1DD020 (same body as BAPAMoveToObject's) +float BAPAMoveToObjectFinding::getSimpleTargetDistance(Bot* bot) +{ + return std::sqrt(BAPAMoveToObjectFinding::getSimpleTargetDistanceSqr(bot)); +} + +// ELF 0x1DD110: neither information is null-checked. +float BAPAMoveToObjectFinding::getSimpleTargetDistanceSqr(Bot* bot) +{ + const Vec3& a = bapinline::info(bot->getCurrentEquipment())->getPosition(); + const Vec3& b = bapinline::info(m_object)->getPosition(); + const double dz = static_cast(a.z) - b.z; + const double dx = static_cast(a.x) - b.x; + const double dy = static_cast(a.y) - b.y; + return static_cast(dz * dz + dx * dx + dy * dy); +} + +// ELF 0x1DD650 +int BAPAMoveToObjectFinding::usesPathfinding() +{ + return 1; +} + +// ELF 0x1DD250: min^2 <= d^2 <= m_distance^2. +int BAPAMoveToObjectFinding::withinDistance() +{ + const float d = getSimpleTargetDistanceSqr(m_bot); + return (d <= m_distanceSqr && m_minDistanceSqr <= d) ? 1 : 0; +} + +// ELF 0x1DB310: the horizontal right of a direction, (z, y, -x) - written y, x, z in that order +// (`mov 4(%edx)->4(%ecx); mov 8(%edx)->(%ecx); xor $0x80000000 of (%edx) -> 8(%ecx)`). A global +// function of this TU (called through the PLT). +void getRight(const Vec3& direction, Vec3& right) +{ + right.y = direction.y; + right.x = direction.z; + right.z = -direction.x; +} + +// ELF 0x1DB360 (0xDE0 bytes). `distance` is the current distance to the object, `ownPosition` +// the bot's, `goal` the object's last valid position with its quad tree / polygon; the direction +// argument is unused. Both path flags cleared; no bot or object information: m_pathValid2 = +// false and nothing else. The arrive distance is 1.1 * the object's physical radius (FLT_MAX +// without one). Then: +// * at or beyond m_minDistance (0x1DB496 `fucompi; jbe`) or `fresh`: no sprint, straight at the +// goal with the caller's quad tree / polygon. +// * nearer: three flank offsets of length d = min((m_distance - m_minDistance) * 0.2, 10) + +// m_minDistance round the goal - a soldier moving faster than 1.5 m/s horizontally (the object's +// mobile, or its primary's; not null-checked): the side of its velocity facing the bot +// (0x1DBD7E `setae`: flipped when dot < 0), its opposite and the right of the unflipped side; +// a soldier otherwise: away from the goal towards the bot, then its right and left; anything +// else (a vehicle): along the object's transformation row 2, then right and left. Sprinting +// from the bot's position, each offset is traced (IAIPathfinding slot +0x90, 0x1DB82A) until +// one is clear; the goal is 98 % of the way to the clear trace end, or else to the blocked end +// farthest from the goal (zero / -1 if none is farther than 0), with the trace's polygon and +// BotNavigation +0xCC as the island; its height is then the terrain's (slot +0x14). +// Then BotNavigation::initPathfinding(island, polygon, goal, arrive, m_distance) and the time. +void BAPAMoveToObjectFinding::initObjectFinding(float distance, const Vec3&, const Vec3& ownPosition, + unsigned int quadTree, unsigned int polygon, const Vec3& goal, + bool fresh) +{ + m_movingAway = false; + m_pathDone = false; + Information* self = bapinline::info(m_bot->getCurrentEquipment()); + if (!self) { + m_pathValid2 = false; + return; + } + Information* target = bapinline::info(m_object); + if (!target) { + m_pathValid2 = false; + return; + } + IPIMobile* mobile = target->getMobile(); + if (!mobile && !target->isPrimary()) { + Information* primary = bapinline::info(target->getPrimaryObject(m_bot->getSide())); + if (primary) + mobile = primary->getMobile(); + } + float arrive = 3.4028235e+38f; + if (IPIPhysical* physical = target->getPhysical()) + arrive = physical->getRadius() * 1.1f; // fmuls by the float constant 0x3F8CCCCD + const int equipmentType = self->getUnit()->getEquipmentType(); + + if (!(m_minDistance > distance) || fresh) { // 0x1DB496 jbe + m_movingAway = false; + setIsSprinting(m_bot, false, bapinline::vec3(0.0f, 0.0f, 0.0f), 0xFFFFFFFFu); + m_coordinate = goal; + } else { + Vec3 offsets[3]; + for (int i = 0; i < 3; ++i) + offsets[i] = bapinline::vec3(0.0f, 0.0f, 0.0f); + const Vec3& speed = mobile->getSpeed(); + Vec3 flat = bapinline::vec3(speed.x, 0.0f, speed.z); + const float flatSpeed = std::sqrt(flat.x * flat.x + 0.0f * 0.0f + flat.z * flat.z); + const bool soldier = (self->getObjectTypeFlags() & 0x200000u) != 0; + if (!soldier || !(flatSpeed > 1.5f)) { // 0x1DB53E ja + float d = (m_distance - m_minDistance) * 0.2f; + if (10.0f < d) + d = 10.0f; + d = d + m_minDistance; + if (!soldier) { + const Mat4& t = self->getTransformation(); + offsets[0] = bapinline::vec3(t.m[8] * d, t.m[9] * d, d * t.m[10]); + } else { + Vec3 away = bapinline::sub(ownPosition, goal); + bapinline::normalize(away); + offsets[0] = bapinline::vec3(away.x * d, away.y * d, d * away.z); + } + getRight(offsets[0], offsets[1]); + offsets[2] = bapinline::vec3(-offsets[1].x, -offsets[1].y, -offsets[1].z); + } else { + const float inv = 1.0f / flatSpeed; + flat = bapinline::vec3(flat.x * inv, flat.y * inv, inv * flat.z); + Vec3 side = bapinline::vec3(0.0f, 0.0f, 0.0f); + getRight(flat, side); + const bool behind = !(bapinline::dot(bapinline::sub(ownPosition, goal), side) >= 0.0f); // 0x1DBD7A setae + if (behind) + side = bapinline::vec3(-side.x, -side.y, -side.z); + float d = (m_distance - m_minDistance) * 0.2f; + if (10.0f < d) + d = 10.0f; + d = d + m_minDistance; + offsets[0] = bapinline::vec3(side.x * d, side.y * d, d * side.z); + offsets[1] = bapinline::vec3(-offsets[0].x, -offsets[0].y, -offsets[0].z); + const Vec3 unflipped = behind ? offsets[1] : offsets[0]; + getRight(unflipped, offsets[2]); + } + + m_movingAway = true; + setIsSprinting(m_bot, true, self->getPosition(), 0xFFFFFFFFu); + BotNavigation* navigation = m_bot->getBotNavigation(); + float bestDistSqr = 0.0f; + unsigned int bestPolygon = 0xFFFFFFFFu; + Vec3 end = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 best = bapinline::vec3(0.0f, 0.0f, 0.0f); + unsigned int endPolygon; + bool clear; + int i = 0; + do { + const Vec3 candidate = bapinline::add(offsets[i], goal); + clear = IAIPathfinding::instance->trace(navigation, false, candidate, end, endPolygon, equipmentType, -1, + 0.0f, 0, 0); + if (!clear) { + const Vec3 back = bapinline::sub(goal, end); + const float distSqr = back.x * back.x + back.y * back.y + back.z * back.z; + if (bestDistSqr < distSqr) { + best = bapinline::vec3(goal.x + (end.x - goal.x) * 0.98f, goal.y + (end.y - goal.y) * 0.98f, + goal.z + (end.z - goal.z) * 0.98f); + bestPolygon = endPolygon; + bestDistSqr = distSqr; + } + } + ++i; + } while (!clear && i < 3); + quadTree = navigation->getLastValidIsland(); + if (!clear) { + m_coordinate = best; + polygon = bestPolygon; + } else { + m_coordinate = bapinline::vec3(goal.x + (end.x - goal.x) * 0.98f, goal.y + (end.y - goal.y) * 0.98f, + goal.z + (end.z - goal.z) * 0.98f); + polygon = endPolygon; + } + } + + m_previousSpeed = 0.0f; + m_flagEA = false; + if (m_movingAway) + m_coordinate.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(m_coordinate.x, m_coordinate.z); + m_pathValid2 = m_bot->getBotNavigation()->initPathfinding(quadTree, polygon, m_coordinate, arrive, m_distance); + m_lastInitTime = bapinline::gameTime(); +} + +// ELF 0x1DD2A0: the bot's current vehicle/soldier is within 1 m of the goal (not null-checked). +bool BAPAMoveToObjectFinding::isAtCoordinate() +{ + const Vec3& p = bapinline::info(m_bot->getCurrentEquipment())->getPosition(); + return bapinline::lengthSqr(bapinline::sub(p, m_coordinate)) < 1.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.h new file mode 100644 index 000000000..a0921a06d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.h @@ -0,0 +1,67 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTFINDING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTFINDING_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPAMoveToObject.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B86C0 (40 words), package C-actions. +// Moves to an object with pathfinding, re-planning towards the object's last valid position +// (initObjectFinding) and sprinting/flanking as needed. +class BAPAMoveToObjectFinding : public BAPAMoveToObject +{ +public: + BAPAMoveToObjectFinding(Bot*, unsigned int, float, float, float, BAPCondition*, unsigned long long, int, BAPCondition*, float, int); // 0x1DB1A0 + virtual ~BAPAMoveToObjectFinding(); // 0x1DC0C0 + + virtual void streamSelf(std::ostream&) const; // 0x1DD430, slot +0x1C; from the base declaration + virtual bool getIsMovingAway(); // 0x1DD660, slot +0x24; from the base declaration + virtual int update(Vec2&, bool&, bool&, float); // 0x1DC1C0, slot +0x2C; from the base declaration + virtual bool isFinished(Bot*); // 0x1DD340, slot +0x30; from the base declaration + virtual bool getLargestAngleDiff(float&); // 0x1DD200, slot +0x38; from the base declaration + virtual float getTargetDistance(); // 0x1DD1D0, slot +0x3C; from the base declaration + virtual float getSimpleTargetDistance(Bot*); // 0x1DD020, slot +0x44; from the base declaration + virtual float getSimpleTargetDistanceSqr(Bot*); // 0x1DD110, slot +0x48; from the base declaration + virtual int usesPathfinding(); // 0x1DD650, slot +0x4C; from the base declaration + virtual int withinDistance(); // 0x1DD250, slot +0x50; from the base declaration + + void initObjectFinding(float, const Vec3&, const Vec3&, unsigned int, unsigned int, const Vec3&, bool); // 0x1DB360; [INFERRED] ELF void + bool isAtCoordinate(); // 0x1DD2A0; [INFERRED] ELF bool + +private: + /* +0xC8 */ int m_zeroC8[8]; // +0xC8..+0xE4 = 0; [UNRESOLVED] + /* +0xE9 */ bool m_flagE9; // = false; [UNRESOLVED] + /* +0xEA */ bool m_flagEA; // initObjectFinding: false; [UNRESOLVED] + /* +0xEC */ int m_intEC; // = 1; [UNRESOLVED] + /* +0xF0 */ Bot* m_bot; + /* +0xF4 */ BAPCondition* m_replanCondition; // owned; update evaluates it on the replan timer; [INFERRED] name + /* +0xF8 */ bool m_flagF8; // = true; [UNRESOLVED] + /* +0xFC */ float m_minDistance; // clamped to m_distance + /* +0x100 */ float m_minDistanceSqr; + /* +0x104 */ bool m_pathDone; // updatePath's flag + /* +0x105 */ bool m_movingAway; // getIsMovingAway; set when initObjectFinding flanks + /* +0x106 */ bool m_pathStarted; + /* +0x107 */ bool m_flag107; // = false; [UNRESOLVED] + /* +0x108 */ int m_index; // the ctor's last int; printed as "[n]" unless -1 + /* +0x10C */ double m_lastInitTime; // = -1.0; game time of the last initObjectFinding +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAMOVETOOBJECTFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp new file mode 100644 index 000000000..9aeebeff8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp @@ -0,0 +1,56 @@ +// Adds a plan-variable amount to a sensed object's notification word for type zero. + +// static init: ELF 0x1DD970 (__tcf_0 0x1DD9D0, _GLOBAL__I 0x1DDA00): 's Init object only. +#include + +#include "BAPANotifyBot.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DD6D0 (C1; C2 0x1DD670) +BAPANotifyBot::BAPANotifyBot(Type type, BAPVariable* amount, BAPVariable* object) + : BAPAction(UninitializedPatternId()), m_type(type), m_amount(amount), m_object(object) +{ +} + +// ELF 0x1DD770 (D1; D2 0x1DD730, D0 0x1DD7B0) +BAPANotifyBot::~BAPANotifyBot() +{ +} + +// ELF 0x1DD800 +bool BAPANotifyBot::execute(Bot* bot, bool& success, bool& finished) +{ + if (m_type == 0) { + SensedObject* object = bot->getSensedObjectFromHandle(m_object->m_value); + if (object) + object->m_unresolved44 += m_amount->m_value; + } else { + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp", 45, "") << "Unkown type"; + } + success = true; + finished = true; + return true; +} + +// ELF 0x1DD950 +BAPStatementType BAPANotifyBot::getId() const +{ + return BAPSTNotifyBot; +} + +// ELF 0x1DD960 +bool BAPANotifyBot::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h new file mode 100644 index 000000000..73668ed71 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.h @@ -0,0 +1,38 @@ +// Adds a plan-variable amount to a sensed object's notification word for type zero. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPANOTIFYBOT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPANOTIFYBOT_H + +#include "BAPAction.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8780 (8 words), package G-vehicles. +class BAPANotifyBot : public BAPAction +{ +public: + enum Type : int; // [UNRESOLVED] enumerators + BAPANotifyBot(BAPANotifyBot::Type, BAPVariable*, BAPVariable*); // 0x1DD6D0 + virtual ~BAPANotifyBot(); // 0x1DD770 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DD800, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DD950, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DD960, slot +0x14; from the base declaration +private: + /* +0x14 */ Type m_type; + /* +0x18 */ BAPVariable* m_amount; + /* +0x1C */ BAPVariable* m_object; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPANOTIFYBOT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp new file mode 100644 index 000000000..1af78f9a0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp @@ -0,0 +1,49 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DDBE0 (__tcf_0 0x1DDC40, _GLOBAL__I 0x1DDC70): 's Init object only. +#include + +#include "BAPAOverrideSensingAgent.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DDA70 (C1; C2 0x1DDA20): the inline base only (+0x04, +0x08 = 0; +0x10 untouched). +BAPAOverrideSensingAgent::BAPAOverrideSensingAgent() +{ + m_controls = 0; +} + +// ELF 0x1DDB00 (D1; D2 0x1DDAC0, D0 0x1DDB40) +BAPAOverrideSensingAgent::~BAPAOverrideSensingAgent() +{ +} + +// ELF 0x1DDB90: hands the look to the plan (SensingAgent::setOverride(true)); done at once. +bool BAPAOverrideSensingAgent::execute(Bot* bot, bool& ok, bool& failed) +{ + bot->getSensingAgent()->setOverride(true); + ok = true; + failed = true; + return false; +} + +// ELF 0x1DDCA0 +BAPStatementType BAPAOverrideSensingAgent::getId() const +{ + return BAPSTOverrideSensingAgent; // 21 +} + +// ELF 0x1DDC90 +bool BAPAOverrideSensingAgent::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.h new file mode 100644 index 000000000..054107346 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAOVERRIDESENSINGAGENT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAOVERRIDESENSINGAGENT_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B87C0 (8 words), operator new 0x14/0x2C, package C-actions. +// No data of its own (operator new 0x14: the BAPStatement base; the image leaves +0x10 unwritten, the shared base ctor zeroes it). +class BAPAOverrideSensingAgent : public BAPAction +{ +public: + BAPAOverrideSensingAgent(); // 0x1DDA70 + virtual ~BAPAOverrideSensingAgent(); // 0x1DDB00 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DDB90, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DDCA0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DDC90, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAOVERRIDESENSINGAGENT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp new file mode 100644 index 000000000..e5e9db0ce --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp @@ -0,0 +1,62 @@ +// Enables or disables physics on the bot's primary equipment when its current state differs. + +// static init: ELF 0x1DDF20 (__tcf_0 0x1DDF80, _GLOBAL__I 0x1DDFB0): 's Init object only. +#include + +#include "BAPAPhysicsEnable.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DDD00 (C1; C2 0x1DDCB0) +BAPAPhysicsEnable::BAPAPhysicsEnable(bool enable) + : BAPAction(UninitializedPatternId()), m_enable(enable) +{ +} + +// ELF 0x1DDD90 (D1; D2 0x1DDD50, D0 0x1DDDD0) +BAPAPhysicsEnable::~BAPAPhysicsEnable() +{ +} + +// ELF 0x1DDE20 +bool BAPAPhysicsEnable::execute(Bot* bot, bool& success, bool& finished) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (self && self->isPrimary()) { + IAIObjectPhysical* physical = self->getAIObject()->getPhysical(); + if (m_enable) { + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(bot->getSide()); + } else { + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(bot->getSide()); + } + } + finished = true; + success = true; + return true; +} + +// ELF 0x1DDFD0 +BAPStatementType BAPAPhysicsEnable::getId() const +{ + return BAPSTPhysicsEnable; +} + +// ELF 0x1DDFE0 +bool BAPAPhysicsEnable::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.h new file mode 100644 index 000000000..38dca7627 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.h @@ -0,0 +1,34 @@ +// Enables or disables physics on the bot's primary equipment when its current state differs. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPHYSICSENABLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPHYSICSENABLE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8800 (8 words), package H-deferred. +class BAPAPhysicsEnable : public BAPAction +{ +public: + explicit BAPAPhysicsEnable(bool); // 0x1DDD00 + virtual ~BAPAPhysicsEnable(); // 0x1DDD90 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DDE20, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DDFD0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DDFE0, slot +0x14; from the base declaration +private: + /* +0x14 */ bool m_enable; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPHYSICSENABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp new file mode 100644 index 000000000..2160de40c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp @@ -0,0 +1,73 @@ +// C4 action: places or removes the bot's C4 (AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp in the +// image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF +// address. +// +// static init: ELF 0x1DE280 (__tcf_0 0x1DE2E0, _GLOBAL__I 0x1DE310): the guard object only. + +#include "BAPAPlaceC4.h" + +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DE050 (C1; C2 0x1DDFF0): the inline BAPStatement constructor (+0x04, +0x08 zeroed), then +// +0x14 type, +0x18 target, +0x1C place. The image leaves +0x10 (pattern id) unwritten; the tree's +// BAPStatement() stores 0 there [CHOSEN, not recovered]. +BAPAPlaceC4::BAPAPlaceC4(int placementType, AIStrategicObject* target, bool place) +{ + m_placementType = placementType; + m_target = target; + m_place = place; +} + +// ELF 0x1DE0F0 (D1; D2 0x1DE0B0, D0 0x1DE130): base destructors only. +BAPAPlaceC4::~BAPAPlaceC4() +{ +} + +// ELF 0x1DE180: place: Bot +0x14C placeC4(type, position of the bot's equipment, target) unless +// +0x150 isC4Placed; remove: +0x154 removeC4 when placed. Both flags set, returns false. The +// equipment information is not null-checked, as compiled. +bool BAPAPlaceC4::execute(Bot* bot, bool& ok, bool& failed) +{ + if (m_place) + { + if (!bot->isC4Placed()) + { + // 0x1DE1D7 + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3 position = info->getPosition(); + bot->placeC4(m_placementType, position, m_target); + } + } + else if (bot->isC4Placed()) + { + bot->removeC4(); // 0x1DE267 + } + ok = true; + failed = true; + return false; +} + +// ELF 0x1DE340 +BAPStatementType BAPAPlaceC4::getId() const +{ + return BAPSTPlaceC4; // 22 +} + +// ELF 0x1DE330 +bool BAPAPlaceC4::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h new file mode 100644 index 000000000..fd395dd97 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPLACEC4_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPLACEC4_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class Bot; + +// ELF: vtable 0x4B8840 (8 words), operator new 0x20, package F-infantry. Places the bot's C4 at +// its position (place = true) or removes it, once, and finishes at once. +class BAPAPlaceC4 : public BAPAction +{ +public: + BAPAPlaceC4(int /* [UNRESOLVED] Bot::C4PlacementType */, AIStrategicObject*, bool); // 0x1DE050 + virtual ~BAPAPlaceC4(); // 0x1DE0F0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DE180, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DE340, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DE330, slot +0x14; from the base declaration + +private: + /* +0x14 */ int m_placementType; // Bot::C4PlacementType (kept int, see Bot::placeC4) + /* +0x18 */ AIStrategicObject* m_target; + /* +0x1C */ bool m_place; // true: place unless placed; false: remove if placed [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAPLACEC4_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp new file mode 100644 index 000000000..e5d3d4c9d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp @@ -0,0 +1,104 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DE790 (__tcf_0 0x1DE7F0, _GLOBAL__I 0x1DE820): 's Init object only. +#include + +#include "BAPAResetControls.h" + +#include "BAPActionInline.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DE3D0 (C1; C2 0x1DE350): group form, no single input, controls = 0. +BAPAResetControls::BAPAResetControls(bool resetMove, bool resetLook, bool resetTrigger, int tag) +{ + m_resetMove = resetMove; + m_resetLook = resetLook; + m_input = static_cast(0); + m_resetTrigger = resetTrigger; + m_controls = 0; + m_patternId = tag; +} + +// ELF 0x1DE4D0 (C1; C2 0x1DE450): one input. `movl $1,%eax; shll %cl,%eax` then `sarl $31` into +// the high word: the 32-bit shift (count & 31) sign-extended to 64 bits, kept as in the image. +BAPAResetControls::BAPAResetControls(io::PlayerInputMap input, int tag) +{ + m_input = input; + m_resetMove = false; + m_resetLook = false; + m_resetTrigger = false; + m_patternId = tag; + const int bit = static_cast(1u << (static_cast(input) & 31u)); + m_controls = static_cast(static_cast(bit)); +} + +// ELF 0x1DE590 (D1; D2 0x1DE550, D0 0x1DE5D0) +BAPAResetControls::~BAPAResetControls() +{ +} + +// ELF 0x1DE660 +bool BAPAResetControls::execute(Bot*, bool& ok, bool& failed) +{ + ok = true; + failed = true; + return true; +} + +// ELF 0x1DE620 +unsigned long long BAPAResetControls::getControls() +{ + return m_controls; +} + +// ELF 0x1DE840 +BAPStatementType BAPAResetControls::getId() const +{ + return BAPSTResetControls; // 14 +} + +// ELF 0x1DE850 +bool BAPAResetControls::hasDefault() +{ + return false; +} + +// ELF 0x1DE680: "(" then the single input or the group labels, then ")" endl. +void BAPAResetControls::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + bapinline::streamType(out, getId()) << "("; + if (hasSingleInput()) { + bapinline::streamInput(out, getInput()); + } else { + if (m_resetMove) + out << "Move "; + if (m_resetLook) + out << "Look "; + if (m_resetTrigger) + out << "Trigger"; + } + out << ")" << std::endl; +} + +// ELF 0x1DE630: `(+0x0C | +0x08) != 0` +bool BAPAResetControls::hasSingleInput() const +{ + return m_controls != 0; +} + +// ELF 0x1DE650 +io::PlayerInputMap BAPAResetControls::getInput() const +{ + return m_input; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.h new file mode 100644 index 000000000..f07fb7355 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARESETCONTROLS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARESETCONTROLS_H + +#include +#include "../../../../IO/Input/Input.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B88C0 (8 words), operator new 0x1C/0x20, package C-actions. +// Resets either one input (the PlayerInputMap form: controls = the sign-extended 32-bit +// `1 << input`) or whole groups (move / look / trigger; controls = 0). The work is done by +// EntryInfanteryResetControls; the statement's own execute just succeeds. +class BAPAResetControls : public BAPAction +{ +public: + BAPAResetControls(bool, bool, bool, int); // 0x1DE3D0 + BAPAResetControls(io::PlayerInputMap, int); // 0x1DE4D0 + virtual ~BAPAResetControls(); // 0x1DE590 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DE660, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1DE620, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1DE840, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DE850, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1DE680, slot +0x1C; from the base declaration + + bool hasSingleInput() const; // 0x1DE630; [INFERRED] ELF bool, callers {'bool': 7} + io::PlayerInputMap getInput() const; // 0x1DE650 (+0x18) + + // Read inline by the reset entries, so public. [INFERRED] names from streamSelf's labels. + /* +0x14 */ bool m_resetMove; // "Move " + /* +0x15 */ bool m_resetLook; // "Look " + /* +0x16 */ bool m_resetTrigger; // "Trigger" + /* +0x18 */ io::PlayerInputMap m_input; // 0 in the group form +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp new file mode 100644 index 000000000..d6ed30fd5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp @@ -0,0 +1,73 @@ +// Revive action. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries +// its ELF address. + +// static init: ELF 0x1DEB00 (__tcf_0 0x1DEB60, _GLOBAL__I 0x1DEB90): 's Init object only. +#include + +#include "BAPARevive.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../../IO/Input/Input.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DE8B0 (C1; C2 0x1DE860): the inline BAPStatement constructor (+0x04, +0x08 zeroed, +// instance counter), +0x10 = pattern id, +0x14 = false. +BAPARevive::BAPARevive(int patternId) + : BAPStatement(patternId) +{ + m_firePressed = false; +} + +// ELF 0x1DE940 (D1; D2 0x1DE900, D0 0x1DE980): base destructors only. +BAPARevive::~BAPARevive() +{ +} + +// ELF 0x1DE9D0: requests the crouching pose (Bot +0x194 requestSoldierPose(2, true)). Once the +// bot's equipment is crouching, alternate executions press fire (written inline: the value 1 when +// the fire input is mapped) and release it through io::Input::setInput(PIFire, 0) with the second +// flag set. Always sets the first flag and returns true. The equipment information is not +// null-checked, as compiled. +bool BAPARevive::execute(Bot* bot, bool& ok, bool& finished) +{ + bot->requestSoldierPose(2, true); + if (bapinline::info(bot->getCurrentEquipment())->getSoldierPose() == SPCrouching) + { + if (!m_firePressed) + { + io::PlayerInput* const input = bot->getInput(); + if ((input->mappingFlags >> io::PIFire) & 1ULL) + input->inputs[io::PIFire] = 1.0f; + m_firePressed = true; + } + else + { + finished = true; + bot->getInput()->setInput(io::PIFire, 0.0f); + m_firePressed = false; + } + } + ok = true; + return true; +} + +// ELF 0x1DEAE0 +BAPStatementType BAPARevive::getId() const +{ + return BAPSTRevive; // 44 +} + +// ELF 0x1DEAF0 +bool BAPARevive::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h new file mode 100644 index 000000000..96953c256 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARevive.h @@ -0,0 +1,36 @@ +// Revive action: crouches and presses fire once per two executions (the shock paddles). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAREVIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAREVIVE_H + +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8940 (8 words), operator new 0x18/0x2C, package F-infantry. +class BAPARevive : public BAPStatement +{ +public: + explicit BAPARevive(int); // 0x1DE8B0 + virtual ~BAPARevive(); // 0x1DE940 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DE9D0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DEAE0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DEAF0, slot +0x14; from the base declaration + +private: + /* +0x14 */ bool m_firePressed; // [INFERRED] name: set by the execute that presses fire +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAREVIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp new file mode 100644 index 000000000..51402da9f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp @@ -0,0 +1,95 @@ +// Roll-action state recovered from libaidll.so. +// static init: ELF 0x1DF350 (__tcf_0 0x1DF3B0, _GLOBAL__I 0x1DF3E0): 's Init object only. +#include +#include "BAPARoll3d.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DEEB0 (C1; C2 0x1DEBB0) +BAPARoll3d::BAPARoll3d(Bot* bot, int direction, float roll, float maxSpeed, + BAPCondition* condition, unsigned long long controls, float, int tag) + : BAPAction(UninitializedPatternId()) +{ + m_maxSpeed = maxSpeed; + m_roll = roll; + m_vector1C = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_float28 = 0.0f; + m_direction = direction; + m_forward = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_up = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_right = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_flatFacing = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vector6C = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_vector78 = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_breakCondition = condition; + Information* self = bapinline::info(bot->getCurrentEquipment()); + Vec2 facing; + facing.x = 0.0f; + facing.y = 0.0f; + const Vec3 direction3 = self->getFaceing(); + vec3ToVec2XZ(direction3, facing); + bapinline::normalize(facing); + addVec2ToVec3XZ(facing, m_flatFacing); + const Mat4& first = self->getTransformation(); + m_vector78 = bapinline::vec3(first.m[4], first.m[5], first.m[6]); + const Mat4& second = self->getTransformation(); + m_vector6C = bapinline::vec3(second.m[4], second.m[5], second.m[6]); + m_patternId = tag; + m_breakCondition->setOwner(this); + m_initialAltitude = self->getAltitude(self->getMobile()->getSpeed()); + m_controls = controls; +} + +// ELF 0x1DF210 (D1; D2 0x1DF1A0, D0 0x1DF280) +BAPARoll3d::~BAPARoll3d() +{ + delete m_breakCondition; +} + +// ELF 0x1DF2F0 +bool BAPARoll3d::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1DF310 +unsigned long long BAPARoll3d::getControls() +{ + return m_controls; +} + +// ELF 0x1DF400 +BAPStatementType BAPARoll3d::getId() const +{ + return BAPSTRoll3d; +} + +// ELF 0x1DF320 +bool BAPARoll3d::hasDefault() +{ + return false; +} + +// ELF 0x1DF330 +float BAPARoll3d::getMaxSpeed() +{ + return m_maxSpeed; +} + +// ELF 0x1DF340 +BAPCondition* BAPARoll3d::getBreakCondition() +{ + return m_breakCondition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h new file mode 100644 index 000000000..be5bc62ec --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.h @@ -0,0 +1,54 @@ +// Roll state consumed by the plane interpreter; owns its required break condition. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAROLL3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAROLL3D_H + +#include "BAPAction.h" +#include "../../../../Math/Vec3.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8980 (8 words), package H-deferred. +class BAPARoll3d : public BAPAction +{ +public: + BAPARoll3d(Bot*, int, float, float, BAPCondition*, unsigned long long, float, int); // 0x1DEEB0 + virtual ~BAPARoll3d(); // 0x1DF210 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DF2F0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1DF310, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1DF400, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DF320, slot +0x14; from the base declaration + + float getMaxSpeed(); // 0x1DF330; [INFERRED] ELF float + BAPCondition* getBreakCondition(); // 0x1DF340 + // [INFERRED] names. The plane entry reads and updates these fields inline. + /* +0x14 */ float m_maxSpeed; + /* +0x18 */ float m_roll; + /* +0x1C */ Vec3 m_vector1C; + /* +0x28 */ float m_float28; + /* +0x2C */ float m_float2C; // shipped defect: constructor leaves this and +0x30 uninitialized + /* +0x30 */ float m_previousY; + /* +0x34 */ int m_direction; + /* +0x38 */ float m_initialAltitude; + /* +0x3C */ Vec3 m_forward; + /* +0x48 */ Vec3 m_up; + /* +0x54 */ Vec3 m_right; + /* +0x60 */ Vec3 m_flatFacing; + /* +0x6C */ Vec3 m_vector6C; + /* +0x78 */ Vec3 m_vector78; + /* +0x84 */ BAPCondition* m_breakCondition; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAROLL3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp new file mode 100644 index 000000000..dbeb57b33 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp @@ -0,0 +1,138 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); objdump listings with Ghidra cross-checks, ELF +// addresses on every body. Static init: ELF 0x1DFB40 (the guard object only). + +#include "BAPARunOverObject.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/CarControl.h" +#include "../Main/IAIPathfinding.h" +#include "../../../../Math/Vec3.h" + +#include +// static init: ELF 0x1DFB40 (__tcf_0 0x1DFBA0, _GLOBAL__I 0x1DFBD0): 's Init object only. +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DF470 (C1; C2 0x1DF410). BAPStatement() (controls 0), then the members. +BAPARunOverObject::BAPARunOverObject(unsigned int object, unsigned long long controls, int patternId) +{ + m_object = object; + m_controls18 = controls; + m_patternId = patternId; +} + +// ELF 0x1DFBF0 (D1; D0 0x1DFC30): base only. +BAPARunOverObject::~BAPARunOverObject() +{ +} + +// ELF 0x1DF4D0 (listing; Ghidra cross-check). Without the bot's equipment it returns false and +// leaves ok = true, done = false. Without the target's information, or when IAIPathfinding +0x8C +// finds no clear line from the bot's last valid position to the target's (for the bot's vehicle +// number), it is done. Otherwise the intercept point is the target's position advanced by its +// velocity over the bot's travel time, refined once; the car steers at it with speed 50 through +// CarControl::controlTowardsDirection, the angle measured from the bot's normalised XZ facing. +// Shipped quirks kept: the target's mobile part is used unchecked, the bot's speed is not tested +// against zero, the trace's hit point is unused. +bool BAPARunOverObject::execute(Bot* bot, bool& ok, bool& done) +{ + ok = true; + done = false; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment) + return false; + IPIMobile* const mobile = equipment->getMobile(); + IPIPhysical* const physical = equipment->getPhysical(); + Information* const target = informationManager->getInformation(m_object); + if (!target) + { + done = true; + return true; + } + IPIMobile* const targetMobile = target->getMobile(); + const IPIMobile::ValidPos& targetValid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + const IPIMobile::ValidPos& ownValid = mobile->getLastValidPosition(); + Vec3 hit; + hit.x = 0.0f; + hit.y = 0.0f; + hit.z = 0.0f; + unsigned int polygon; + const int equipmentType = equipment->getUnit()->getEquipmentType(); + if (!IAIPathfinding::instance->trace(ownValid.polygon, ownValid.quadTree, mobile->getVehicleNumber(), + ownValid.position, targetValid.position, hit, polygon, equipmentType, + -1, 0.0f, 5, 0)) + { + done = true; + return true; + } + + const Vec3& own = equipment->getPosition(); + const Vec3& at = target->getPosition(); + const float dx = at.x - own.x; + const float dy = at.y - own.y; + const float dz = at.z - own.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + const float speed = mobile->getSpeedMagnitude(); + const float time = distance / speed; + const Vec3& velocity = targetMobile->getSpeed(); + Vec3 predicted; + predicted.x = at.x + time * velocity.x; + predicted.y = at.y + time * velocity.y; + predicted.z = at.z + time * velocity.z; + const float px = predicted.x - own.x; + const float py = predicted.y - own.y; + const float pz = predicted.z - own.z; + const float refinedTime = std::sqrt(pz * pz + px * px + py * py) / speed; + const Vec3& velocity2 = targetMobile->getSpeed(); + Vec3 intercept; + intercept.x = refinedTime * velocity2.x + at.x; + intercept.y = refinedTime * velocity2.y + at.y; + intercept.z = refinedTime * velocity2.z + at.z; + Vec3 toIntercept; + toIntercept.x = intercept.x - own.x; + toIntercept.y = intercept.y - own.y; + toIntercept.z = intercept.z - own.z; + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + vec3ToVec2XZ(toIntercept, direction); + + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + Vec2 facing; + facing.x = 0.0f; + facing.y = 0.0f; + vec3ToVec2XZ(equipment->getFaceing(), facing); + bapinline::normalize(facing); + getNormal(facing, normal); + const float angle = getSignedDiffAngleToDirWithNormal(facing, normal, direction); + ok = CarControl::controlTowardsDirection(equipment, equipment->getControlInfo(), mobile, physical, bot->getInput(), + 50.0f, 1.0f, angle, 1.0f, 1.0f) != 0; + return true; +} + +// ELF 0x1DFB30 +BAPStatementType BAPARunOverObject::getId() const +{ + return BAPSTRunOverObject; +} + +// ELF 0x1DFB20 +bool BAPARunOverObject::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.h new file mode 100644 index 000000000..cb0bc9e2e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.h @@ -0,0 +1,40 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every declaration. +// Drives a car at an object's predicted position (BBPRunOverSoldier's plan). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARUNOVEROBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARUNOVEROBJECT_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8A00 (8 words), package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPARunOverObject : public BAPAction +{ +public: + BAPARunOverObject(unsigned int object, unsigned long long controls, int patternId); // 0x1DF470 (C2 0x1DF410) + virtual ~BAPARunOverObject(); // 0x1DFBF0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DF4D0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DFB30, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DFB20, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_object; // information handle of the target + /* +0x18 */ unsigned long long m_controls18; // the constructor's controls; no reader. The base + // m_controls (+0x08) stays 0, so getControls + // (BAPStatement's, slot +0x0C) answers 0 [INFERRED name] +}; // operator new size 0x20 (BBPRunOverSoldier::createPlan) + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPARUNOVEROBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp new file mode 100644 index 000000000..feea7da3c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp @@ -0,0 +1,57 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1DFEB0 (__tcf_0 0x1DFF10, _GLOBAL__I 0x1DFF40): 's Init object only. +#include + +#include "BAPASendRadioMessage.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DFCF0 (C1; C2 0x1DFC80): +4/+8/+0xC = 0, then +0x14 type, +0x18 channel, +0x1C priority, +// +0x20 the last int, +0x24 the float, +0x10 the pattern id (the image's store order). +BAPASendRadioMessage::BAPASendRadioMessage(AIRadioMessageType type, AIRadioChannelType channel, + unsigned int priority, float delay, int patternId, int target) +{ + m_controls = 0; + m_type = type; + m_channel = channel; + m_priority = priority; + m_target = target; + m_delay = delay; + m_patternId = patternId; +} + +// ELF 0x1DFDA0 (D0 0x1DFDE0) +BAPASendRadioMessage::~BAPASendRadioMessage() +{ +} + +// ELF 0x1DFE30: getCommunicationAgent (Bot +0xB0)->enqueueRadioMessage(+0x14, +0x18, +0x1C, +0x24, +0x20). +bool BAPASendRadioMessage::execute(Bot* bot, bool& ok, bool& finished) +{ + bot->getCommunicationAgent()->enqueueRadioMessage(m_type, m_channel, m_priority, m_delay, m_target); + ok = true; + finished = true; + return true; +} + +// ELF 0x1DFF60 +BAPStatementType BAPASendRadioMessage::getId() const +{ + return BAPSTSendRadioMessage; // 37 +} + +// ELF 0x1DFEA0 +bool BAPASendRadioMessage::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.h new file mode 100644 index 000000000..1a94d0d18 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.h @@ -0,0 +1,41 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENDRADIOMESSAGE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENDRADIOMESSAGE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8A40 (8 words), operator new 0x28, package F-infantry. +// Queues one radio message on the bot's CommunicationAgent (enqueueRadioMessage). +class BAPASendRadioMessage : public BAPAction +{ +public: + BAPASendRadioMessage(AIRadioMessageType, AIRadioChannelType, unsigned int, float, int, int); // 0x1DFCF0 + virtual ~BAPASendRadioMessage(); // 0x1DFDA0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1DFE30, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1DFF60, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1DFEA0, slot +0x14; from the base declaration + +private: + /* +0x14 */ AIRadioMessageType m_type; + /* +0x18 */ AIRadioChannelType m_channel; + /* +0x1C */ unsigned int m_priority; + /* +0x20 */ int m_target; // the constructor's last int, enqueueRadioMessage's last argument + /* +0x24 */ float m_delay; // [INFERRED] name: enqueueRadioMessage's float +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENDRADIOMESSAGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp new file mode 100644 index 000000000..01d45f993 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp @@ -0,0 +1,55 @@ +// Sensing statement with two required, owned conditions; direct execution refuses the action. + +#include "BAPASense.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1DFFE0 (C1; C2 0x1DFF70) +BAPASense::BAPASense(BAPCondition* first, BAPCondition* second, int tag) + : BAPAction(UninitializedPatternId()), m_firstCondition(first), m_secondCondition(second) +{ + m_firstCondition->setOwner(this); + m_secondCondition->setOwner(this); + m_patternId = tag; +} + +// ELF 0x1E00C0 (D1; D2 0x1E0050, D0 0x1E0130) +BAPASense::~BAPASense() +{ + delete m_firstCondition; + delete m_secondCondition; +} + +// ELF 0x1E01B0 +bool BAPASense::execute(Bot*, bool& success, bool& finished) +{ + success = false; + finished = true; + return false; +} + +// ELF 0x1E01D0 +unsigned long long BAPASense::getControls() +{ + return 0; +} + +// ELF 0x1E01E0 +BAPStatementType BAPASense::getId() const +{ + return BAPSTSense; +} + +// ELF 0x1E01F0 +bool BAPASense::hasDefault() +{ + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.h new file mode 100644 index 000000000..729e7cb69 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASense.h @@ -0,0 +1,39 @@ +// Sensing statement with two required, owned conditions; direct execution refuses the action. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENSE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8AC0 (8 words), package H-deferred. +class BAPASense : public BAPAction +{ +public: + BAPASense(BAPCondition*, BAPCondition*, int); // 0x1DFFE0 + virtual ~BAPASense(); // 0x1E00C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E01B0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E01D0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E01E0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E01F0, slot +0x14; from the base declaration +private: + // EntrySense reads these inline (ELF 0x2C3A5A / 0x2C3AA0). + friend class EntrySense; + /* +0x14 */ BAPCondition* m_firstCondition; + /* +0x18 */ BAPCondition* m_secondCondition; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASENSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp new file mode 100644 index 000000000..34ff0a028 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp @@ -0,0 +1,71 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E05A0 (__tcf_0 0x1E0600, _GLOBAL__I 0x1E0630): 's Init object only. +#include + +#include "BAPASetSensingAgentFocus.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E0280 (C1; C2 0x1E01F0 region): target form. +BAPASetSensingAgentFocus::BAPASetSensingAgentFocus(float weight, unsigned int target, int tag, bool flag) +{ + m_controls = 0; + m_direction.x = 0.0f; + m_direction.y = 0.0f; + m_direction.z = 0.0f; + m_patternId = tag; + m_weight = weight; + m_target = target; + m_isTarget = true; + m_flag = flag; +} + +// ELF 0x1E0390: direction form (+0x1C is left unwritten). +BAPASetSensingAgentFocus::BAPASetSensingAgentFocus(float weight, const Vec3& direction, int tag, bool flag) +{ + m_controls = 0; + m_patternId = tag; + m_weight = weight; + m_direction = direction; + m_isTarget = false; + m_flag = flag; +} + +// ELF 0x1E0460 (D1; D2 0x1E0420 region, D0 0x1E04A0) +BAPASetSensingAgentFocus::~BAPASetSensingAgentFocus() +{ +} + +// ELF 0x1E04F0 +bool BAPASetSensingAgentFocus::execute(Bot* bot, bool& ok, bool& failed) +{ + if (m_isTarget) + bot->getSensingAgent()->insertPlanTargetInformation(m_weight, m_target, m_flag); + else + bot->getSensingAgent()->insertPlanDirectionInformation(m_weight, m_direction, m_flag); + ok = true; + failed = true; + return true; +} + +// ELF 0x1E0650 +BAPStatementType BAPASetSensingAgentFocus::getId() const +{ + return BAPSTSetSensingAgentFocus; // 35 +} + +// ELF 0x1E0590 +bool BAPASetSensingAgentFocus::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.h new file mode 100644 index 000000000..8f1becf17 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.h @@ -0,0 +1,46 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASETSENSINGAGENTFOCUS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASETSENSINGAGENTFOCUS_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8B00 (8 words), operator new 0x30, package C-actions. +// Puts a focus target (object handle) or a focus direction into the bot's SensingAgent. +class BAPASetSensingAgentFocus : public BAPAction +{ +public: + BAPASetSensingAgentFocus(float, unsigned int, int, bool); // 0x1E0280 + BAPASetSensingAgentFocus(float, const Vec3&, int, bool); // 0x1E0390 + virtual ~BAPASetSensingAgentFocus(); // 0x1E0460 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E04F0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E0650, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E0590, slot +0x14; from the base declaration + +private: + /* +0x14 */ float m_weight; // the ctor's float, first argument of both insertPlan* calls; [INFERRED] name + /* +0x18 */ bool m_flag; // the ctor's bool, last argument of both calls; [UNRESOLVED] meaning + /* +0x1C */ unsigned int m_target; // information handle (target form) + /* +0x20 */ Vec3 m_direction; // = 0 in the target form + /* +0x2C */ bool m_isTarget; // true: target form, false: direction form +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASETSENSINGAGENTFOCUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp new file mode 100644 index 000000000..28fa938d8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp @@ -0,0 +1,115 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPASoldierPose.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// `+0x08 = 0; +0x0C = 0x60` in every constructor: (1 << PILie) | (1 << PICrouch). +const unsigned long long kSoldierPoseControls = 0x6000000000ULL; +} + +// ELF 0x1E0740 (C1): one pose for all three cases, fire threshold 2, control threshold 0, +// no object, 5 s between changes; no break condition. +BAPASoldierPose::BAPASoldierPose(SoldierPose pose, BAPCondition* run, int tag, bool flag) + : BAPAComponentSoldierPose(pose, pose, 2.0f, pose, 0.0f, 0xFFFFFFFFu, 5.0f) +{ + m_breakCondition = 0; + m_runCondition = run; + m_flag = flag; + run->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0900 (C1): as above with a followed object. +BAPASoldierPose::BAPASoldierPose(SoldierPose pose, BAPCondition* run, int tag, unsigned int object, bool flag) + : BAPAComponentSoldierPose(pose, pose, 2.0f, pose, 0.0f, object, 5.0f) +{ + m_breakCondition = 0; + m_runCondition = run; + m_flag = flag; + run->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0AD0 (C1): run and break conditions (both owners set unconditionally). +BAPASoldierPose::BAPASoldierPose(SoldierPose pose, BAPCondition* run, BAPCondition* brk, int tag, bool flag) + : BAPAComponentSoldierPose(pose, pose, 2.0f, pose, 0.0f, 0xFFFFFFFFu, 5.0f) +{ + m_runCondition = run; + m_breakCondition = brk; + m_flag = flag; + run->setOwner(this); + m_breakCondition->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0CC0 (C1): the full chooser; the int fire threshold is converted to float. +BAPASoldierPose::BAPASoldierPose(SoldierPose normal, SoldierPose incommingFire, int fireObjectsThreshold, + SoldierPose danger, float controlThreshold, BAPCondition* run, + BAPCondition* brk, int tag, bool flag) + : BAPAComponentSoldierPose(normal, incommingFire, static_cast(fireObjectsThreshold), danger, + controlThreshold, 0xFFFFFFFFu, 5.0f) +{ + m_runCondition = run; + m_breakCondition = brk; + m_flag = flag; + if (run) + run->setOwner(this); + if (m_breakCondition) + m_breakCondition->setOwner(this); + m_controls = kSoldierPoseControls; + m_patternId = tag; +} + +// ELF 0x1E0E50 (D1; D0 0x1E0EE0; thunk D0 0x1E1000 through the +0x14 base): deletes both conditions. +BAPASoldierPose::~BAPASoldierPose() +{ + if (m_runCondition) + delete m_runCondition; + if (m_breakCondition) + delete m_breakCondition; +} + +// ELF 0x1E0FA0: runs only through EntrySoldierPose. +bool BAPASoldierPose::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E0F80 +BAPStatementType BAPASoldierPose::getId() const +{ + return BAPSTSoldierPose; // 26 +} + +// ELF 0x1E0F90 +bool BAPASoldierPose::hasDefault() +{ + return false; +} + +// ELF 0x1E0FC0 +BAPCondition* BAPASoldierPose::getRunCondition() +{ + return m_runCondition; +} + +// ELF 0x1E0FD0 +BAPCondition* BAPASoldierPose::getBreakCondition() +{ + return m_breakCondition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.h new file mode 100644 index 000000000..f3b67fc45 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.h @@ -0,0 +1,55 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASOLDIERPOSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASOLDIERPOSE_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "BAPAComponentSoldierPose.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8B80 (26 words; the BAPAComponentSoldierPose part at +0x14 uses 0x4B8BB0), package C-actions. +// Size 0x4C. Holds a soldier pose while the run condition holds; EntrySoldierPose does the work. +// Controls = PILie | PICrouch (`+0x0C = 0x60`: bits 37, 38). +class BAPASoldierPose : public BAPAction, public BAPAComponentSoldierPose +{ +public: + BAPASoldierPose(SoldierPose, BAPCondition*, int, bool); // 0x1E0740 + BAPASoldierPose(SoldierPose, BAPCondition*, int, unsigned int, bool); // 0x1E0900 + BAPASoldierPose(SoldierPose, BAPCondition*, BAPCondition*, int, bool); // 0x1E0AD0 + BAPASoldierPose(SoldierPose, SoldierPose, int, SoldierPose, float, BAPCondition*, BAPCondition*, int, bool); // 0x1E0CC0 + virtual ~BAPASoldierPose(); // 0x1E0E50 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E0FA0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E0F80, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E0F90, slot +0x14; from the base declaration + + BAPCondition* getRunCondition(); // 0x1E0FC0 (+0x40) + BAPCondition* getBreakCondition(); // 0x1E0FD0 (+0x44) + // [INFERRED] inline (no symbol): EntrySoldierPose::execute 0x2C3DBF `movzbl 0x48(%ecx)` passes + // it to Bot::requestSoldierPose. + bool getFlag() const { return m_flag; } + +private: + /* +0x40 */ BAPCondition* m_runCondition; + /* +0x44 */ BAPCondition* m_breakCondition; // may be null + /* +0x48 */ bool m_flag; // the ctors' last bool; [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPASOLDIERPOSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp new file mode 100644 index 000000000..36b395528 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp @@ -0,0 +1,108 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E1960 (__tcf_0 0x1E19C0, _GLOBAL__I 0x1E19F0): 's Init object only. +#include + +#include "BAPATrigger.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../Main/IBotManager.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E10F0 (C1; C2 0x1E0FE0 region) +BAPATrigger::BAPATrigger(io::PlayerInputMap input, BAPCondition* start, BAPCondition* stop, + unsigned long long controls, int tag, double duration, bool flag) +{ + m_startCondition = start; + m_input = input; + m_started = false; + m_stopCondition = stop; + m_flag = flag; + if (start) + start->setOwner(this); + if (m_stopCondition) + m_stopCondition->setOwner(this); + m_patternId = tag; + m_controls = controls; + m_endTime = bapinline::gameTime() + duration; +} + +// ELF 0x1E1240 (D1; D0 0x1E12C0): deletes both conditions. +BAPATrigger::~BAPATrigger() +{ + if (m_startCondition) + delete m_startCondition; + if (m_stopCondition) + delete m_stopCondition; +} + +// ELF 0x1E1340: runs only through EntryTrigger. +bool BAPATrigger::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E1A10 +unsigned long long BAPATrigger::getControls() +{ + return m_controls; +} + +// ELF 0x1E1A20 +BAPStatementType BAPATrigger::getId() const +{ + return BAPSTTrigger; // 11 +} + +// ELF 0x1E1A30 +bool BAPATrigger::hasDefault() +{ + return false; +} + +// ELF 0x1E1360: any level but 0 writes "Pushed button with id ''". +void BAPATrigger::debug(BotScriptDebugger::DebugLevel level, std::string& text) +{ + if (level != 0) { + std::ostringstream os; + bapinline::streamInput(os << "Pushed button with id '", m_input) << "'"; + text = os.str(); + } +} + +// ELF 0x1E17A0 +void BAPATrigger::streamSelf(std::ostream& out) const +{ + IBotManager* bm = IBotManager::instance; + bm->tabulate(out); + bapinline::streamInput(bapinline::streamType(out, getId()) << "(", m_input) << ")" << std::endl; + bm->tabulate(out); + out << '[' << std::endl; + bm->increaseTabLevel(); + bm->tabulate(out); + out << "StartCondition: "; + if (m_startCondition) + bapinline::streamCondition(out, m_startCondition); + out << std::endl; + bm->tabulate(out); + out << "StopCondition: "; + if (m_stopCondition) + bapinline::streamCondition(out, m_stopCondition); + out << std::endl; + bm->decreaseTabLevel(); + bm->tabulate(out); + out << ']' << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h new file mode 100644 index 000000000..3dc84cd31 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGER_H + +#include +#include +#include "../../../../IO/Input/Input.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8C80 (8 words), operator new 0x30, package C-actions. +// Presses one input; EntryTrigger does the work and reads the fields below inline (public). +class BAPATrigger : public BAPAction +{ +public: + BAPATrigger(io::PlayerInputMap, BAPCondition*, BAPCondition*, unsigned long long, int, double, bool); // 0x1E10F0 + virtual ~BAPATrigger(); // 0x1E1240 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E1340, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E1A10, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E1A20, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E1A30, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1E1360, slot +0x18; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E17A0, slot +0x1C; from the base declaration + + // [INFERRED] names from streamSelf's labels. + /* +0x14 */ io::PlayerInputMap m_input; + /* +0x18 */ BAPCondition* m_startCondition; // "StartCondition: ", may be null + /* +0x1C */ BAPCondition* m_stopCondition; // "StopCondition: ", may be null + /* +0x20 */ bool m_started; // = false; [UNRESOLVED] name, written by the entry + /* +0x24 */ double m_endTime; // game time at construction + the ctor's double + /* +0x2C */ bool m_flag; // the ctor's last bool; [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp new file mode 100644 index 000000000..b76809807 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp @@ -0,0 +1,101 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E1FE0 (__tcf_0 0x1E2040, _GLOBAL__I 0x1E2070): 's Init object only. +#include + +#include "BAPATriggerContinously.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E1B20 (C1; C2 0x1E1A40 identical) +BAPATriggerContinously::BAPATriggerContinously(io::PlayerInputMap input, BAPCondition* start, + BAPCondition* stop, BAPCondition* abort, + unsigned long long controls, int tag, double duration) +{ + m_startCondition = start; + m_input = input; + m_stopCondition = stop; + m_started = false; + m_abortCondition = abort; + start->setOwner(this); + if (m_stopCondition) + m_stopCondition->setOwner(this); + if (m_abortCondition) + m_abortCondition->setOwner(this); + m_patternId = tag; + m_controls = controls; + m_endTime = bapinline::gameTime() + duration; +} + +// ELF 0x1E1C90 (D1; D2 0x1E1C00, D0 0x1E1D20): deletes start, stop, abort (virtual D0). +BAPATriggerContinously::~BAPATriggerContinously() +{ + if (m_startCondition) + delete m_startCondition; + if (m_stopCondition) + delete m_stopCondition; + if (m_abortCondition) + delete m_abortCondition; +} + +// ELF 0x1E1DB0: runs only through EntryTriggerContinously. +bool BAPATriggerContinously::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E2090 +unsigned long long BAPATriggerContinously::getControls() +{ + return m_controls; +} + +// ELF 0x1E20A0 +BAPStatementType BAPATriggerContinously::getId() const +{ + return BAPSTTriggerContinously; // 12 +} + +// ELF 0x1E20B0 +bool BAPATriggerContinously::hasDefault() +{ + return false; +} + +// ELF 0x1E1DD0 +void BAPATriggerContinously::streamSelf(std::ostream& out) const +{ + IBotManager* bm = IBotManager::instance; + bm->tabulate(out); + bapinline::streamInput(bapinline::streamType(out, getId()) << "(", m_input) << ")" << std::endl; + bm->tabulate(out); + out << '[' << std::endl; + bm->increaseTabLevel(); + bm->tabulate(out); + bapinline::streamCondition(out << "StartCondition: ", m_startCondition) << std::endl; + if (m_stopCondition) { + bm->tabulate(out); + bapinline::streamCondition(out << "StopCondition: ", m_stopCondition) << std::endl; + } + if (m_abortCondition) { + bm->tabulate(out); + bapinline::streamCondition(out << "AbortCondition: ", m_abortCondition) << std::endl; + } + bm->decreaseTabLevel(); + bm->tabulate(out); + out << ']' << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.h new file mode 100644 index 000000000..7ab2fc0ac --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.h @@ -0,0 +1,51 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGERCONTINOUSLY_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGERCONTINOUSLY_H + +#include +#include "../../../../IO/Input/Input.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8D00 (8 words), package C-actions. +// Holds one input while the plan runs; EntryTriggerContinously does the work and reads the +// fields below inline (public). Size 0x30. +class BAPATriggerContinously : public BAPAction +{ +public: + BAPATriggerContinously(io::PlayerInputMap, BAPCondition*, BAPCondition*, BAPCondition*, unsigned long long, int, double); // 0x1E1B20 + virtual ~BAPATriggerContinously(); // 0x1E1C90 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E1DB0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E2090, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E20A0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E20B0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E1DD0, slot +0x1C; from the base declaration + + // [INFERRED] names from streamSelf's labels. + /* +0x14 */ io::PlayerInputMap m_input; + /* +0x18 */ BAPCondition* m_startCondition; // "StartCondition: ", required (owner set unconditionally) + /* +0x1C */ BAPCondition* m_stopCondition; // "StopCondition: ", may be null + /* +0x20 */ BAPCondition* m_abortCondition; // "AbortCondition: ", may be null + /* +0x24 */ bool m_started; // = false; [UNRESOLVED] name, written by the entry + /* +0x28 */ double m_endTime; // game time at construction + the ctor's double +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATRIGGERCONTINOUSLY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp new file mode 100644 index 000000000..866ade64d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp @@ -0,0 +1,50 @@ +// Turn statement base. Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPATurn.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1E22B0, __tcf_0 0x1E2310, _GLOBAL__I 0x1E2340). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2140 (C1; C2 0x1E20C0). The inline BAPStatement base clears +0x04/+0x08 and counts +// `news`; then +0x14 = cond, +0x18 = speed, +0x1C/+0x20 and +0x28..+0x30 = 0 (+0x24 is left), +// +0x08 = controls, +0x10 = tag. The condition's owner is set by the derived constructors. +BAPATurn::BAPATurn(float turnSpeed, BAPCondition* endCondition, unsigned long long controls, int tag) +{ + m_endCondition = endCondition; + m_turnSpeed = turnSpeed; + m_float1C = 0.0f; + m_float20 = 0.0f; + m_vec28.x = 0.0f; + m_vec28.y = 0.0f; + m_vec28.z = 0.0f; + m_controls = controls; + m_patternId = tag; +} + +// ELF 0x1E2200 (D1; D2 0x1E21C0, D0 0x1E2240): only the inline base destructor (`destroys`). +BAPATurn::~BAPATurn() +{ +} + +// ELF 0x1E2290: a turn never runs by itself (the entries do the work): ok = false, failed = true. +bool BAPATurn::execute(Bot*, bool& ok, bool& failed) +{ + ok = false; + failed = true; + return false; +} + +// ELF 0x1E2360 (weak) +BAPStatementType BAPATurn::getId() const +{ + return BAPSTTurn; // 24 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h new file mode 100644 index 000000000..819aed077 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurn.h @@ -0,0 +1,46 @@ +// Turn statement base: the vehicle turn entries steer towards getDirection(). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURN_H + +#include "../../../../Math/Vec3.h" +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8D40 (9 words), package H-deferred. Size 0x34 (BAPATurnTowardsDirection's data +// starts at +0x34). +class BAPATurn : public BAPAction +{ +public: + BAPATurn(float, BAPCondition*, unsigned long long, int); // 0x1E2140 + virtual ~BAPATurn(); // 0x1E2200 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E2290, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E2360, slot +0x10; from the base declaration + virtual bool hasDefault() { return false; } // 0x1E2370 (weak), slot +0x14 + virtual Vec3 getDirection(bool&) = 0; // no body, slot +0x20; [INFERRED] from BAPATurnTowardsObject: ELF sret (returned through a hidden pointer) + + // [INFERRED] names; the constructor's stores are attested. The turn entries own the reads. + /* +0x14 */ BAPCondition* m_endCondition; // the derived classes own and delete it + /* +0x18 */ float m_turnSpeed; // the ctor's float + /* +0x1C */ float m_float1C; // = 0 [UNRESOLVED] + /* +0x20 */ float m_float20; // = 0 [UNRESOLVED] + /* +0x24 */ float m_unwritten24; // [UNRESOLVED] not written by the constructor + /* +0x28 */ Vec3 m_vec28; // = 0 [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp new file mode 100644 index 000000000..81987c9af --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp @@ -0,0 +1,42 @@ +// Turn statement towards a fixed direction. Recovered from libaidll.so 1.5.3153 (ia-32); ELF +// addresses on every body. + +#include "BAPATurnTowardsDirection.h" + +#include "BAPCondition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1E25D0, __tcf_0 0x1E2630, _GLOBAL__I 0x1E2660). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2410 (C1; C2 0x1E2380): the base, the direction, then the end condition's owner (not +// null-checked). +BAPATurnTowardsDirection::BAPATurnTowardsDirection(const Vec3& direction, float turnSpeed, BAPCondition* endCondition, + unsigned long long controls, int tag) + : BAPATurn(turnSpeed, endCondition, controls, tag) +{ + m_direction = direction; + m_endCondition->setOwner(this); +} + +// ELF 0x1E24F0 (D1; D2 0x1E24A0, D0 0x1E2540): deletes the end condition. +BAPATurnTowardsDirection::~BAPATurnTowardsDirection() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1E25A0: always valid. +Vec3 BAPATurnTowardsDirection::getDirection(bool& ok) +{ + ok = true; + return m_direction; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.h new file mode 100644 index 000000000..4027cd0b0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.h @@ -0,0 +1,34 @@ +// Turn statement towards a fixed direction. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSDIRECTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSDIRECTION_H + +#include "../../../../Math/Vec3.h" +#include "BAPATurn.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; + +// ELF: vtable 0x4B8D80 (9 words), package H-deferred. +class BAPATurnTowardsDirection : public BAPATurn +{ +public: + BAPATurnTowardsDirection(const Vec3&, float, BAPCondition*, unsigned long long, int); // 0x1E2410 + virtual ~BAPATurnTowardsDirection(); // 0x1E24F0 + + virtual Vec3 getDirection(bool&); // 0x1E25A0, slot +0x20; from the base declaration + + /* +0x34 */ Vec3 m_direction; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSDIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp new file mode 100644 index 000000000..7f53496fc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp @@ -0,0 +1,61 @@ +// Turn statement towards an object. Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on +// every body. + +#include "BAPATurnTowardsObject.h" + +#include "BAPActionInline.h" +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1E2B30, __tcf_0 0x1E2B90, _GLOBAL__I 0x1E2BC0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E27C0 (C1; C2 0x1E2680): the base, the target at +0x38, the bot at +0x34. For the bot's +// equipment and then the target, a non-primary information asks for its primary object of the +// bot's side; both answers are discarded as compiled (neither information is null-checked). +// Finally the end condition's owner (not null-checked). +BAPATurnTowardsObject::BAPATurnTowardsObject(Bot* bot, unsigned int target, float turnSpeed, + BAPCondition* endCondition, unsigned long long controls, int tag) + : BAPATurn(turnSpeed, endCondition, controls, tag) +{ + m_target = target; + m_bot = bot; + Information* const self = bapinline::info(bot->getCurrentEquipment()); + if (!self->isPrimary()) + self->getPrimaryObject(bot->getSide()); // [UNRESOLVED] result unused in the image (0x1E28EC) + Information* const object = bapinline::info(target); + if (!object->isPrimary()) + object->getPrimaryObject(bot->getSide()); // [UNRESOLVED] result unused in the image (0x1E28CB) + m_endCondition->setOwner(this); +} + +// ELF 0x1E2950 (D1; D2 0x1E2900, D0 0x1E29A0): deletes the end condition. +BAPATurnTowardsObject::~BAPATurnTowardsObject() +{ + if (m_endCondition) + delete m_endCondition; +} + +// ELF 0x1E2A00: target position minus the bot's equipment position (not normalised; the +// equipment information is not null-checked). A stale target: ok = false and (1, 0, 0). +Vec3 BAPATurnTowardsObject::getDirection(bool& ok) +{ + Information* const target = bapinline::info(m_target); + ok = target != 0; + if (!ok) + return bapinline::vec3(1.0f, 0.0f, 0.0f); + const Vec3& selfPosition = bapinline::info(m_bot->getCurrentEquipment())->getPosition(); + const Vec3& targetPosition = target->getPosition(); + return bapinline::vec3(targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.h new file mode 100644 index 000000000..ac0227975 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.h @@ -0,0 +1,37 @@ +// Turn statement towards an object. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSOBJECT_H + +#include "../../../../Math/Vec3.h" +#include "BAPATurn.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B8DC0 (9 words), package H-deferred. Size 0x3C (`operator new(0x3c)` in +// BBPFire2dDriver::createPlan). +class BAPATurnTowardsObject : public BAPATurn +{ +public: + BAPATurnTowardsObject(Bot*, unsigned int, float, BAPCondition*, unsigned long long, int); // 0x1E27C0 + virtual ~BAPATurnTowardsObject(); // 0x1E2950 + + virtual Vec3 getDirection(bool&); // 0x1E2A00, slot +0x20; from the base declaration + + /* +0x34 */ Bot* m_bot; + /* +0x38 */ unsigned int m_target; // information handle +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPATURNTOWARDSOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp new file mode 100644 index 000000000..3ad32c864 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp @@ -0,0 +1,56 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E2DA0 (__tcf_0 0x1E2E00, _GLOBAL__I 0x1E2E30): 's Init object only. +#include + +#include "BAPAUpdateVehicle.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2C30 (C1; C2 0x1E2BE0): +4/+8/+0xC = 0, +0x10 = the pattern id. +BAPAUpdateVehicle::BAPAUpdateVehicle(int patternId) + : BAPAction() +{ + m_controls = 0; + m_patternId = patternId; +} + +// ELF 0x1E2CC0 (D0 0x1E2D00): the inlined ~BAPStatement only. +BAPAUpdateVehicle::~BAPAUpdateVehicle() +{ +} + +// ELF 0x1E2D50: BotMain::setUpdateCurrentEquipment, then ok = finished = true. +bool BAPAUpdateVehicle::execute(Bot* bot, bool& ok, bool& finished) +{ + static_cast(bot)->setUpdateCurrentEquipment(); + ok = true; + finished = true; + return true; +} + +// ELF 0x1E2E50 +unsigned long long BAPAUpdateVehicle::getControls() +{ + return 0; +} + +// ELF 0x1E2E60 +BAPStatementType BAPAUpdateVehicle::getId() const +{ + return BAPSTUpdateVehicle; // 27 +} + +// ELF 0x1E2D90 +bool BAPAUpdateVehicle::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.h new file mode 100644 index 000000000..dc882ba18 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.h @@ -0,0 +1,36 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUPDATEVEHICLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUPDATEVEHICLE_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8E00 (8 words), operator new 0x14, package F-infantry. +// Asks the bot to re-read its current equipment (BotMain::setUpdateCurrentEquipment) after a change. +// The constructor argument is the creating pattern's id (BAPStatement +0x10). +class BAPAUpdateVehicle : public BAPAction +{ +public: + explicit BAPAUpdateVehicle(int); // 0x1E2C30 + virtual ~BAPAUpdateVehicle(); // 0x1E2CC0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E2D50, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E2E50, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E2E60, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E2D90, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUPDATEVEHICLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp new file mode 100644 index 000000000..f314c99b6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp @@ -0,0 +1,79 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E3180 (__tcf_0 0x1E31E0, _GLOBAL__I 0x1E3210): 's Init object only. +#include + +#include "BAPAUseFlareOnMissileLock.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E2EE0 (C1) +BAPAUseFlareOnMissileLock::BAPAUseFlareOnMissileLock(Bot* bot, unsigned long long controls, int patternId) +{ + m_bot = bot; + m_controls = controls; + m_lockTime = -1.0; + m_locked = false; + m_patternId = patternId; +} + +// ELF 0x1E2F90 (D0 0x1E2FD0) +BAPAUseFlareOnMissileLock::~BAPAUseFlareOnMissileLock() +{ +} + +// ELF 0x1E3020. `time` is a function-static double (data 0x4B8E68 = 1.0). The flare input is +// written inline (mapped bit 47 -> inputs[47] = 1). The information is not null-checked. +bool BAPAUseFlareOnMissileLock::execute(Bot* bot, bool& ok, bool& failed) +{ + static double time = 1.0; + Information* info = bapinline::info(bot->getCurrentEquipment()); + IPIUnit* unit = info->getUnit(); + const int status = unit->getMissileLockStatus(); + const double now = bapinline::gameTime(); + bool locked = m_locked; + if (!locked && 0 < status) { + m_locked = true; + locked = true; + m_lockTime = now; + } + double wait = time; + if (!(info->getObjectTypeFlags() & 0x10u)) + wait = 0.0; + if (locked && wait <= now - m_lockTime) { + io::PlayerInput* input = bot->getInput(); + if ((input->mappingFlags >> io::PIFlareFire) & 1ULL) + input->inputs[io::PIFlareFire] = 1.0f; + unit->setMissileLockStatus(0); + m_locked = false; + } + ok = true; + failed = true; + return true; +} + +// ELF 0x1E3160 +BAPStatementType BAPAUseFlareOnMissileLock::getId() const +{ + return BAPSTUseFlareOnMissileLock; // 40 +} + +// ELF 0x1E3170 +bool BAPAUseFlareOnMissileLock::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.h new file mode 100644 index 000000000..daa30166a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUSEFLAREONMISSILELOCK_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUSEFLAREONMISSILELOCK_H + +#include "BAPAction.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B8E80 (8 words), operator new 0x24, package C-actions. +// Fires flares (PIFlareFire) once a missile lock on the bot's vehicle has lasted the +// static delay (1 s for vehicles with type flag 0x10, else at once), then clears the lock status. +class BAPAUseFlareOnMissileLock : public BAPAction +{ +public: + BAPAUseFlareOnMissileLock(Bot*, unsigned long long, int); // 0x1E2EE0 + virtual ~BAPAUseFlareOnMissileLock(); // 0x1E2F90 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E3020, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1E3160, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E3170, slot +0x14; from the base declaration + +private: + /* +0x14 */ Bot* m_bot; + /* +0x18 */ double m_lockTime; // = -1.0 + /* +0x20 */ bool m_locked; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPAUSEFLAREONMISSILELOCK_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAction.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAction.h new file mode 100644 index 000000000..1995b99d5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAction.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTION_H + +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// Action base. Vtable 0x4B8000; no members of its own (inline in the image). +// ELF: vtable 0x4B8000 (8 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPAction : public BAPStatement +{ +public: + BAPAction() = default; + virtual ~BAPAction() {} // weak in the image (inline) + +protected: + // [CHOSEN, not recovered] forward the selector for BAPADebug's omitted pattern-id store + // (inline base construction in ELF 0x1FB6F0). + explicit BAPAction(UninitializedPatternId tag) : BAPStatement(tag) {} +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h new file mode 100644 index 000000000..59ebceb9d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h @@ -0,0 +1,152 @@ +// [CHOSEN, not recovered] package C (ai-w1-c-actions): the inline helpers the BAP actions and +// conditions spell out in place. libaidll.so has no symbol for any of them; each one is the exact +// expansion seen in the bodies that cite it (ELF addresses there). Header-only, no build-list entry. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTIONINLINE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTIONINLINE_H + +#include "../../../../Math/Vec3.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../AIKnowledge/InformationManager.h" +#include "../Main/AIDllFrontier.h" +#include "BAPCondition.h" +#include "BAPTypes.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../AIUtils/IgnoreListPredicate.h" +#include "../Main/AIStreamOperators.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +class BAPCondition; +class IAIObject; + +namespace bapinline { + +// informationManager->m_pool->get(handle): `h & 0xFFFF` one-based slot, `h >> 16` generation +// (e.g. BAPALookAtObject::getLookDirection 0x1D3320, BAPAMergeSoldierInputs::execute 0x1D3F00). +inline Information* info(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +// `(mappingFlags >> i) & 1 ? inputs[i] : 0.0f`: an unmapped input reads as zero +// (BAPAMergeSoldierInputs::execute 0x1D3FF0: bit 13 then +0x34; bit 3 then +0x0C). +inline float mappedInput(const io::PlayerInput* in, io::PlayerInputMap i) +{ + return ((in->mappingFlags >> static_cast(i)) & 1ULL) ? in->inputs[i] : 0.0f; +} + +inline Vec3 vec3(float x, float y, float z) +{ + Vec3 v; + v.x = x; + v.y = y; + v.z = z; + return v; +} + +inline Vec3 sub(const Vec3& a, const Vec3& b) { return vec3(a.x - b.x, a.y - b.y, a.z - b.z); } +inline Vec3 add(const Vec3& a, const Vec3& b) { return vec3(a.x + b.x, a.y + b.y, a.z + b.z); } +inline float dot(const Vec3& a, const Vec3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } +inline float lengthSqr(const Vec3& a) { return dot(a, a); } + +// The engine's inline Vec3 normalise: left alone within FLT_EPSILON of unit length, zeroed when +// the squared length is below FLT_EPSILON, else scaled by 1/sqrt (0x1D3495..0x1D351A). +inline void normalize(Vec3& v) +{ + const float lsq = lengthSqr(v); + if (std::fabs(1.0f - lsq) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.1920929e-07f) { + v = vec3(0.0f, 0.0f, 0.0f); + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x *= inv; + v.y *= inv; + v.z *= inv; +} + +// The Vec2 variant: zeroed below FLT_EPSILON^2 (1.4210855e-14), BAPAMergeSoldierInputs 0x1D3F00. +inline void normalize(Vec2& v) +{ + const float lsq = v.x * v.x + v.y * v.y; + if (std::fabs(lsq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lsq) < 1.4210855e-14f) { + v.x = 0.0f; + v.y = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lsq); + v.x *= inv; + v.y *= inv; +} + +// CommonSingletonServer::m_iBFTimer->vfn+0x08 / +0x0C (BAPATriggerContinously ctor 0x1E1BDF). +inline double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +inline double timeIncrease() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); +} + +// operator<<(std::ostream&, const BAPCondition&) (ELF 0x1F80D0, A-core's BAPCondition.cpp). +inline std::ostream& streamCondition(std::ostream& out, const BAPCondition* condition) +{ + return out << *condition; +} + +// [FRONTIER] io::operator<<(std::ostream&, PlayerInputMap) is the engine's (IO/Input/InputMapStream.cpp, +// a bf2 export the shipped libaidll imports through its PLT); that TU is not in the bf2_aidll +// source list (coordinator decision requested), so the debug text stops here. +inline std::ostream& streamInput(std::ostream& out, io::PlayerInputMap) +{ + BF2_AI_FRONTIER("dice::hfe::io::operator<<(std::ostream&, PlayerInputMap) (engine export, not linked into bf2_aidll)"); + return out; +} + +// operator<<(std::ostream&, BAPStatementType) (ELF 0x3C7D90) and operator<<(std::ostream&, +// BAPConditionType) (0x3C7AE0), ai-main's Main/AIStreamOperators.cpp. +inline std::ostream& streamType(std::ostream& out, BAPStatementType type) +{ + return out << type; +} + +inline std::ostream& streamType(std::ostream& out, BAPConditionType type) +{ + return out << type; +} + +// `std::vector ignore; ignore.push_back(object); IgnoreListPredicate pred(ignore); +// m_iaiObjectEnvironment->collideLineWithWorld(from, to, &pred, &hit)` (slot +0x44), spelled out +// in BAPConSplashDamage::evaluate (push_back 0x1EA618, ctor 0x1EA627), BAPConOkToThrowGrenade:: +// evaluate (two traces; the second reuses the predicate after `ignore.resize(0); +// ignore.push_back(target)`, the same one-element list) and BAPWrapperAiming::getGroundLevelAtPos +// 0x1F8CF0. `hit` is the caller's zeroed output. +inline bool collideLineIgnoring(const Vec3& from, const Vec3& to, IAIObject* object, Vec3& hit) +{ + std::vector ignore; + ignore.push_back(object); + IgnoreListPredicate predicate(ignore); + return static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(from, to, &predicate, &hit); +} + +} // namespace bapinline +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPACTIONINLINE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h new file mode 100644 index 000000000..8e5070277 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPBoleanOp.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPBOLEANOP_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPBOLEANOP_H + +#include +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; + +// Base of And/Or/Not. Vtable 0x4B9E60. Inline in the image: BAPConAnd() 0x1F3D30 stores the +// BAPBoleanOp vptr, +4 = 0 and builds the list before its own vptr; ~BAPConAnd 0x1F3E10 deletes the +// children under its own vptr, then clears and frees the list under BAPBoleanOp's. +// ELF: vtable 0x4B9E60 (6 words), package S0-skeleton (layout: A-core). +class BAPBoleanOp : public BAPCondition +{ +public: + BAPBoleanOp() {} + virtual ~BAPBoleanOp() {} // weak in the image (inline); the list destructor runs here + + virtual void addCondition(BAPCondition*) = 0; // no body, slot +0x14; ELF void (BAPConAnd 0x1F40A0) + +protected: + /* +0x08 */ std::list m_conditions; // owned: the derived destructors delete them +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPBOLEANOP_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp new file mode 100644 index 000000000..f265198d2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp @@ -0,0 +1,91 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build compares the squared miss distance in extended precision. + +// static init: ELF 0x1EB440 (__tcf_0 0x1EB4A0, _GLOBAL__I 0x1EB4D0): 's Init object only. +#include + +#include "BAPCConBombPrecision3d.h" + +#include +#include + +#include "../AIBot/BotMain.h" +#include "BAPAAimAt3d.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EB110 (C1; C2 0x1EB0B0) +BAPCConBombPrecision3d::BAPCConBombPrecision3d(BAPAAimAt3d* aim, float precision, bool waitForClosest) +{ + m_precisionSq = std::max(0.01f, precision * precision); + m_aim = aim; + m_bestDistanceSq = FLT_MAX; + m_float14 = FLT_MAX; + m_waitForClosest = waitForClosest; +} + +// ELF 0x1EB4F0 (D0 0x1EB510): base only. +BAPCConBombPrecision3d::~BAPCConBombPrecision3d() +{ +} + +// ELF 0x1EB170. The aimer transform is fetched and not used; a failed closest approach keeps its +// best distance (unlike BAPCConPrecision3d), as compiled. +bool BAPCConBombPrecision3d::evaluate(Bot* bot) +{ + if (!m_aim->isAimVecValid()) + return false; + if (!bapinline::info(bot->getCurrentEquipment())) + return false; + double impactTime; + m_aim->getImpactTime(impactTime); + Vec3 aimVec = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getLastAimVec(aimVec); + m_aim->getAimerTransform(); + Vec3 predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getPredictedPosition(predicted); + Vec3 impact = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aim->getImpactPosition(impact, impactTime - bapinline::gameTime())) + return false; + const float distanceSq = bapinline::lengthSqr(bapinline::sub(predicted, impact)); + + if (m_waitForClosest) + { + const float precisionSq = m_precisionSq; + if (!(precisionSq * 0.25f > distanceSq)) + { + const float best = m_bestDistanceSq; + if (best > 0.01 && best >= distanceSq) + { + m_bestDistanceSq = distanceSq; // still closing in + if (precisionSq >= distanceSq) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return false; + } + if (!(precisionSq >= best)) + return false; + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + m_bestDistanceSq = FLT_MAX; + return true; + } + } + else if (!(m_precisionSq >= distanceSq)) + { + return false; + } + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; +} + +// ELF 0x1EB430 +BAPConditionType BAPCConBombPrecision3d::getConditionType() const +{ + return BAPCTBombPrecision3d; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.h new file mode 100644 index 000000000..7e1a9639b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.h @@ -0,0 +1,42 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONBOMBPRECISION3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONBOMBPRECISION3D_H + +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPAAimAt3d; +class Bot; + +// ELF: vtable 0x4B9510 (5 words), operator new 0x1C, package G-vehicles. +// BAPCConPrecision3d for bombs, without the angle test: the squared precision is at least 0.01; +// with waitForClosest a miss within half the precision answers at once. +class BAPCConBombPrecision3d : public BAPConnectedCondition +{ +public: + BAPCConBombPrecision3d(BAPAAimAt3d*, float, bool); // 0x1EB110 + virtual ~BAPCConBombPrecision3d(); // 0x1EB4F0 + + virtual bool evaluate(Bot*); // 0x1EB170, slot +0x00 + virtual BAPConditionType getConditionType() const; // 0x1EB430, slot +0x04 + +private: + /* +0x08 */ float m_precisionSq; + /* +0x0C */ BAPAAimAt3d* m_aim; + /* +0x10 */ float m_bestDistanceSq; // FLT_MAX: no approach yet + /* +0x14 */ float m_float14; // [UNRESOLVED] constructed FLT_MAX, never read + /* +0x18 */ bool m_waitForClosest; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONBOMBPRECISION3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp new file mode 100644 index 000000000..7c20610a1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp @@ -0,0 +1,94 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EB990 (__tcf_0 0x1EB9F0, _GLOBAL__I 0x1EBA20): 's Init object only. +#include + +#include "BAPCConLookDeviation.h" + +#include "BAPALook.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../../Math/Mat4.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EB5D0 (C1) +BAPCConLookDeviation::BAPCConLookDeviation(BAPALook* look, float angle, bool flat) +{ + m_look = look; + m_flat = flat; + float a = 0.0f; + if (0.0f <= angle) { + a = angle; + if (3.1415927f < angle) + a = 3.1415927f; + } + m_cosLimit = std::cos(a); +} + +// ELF 0x1EB670 (D0 0x1EB690) +BAPCConLookDeviation::~BAPCConLookDeviation() +{ +} + +// ELF 0x1EB6D0: dot of the normalised look direction with camera row 2 (forward, +0x20) of +// IAIPlayer::getCameraTransformation (+0x8C) against the cosine limit; too short a direction or +// no player/information/look: false. +bool BAPCConLookDeviation::evaluate(Bot* bot) +{ + if (!bapinline::info(bot->getCurrentEquipment())) + return false; + bool valid; + Vec3 d = m_look->getLookDirection(valid); + if (!valid) + return false; + if (!m_flat) { + const float len = std::sqrt(d.z * d.z + d.y * d.y + d.x * d.x); + if (0.001f <= len) { + const float inv = 1.0f / len; + d.x *= inv; + d.y *= inv; + d.z = inv * d.z; + if (!bot->getPlayer()) + return false; + const Mat4& cam = *static_cast(bot->getPlayer()->getCameraTransformation()); + return m_cosLimit <= d.z * cam.m[10] + d.y * cam.m[9] + d.x * cam.m[8]; + } + return false; + } + d.y = 0.0f; + const float len = std::sqrt(d.z * d.z + d.x * d.x + 0.0f); + if (0.0001f <= len) { + const float inv = 1.0f / len; + d.x *= inv; + d.y *= inv; + d.z = inv * d.z; + if (!bot->getPlayer()) + return false; + const Mat4& cam = *static_cast(bot->getPlayer()->getCameraTransformation()); + const float fx = cam.m[8]; + const float fz = cam.m[10]; + const float flen = std::sqrt(fx * fx + 0.0f + fz * fz); + if (0.0001f <= flen) { + const float finv = 1.0f / flen; + return m_cosLimit <= fx * finv * d.x + 0.0f * finv * d.y + finv * fz * d.z; + } + } + return false; +} + +// ELF 0x1EB980 +BAPConditionType BAPCConLookDeviation::getConditionType() const +{ + return BAPCTLookDeviation; // 0 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.h new file mode 100644 index 000000000..0e77757e1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONLOOKDEVIATION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONLOOKDEVIATION_H + +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPALook; +class Bot; + +// ELF: vtable 0x4B9548 (5 words), operator new 0xC/0x14, package C-actions. +// True while the camera looks within an angle of the connected look's direction (3d, or XZ +// with the flag). Not owned: the look statement belongs to the plan. +class BAPCConLookDeviation : public BAPConnectedCondition +{ +public: + BAPCConLookDeviation(BAPALook*, float, bool); // 0x1EB5D0 + virtual ~BAPCConLookDeviation(); // 0x1EB670 + + virtual bool evaluate(Bot*); // 0x1EB6D0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EB980, slot +0x04; from the base declaration + +private: + /* +0x08 */ float m_cosLimit; // cos(clamp(angle, 0, pi)) + /* +0x0C */ BAPALook* m_look; + /* +0x10 */ bool m_flat; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONLOOKDEVIATION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp new file mode 100644 index 000000000..bacee5d32 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp @@ -0,0 +1,199 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EC520 (__tcf_0 0x1EC580, _GLOBAL__I 0x1EC5B0): 's Init object only. +#include + +#include "BAPCConPrecision.h" + +#include "BAPAAimAt.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The function-static `negativeYLimitFactor` of BAPCConPrecision::evaluate (ELF .data 0x4B95A4). +const float negativeYLimitFactor = 0.1f; + +} // namespace + +// ELF 0x1EBAF0 (C1; C2 0x1EBA40): against an aim action. +BAPCConPrecision::BAPCConPrecision(unsigned int target, BAPAAimAt* aim, float precision, bool waitForBest, + bool limitPositiveY, bool noAngleCheck) +{ + m_target = target; + m_precisionSqr = 0.01f <= precision * precision ? precision * precision : 0.01f; + m_precision = 0.1f <= precision ? precision : 0.1f; + m_aim = aim; + m_bestDistanceSqr = FLT_MAX; + m_aimValid = 0; + m_aimDirection = 0; + m_waitForBest = waitForBest; + m_noAngleCheck = noAngleCheck; + m_limitPositiveY = limitPositiveY; + if (!noAngleCheck) + m_angleLimit = std::atan(m_precision / 50.0f); +} + +// ELF 0x1EBC50 (C1; C2 0x1EBBA0): against BAPWrapperAiming's output variables. +BAPCConPrecision::BAPCConPrecision(unsigned int target, BAPVariable* aimValid, BAPVariable* aimDirection, + BAPVariable* aimPoint, float precision, bool waitForBest, + bool limitPositiveY, bool noAngleCheck) +{ + m_target = target; + m_precisionSqr = 0.01f <= precision * precision ? precision * precision : 0.01f; + m_aim = 0; + m_bestDistanceSqr = FLT_MAX; + m_precision = 0.1f <= precision ? precision : 0.1f; + m_waitForBest = waitForBest; + m_aimValid = aimValid; + m_aimDirection = aimDirection; + m_aimPoint = aimPoint; + m_noAngleCheck = noAngleCheck; + m_limitPositiveY = limitPositiveY; + if (!noAngleCheck) + m_angleLimit = std::atan(m_precision / 50.0f); +} + +// ELF 0x1EBD20 (D1; D0 0x1EBD40): base only. +BAPCConPrecision::~BAPCConPrecision() +{ +} + +// ELF 0x1EBD80. True when the shot would hit within the precision. Without the target +// information: false. +// Aim action: needs a valid aim; an "aimer only" weapon pointing exactly along the last aim vector +// (dot >= 1 with the aimer transform's row 2) fires at once. Otherwise the miss is the distance +// between the predicted target position and the Aimer's impact position at the impact time; with +// m_waitForBest the condition waits while the miss still shrinks and fires on the first shot that +// is no better than the best so far (when that best was within the precision). Every positive +// answer stamps BotMain::setHadPrecisionTimeStamp(now); the "still improving" path stamps when +// within the precision but answers false (0x1EC41A..0x1EC43D). +// Variables: needs the valid flag; the miss is the angle between the weapon's projectile-origin +// row 2 and the aim direction (unless m_noAngleCheck), then the offset of that row from the aim +// direction scaled by the distance to the aim point: horizontally within the precision and +// vertically (signed square) within +-20% of it (the lower bound times negativeYLimitFactor, the +// upper one too when m_limitPositiveY). Vehicles close to a non-soldier target (|dy| < 5, < 15 m) +// and vehicles using static attacks skip the angle and vertical checks. +bool BAPCConPrecision::evaluate(Bot* bot) +{ + Information* target = bapinline::info(m_target); + if (!target) + return false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + + if (!m_aimValid) { + if (!m_aim->isAimingValid()) + return false; + double impactTime; + m_aim->getImpactTime(impactTime); + Vec3 lastAim = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getLastAimVec(lastAim); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon && weapon->useAimerOnly()) { + const Mat4* t = m_aim->getAimerTransform(); + if (1.0f <= t->m[10] * lastAim.z + t->m[8] * lastAim.x + t->m[9] * lastAim.y) { + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; + } + } + Vec3 predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getPredictedPosition(predicted); + Vec3 impact = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aim->getImpactPosition(impact, impactTime - bapinline::gameTime())) + return false; + const Vec3 miss = bapinline::sub(predicted, impact); + const float d = miss.z * miss.z + miss.x * miss.x + miss.y * miss.y; + if (!m_waitForBest) { + if (m_precisionSqr <= d) + return false; + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; + } + const float best = m_bestDistanceSqr; + if (best <= 0.01f || best <= d) { + m_bestDistanceSqr = FLT_MAX; + if (m_precisionSqr < best) + return false; + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return true; + } + m_bestDistanceSqr = d; + if (d <= m_precisionSqr) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return false; + } + + if (!m_aimValid->m_value) + return false; + Information* own = bapinline::info(bot->getCurrentEquipment()); // re-read; not null-checked + IPIArmament* armament = own->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) + return false; + const Vec3& point = m_aimPoint->m_value; + const Vec3& from = own->getPosition(); + const Vec3 toPoint = bapinline::sub(point, from); + float distance = std::sqrt(toPoint.x * toPoint.x + toPoint.y * toPoint.y + toPoint.z * toPoint.z); + bool closeVehicle = false; + if (5.0f <= std::fabs(point.y - from.y)) { + } else if (!(target->getObjectTypeFlags() & 0x200000u)) { + if (!(own->getObjectTypeFlags() & 0x200000u) && distance < 15.0f) + closeVehicle = true; + } + bool staticAttack = false; + if (!(own->getObjectTypeFlags() & 0x200000u)) + staticAttack = static_cast(bot)->getUseStaticAttack(); + + const Vec3 aim = m_aimDirection->m_value; + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3 forward = bapinline::vec3(origin.m[8], origin.m[9], origin.m[10]); + if (!m_noAngleCheck && !closeVehicle && !staticAttack) { + float c = forward.x * aim.x + forward.y * aim.y + forward.z * aim.z; + if (c < -1.0f) + c = -1.0f; + else if (1.0f < c) + c = 1.0f; + if (m_angleLimit <= std::acos(c)) + return false; + } + const float ox = (forward.x - aim.x) * distance; + const float oz = (forward.z - aim.z) * distance; + const float oy = (forward.y - aim.y) * distance; + const float sign = oy <= 0.0f ? (0.0f <= oy ? 0.0f : -1.0f) : 1.0f; + const float verticalSqr = oy * oy * sign; + float upper = m_precisionSqr * 0.2f; + const float lower = -upper; + if (m_limitPositiveY) + upper = upper * negativeYLimitFactor; + if (m_precisionSqr < ox * ox + oz * oz) + return false; + if (!closeVehicle && !staticAttack) { + if (upper < verticalSqr) + return false; + if (verticalSqr < lower * negativeYLimitFactor) + return false; + } + return true; +} + +// ELF 0x1EC510 +BAPConditionType BAPCConPrecision::getConditionType() const +{ + return BAPCTPrecision; // 1 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.h new file mode 100644 index 000000000..a2b18e964 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION_H + +#include "../../../../Math/Vec3.h" +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPAAimAt; +class Bot; + +// ELF: vtable 0x4B95A8 (5 words), package C-actions. +class BAPCConPrecision : public BAPConnectedCondition +{ +public: + BAPCConPrecision(unsigned int, BAPAAimAt*, float, bool, bool, bool); // 0x1EBAF0 + BAPCConPrecision(unsigned int, BAPVariable*, BAPVariable*, BAPVariable*, float, bool, bool, bool); // 0x1EBC50 + virtual ~BAPCConPrecision(); // 0x1EBD20 + + virtual bool evaluate(Bot*); // 0x1EBD80, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EC510, slot +0x04; from the base declaration + +private: + /* +0x08 */ unsigned int m_target; // information handle (only null-checked) + /* +0x0C */ float m_precisionSqr; // max(precision^2, 0.01) + /* +0x10 */ float m_precision; // max(precision, 0.1) + /* +0x14 */ BAPAAimAt* m_aim; // first constructor; 0 with the variables + /* +0x18 */ float m_bestDistanceSqr; // = FLT_MAX; with m_waitForBest + /* +0x1C */ bool m_waitForBest; // fire when the miss stops shrinking + /* +0x20 */ BAPVariable* m_aimValid; // second constructor (BAPWrapperAiming's outputs) + /* +0x24 */ BAPVariable* m_aimDirection; + /* +0x28 */ BAPVariable* m_aimPoint; // not written by the first constructor + /* +0x2C */ bool m_limitPositiveY; // the upper vertical limit is scaled too + /* +0x2D */ bool m_noAngleCheck; + /* +0x30 */ float m_angleLimit; // atan(m_precision / 50) unless m_noAngleCheck +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp new file mode 100644 index 000000000..421f2e487 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp @@ -0,0 +1,95 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build compares the squared miss distance in extended precision. + +// static init: ELF 0x1ECA30 (__tcf_0 0x1ECA90, _GLOBAL__I 0x1ECAC0): 's Init object only. +#include + +#include "BAPCConPrecision3d.h" + +#include +#include + +#include "../AIBot/BotMain.h" +#include "BAPAAimAt3d.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EC650 (C1; C2 0x1EC5D0) +BAPCConPrecision3d::BAPCConPrecision3d(unsigned int object, BAPAAimAt3d* aim, float precision, bool waitForClosest) +{ + m_precision = precision; + m_object = object; + m_precisionSq = precision * precision; + m_aim = aim; + m_waitForClosest = waitForClosest; + m_bestDistanceSq = FLT_MAX; + m_maxAngle = std::atan(precision / 80.0f); +} + +// ELF 0x1EC6F0 (D1 0x1EC6D0, D0 0x1EC710): base only. +BAPCConPrecision3d::~BAPCConPrecision3d() +{ +} + +// ELF 0x1EC750. The bot's own information is looked up and not used, as compiled. +bool BAPCConPrecision3d::evaluate(Bot* bot) +{ + if (!m_aim->isAimVecValid()) + return false; + if (!bapinline::info(m_object)) + return false; + bot->getCurrentEquipment(); + double impactTime; + m_aim->getImpactTime(impactTime); + Vec3 aimVec = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getLastAimVec(aimVec); + const Mat4& transform = m_aim->getAimerTransform(); + float cosine = transform.m[8] * aimVec.x + transform.m[9] * aimVec.y + transform.m[10] * aimVec.z; + if (cosine < -1.0f) + cosine = -1.0f; + else if (cosine > 1.0f) + cosine = 1.0f; + if (std::acos(cosine) > m_maxAngle) + return false; + + Vec3 predicted = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aim->getPredictedPosition(predicted); + Vec3 impact = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aim->getImpactPosition(impact, impactTime - bapinline::gameTime())) + return false; + const float distanceSq = bapinline::lengthSqr(bapinline::sub(predicted, impact)); + + if (!m_waitForClosest) + { + const bool hit = distanceSq <= m_precisionSq; + if (hit) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return hit; + } + const float best = m_bestDistanceSq; + if (best > 0.01f && best >= distanceSq) + { + m_bestDistanceSq = distanceSq; // still closing in + if (distanceSq <= m_precisionSq) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + return false; + } + const bool hit = best <= m_precisionSq; + if (hit) + static_cast(bot)->setHadPrecisionTimeStamp(bapinline::gameTime()); + m_bestDistanceSq = FLT_MAX; + return hit; +} + +// ELF 0x1ECA20 +BAPConditionType BAPCConPrecision3d::getConditionType() const +{ + return BAPCTPrecision3d; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.h new file mode 100644 index 000000000..1ecfc0025 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.h @@ -0,0 +1,46 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION3D_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION3D_H + +#include "BAPConnectedCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPAAimAt3d; +class Bot; + +// ELF: vtable 0x4B95D0 (5 words), operator new 0x24, package G-vehicles. +// True when the aim's trajectory passes within `precision` of the target's predicted position and +// the aim deviates from the weapon's forward axis by at most atan(precision / 80). With +// waitForClosest it holds fire while the miss distance still shrinks and answers once it grows. +// Each hit stamps BotMain::setHadPrecisionTimeStamp. +class BAPCConPrecision3d : public BAPConnectedCondition +{ +public: + BAPCConPrecision3d(unsigned int, BAPAAimAt3d*, float, bool); // 0x1EC650 + virtual ~BAPCConPrecision3d(); // 0x1EC6F0 + + virtual bool evaluate(Bot*); // 0x1EC750, slot +0x00 + virtual BAPConditionType getConditionType() const; // 0x1ECA20, slot +0x04 + +private: + /* +0x08 */ unsigned int m_object; // checked for information only + /* +0x0C */ float m_precisionSq; + /* +0x10 */ float m_precision; + /* +0x14 */ BAPAAimAt3d* m_aim; + /* +0x18 */ bool m_waitForClosest; // [INFERRED] name; callers pass !weapon->getBurst() + /* +0x1C */ float m_bestDistanceSq; // FLT_MAX: no approach yet + /* +0x20 */ float m_maxAngle; // atanf(precision / 80) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCCONPRECISION3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h new file mode 100644 index 000000000..ee8a2ff1b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombiner.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINER_H + +#include +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// Base of the serial and parallel combiners. Vtable 0x4B9080. Inline in the image: every combiner +// constructor (BAPCombinerSerial(int, int) 0x1E6150, BAPCombinerParallel(int, int, bool) 0x1E4910) +// stores the BAPCombiner vptr, builds the statement list, then under its own vptr stores +// +0x18 = 0 and +0x1C = true (or the `bool` argument), then +0x10. The combiner destructors delete +// the children under their own vptr; the list is freed under BAPCombiner's (0x1E664C). +// ELF: vtable 0x4B9080 (9 words), package S0-skeleton (layout: A-core). +class BAPCombiner : public BAPStatement +{ + // [INFERRED] friendship: PrettyPrinter::prettyPrintScriptNode (libaidll ELF 0x1CAE60) reads the + // statement list, cursor and debug id inline. + friend class PrettyPrinter; +public: + virtual ~BAPCombiner() {} // weak in the image (inline); the list destructor runs here + + virtual unsigned long long getControls() = 0; // slot +0x0C: __cxa_pure_virtual in vtable 0x4B9080 (re-declared pure) + virtual void addStatement(BAPStatement*) = 0; // no body, slot +0x20; ELF void (BAPCombinerSerial 0x1E69A0) + +protected: + BAPCombiner(int patternId, bool waitForChild) + : BAPStatement(patternId), m_current(), m_waitForChild(waitForChild) {} + + /* +0x14 */ std::list m_statements; // owned children, in order + /* +0x18 */ std::list::iterator m_current; // = 0 in the constructors, then begin() + // +0x1C: true unless the (int, bool, ...) constructors pass false. Serial: advance only when the + // child reports finished (0x1E68E6); Parallel: copied into `finished` before the children run + // (0x1E57F0). [INFERRED] name. + /* +0x1C */ bool m_waitForChild; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp new file mode 100644 index 000000000..862a2199b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp @@ -0,0 +1,168 @@ +// BAPCombinerParallel: recovered by package A-core from libaidll.so (TU BAPCombinerParallel.cpp, +// 0x1E4910..0x1E6150). Every body carries its ELF address. + +// static init: ELF 0x1E5C20 (__tcf_0 0x1E5C80, _GLOBAL__I 0x1E5CB0): 's Init object only. +#include + +#include "BAPCombinerParallel.h" + +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E4910 (C2; C1 0x1E4AA0). The controls are zeroed again and the list cleared in the body. +BAPCombinerParallel::BAPCombinerParallel(int patternId, int debugId, bool neverFinish) + : BAPCombiner(patternId, true) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements.clear(); +} + +// ELF 0x1E4B70 (C2; C1 0x1E4C50). +BAPCombinerParallel::BAPCombinerParallel(int patternId, bool waitForChild, int debugId, bool neverFinish) + : BAPCombiner(patternId, waitForChild) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements.clear(); +} + +// ELF 0x1E4D30 (C2; C1 0x1E4F10). Takes ownership; the controls are the union of the children's. +BAPCombinerParallel::BAPCombinerParallel(std::list& statements, int patternId, int debugId, + bool neverFinish) + : BAPCombiner(patternId, true) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements = statements; + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + (*it)->m_owner = this; + m_controls |= (*it)->getControls(); + m_isFinished.insert(m_isFinished.end(), false); + } +} + +// ELF 0x1E50F0 (C2; C1 0x1E52E0). +BAPCombinerParallel::BAPCombinerParallel(std::list& statements, int patternId, bool waitForChild, + int debugId, bool neverFinish) + : BAPCombiner(patternId, waitForChild) + , m_debugId(debugId) + , m_neverFinish(neverFinish) +{ + m_controls = 0; + m_statements = statements; + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + (*it)->m_owner = this; + m_controls |= (*it)->getControls(); + m_isFinished.insert(m_isFinished.end(), false); + } +} + +// ELF 0x1E54D0 (D2; D1 0x1E55C0, D0 0x1E56B0). Deletes the children (slot +8). +BAPCombinerParallel::~BAPCombinerParallel() +{ + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1E57B0 (108 instructions); the rules are in the header. Always returns 1. +bool BAPCombinerParallel::execute(Bot* bot, bool& ok, bool& finished) +{ + bool childFinished = false; + bool childOk = true; + finished = m_waitForChild; + ok = true; + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E57FF. + PlanInterpreter* interpreter = static_cast(bot)->getPlanInterpreter(); + std::list::iterator finishedFlag = m_isFinished.begin(); // never advanced (retail) + + for (m_current = m_statements.begin(); m_current != m_statements.end(); ++m_current) + { + (*m_current)->getControls(); // called, result unused (0x1E5858) + interpreter->execute(*m_current, bot, childOk, childFinished); + ok = ok && childOk; + if (m_waitForChild) + finished = finished && childFinished; + else + finished = finished || childFinished; + *finishedFlag = childFinished; + } + + if (m_neverFinish) + finished = false; + return true; +} + +// ELF 0x1E5940. +unsigned long long BAPCombinerParallel::getControls() +{ + return m_controls; +} + +// ELF 0x1E6140. +BAPStatementType BAPCombinerParallel::getId() const +{ + return BAPSTParallel; +} + +// ELF 0x1E5950. +bool BAPCombinerParallel::hasDefault() +{ + return true; +} + +// ELF 0x1E5A70. "Parallell" is the image's spelling. +void BAPCombinerParallel::streamSelf(std::ostream& os) const +{ + IBotManager::instance->tabulate(os); + os << "Parallell combiner"; + if (m_debugId != -1) + os << "(" << m_debugId << ")"; + os << std::endl; + + IBotManager::instance->tabulate(os); + os << '{' << std::endl; + IBotManager::instance->increaseTabLevel(); + for (std::list::const_iterator it = m_statements.begin(); it != m_statements.end(); ++it) + os << **it; + IBotManager::instance->decreaseTabLevel(); + IBotManager::instance->tabulate(os); + os << '}' << std::endl; +} + +// ELF 0x1E5960. A null statement is ignored. +void BAPCombinerParallel::addStatement(BAPStatement* statement) +{ + if (statement == 0) + return; + statement->m_owner = this; + m_statements.insert(m_statements.end(), statement); + m_controls |= statement->getControls(); + m_isFinished.insert(m_isFinished.end(), false); +} + +// ELF 0x1E5A60. +const std::list& BAPCombinerParallel::getIsFinished() const +{ + return m_isFinished; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.h new file mode 100644 index 000000000..12a13400d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.h @@ -0,0 +1,63 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERPARALLEL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERPARALLEL_H + +#include +#include +#include "BAPCombiner.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// Runs all children every tick, in order. Completion rules (execute 0x1E57B0): +// * ok = true and finished = waitForChild before the loop; the children share one ok/finished +// pair that is not reset between them (child ok starts true, child finished false); +// * after each child: ok &= child ok; finished = waitForChild ? (finished && child finished) +// : (finished || child finished), i.e. all children finished, or any child finished; +// * neverFinish forces finished = false at the end. An empty combiner reports ok and +// finished = waitForChild (unless neverFinish). +// Each child's finished flag is stored into the FIRST element of m_isFinished only (the image never +// advances that iterator, 0x1E58CE). Each child's getControls() is called and discarded first. +// sizeof 0x2C. +// ELF: vtable 0x4B9040 (9 words), operator new 0x2C, package A-core. +class BAPCombinerParallel : public BAPCombiner +{ + // [INFERRED] friendship: PrettyPrinter::prettyPrintScriptNode (libaidll ELF 0x1CAE60) reads the + // statement list, cursor and debug id inline. + friend class PrettyPrinter; +public: + BAPCombinerParallel(int patternId, int debugId, bool neverFinish); // 0x1E4AA0 + BAPCombinerParallel(int patternId, bool waitForChild, int debugId, bool neverFinish); // 0x1E4C50 + BAPCombinerParallel(std::list& statements, int patternId, int debugId, bool neverFinish); // 0x1E4F10 + BAPCombinerParallel(std::list& statements, int patternId, bool waitForChild, int debugId, + bool neverFinish); // 0x1E52E0 + virtual ~BAPCombinerParallel(); // 0x1E55C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E57B0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E5940, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E6140, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E5950, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E5A70, slot +0x1C; from the base declaration + virtual void addStatement(BAPStatement*); // 0x1E5960, slot +0x20; from the base declaration + + const std::list& getIsFinished() const; // 0x1E5A60: returns this + 0x20 + +private: + /* +0x20 */ std::list m_isFinished; // one false per child (addStatement / list constructors) + /* +0x24 */ int m_debugId; // second constructor int, -1 from the creators; streamSelf only [INFERRED] name + /* +0x28 */ bool m_neverFinish; // last constructor bool [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERPARALLEL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp new file mode 100644 index 000000000..4c79fb716 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp @@ -0,0 +1,152 @@ +// BAPCombinerSerial: recovered by package A-core from libaidll.so (TU BAPCombinerSerial.cpp, +// 0x1E6150..0x1E6CF0). Every body carries its ELF address. + +// static init: ELF 0x1E6C30 (__tcf_0 0x1E6C90, _GLOBAL__I 0x1E6CC0): 's Init object only. +#include + +#include "BAPCombinerSerial.h" + +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E6150 (C2; C1 0x1E6200). The body clears the (new, empty) list, then rewinds. +BAPCombinerSerial::BAPCombinerSerial(int patternId, int debugId) + : BAPCombiner(patternId, true) + , m_debugId(debugId) +{ + m_statements.clear(); + m_current = m_statements.begin(); +} + +// ELF 0x1E62B0 (C2; C1 0x1E6360). +BAPCombinerSerial::BAPCombinerSerial(int patternId, bool waitForChild, int debugId) + : BAPCombiner(patternId, waitForChild) + , m_debugId(debugId) +{ + m_statements.clear(); + m_current = m_statements.begin(); +} + +// ELF 0x1E6410 (C2; C1 0x1E6500). Copies the list and takes ownership of its statements. +BAPCombinerSerial::BAPCombinerSerial(std::list& statements, int patternId, int debugId) + : BAPCombiner(patternId, true) + , m_debugId(debugId) +{ + m_statements = statements; + m_current = m_statements.begin(); + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + (*it)->m_owner = this; +} + +// ELF 0x1E65F0 (D2; D1 0x1E66B0, D0 0x1E6770). Deletes the children (slot +8). +BAPCombinerSerial::~BAPCombinerSerial() +{ + for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1E6840 (84 instructions). The child's own result is ignored; this always returns 1. +bool BAPCombinerSerial::execute(Bot* bot, bool& ok, bool& finished) +{ + if (m_current == m_statements.end()) + { + ok = true; + finished = true; + m_current = m_statements.begin(); + return true; + } + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E68BA. + static_cast(bot)->getPlanInterpreter()->execute(*m_current, bot, ok, finished); + + if (m_waitForChild) + { + if (!finished) + return true; + ++m_current; + if (m_current != m_statements.end()) + { + finished = false; + return true; + } + } + else + { + ++m_current; + if (!finished && m_current != m_statements.end()) + return true; + } + + finished = true; + m_current = m_statements.begin(); + return true; +} + +// ELF 0x1E6970: the current child's controls. Retail reads through m_current without an end() +// check (only an empty combiner can be at end() here, see execute). +unsigned long long BAPCombinerSerial::getControls() +{ + return (*m_current)->getControls(); +} + +// ELF 0x1E6CE0. +BAPStatementType BAPCombinerSerial::getId() const +{ + return BAPSTSerial; +} + +// ELF 0x1E6990. +bool BAPCombinerSerial::hasDefault() +{ + return true; +} + +// ELF 0x1E6A20. IBotManager::tabulate/increaseTabLevel/decreaseTabLevel are +0x88/+0x80/+0x84. +void BAPCombinerSerial::streamSelf(std::ostream& os) const +{ + IBotManager::instance->tabulate(os); + os << "Serial combiner"; + if (m_debugId != -1) + os << "(" << m_debugId << ")"; + os << std::endl; + + IBotManager::instance->tabulate(os); + os << '{' << std::endl; + IBotManager::instance->increaseTabLevel(); + for (std::list::const_iterator it = m_statements.begin(); it != m_statements.end(); ++it) + { + if (std::list::const_iterator(m_current) == it) + { + IBotManager::instance->tabulate(os); + os << "/*Active serial statement*/" << std::endl; + } + os << **it; + } + IBotManager::instance->decreaseTabLevel(); + IBotManager::instance->tabulate(os); + os << '}' << std::endl; +} + +// ELF 0x1E69A0. A null statement is ignored; adding rewinds. +void BAPCombinerSerial::addStatement(BAPStatement* statement) +{ + if (statement == 0) + return; + statement->m_owner = this; + m_statements.insert(m_statements.end(), statement); + m_current = m_statements.begin(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.h new file mode 100644 index 000000000..b21441078 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.h @@ -0,0 +1,56 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERSERIAL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERSERIAL_H + +#include +#include +#include "BAPCombiner.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// Runs its children one after the other. Completion rules (execute 0x1E6840): +// * empty list, or the current child is past the end: ok = finished = true, rewind, done; +// * waitForChild (default): the current child runs each tick; when it reports finished the +// combiner moves to the next one, and reports finished (and rewinds) after the last; +// * !waitForChild: every tick runs the current child once and moves on; a child that reports +// finished ends the whole sequence (finished stays true, rewind). +// `ok` is whatever the last child reported. sizeof 0x24. +// ELF: vtable 0x4B90E0 (9 words), operator new 0x24, package A-core. +class BAPCombinerSerial : public BAPCombiner +{ + // [INFERRED] friendship: PrettyPrinter::prettyPrintScriptNode (libaidll ELF 0x1CAE60) reads the + // statement list, cursor and debug id inline. + friend class PrettyPrinter; +public: + BAPCombinerSerial(int patternId, int debugId); // 0x1E6200 + BAPCombinerSerial(int patternId, bool waitForChild, int debugId); // 0x1E6360 + BAPCombinerSerial(std::list& statements, int patternId, int debugId); // 0x1E6500 + virtual ~BAPCombinerSerial(); // 0x1E66B0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E6840, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E6970, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E6CE0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E6990, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E6A20, slot +0x1C; from the base declaration + virtual void addStatement(BAPStatement*); // 0x1E69A0, slot +0x20; from the base declaration + +private: + // +0x20: second constructor int; the creators pass -1. Only streamSelf reads it ("(n)" unless + // -1). [INFERRED] name. + /* +0x20 */ int m_debugId; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCOMBINERSERIAL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp new file mode 100644 index 000000000..8d2051998 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp @@ -0,0 +1,44 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E6E00 (__tcf_0 0x1E6E60, _GLOBAL__I 0x1E6E90): 's Init object only. +#include + +#include "BAPConAllowFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E6D20 (C1) +BAPConAllowFire::BAPConAllowFire() +{ +} + +// ELF 0x1E6D70 (D0 0x1E6D90): base only. +BAPConAllowFire::~BAPConAllowFire() +{ +} + +// ELF 0x1E6DD0 +bool BAPConAllowFire::evaluate(Bot* bot) +{ + return bot->isFireAllowed(); +} + +// ELF 0x1E6DF0 +BAPConditionType BAPConAllowFire::getConditionType() const +{ + return BAPCTAllowFire; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.h new file mode 100644 index 000000000..f2d8ffa96 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONALLOWFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONALLOWFIRE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9118 (5 words), operator new 0x8/0xC, package C-actions. +// Bot::isFireAllowed (+0x138). No data. +class BAPConAllowFire : public BAPCondition +{ +public: + BAPConAllowFire(); // 0x1E6D20 + virtual ~BAPConAllowFire(); // 0x1E6D70 + + virtual bool evaluate(Bot*); // 0x1E6DD0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E6DF0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONALLOWFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp new file mode 100644 index 000000000..198924d81 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp @@ -0,0 +1,77 @@ +// BAPConAnd: recovered by package A-core from libaidll.so (TU without a FILE symbol, 0x1F3B10..0x1F41F0). +// Every body carries its ELF address. + +#include "BAPConAnd.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F3B10 (C2; C1 0x1F3C80). Copies the list and takes ownership of its conditions. +BAPConAnd::BAPConAnd(std::list& conditions) +{ + m_conditions = conditions; + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + (*it)->m_owner = this; +} + +// ELF 0x1F3D30 (C2; C1 0x1F3DA0). +BAPConAnd::BAPConAnd() +{ + m_conditions.clear(); +} + +// ELF 0x1F3E10 (D2; D1 and D0 follow). Deletes the conditions (slot +0x10); the list itself goes with +// BAPBoleanOp. +BAPConAnd::~BAPConAnd() +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1F4030. +bool BAPConAnd::evaluate(Bot* bot) +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (!(*it)->evaluate(bot)) + return false; + } + return true; +} + +// ELF 0x1F40A0: no null check. +void BAPConAnd::addCondition(BAPCondition* condition) +{ + condition->m_owner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F4110. +BAPConditionType BAPConAnd::getConditionType() const +{ + return BAPCTAnd; +} + +// ELF 0x1F4120: "(" c1 " && " c2 ... ")". +void BAPConAnd::streamSelf(std::ostream& os) const +{ + os << "("; + std::list::const_iterator it = m_conditions.begin(); + if (it != m_conditions.end()) + { + os << **it; + for (++it; it != m_conditions.end(); ++it) + os << " && " << **it; + } + os << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h new file mode 100644 index 000000000..4df45f9e6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.h @@ -0,0 +1,40 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONAND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONAND_H + +#include +#include +#include "BAPBoleanOp.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B9E40 (6 words), operator new 0x8/0xC, package A-core. +// True when every condition is (an empty And is true); stops at the first false. Owns its +// conditions (BAPBoleanOp::m_conditions). sizeof 0xC. +class BAPConAnd : public BAPBoleanOp +{ +public: + explicit BAPConAnd(std::list&); // 0x1F3C80 + BAPConAnd(); // 0x1F3DA0 + virtual ~BAPConAnd(); // 0x1F3EC0 + + virtual bool evaluate(Bot*); // 0x1F4030, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F4110, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F4120, slot +0x08; from the base declaration + virtual void addCondition(BAPCondition*); // 0x1F40A0, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONAND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp new file mode 100644 index 000000000..d971ef32e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E70C0 (__tcf_0 0x1E7120, _GLOBAL__I 0x1E7150): 's Init object only. +#include + +#include "BAPConDistanceToProj.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E6EF0 (C1) +BAPConDistanceToProj::BAPConDistanceToProj(IPIArmament* armament, float distance) +{ + m_distanceSqr = distance * distance; + m_armament = armament; +} + +// ELF 0x1E7050 (D0 0x1E7070) +BAPConDistanceToProj::~BAPConDistanceToProj() +{ +} + +// ELF 0x1E6F30: IPIArmament::getProjectilePosition (+0x38); the information is not null-checked. +bool BAPConDistanceToProj::evaluate(Bot* bot) +{ + Vec3 p = bapinline::vec3(0.0f, 0.0f, 0.0f); + bool result = false; + if (m_armament->getProjectilePosition(p)) { + const Vec3& self = bapinline::info(bot->getCurrentEquipment())->getPosition(); + result = (p.z - self.z) * (p.z - self.z) + (p.x - self.x) * (p.x - self.x) + (p.y - self.y) * (p.y - self.y) + < m_distanceSqr; + } + return result; +} + +// ELF 0x1E70B0 +BAPConditionType BAPConDistanceToProj::getConditionType() const +{ + return BAPCTDistanceToProj; // 15 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.h new file mode 100644 index 000000000..5dc2955ca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDISTANCETOPROJ_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDISTANCETOPROJ_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class IPIArmament; + +// ELF: vtable 0x4B9168 (5 words), operator new 0x10, package C-actions. +// The armament's live projectile is closer than the distance to the bot's current +// vehicle/soldier; no projectile: false. +class BAPConDistanceToProj : public BAPCondition +{ +public: + BAPConDistanceToProj(IPIArmament*, float); // 0x1E6EF0 + virtual ~BAPConDistanceToProj(); // 0x1E7050 + + virtual bool evaluate(Bot*); // 0x1E6F30, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E70B0, slot +0x04; from the base declaration + +private: + /* +0x08 */ IPIArmament* m_armament; + /* +0x0C */ float m_distanceSqr; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDISTANCETOPROJ_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp new file mode 100644 index 000000000..1b03a1a9f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp @@ -0,0 +1,31 @@ +// End-of-path condition from libaidll.so. The shipped evaluator always returns false. + +// static init: ELF 0x1E7180 (__tcf_0 0x1E71E0, _GLOBAL__I 0x1E7210): 's Init object only. +#include + +#include "BAPConEndOfPath.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E7230 (D1; D0 0x1E7250): base destruction only. +BAPConEndOfPath::~BAPConEndOfPath() +{ +} + +// ELF 0x1E7170 +bool BAPConEndOfPath::evaluate(Bot*) +{ + return false; +} + +// ELF 0x1E7290 +BAPConditionType BAPConEndOfPath::getConditionType() const +{ + return BAPCTEndOfPath; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.h new file mode 100644 index 000000000..5d4880ec7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.h @@ -0,0 +1,30 @@ +// End-of-path condition. The retail evaluator is an unconditional false. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONENDOFPATH_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONENDOFPATH_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9190 (5 words), package H-deferred. +class BAPConEndOfPath : public BAPCondition +{ +public: + virtual ~BAPConEndOfPath(); // 0x1E7230 + + virtual bool evaluate(Bot*); // 0x1E7170, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7290, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONENDOFPATH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp new file mode 100644 index 000000000..1e5a52da2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp @@ -0,0 +1,34 @@ +// BAPConFalse: recovered by ai-main from libaidll.so (0x1C1920..0x1C1990; S0 skeleton file). +// Every body carries its ELF address. + +#include "BAPConFalse.h" + +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1C1940 (D1, D0 0x1C1960): only the vtable store of the (empty) BAPCondition base +// (GOT -0x1550 + 8); nothing of its own. +BAPConFalse::~BAPConFalse() +{ +} + +// ELF 0x1C1920: `xorl %eax, %eax; ret`. +bool BAPConFalse::evaluate(Bot*) +{ + return false; +} + +// ELF 0x1C1930: `movl $0x6, %eax; ret` (6 = BAPCTFalse). +BAPConditionType BAPConFalse::getConditionType() const +{ + return BAPCTFalse; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h new file mode 100644 index 000000000..6ef0e7744 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.h @@ -0,0 +1,35 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONFALSE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONFALSE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B74E0 (5 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConFalse : public BAPCondition +{ +public: + virtual ~BAPConFalse(); // 0x1C1940 + + virtual bool evaluate(Bot*); // 0x1C1920, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1C1930, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONFALSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp new file mode 100644 index 000000000..c40251ba5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp @@ -0,0 +1,41 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1E7360 (__tcf_0 0x1E73C0, _GLOBAL__I 0x1E73F0): 's Init object only. +#include + +#include "BAPConInsideBattleZone.h" + +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIBot/BotMain.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E72D0 (C1; C2 0x1E72A0) +BAPConInsideBattleZone::BAPConInsideBattleZone(float distance) +{ + m_distance = distance; +} + +// ELF 0x1E7410 (D0 0x1E7430): base only. +BAPConInsideBattleZone::~BAPConInsideBattleZone() +{ +} + +// ELF 0x1E7300 +bool BAPConInsideBattleZone::evaluate(Bot* bot) +{ + return static_cast(CommonSingletonServer::m_iaiTerrain)->isInsideCombatArea(bot->getPlayer()); +} + +// ELF 0x1E7350 +BAPConditionType BAPConInsideBattleZone::getConditionType() const +{ + return BAPCTInsideBattleZone; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.h new file mode 100644 index 000000000..26f2ce85d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.h @@ -0,0 +1,37 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONINSIDEBATTLEZONE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONINSIDEBATTLEZONE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B91B8 (5 words), operator new 0xC/0x7C, package G-vehicles. +// True while the bot's player is inside the combat area (IAITerrain::isInsideCombatArea). The +// constructor's distance is stored but not read. +class BAPConInsideBattleZone : public BAPCondition +{ +public: + explicit BAPConInsideBattleZone(float); // 0x1E72D0 + virtual ~BAPConInsideBattleZone(); // 0x1E7410 + + virtual bool evaluate(Bot*); // 0x1E7300, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7350, slot +0x04; from the base declaration + +private: + /* +0x08 */ float m_distance; // [INFERRED] name: callers pass 150 and 200 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONINSIDEBATTLEZONE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp new file mode 100644 index 000000000..ac378dc2a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp @@ -0,0 +1,44 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E75D0 (__tcf_0 0x1E7630, _GLOBAL__I 0x1E7660): 's Init object only. +#include + +#include "BAPConIsSprinting.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E74A0 (C1) +BAPConIsSprinting::BAPConIsSprinting() +{ +} + +// ELF 0x1E74F0 (D0 0x1E7510): base only. +BAPConIsSprinting::~BAPConIsSprinting() +{ +} + +// ELF 0x1E7550 +bool BAPConIsSprinting::evaluate(Bot* bot) +{ + return bapinline::mappedInput(bot->getInput(), io::PISprint) != 0.0f; +} + +// ELF 0x1E75C0 +BAPConditionType BAPConIsSprinting::getConditionType() const +{ + return BAPCTIsSprinting; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.h new file mode 100644 index 000000000..8ed675135 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISSPRINTING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISSPRINTING_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9208 (5 words), operator new 0x8/0xC, package C-actions. +// The bot presses sprint: the mapped PISprint input (bit 13, +0x34) is not 0. No data. +class BAPConIsSprinting : public BAPCondition +{ +public: + BAPConIsSprinting(); // 0x1E74A0 + virtual ~BAPConIsSprinting(); // 0x1E74F0 + + virtual bool evaluate(Bot*); // 0x1E7550, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E75C0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISSPRINTING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp new file mode 100644 index 000000000..0e1694eb9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp @@ -0,0 +1,38 @@ +// Tests the borrowed trigger action's started flag. + +// static init: ELF 0x1E7780 (__tcf_0 0x1E77E0, _GLOBAL__I 0x1E7810): 's Init object only. +#include + +#include "BAPConIsTriggered.h" + +#include "BAPATrigger.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E76B0 (C1; C2 0x1E7680) +BAPConIsTriggered::BAPConIsTriggered(BAPATrigger* trigger) : m_trigger(trigger) +{ +} + +// ELF 0x1E7710 (D1; D2 0x1E76F0, D0 0x1E7730) +BAPConIsTriggered::~BAPConIsTriggered() +{ +} + +// ELF 0x1E76E0 +bool BAPConIsTriggered::evaluate(Bot*) +{ + return m_trigger->m_started; +} + +// ELF 0x1E7770 +BAPConditionType BAPConIsTriggered::getConditionType() const +{ + return BAPCTIsTriggered; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.h new file mode 100644 index 000000000..20ad58393 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.h @@ -0,0 +1,35 @@ +// Tests the borrowed trigger action's started flag. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISTRIGGERED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISTRIGGERED_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPATrigger; +class Bot; + +// ELF: vtable 0x4B9268 (5 words), package H-deferred. +class BAPConIsTriggered : public BAPCondition +{ +public: + explicit BAPConIsTriggered(BAPATrigger*); // 0x1E76B0 + virtual ~BAPConIsTriggered(); // 0x1E7710 + + virtual bool evaluate(Bot*); // 0x1E76E0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7770, slot +0x04; from the base declaration + +private: + /* +0x08 */ BAPATrigger* m_trigger; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONISTRIGGERED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp new file mode 100644 index 000000000..916313858 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp @@ -0,0 +1,35 @@ +// BAPConIteration: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1E7830..0x1E7940). Every body carries its ELF address. + +#include "BAPConIteration.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E7830 (C2; C1 0x1E7860). +BAPConIteration::BAPConIteration(int count) + : m_count(count) +{ +} + +// ELF 0x1E7890 (D2; D1 0x1E78B0, D0 0x1E78D0): the vptr store only. +BAPConIteration::~BAPConIteration() +{ +} + +// ELF 0x1E7910. +bool BAPConIteration::evaluate(Bot*) +{ + return --m_count <= 0; +} + +// ELF 0x1E7930. +BAPConditionType BAPConIteration::getConditionType() const +{ + return BAPCTIteration; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.h new file mode 100644 index 000000000..2c04f916e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.h @@ -0,0 +1,36 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONITERATION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONITERATION_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9290 (5 words), package A-core. +// True on the n-th evaluate and on every later one (counts down, no reset). sizeof 0xC. +class BAPConIteration : public BAPCondition +{ +public: + explicit BAPConIteration(int); // 0x1E7860 + virtual ~BAPConIteration(); // 0x1E78B0 + + virtual bool evaluate(Bot*); // 0x1E7910, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7930, slot +0x04; from the base declaration + +private: + /* +0x08 */ int m_count; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONITERATION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp new file mode 100644 index 000000000..102356882 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp @@ -0,0 +1,68 @@ +// Fixed-point line-of-fire condition recovered from libaidll.so. +// static init: ELF 0x1E7EE0 (__tcf_0 0x1E7F40, _GLOBAL__I 0x1E7F70): 's Init object only. +#include +#include "BAPConLineOfFire.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Core/Debug.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E79B0 (C1; C2 0x1E7940) +BAPConLineOfFire::BAPConLineOfFire(const Vec3& target, bool flag) + : m_target(target), m_useCamera(true), m_flag15(flag) +{ +} + +// ELF 0x1E7A90 (C1; C2 0x1E7A20) +BAPConLineOfFire::BAPConLineOfFire(const Vec3& target, bool flag, SoldierPose pose) + : m_target(target), m_useCamera(false), m_flag15(flag), m_pose(pose) +{ +} + +// ELF 0x1E7B20 (D1; D2 0x1E7B00, D0 0x1E7B40) +BAPConLineOfFire::~BAPConLineOfFire() +{ +} + +// ELF 0x1E7B80 +bool BAPConLineOfFire::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + Vec3 from = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (m_useCamera) { + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + from = bapinline::vec3(camera.m[12], camera.m[13], camera.m[14]); + } else { + const Vec3 local = self->getAIObject()->getSoldierPoseCameraPosition(m_pose); + const Mat4& transform = self->getTransformation(); + from.x = local.x * transform.m[0] + local.y * transform.m[4] + local.z * transform.m[8] + transform.m[12]; + from.y = local.x * transform.m[1] + local.y * transform.m[5] + local.z * transform.m[9] + transform.m[13]; + from.z = local.x * transform.m[2] + local.y * transform.m[6] + local.z * transform.m[10] + transform.m[14]; + } + std::vector ignore; + ignore.push_back(self->getAIObject()); + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp", 58, "") + << "Does not work with transparancy."; + bool hit; + return !static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(from, m_target, ignore, bot->getLodLevel() != 0, 0.75f, false, hit); +} + +// ELF 0x1E7ED0 +BAPConditionType BAPConLineOfFire::getConditionType() const +{ + return BAPCTLineOfFire; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.h new file mode 100644 index 000000000..056c6352a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.h @@ -0,0 +1,39 @@ +// Tests the line from the bot's camera (or the selected soldier pose) to a fixed point. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONLINEOFFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONLINEOFFIRE_H + +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B92B8 (5 words), operator new 0x1C, package H-deferred. +class BAPConLineOfFire : public BAPCondition +{ +public: + BAPConLineOfFire(const Vec3&, bool); // 0x1E79B0 + BAPConLineOfFire(const Vec3&, bool, SoldierPose); // 0x1E7A90 + virtual ~BAPConLineOfFire(); // 0x1E7B20 + + virtual bool evaluate(Bot*); // 0x1E7B80, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E7ED0, slot +0x04; from the base declaration +private: + /* +0x08 */ Vec3 m_target; + /* +0x14 */ bool m_useCamera; + /* +0x15 */ bool m_flag15; // [UNRESOLVED] constructor flag; never read by the shipped evaluator + /* +0x18 */ SoldierPose m_pose; // initialized only by the pose-taking constructor +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONLINEOFFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp new file mode 100644 index 000000000..cfe6a09a5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp @@ -0,0 +1,72 @@ +// BAPConNot: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1F4580..0x1F4D30). Every body carries its ELF address. + +#include "BAPConNot.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F4580 (C2; C1 0x1F46E0). No null check. +BAPConNot::BAPConNot(BAPCondition* condition) +{ + condition->m_owner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F4780 (C2; C1 0x1F4850). Only the list's front is taken (owner set, appended). +BAPConNot::BAPConNot(std::list& conditions) +{ + m_conditions.clear(); + conditions.front()->m_owner = this; + m_conditions.insert(m_conditions.end(), conditions.front()); +} + +// ELF 0x1F4920 (C2; C1 0x1F4990). +BAPConNot::BAPConNot() +{ + m_conditions.clear(); +} + +// ELF 0x1F4A00 (D2; D1 0x1F4AB0, D0 0x1F4B60). Deletes the conditions (slot +0x10). +BAPConNot::~BAPConNot() +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1F4C20: front() without an empty check (retail). +bool BAPConNot::evaluate(Bot* bot) +{ + return !m_conditions.front()->evaluate(bot); +} + +// ELF 0x1F4C50: ignored once a condition is present. +void BAPConNot::addCondition(BAPCondition* condition) +{ + if (!m_conditions.empty()) + return; + condition->m_owner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F4CC0. +BAPConditionType BAPConNot::getConditionType() const +{ + return BAPCTNot; +} + +// ELF 0x1F4CD0. +void BAPConNot::streamSelf(std::ostream& os) const +{ + os << "NOT(" << *m_conditions.front() << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h new file mode 100644 index 000000000..600cf9e56 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.h @@ -0,0 +1,42 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNOT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNOT_H + +#include +#include +#include "BAPBoleanOp.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B9EA0 (6 words), operator new 0xC/0x20/0x2C, package A-core. +// Negates the first condition of the list (evaluate reads front() without an empty check, as +// the image does). addCondition only accepts the first one; the list constructor takes only the +// list's front. Owns its condition. sizeof 0xC. +class BAPConNot : public BAPBoleanOp +{ +public: + explicit BAPConNot(BAPCondition*); // 0x1F46E0 + explicit BAPConNot(std::list&); // 0x1F4850 + BAPConNot(); // 0x1F4990 + virtual ~BAPConNot(); // 0x1F4AB0 + + virtual bool evaluate(Bot*); // 0x1F4C20, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F4CC0, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F4CD0, slot +0x08; from the base declaration + virtual void addCondition(BAPCondition*); // 0x1F4C50, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNOT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObject.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObject.h new file mode 100644 index 000000000..024608cd8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObject.h @@ -0,0 +1,31 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECT_H + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConObject : public BAPCondition +{ +public: + // Inline in the image (no symbol); every subclass ctor stores the object handle at +0x08. + /* +0x08 */ unsigned int m_object; // information handle of the tested object +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp new file mode 100644 index 000000000..2a8162096 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp @@ -0,0 +1,93 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1ECFC0 (__tcf_0 0x1ED020, _GLOBAL__I 0x1ED050): 's Init object only. +#include + +#include "BAPConObjectBehind.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1ECB20 (C1; C2 0x1ECAE0): +4 = 0, +8 handle, +0xC threshold, +0x10 flag. +BAPConObjectBehind::BAPConObjectBehind(unsigned int object, float threshold, bool useEstimate) +{ + setOwner(0); + m_object = object; + m_threshold = threshold; + m_useEstimate = useEstimate; +} + +// ELF 0x1ECB80 (D0 0x1ECBA0) +BAPConObjectBehind::~BAPConObjectBehind() +{ +} + +// ELF 0x1ECBE0. Object position (XZ): the IPIMobile (+0x38) position estimate (vfn +0x2C) when +// +0x10 is set and the object has one, else getPosition (vfn +0x30). Bot position: the current +// equipment's getPosition (no null test in the image). Forward: transformation (vfn +0x3C) row 2 +// (+0x20) in XZ, normalised in place; direction object->bot normalised by the same inline +// (1.1920929e-07 / 1.4210855e-14 thresholds). 0x1ECEA2 `flds 0xc(%eax)`, `fucompi`, `setae`: +// threshold >= dot. +bool BAPConObjectBehind::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + Information* equipment = bapinline::info(bot->getCurrentEquipment()); + + Vec2 objectPosition; + objectPosition.x = 0.0f; + objectPosition.y = 0.0f; + IPIMobile* mobile = object->getMobile(); + if (!m_useEstimate || !mobile) { + vec3ToVec2XZ(object->getPosition(), objectPosition); + } else { + Vec3 estimate; + estimate.x = 0.0f; + estimate.y = 0.0f; + estimate.z = 0.0f; + mobile->getPositionEstimate(estimate); + vec3ToVec2XZ(estimate, objectPosition); + } + + Vec2 botPosition; + botPosition.x = 0.0f; + botPosition.y = 0.0f; + vec3ToVec2XZ(equipment->getPosition(), botPosition); + + Vec2 forward; + forward.x = 0.0f; + forward.y = 0.0f; + const Mat4& transformation = object->getTransformation(); + Vec3 row2; + row2.x = transformation.m[8]; + row2.y = transformation.m[9]; + row2.z = transformation.m[10]; + vec3ToVec2XZ(row2, forward); + bapinline::normalize(forward); + + Vec2 direction; + direction.x = botPosition.x - objectPosition.x; + direction.y = botPosition.y - objectPosition.y; + bapinline::normalize(direction); + + return direction.x * forward.x + direction.y * forward.y <= m_threshold; +} + +// ELF 0x1ECFB0 +BAPConditionType BAPConObjectBehind::getConditionType() const +{ + return BAPCTObjectBehind; // 17 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.h new file mode 100644 index 000000000..b804d6585 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.h @@ -0,0 +1,37 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTBEHIND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTBEHIND_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B95F8 (5 words), operator new 0x14, package F-infantry. +// True when the bot's equipment is behind the object: the XZ direction object->bot dotted with the +// object's forward axis (transformation row 2) is at most the threshold. True when the object is gone. +class BAPConObjectBehind : public BAPConObject +{ +public: + BAPConObjectBehind(unsigned int, float, bool); // 0x1ECB20 + virtual ~BAPConObjectBehind(); // 0x1ECB80 + + virtual bool evaluate(Bot*); // 0x1ECBE0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1ECFB0, slot +0x04; from the base declaration +private: + /* +0x0C */ float m_threshold; // compared with the dot product (createPlan passes -0.95 / -0.8) + /* +0x10 */ bool m_useEstimate; // use the object's IPIMobile position estimate when it has one +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTBEHIND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp new file mode 100644 index 000000000..6bcec400e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp @@ -0,0 +1,132 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1ED840 (__tcf_0 0x1ED8A0, _GLOBAL__I 0x1ED8D0): 's Init object only. +#include + +#include "BAPConObjectDistance.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1ED0D0 (C1): max distance only. +BAPConObjectDistance::BAPConObjectDistance(unsigned int object, float maxDistance, bool estimate, bool flat, + bool outside) +{ + m_object = object; + m_minDistanceSqr = 0.0f; + m_estimate = estimate; + m_flat = flat; + m_lastDistanceSqr = 0.0f; + m_maxDistanceSqr = maxDistance * maxDistance; + m_outside = outside; +} + +// ELF 0x1ED190 (C1) +BAPConObjectDistance::BAPConObjectDistance(unsigned int object, float minDistance, float maxDistance, bool estimate, + bool flat) +{ + m_object = object; + m_estimate = estimate; + m_outside = false; + m_maxDistanceSqr = maxDistance * maxDistance; + m_flat = flat; + m_minDistanceSqr = minDistance * minDistance; + m_lastDistanceSqr = 0.0f; +} + +// ELF 0x1ED210 (D0 0x1ED230) +BAPConObjectDistance::~BAPConObjectDistance() +{ +} + +// ELF 0x1ED270 (the bot's information is not null-checked) +bool BAPConObjectDistance::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + Information* self = bapinline::info(bot->getCurrentEquipment()); + float a, b; // the two partial sums the image adds last + if (!m_estimate) { + if (!m_flat) { + const Vec3& s = self->getPosition(); + const Vec3& o = object->getPosition(); + const float dx = o.x - s.x; + const float dy = o.y - s.y; + const float dz = o.z - s.z; + b = dz * dz; + a = dx * dx + dy * dy; + } else { + const float sx = self->getPosition().x; + const float sz = self->getPosition().z; + const float ox = object->getPosition().x; + const float oz = object->getPosition().z; + b = (ox - sx) * (ox - sx); + a = (oz - sz) * (oz - sz); + } + } else { + Vec3 p = bapinline::vec3(0.0f, 0.0f, 0.0f); + IPIMobile* mobile = object->getMobile(); + if (!mobile) + p = object->getPosition(); + else + mobile->getPositionEstimate(p); + const Vec3& s = self->getPosition(); + if (!m_flat) { + const float dx = p.x - s.x; + const float dy = p.y - s.y; + const float dz = p.z - s.z; + b = dz * dz; + a = dx * dx + dy * dy; + } else { + const float dx = p.x - s.x; + const float dz = p.z - s.z; + b = dx * dx; + a = dz * dz; + } + } + const float d = a + b; + m_lastDistanceSqr = d; + if (!m_outside) + return m_minDistanceSqr <= d && d <= m_maxDistanceSqr; + return m_maxDistanceSqr < d; +} + +// ELF 0x1ED640 +BAPConditionType BAPConObjectDistance::getConditionType() const +{ + return BAPCTObjectDistance; // 18 +} + +// ELF 0x1ED650 +void BAPConObjectDistance::streamSelf(std::ostream& out) const +{ + if (!m_outside) { + out << "ObjectDistance(" << static_cast(std::sqrt(m_minDistanceSqr)) << " <= ["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] <= " << static_cast(std::sqrt(m_maxDistanceSqr)) << ")"; + } else { + out << "ObjectDistance["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] > " << static_cast(std::sqrt(m_maxDistanceSqr)); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.h new file mode 100644 index 000000000..8206d6ed1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCE_H + +#include +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9620 (5 words), operator new 0x1C, package C-actions. +// min^2 <= d^2 <= max^2 (or d^2 > max^2 with the outside flag) between the bot's current +// vehicle/soldier and an object (3d or XZ; optionally its estimated position). No object: true. +class BAPConObjectDistance : public BAPConObject +{ +public: + BAPConObjectDistance(unsigned int, float, bool, bool, bool); // 0x1ED0D0 + BAPConObjectDistance(unsigned int, float, float, bool, bool); // 0x1ED190 + virtual ~BAPConObjectDistance(); // 0x1ED210 + + virtual bool evaluate(Bot*); // 0x1ED270, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1ED640, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1ED650, slot +0x08; from the base declaration + +private: + /* +0x0C */ float m_minDistanceSqr; + /* +0x10 */ float m_maxDistanceSqr; + /* +0x14 */ bool m_estimate; // IPIMobile::getPositionEstimate (+0x2C) instead of the position + /* +0x15 */ bool m_flat; // XZ only + /* +0x16 */ bool m_outside; // "d > max" form + /* +0x18 */ float m_lastDistanceSqr; // = 0 ("not calculated") +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp new file mode 100644 index 000000000..452690e23 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp @@ -0,0 +1,91 @@ +// Object-to-point distance condition recovered from libaidll.so. +// static init: ELF 0x1EDF10 (__tcf_0 0x1EDF70, _GLOBAL__I 0x1EDFA0): 's Init object only. +#include +#include "BAPConObjectDistanceToPoint.h" +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1ED980 (C1; C2 0x1ED8F0) +BAPConObjectDistanceToPoint::BAPConObjectDistanceToPoint(const Vec3& point, unsigned int object, + float maxDistance, bool estimate, bool flat) + : m_minDistanceSqr(0.0f), m_maxDistanceSqr(maxDistance * maxDistance), + m_estimate(estimate), m_flat(flat), m_point(point), m_lastDistanceSqr(0.0f) +{ + m_object = object; +} + +// ELF 0x1EDAA0 (C1; C2 0x1EDA10) +BAPConObjectDistanceToPoint::BAPConObjectDistanceToPoint(const Vec3& point, unsigned int object, + float minDistance, float maxDistance, + bool estimate, bool flat) + : m_minDistanceSqr(minDistance * minDistance), m_maxDistanceSqr(maxDistance * maxDistance), + m_estimate(estimate), m_flat(flat), m_point(point), m_lastDistanceSqr(0.0f) +{ + m_object = object; +} + +// ELF 0x1EDB50 (D1; D2 0x1EDB30, D0 0x1EDB70) +BAPConObjectDistanceToPoint::~BAPConObjectDistanceToPoint() +{ +} + +// ELF 0x1EDBB0 +bool BAPConObjectDistanceToPoint::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + float distanceSqr; + if (m_estimate) { + IPIMobile* mobile = object->getMobile(); + Vec3 position = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (mobile) + mobile->getPositionEstimate(position); + else + position = object->getPosition(); + if (m_flat) + distanceSqr = distXZSqr(position, m_point); + else { + const Vec3 delta = bapinline::sub(position, m_point); + distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + } + } else if (m_flat) { + distanceSqr = distXZSqr(object->getPosition(), m_point); + } else { + const Vec3 delta = bapinline::sub(object->getPosition(), m_point); + distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + } + m_lastDistanceSqr = distanceSqr; + return m_minDistanceSqr <= distanceSqr && distanceSqr <= m_maxDistanceSqr; +} + +// ELF 0x1EDF00 +BAPConditionType BAPConObjectDistanceToPoint::getConditionType() const +{ + return BAPCTObjectDistanceToPoint; +} + +// ELF 0x1EDD80 +void BAPConObjectDistanceToPoint::streamSelf(std::ostream& out) const +{ + out << "PointDistance["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] < " << static_cast(std::sqrt(m_maxDistanceSqr)); + if (m_minDistanceSqr != 0.0f) + out << " && PointDistance[" << static_cast(std::sqrt(m_lastDistanceSqr)) + << "] > " << static_cast(std::sqrt(m_minDistanceSqr)); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.h new file mode 100644 index 000000000..34addbb93 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.h @@ -0,0 +1,42 @@ +// Tests an object's distance from a fixed point; missing information satisfies the condition. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCETOPOINT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCETOPOINT_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9648 (5 words), package H-deferred. +class BAPConObjectDistanceToPoint : public BAPConObject +{ +public: + BAPConObjectDistanceToPoint(const Vec3&, unsigned int, float, bool, bool); // 0x1ED980 + BAPConObjectDistanceToPoint(const Vec3&, unsigned int, float, float, bool, bool); // 0x1EDAA0 + virtual ~BAPConObjectDistanceToPoint(); // 0x1EDB50 + + virtual bool evaluate(Bot*); // 0x1EDBB0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EDF00, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1EDD80, slot +0x08; from the base declaration +private: + /* +0x0C */ float m_minDistanceSqr; + /* +0x10 */ float m_maxDistanceSqr; + /* +0x14 */ bool m_estimate; + /* +0x15 */ bool m_flat; + /* +0x18 */ Vec3 m_point; + /* +0x24 */ float m_lastDistanceSqr; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTDISTANCETOPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp new file mode 100644 index 000000000..27f713f1f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp @@ -0,0 +1,49 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EE160 (__tcf_0 0x1EE1C0, _GLOBAL__I 0x1EE1F0): 's Init object only. +#include + +#include "BAPConObjectEnemyOccupied.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIUtils/VehicleOccupancy.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EDFF0 (C1; C2 0x1EDFC0): +4 = 0, +8 = the handle. +BAPConObjectEnemyOccupied::BAPConObjectEnemyOccupied(unsigned int object) +{ + setOwner(0); + m_object = object; +} + +// ELF 0x1EE0F0 (D0 0x1EE110) +BAPConObjectEnemyOccupied::~BAPConObjectEnemyOccupied() +{ +} + +// ELF 0x1EE020: vehicleOccupied(handle, bot side) (Bot +0xE0), then the information's side +// (vfn +0x44, Information::getSide) against the bot's side again. +bool BAPConObjectEnemyOccupied::evaluate(Bot* bot) +{ + if (!vehicleOccupied(m_object, bot->getSide())) + return false; + Information* info = bapinline::info(m_object); + if (!info) + return false; + return info->getSide() != bot->getSide(); +} + +// ELF 0x1EE150 +BAPConditionType BAPConObjectEnemyOccupied::getConditionType() const +{ + return BAPCTObjectEnemyOccupied; // 20 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.h new file mode 100644 index 000000000..bb387c9ac --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.h @@ -0,0 +1,33 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTENEMYOCCUPIED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTENEMYOCCUPIED_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9670 (5 words), operator new 0xC, package F-infantry. +// True when vehicleOccupied(object, bot side) and the object's side differs from the bot's. +class BAPConObjectEnemyOccupied : public BAPConObject +{ +public: + explicit BAPConObjectEnemyOccupied(unsigned int); // 0x1EDFF0 + virtual ~BAPConObjectEnemyOccupied(); // 0x1EE0F0 + + virtual bool evaluate(Bot*); // 0x1EE020, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE150, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTENEMYOCCUPIED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp new file mode 100644 index 000000000..4bb14e841 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp @@ -0,0 +1,39 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1EE350 (__tcf_0 0x1EE3B0, _GLOBAL__I 0x1EE3E0): 's Init object only. +#include + +#include "BAPConObjectExists.h" + +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EE240 (C1; C2 0x1EE210) +BAPConObjectExists::BAPConObjectExists(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1EE2E0 (C1 0x1EE2C0, D0 0x1EE300): base only. +BAPConObjectExists::~BAPConObjectExists() +{ +} + +// ELF 0x1EE270 +bool BAPConObjectExists::evaluate(Bot*) +{ + return bapinline::info(m_object) != 0; +} + +// ELF 0x1EE340 +BAPConditionType BAPConObjectExists::getConditionType() const +{ + return BAPCTObjectExists; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.h new file mode 100644 index 000000000..525f2a6e2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.h @@ -0,0 +1,33 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTEXISTS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTEXISTS_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9698 (5 words), operator new 0xC, package F-infantry. +// True while the object has information. +class BAPConObjectExists : public BAPConObject +{ +public: + explicit BAPConObjectExists(unsigned int); // 0x1EE240 + virtual ~BAPConObjectExists(); // 0x1EE2E0 + + virtual bool evaluate(Bot*); // 0x1EE270, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE340, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTEXISTS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp new file mode 100644 index 000000000..3321b1b8d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp @@ -0,0 +1,57 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EE5E0 (__tcf_0 0x1EE640, _GLOBAL__I 0x1EE670): 's Init object only. +#include + +#include "BAPConObjectHealth.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EE440 (C1) +BAPConObjectHealth::BAPConObjectHealth(unsigned int object, float health) +{ + m_object = object; + m_health = health; +} + +// ELF 0x1EE4A0 (D0 0x1EE4C0): base only. +BAPConObjectHealth::~BAPConObjectHealth() +{ +} + +// ELF 0x1EE500 +bool BAPConObjectHealth::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + bool result = false; + if (info) + result = info->getPhysical()->getHealth() <= m_health; + return result; +} + +// ELF 0x1EE580 +BAPConditionType BAPConObjectHealth::getConditionType() const +{ + return BAPCTObjectHealth; +} + +// ELF 0x1EE590 +void BAPConObjectHealth::streamSelf(std::ostream& out) const +{ + out << "ObjectHealth <= " << static_cast(m_health); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.h new file mode 100644 index 000000000..51f66c79c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.h @@ -0,0 +1,41 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTHEALTH_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTHEALTH_H + +#include +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B96C0 (5 words), operator new 0xC/0x10, package C-actions. +// The object's health (IPIPhysical::getHealth) is at most the limit; no information: false. +class BAPConObjectHealth : public BAPConObject +{ +public: + BAPConObjectHealth(unsigned int, float); // 0x1EE440 + virtual ~BAPConObjectHealth(); // 0x1EE4A0 + + virtual bool evaluate(Bot*); // 0x1EE500, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE580, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1EE590, slot +0x08; from the base declaration + +private: + /* +0x0C */ float m_health; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTHEALTH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp new file mode 100644 index 000000000..35bfc4243 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp @@ -0,0 +1,59 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build adds the scaled forward axis to the position in extended +// precision before rounding the point. + +// static init: ELF 0x1EE9E0 (__tcf_0 0x1EEA40, _GLOBAL__I 0x1EEA70): 's Init object only. +#include + +#include "BAPConObjectInFront.h" + +#include "../../../../Math/Mat4.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EE6D0 (C1; C2 0x1EE690) +BAPConObjectInFront::BAPConObjectInFront(unsigned int object, float distance, float minDot) +{ + m_object = object; + m_distance = distance; + m_minDot = minDot; +} + +// ELF 0x1EE730 (D1 0x1EE710, D0 0x1EE750): base only. +BAPConObjectInFront::~BAPConObjectInFront() +{ +} + +// ELF 0x1EE790. No information on the object or the bot's vehicle: false. +bool BAPConObjectInFront::evaluate(Bot* bot) +{ + Information* const target = bapinline::info(m_object); + if (!target) + return false; + Information* const self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + const Mat4& transformation = self->getTransformation(); + const Vec3 forward = bapinline::vec3(transformation.m[8], transformation.m[9], transformation.m[10]); + const Vec3& position = self->getPosition(); + const Vec3 ahead = bapinline::vec3(forward.x * m_distance, forward.y * m_distance, forward.z * m_distance); + const Vec3 front = bapinline::add(ahead, position); + Vec3 direction = bapinline::sub(target->getPosition(), front); + bapinline::normalize(direction); + return bapinline::dot(forward, direction) > m_minDot; +} + +// ELF 0x1EE9D0 +BAPConditionType BAPConObjectInFront::getConditionType() const +{ + return BAPCTObjectInFront; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.h new file mode 100644 index 000000000..33ce20d85 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.h @@ -0,0 +1,38 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINFRONT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINFRONT_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B96E8 (5 words), operator new 0x14, package F-infantry. +// True when the direction from a point `distance` ahead of the bot's vehicle to the object deviates +// from the vehicle's forward axis by a cosine above `minDot`. +class BAPConObjectInFront : public BAPConObject +{ +public: + BAPConObjectInFront(unsigned int, float, float); // 0x1EE6D0 + virtual ~BAPConObjectInFront(); // 0x1EE730 + + virtual bool evaluate(Bot*); // 0x1EE790, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EE9D0, slot +0x04; from the base declaration + +private: + /* +0x0C */ float m_distance; // [INFERRED] names + /* +0x10 */ float m_minDot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINFRONT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp new file mode 100644 index 000000000..39fcf1823 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp @@ -0,0 +1,46 @@ +// Tests whether the object is inside the bot's assigned landing zone. + +// static init: ELF 0x1EEC20 (__tcf_0 0x1EEC80, _GLOBAL__I 0x1EECB0): 's Init object only. +#include + +#include "BAPConObjectInLandingZone.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIStrategicEntity/AILandingZone.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EEAD0 (C1; C2 0x1EEA90) +BAPConObjectInLandingZone::BAPConObjectInLandingZone(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1EEB30 (D1; D2 0x1EEB10, D0 0x1EEB50) +BAPConObjectInLandingZone::~BAPConObjectInLandingZone() +{ +} + +// ELF 0x1EEB90 +bool BAPConObjectInLandingZone::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object || !static_cast(bot)->m_ptr232) + return false; + const Vec3& position = object->getPosition(); + return static_cast(static_cast(bot)->m_ptr232)->isInZone(position); +} + +// ELF 0x1EECD0 +BAPConditionType BAPConObjectInLandingZone::getConditionType() const +{ + return BAPCTObjectInLandingZone; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.h new file mode 100644 index 000000000..a0f8cfaed --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.h @@ -0,0 +1,31 @@ +// Tests whether the object is inside the bot's assigned landing zone. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINLANDINGZONE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINLANDINGZONE_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9710 (5 words), package H-deferred. +class BAPConObjectInLandingZone : public BAPConObject +{ +public: + explicit BAPConObjectInLandingZone(unsigned int); // 0x1EEAD0 + virtual ~BAPConObjectInLandingZone(); // 0x1EEB30 + + virtual bool evaluate(Bot*); // 0x1EEB90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EECD0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINLANDINGZONE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp new file mode 100644 index 000000000..5fcf46b1c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp @@ -0,0 +1,65 @@ +// Camera-frustum condition recovered from libaidll.so. +// static init: ELF 0x1EF010 (__tcf_0 0x1EF070, _GLOBAL__I 0x1EF0A0): 's Init object only. +#include +#include "BAPConObjectInsideFrustum.h" +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EED40 (C1; C2 0x1EECE0) +BAPConObjectInsideFrustum::BAPConObjectInsideFrustum(unsigned int object, TransformType type) + : m_transformType(type), m_frustum(), m_initialize(true) +{ + m_object = object; +} + +// ELF 0x1EEDC0 (D1; D2 0x1EEDA0, D0 0x1EEDE0) +BAPConObjectInsideFrustum::~BAPConObjectInsideFrustum() +{ +} + +// ELF 0x1EEE20 +bool BAPConObjectInsideFrustum::evaluate(Bot* bot) +{ + if (!bot) + return false; + Information* object = bapinline::info(m_object); + if (!object) + return false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self || m_transformType != 0) + return false; + if (m_initialize) { + m_initialize = false; + const float farDistance = bot->getPlayer()->getViewDistance(); + if (self->getObjectTypeFlags() & 0x400000u) { + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + m_frustum.setPerspective(1.570796371f, 1.0f, 0.01f, farDistance, camera); + } else { + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + m_frustum.setPerspective(2.094395161f, 1.0f, 0.01f, farDistance, camera); + } + } + IPIPhysical* physical = object->getPhysical(); + if (physical) { + const float radius = physical->getRadius(); + return m_frustum.inside(object->getPosition(), radius); + } + return m_frustum.inside(object->getPosition(), 1.0f); +} + +// ELF 0x1EF000 +BAPConditionType BAPConObjectInsideFrustum::getConditionType() const +{ + return BAPCTObjectInsideFrustum; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.h new file mode 100644 index 000000000..cb2327d78 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.h @@ -0,0 +1,37 @@ +// Object visibility against a camera frustum initialized on the first eligible evaluation. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINSIDEFRUSTUM_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINSIDEFRUSTUM_H + +#include "BAPConObject.h" +#include "../../../../Math/Frustum.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9738 (5 words), package H-deferred. +class BAPConObjectInsideFrustum : public BAPConObject +{ +public: + enum TransformType : int; // [UNRESOLVED] enumerators + BAPConObjectInsideFrustum(unsigned int, BAPConObjectInsideFrustum::TransformType); // 0x1EED40 + virtual ~BAPConObjectInsideFrustum(); // 0x1EEDC0 + + virtual bool evaluate(Bot*); // 0x1EEE20, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EF000, slot +0x04; from the base declaration +private: + /* +0x00C */ TransformType m_transformType; + /* +0x010 */ Frustum m_frustum; + /* +0x1F8 */ bool m_initialize; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTINSIDEFRUSTUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp new file mode 100644 index 000000000..473abd432 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp @@ -0,0 +1,164 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EF940 (__tcf_0 0x1EF9A0, _GLOBAL__I 0x1EF9D0): 's Init object only. +#include + +#include "BAPConObjectLineOfFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Function statics of hasFriendlySoldiersInLineOfFire (ELF .data 0x4B9784 / 0x4B9788 / 0x4B978C). +const float allowedDistanceShort = 0.5f; +const float allowedDistanceFar = 1.5f; +const float minDistForSideStep = 5.0f; + +} // namespace + +// ELF 0x1EF100 (C1; C2 0x1EF0C0) +BAPConObjectLineOfFire::BAPConObjectLineOfFire(unsigned int object, bool flag) +{ + m_anyPose = true; + m_object = object; + m_flag0D = flag; +} + +// ELF 0x1EF180 (C1; C2 0x1EF140) +BAPConObjectLineOfFire::BAPConObjectLineOfFire(unsigned int object, bool flag, SoldierPose pose) +{ + m_anyPose = false; + m_object = object; + m_flag0D = flag; + m_pose = pose; +} + +// ELF 0x1EF8D0 (D1; D0 0x1EF8F0): base only. +BAPConObjectLineOfFire::~BAPConObjectLineOfFire() +{ +} + +// ELF 0x1EF1C0. True when the bot senses the target directly (record without flag 8); a weapon +// that cannot fire through transparent objects also needs flag 0x40 on the record. A soldier +// additionally needs no friendly soldier in the line of fire. No information for the bot or the +// target: false. +bool BAPConObjectLineOfFire::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + Information* target = bapinline::info(m_object); + if (!self || !target) + return false; + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + bool result = sensed && !(sensed->m_flags & 8u); + IPIArmament* armament = self->getArmament(); + if (armament && armament->getActiveWeapon() != -1) { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon && sensed && !weapon->getFiresThroughTransparent()) { + const bool clear = !(sensed->m_flags & 8u) && !(sensed->m_flags & 0x40u); + result = result && !clear; + } + } + if (result && (self->getObjectTypeFlags() & 0x200000u)) + result = !hasFriendlySoldiersInLineOfFire(bot, self, target); + return result; +} + +// ELF 0x1EF360. Friendly soldiers (same side, not the bot, not the target) between the weapon's +// projectile origin and the target, within a corridor widening from allowedDistanceShort at the +// muzzle to allowedDistanceFar at 50 m (support kit (spawn kit 1) with a range above 100 m and a +// weapon zoom other than 0x40: allowedDistanceShort throughout). A friend closer than +// minDistForSideStep in the bot's facing (XZ dot > 0.9) stamps BotMain::setFriendsInLineOfFireTime +// (now) and answers at once; otherwise the stamp is cleared (0.0) after the scan. The bot's weapon +// is not null-checked. +bool BAPConObjectLineOfFire::hasFriendlySoldiersInLineOfFire(Bot* bot, Information* self, Information* target) +{ + BotMain* main = static_cast(bot); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3& tp = target->getPosition(); + Vec3 dir = bapinline::vec3(tp.x - origin.m[12], tp.y - origin.m[13], tp.z - origin.m[14]); + const float distance = std::sqrt(dir.z * dir.z + dir.x * dir.x + dir.y * dir.y); + if (0.0001f < distance) { + const float inv = 1.0f / distance; + dir.x *= inv; + dir.y *= inv; + dir.z = inv * dir.z; + } + + bool found = false; + const std::vector& players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (unsigned int i = 0; i < players.size(); ++i) { + IAIPlayer* player = players[i]; + if (!player || player->getSide() != bot->getSide()) + continue; + IAIObject* vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); + if (info == self || info == target || !info || !(info->getObjectTypeFlags() & 0x200000u)) + continue; + const Vec3& p = info->getPosition(); + const Vec3 rel = bapinline::vec3(p.x - origin.m[12], p.y - origin.m[13], p.z - origin.m[14]); + const float along = dir.z * rel.z + dir.y * rel.y + dir.x * rel.x; + if (distance < along) + continue; + const Vec3 perp = bapinline::vec3(rel.x - dir.x * along, rel.y - along * dir.y, rel.z - dir.z * along); + const float allowed = (along / 50.0f) * (allowedDistanceFar - allowedDistanceShort) + allowedDistanceShort; + float limit = allowed; + if (weapon->getWeaponZoom() != 0x40 && bot->getSpawnKit() == 1) { + limit = allowedDistanceShort; + if (weapon->getMaxRange() <= 100.0f) + limit = allowed; + } + if (!(perp.z * perp.z + perp.y * perp.y + perp.x * perp.x < limit * limit)) + continue; + found = true; + if (!(along < minDistForSideStep)) + continue; + Vec2 dir2; + dir2.x = 0.0f; + dir2.y = 0.0f; + vec3ToVec2XZ(dir, dir2); + bapinline::normalize(dir2); + const Vec3 facing = self->getFaceing(); + Vec2 face2; + face2.x = 0.0f; + face2.y = 0.0f; + vec3ToVec2XZ(facing, face2); + if (0.9f < dir2.x * face2.x + dir2.y * face2.y) { + main->setFriendsInLineOfFireTime(bapinline::gameTime()); + return true; + } + } + main->setFriendsInLineOfFireTime(0.0); + return found; +} + +// ELF 0x1EF930 +BAPConditionType BAPConObjectLineOfFire::getConditionType() const +{ + return BAPCTObjectLineOfFire; // 26 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.h new file mode 100644 index 000000000..ac53f4c86 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTLINEOFFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTLINEOFFIRE_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; + +// ELF: vtable 0x4B9790 (5 words), operator new 0x10/0x14, package C-actions. +class BAPConObjectLineOfFire : public BAPConObject +{ +public: + BAPConObjectLineOfFire(unsigned int, bool); // 0x1EF100 + BAPConObjectLineOfFire(unsigned int, bool, SoldierPose); // 0x1EF180 + virtual ~BAPConObjectLineOfFire(); // 0x1EF8D0 + + virtual bool evaluate(Bot*); // 0x1EF1C0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EF930, slot +0x04; from the base declaration + + bool hasFriendlySoldiersInLineOfFire(Bot*, Information*, Information*); // 0x1EF360; ELF bool + +private: + /* +0x0C */ bool m_anyPose; // first constructor: true; second: false + /* +0x0D */ bool m_flag0D; // constructor bool; [UNRESOLVED] not read by evaluate + /* +0x10 */ SoldierPose m_pose; // second constructor only; [UNRESOLVED] not read by evaluate +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTLINEOFFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp new file mode 100644 index 000000000..e04df7f88 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp @@ -0,0 +1,43 @@ +// Condition: the object is man down. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); +// every body carries its ELF address. + +#include "BAPConObjectManDown.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EFA20 (C1; C2 0x1EF9F0): +0x04 = 0 by the base, +0x08 = the object handle. +BAPConObjectManDown::BAPConObjectManDown(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1EFA70 (D1; D2 0x1EFA50, D0 0x1EFA90): base only. +BAPConObjectManDown::~BAPConObjectManDown() +{ +} + +// ELF 0x1EFAD0: the object's physical plug-in getManDown (+0x5C); false without information. +bool BAPConObjectManDown::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + bool result = false; + if (info) + result = info->getPhysical()->getManDown(); + return result; +} + +// ELF 0x1EFB40 +BAPConditionType BAPConObjectManDown::getConditionType() const +{ + return BAPCTObjectManDown; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.h new file mode 100644 index 000000000..202faaad2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.h @@ -0,0 +1,31 @@ +// Condition: the object is man down. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMANDOWN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMANDOWN_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B97B8 (5 words), operator new 0xC, package F-infantry. +class BAPConObjectManDown : public BAPConObject +{ +public: + explicit BAPConObjectManDown(unsigned int); // 0x1EFA20 + virtual ~BAPConObjectManDown(); // 0x1EFA70 + + virtual bool evaluate(Bot*); // 0x1EFAD0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EFB40, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMANDOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp new file mode 100644 index 000000000..415d4622c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp @@ -0,0 +1,48 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EFD00 (__tcf_0 0x1EFD60, _GLOBAL__I 0x1EFD90): 's Init object only. +#include + +#include "BAPConObjectMoved.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EFBA0 (C1; C2 0x1EFB50 region) +BAPConObjectMoved::BAPConObjectMoved(unsigned int object, float distance) +{ + setOwner(0); + m_object = object; + m_lastPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_distanceSqr = distance * distance; +} + +// ELF 0x1EFDB0 (D0 0x1EFDD0) +BAPConObjectMoved::~BAPConObjectMoved() +{ +} + +// ELF 0x1EFBF0 +bool BAPConObjectMoved::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + if (info && m_distanceSqr < bapinline::lengthSqr(bapinline::sub(info->getPosition(), m_lastPosition))) { + m_lastPosition = info->getPosition(); + return true; + } + return false; +} + +// ELF 0x1EFCF0 +BAPConditionType BAPConObjectMoved::getConditionType() const +{ + return BAPCTObjectMoved; // 28 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.h new file mode 100644 index 000000000..58723f6a7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMOVED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMOVED_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B97E0 (5 words), operator new 0x1C/0x114, package C-actions. +// True once the object has moved more than the distance since the last true answer +// (the reference point starts at the origin). +class BAPConObjectMoved : public BAPConObject +{ +public: + BAPConObjectMoved(unsigned int, float); // 0x1EFBA0 + virtual ~BAPConObjectMoved(); // 0x1EFDB0 + + virtual bool evaluate(Bot*); // 0x1EFBF0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EFCF0, slot +0x04; from the base declaration + +private: + /* +0x0C */ Vec3 m_lastPosition; // = 0; updated on every true answer + /* +0x18 */ float m_distanceSqr; // the ctor's distance squared +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTMOVED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp new file mode 100644 index 000000000..942f7d39b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp @@ -0,0 +1,45 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EFF70 (__tcf_0 0x1EFFD0, _GLOBAL__I 0x1F0000): 's Init object only. +#include + +#include "BAPConObjectOccupied.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EFE40 (C1; C2 0x1EFE10): +4 = 0, +8 = the handle. +BAPConObjectOccupied::BAPConObjectOccupied(unsigned int object) +{ + setOwner(0); + m_object = object; +} + +// ELF 0x1EFF00 (D0 0x1EFF20): only the base vtable store. +BAPConObjectOccupied::~BAPConObjectOccupied() +{ +} + +// ELF 0x1EFE70: false without the information or its unit plug-in (+0x40). +bool BAPConObjectOccupied::evaluate(Bot*) +{ + Information* info = bapinline::info(m_object); + if (info && info->getUnit()) + return info->getUnit()->isOccupied(); + return false; +} + +// ELF 0x1EFF60 +BAPConditionType BAPConObjectOccupied::getConditionType() const +{ + return BAPCTObjectOccupied; // 29 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.h new file mode 100644 index 000000000..dda5fc82c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.h @@ -0,0 +1,33 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTOCCUPIED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTOCCUPIED_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9848 (5 words), operator new 0xC, package F-infantry. +// True when the object's unit plug-in reports it occupied (IPIUnit::isOccupied). +class BAPConObjectOccupied : public BAPConObject +{ +public: + explicit BAPConObjectOccupied(unsigned int); // 0x1EFE40 + virtual ~BAPConObjectOccupied(); // 0x1EFF00 + + virtual bool evaluate(Bot*); // 0x1EFE70, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EFF60, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTOCCUPIED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp new file mode 100644 index 000000000..fe8984a7b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp @@ -0,0 +1,47 @@ +// Tests whether the object's speed is strictly below a fixed threshold. + +// static init: ELF 0x1F01B0 (__tcf_0 0x1F0210, _GLOBAL__I 0x1F0240): 's Init object only. +#include + +#include "BAPConObjectSpeed.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F0060 (C1; C2 0x1F0020) +BAPConObjectSpeed::BAPConObjectSpeed(unsigned int object, float speed) : m_speed(speed) +{ + m_object = object; +} + +// ELF 0x1F00C0 (D1; D2 0x1F00A0, D0 0x1F00E0) +BAPConObjectSpeed::~BAPConObjectSpeed() +{ +} + +// ELF 0x1F0120 +bool BAPConObjectSpeed::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return false; + IPIMobile* mobile = object->getMobile(); + if (!mobile) + return true; + return mobile->getSpeedMagnitude() < m_speed; +} + +// ELF 0x1F01A0 +BAPConditionType BAPConObjectSpeed::getConditionType() const +{ + return BAPCTObjectSpeed; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.h new file mode 100644 index 000000000..8cab01ec2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.h @@ -0,0 +1,33 @@ +// Tests whether the object's speed is strictly below a fixed threshold. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTSPEED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTSPEED_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9870 (5 words), package H-deferred. +class BAPConObjectSpeed : public BAPConObject +{ +public: + BAPConObjectSpeed(unsigned int, float); // 0x1F0060 + virtual ~BAPConObjectSpeed(); // 0x1F00C0 + + virtual bool evaluate(Bot*); // 0x1F0120, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F01A0, slot +0x04; from the base declaration +private: + /* +0x0C */ float m_speed; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTSPEED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp new file mode 100644 index 000000000..e11310217 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp @@ -0,0 +1,47 @@ +// Tests the inverse of the object's physical in-air state. + +// static init: ELF 0x1F03E0 (__tcf_0 0x1F0440, _GLOBAL__I 0x1F0470): 's Init object only. +#include + +#include "BAPConObjectTouchingLand.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F02A0 (C1; C2 0x1F0260) +BAPConObjectTouchingLand::BAPConObjectTouchingLand(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1F0300 (D1; D2 0x1F02E0, D0 0x1F0320) +BAPConObjectTouchingLand::~BAPConObjectTouchingLand() +{ +} + +// ELF 0x1F0360 +bool BAPConObjectTouchingLand::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return false; + IPIPhysical* physical = object->getPhysical(); + if (!physical) + return false; + return !physical->isInAir(); +} + +// ELF 0x1F0490 +BAPConditionType BAPConObjectTouchingLand::getConditionType() const +{ + return BAPCTObjectTouchingLand; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.h new file mode 100644 index 000000000..f6f87d126 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.h @@ -0,0 +1,31 @@ +// Tests the inverse of the object's physical in-air state. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTTOUCHINGLAND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTTOUCHINGLAND_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9898 (5 words), package H-deferred. +class BAPConObjectTouchingLand : public BAPConObject +{ +public: + explicit BAPConObjectTouchingLand(unsigned int); // 0x1F02A0 + virtual ~BAPConObjectTouchingLand(); // 0x1F0300 + + virtual bool evaluate(Bot*); // 0x1F0360, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F0490, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTTOUCHINGLAND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp new file mode 100644 index 000000000..062704993 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp @@ -0,0 +1,152 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F0D70 (__tcf_0 0x1F0DD0, _GLOBAL__I 0x1F0E00): 's Init object only. +#include + +#include "BAPConObjectValidAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F0510 (C1; C2 0x1F0480): the bot's own equipment shoots. +BAPConObjectValidAiming::BAPConObjectValidAiming(unsigned int object, BAPVariable* aimValid, + BAPVariable* aimDirection, bool trackStaticAttack) +{ + m_shooter = 0xFFFFFFFFu; + m_object = object; + m_aimValid = aimValid; + m_aimDirection = aimDirection; + m_trackStaticAttack = trackStaticAttack; +} + +// ELF 0x1F05F0 (C1; C2 0x1F0580) +BAPConObjectValidAiming::BAPConObjectValidAiming(unsigned int object, unsigned int shooter, BAPVariable* aimValid, + BAPVariable* aimDirection, bool trackStaticAttack) +{ + m_object = object; + m_shooter = shooter; + m_aimValid = aimValid; + m_aimDirection = aimDirection; + m_trackStaticAttack = trackStaticAttack; +} + +// ELF 0x1F0E20 (D1; D0 0x1F0E70): the Aimer and the base only. +BAPConObjectValidAiming::~BAPConObjectValidAiming() +{ +} + +// ELF 0x1F0660. The aim must be solvable (internalAiming) and the camera must be able to turn to +// the direction (IPIControlInfo::validateCameraDirection on m_shooter's, or the bot's, control +// info; not null-checked). Retail quirk: with the Aimer path internalAiming leaves `dir` at zero, +// so the camera check sees (0, 0, 0). With m_trackStaticAttack a failed check stamps the failed +// static attack time and clears both artillery flags (unless the aim failed too and the last +// failed sky attack is at most 2.5 s old: false without stamping), or, while the bot wants to +// simulate artillery, the failed sky attack time. +bool BAPConObjectValidAiming::evaluate(Bot* bot) +{ + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool aimed = internalAiming(bot, dir); + bool valid = false; + if (aimed) { + const unsigned int handle = m_shooter == 0xFFFFFFFFu ? bot->getCurrentEquipment() : m_shooter; + valid = bapinline::info(handle)->getControlInfo()->validateCameraDirection(dir); + } + if (m_trackStaticAttack) { + BotMain* main = static_cast(bot); + const double now = bapinline::gameTime(); + if (!main->getBotWantsToSimulateArtillery()) { + if (!valid) { + if (!aimed && now - main->getTimeOfLastFailedStaticSkyAttack() <= 2.5) + return false; + main->setTimeOfLastFailedStaticAttack(now); + main->setBotWantsToSimulateArtillery(false); + main->setBotIsSimulatingArtillery(false); + } + } else if (!valid) { + main->setTimeOfLastFailedStaticSkyAttack(now); + } + } + return valid; +} + +// ELF 0x1F07E0. With both variables: dir = the direction variable, answer = the valid variable. +// Otherwise solves the Aimer for the active weapon of the bot's current vehicle/soldier against +// the target (its position when not sensed or sensed indirectly (flag 8), else the sensed hit +// point), relative to the weapon's absolute transformation, 0.1 s ahead; `dir` is not written +// (the solution goes to a local). No information, control info, armament, weapon or target: false. +bool BAPConObjectValidAiming::internalAiming(Bot* bot, Vec3& dir) +{ + if (m_aimValid && m_aimDirection) { + dir = m_aimDirection->m_value; + return m_aimValid->m_value; + } + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self || !self->getControlInfo() || !self->getArmament()) + return false; + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) + return false; + Information* target = bapinline::info(m_object); + if (!target) + return false; + IPIMobile* ownMobile = bapinline::info(self->getPrimaryObject(bot->getSide()))->getMobile(); // not null-checked + + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + Vec3 point; + if (!sensed || (sensed->m_flags & 8u)) { + point = target->getPosition(); + } else { + const Mat4& t = target->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + point.x = t.m[8] * l.z + t.m[0] * l.x + t.m[4] * l.y + t.m[12]; + point.y = t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13]; + point.z = l.x * t.m[2] + l.y * t.m[6] + l.z * t.m[10] + t.m[14]; + } + IPIMobile* targetMobile = bapinline::info(target->getPrimaryObject(bot->getSide()))->getMobile(); // not null-checked + const Mat4& weaponTransform = weapon->getAbsoluteTransformation(); + const Vec3 rel = bapinline::vec3(point.x - weaponTransform.m[12], point.y - weaponTransform.m[13], + point.z - weaponTransform.m[14]); + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 ownVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (ownMobile) + ownVelocity = ownMobile->getSpeed(); + if (targetMobile) + targetVelocity = targetMobile->getSpeed(); + m_aimer.setTargetData(rel, targetVelocity, ownVelocity, &weapon->getAbsoluteTransformation(), bapinline::gameTime()); + Vec3 solution = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 solutionTarget = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool indirect = weapon->getIndirect(); + return m_aimer.getFiringDirection(bapinline::gameTime() + 0.1, 0.5f, indirect, solution, solutionTarget, 0); +} + +// ELF 0x1F0D60 +BAPConditionType BAPConObjectValidAiming::getConditionType() const +{ + return BAPCTObjectValidAiming; // 32 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h new file mode 100644 index 000000000..560749524 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h @@ -0,0 +1,47 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "../AIBot/Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B98E8 (5 words), operator new 0x10/0x2C/0x88, package C-actions. +class BAPConObjectValidAiming : public BAPConObject +{ +public: + BAPConObjectValidAiming(unsigned int, BAPVariable*, BAPVariable*, bool); // 0x1F0510 + BAPConObjectValidAiming(unsigned int, unsigned int, BAPVariable*, BAPVariable*, bool); // 0x1F05F0 + virtual ~BAPConObjectValidAiming(); // 0x1F0E20 + + virtual bool evaluate(Bot*); // 0x1F0660, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F0D60, slot +0x04; from the base declaration + + bool internalAiming(Bot*, Vec3&); // 0x1F07E0; ELF bool + + /* +0x0C */ unsigned int m_shooter; // information handle; -1: the bot's equipment + /* +0x10 */ Aimer m_aimer; + /* +0x7C */ BAPVariable* m_aimValid; // with m_aimDirection: taken as the answer + /* +0x80 */ BAPVariable* m_aimDirection; + /* +0x84 */ bool m_trackStaticAttack; // stamp the failed static (sky) attack times +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp new file mode 100644 index 000000000..e9e6c44d5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp @@ -0,0 +1,58 @@ +// Aiming condition restricted to the camera's pitch range. Recovered from libaidll.so 1.5.3153 +// (ia-32); ELF addresses on every body. + +#include "BAPConObjectValidPitchAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1F1110, __tcf_0 0x1F1170, _GLOBAL__I 0x1F11A0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F0F20 (C1; C2 0x1F0EC0): the bot's own equipment shoots; no static-attack tracking. +BAPConObjectValidPitchAiming::BAPConObjectValidPitchAiming(unsigned int object, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F0FE0 (C1; C2 0x1F0F80) +BAPConObjectValidPitchAiming::BAPConObjectValidPitchAiming(unsigned int object, unsigned int shooter, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, shooter, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F11C0 (weak D1; D0 0x1F1210): the Aimer and the base only. +BAPConObjectValidPitchAiming::~BAPConObjectValidPitchAiming() +{ +} + +// ELF 0x1F1040. The aim must be solvable (internalAiming) and the camera must be able to turn +// to the direction in pitch (IPIControlInfo::validateCameraDirectionPitch on m_shooter's, or the +// bot's, control info; the information is not null-checked). +bool BAPConObjectValidPitchAiming::evaluate(Bot* bot) +{ + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!internalAiming(bot, dir)) + return false; + const unsigned int handle = m_shooter == 0xFFFFFFFFu ? bot->getCurrentEquipment() : m_shooter; + return bapinline::info(handle)->getControlInfo()->validateCameraDirectionPitch(dir); +} + +// ELF 0x1F1100 +BAPConditionType BAPConObjectValidPitchAiming::getConditionType() const +{ + return BAPCTObjectValidAiming; // 32, as the base +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.h new file mode 100644 index 000000000..1af48e09d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.h @@ -0,0 +1,37 @@ +// Aiming condition restricted to the camera's pitch range. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPITCHAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPITCHAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObjectValidAiming.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9948 (5 words), operator new 0x88, package H-deferred. +// No members of its own. +class BAPConObjectValidPitchAiming : public BAPConObjectValidAiming +{ +public: + BAPConObjectValidPitchAiming(unsigned int, BAPVariable*, BAPVariable*); // 0x1F0F20 + BAPConObjectValidPitchAiming(unsigned int, unsigned int, BAPVariable*, BAPVariable*); // 0x1F0FE0 + virtual ~BAPConObjectValidPitchAiming(); // 0x1F11C0 + + virtual bool evaluate(Bot*); // 0x1F1040, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1100, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPITCHAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp new file mode 100644 index 000000000..12a91c63c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp @@ -0,0 +1,57 @@ +// Tests the object's position against the selected vehicle and equipment navigation constraints. + +// static init: ELF 0x1F1520 (__tcf_0 0x1F1580, _GLOBAL__I 0x1F15B0): 's Init object only. +#include + +#include "BAPConObjectValidPosition.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F12F0 (C1; C2 0x1F1260) +BAPConObjectValidPosition::BAPConObjectValidPosition(unsigned int object) +{ + m_object = object; + Information* information = bapinline::info(object); + m_vehicle = information->getMobile()->getVehicleNumber(); + m_equipment = information->getUnit()->getEquipmentType(); +} + +// ELF 0x1F13C0 (C1; C2 0x1F1380) +BAPConObjectValidPosition::BAPConObjectValidPosition(unsigned int object, int vehicle, int equipment) + : m_vehicle(vehicle), m_equipment(equipment) +{ + m_object = object; +} + +// ELF 0x1F1420 (D1; D2 0x1F1400, D0 0x1F1440) +BAPConObjectValidPosition::~BAPConObjectValidPosition() +{ +} + +// ELF 0x1F1480 +bool BAPConObjectValidPosition::evaluate(Bot*) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + const Vec3& position = object->getPosition(); + return IAIPathfinding::instance->isValidPosition(m_vehicle, m_equipment, position, true); +} + +// ELF 0x1F15D0 +BAPConditionType BAPConObjectValidPosition::getConditionType() const +{ + return BAPCTObjectValidPosition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.h new file mode 100644 index 000000000..5a0cf598d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.h @@ -0,0 +1,35 @@ +// Tests the object's position against the selected vehicle and equipment navigation constraints. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPOSITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPOSITION_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B99A8 (5 words), package H-deferred. +class BAPConObjectValidPosition : public BAPConObject +{ +public: + explicit BAPConObjectValidPosition(unsigned int); // 0x1F12F0 + BAPConObjectValidPosition(unsigned int, int, int); // 0x1F13C0 + virtual ~BAPConObjectValidPosition(); // 0x1F1420 + + virtual bool evaluate(Bot*); // 0x1F1480, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F15D0, slot +0x04; from the base declaration +private: + /* +0x0C */ int m_vehicle; + /* +0x10 */ int m_equipment; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDPOSITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp new file mode 100644 index 000000000..7adb2fa08 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp @@ -0,0 +1,58 @@ +// Aiming condition restricted to the camera's yaw range. Recovered from libaidll.so 1.5.3153 +// (ia-32); ELF addresses on every body. + +#include "BAPConObjectValidYawAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/Information.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x1F1830, __tcf_0 0x1F1890, _GLOBAL__I 0x1F18C0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F1640 (C1; C2 0x1F15E0): the bot's own equipment shoots; no static-attack tracking. +BAPConObjectValidYawAiming::BAPConObjectValidYawAiming(unsigned int object, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F1700 (C1; C2 0x1F16A0) +BAPConObjectValidYawAiming::BAPConObjectValidYawAiming(unsigned int object, unsigned int shooter, BAPVariable* aimValid, + BAPVariable* aimDirection) + : BAPConObjectValidAiming(object, shooter, aimValid, aimDirection, false) +{ +} + +// ELF 0x1F18E0 (weak D1; D0 0x1F1930): the Aimer and the base only. +BAPConObjectValidYawAiming::~BAPConObjectValidYawAiming() +{ +} + +// ELF 0x1F1760. The aim must be solvable (internalAiming) and the camera must be able to turn +// to the direction in yaw (IPIControlInfo::validateCameraDirectionYaw on m_shooter's, or the +// bot's, control info; the information is not null-checked). +bool BAPConObjectValidYawAiming::evaluate(Bot* bot) +{ + Vec3 dir = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!internalAiming(bot, dir)) + return false; + const unsigned int handle = m_shooter == 0xFFFFFFFFu ? bot->getCurrentEquipment() : m_shooter; + return bapinline::info(handle)->getControlInfo()->validateCameraDirectionYaw(dir); +} + +// ELF 0x1F1820 +BAPConditionType BAPConObjectValidYawAiming::getConditionType() const +{ + return BAPCTObjectValidAiming; // 32, as the base +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.h new file mode 100644 index 000000000..d7e06c1f3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.h @@ -0,0 +1,37 @@ +// Aiming condition restricted to the camera's yaw range. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDYAWAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDYAWAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObjectValidAiming.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9A08 (5 words), operator new 0x88, package H-deferred. +// No members of its own. +class BAPConObjectValidYawAiming : public BAPConObjectValidAiming +{ +public: + BAPConObjectValidYawAiming(unsigned int, BAPVariable*, BAPVariable*); // 0x1F1640 + BAPConObjectValidYawAiming(unsigned int, unsigned int, BAPVariable*, BAPVariable*); // 0x1F1700 + virtual ~BAPConObjectValidYawAiming(); // 0x1F18E0 + + virtual bool evaluate(Bot*); // 0x1F1760, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1820, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVALIDYAWAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp new file mode 100644 index 000000000..03c163b32 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp @@ -0,0 +1,48 @@ +// Tests the sensed object's visible flag while excluding indirect sensing. + +// static init: ELF 0x1F1B40 (__tcf_0 0x1F1BA0, _GLOBAL__I 0x1F1BD0): 's Init object only. +#include + +#include "BAPConObjectVisible.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F19B0 (C1; C2 0x1F1980) +BAPConObjectVisible::BAPConObjectVisible(unsigned int object) +{ + m_object = object; +} + +// ELF 0x1F1A00 (D1; D2 0x1F19E0, D0 0x1F1A20) +BAPConObjectVisible::~BAPConObjectVisible() +{ +} + +// ELF 0x1F1A60 +bool BAPConObjectVisible::evaluate(Bot* bot) +{ + SensedObject* object = bot->getSensedObjectFromHandle(m_object); + return (object->m_flags & 2u) != 0 && (object->m_flags & 8u) == 0; +} + +// ELF 0x1F1AA0 +BAPConditionType BAPConObjectVisible::getConditionType() const +{ + return BAPCTObjectVisible; +} + +// ELF 0x1F1AB0 +void BAPConObjectVisible::operator<<(std::ostream& out) +{ + out << static_cast(getConditionType()) << "(" << m_object << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.h new file mode 100644 index 000000000..811727523 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.h @@ -0,0 +1,33 @@ +// Tests the sensed object's visible flag while excluding indirect sensing. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVISIBLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVISIBLE_H + +#include +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9A40 (6 words), operator new 0xC, package H-deferred. +class BAPConObjectVisible : public BAPConObject +{ +public: + explicit BAPConObjectVisible(unsigned int); // 0x1F19B0 + virtual ~BAPConObjectVisible(); // 0x1F1A00 + + virtual bool evaluate(Bot*); // 0x1F1A60, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1AA0, slot +0x04; from the base declaration + virtual void operator<<(std::ostream&); // 0x1F1AB0, slot +0x14; [INFERRED] ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOBJECTVISIBLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp new file mode 100644 index 000000000..097ac6ea6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp @@ -0,0 +1,135 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E88E0 (__tcf_0 0x1E8940, _GLOBAL__I 0x1E8970): 's Init object only. +#include + +#include "BAPConOkToThrowGrenade.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E7FF0 (C1; C2 0x1E7F90) +BAPConOkToThrowGrenade::BAPConOkToThrowGrenade(unsigned int object, BAPVariable* targetPoint, + BAPVariable* throwDirection) +{ + m_object = object; + m_targetPoint = targetPoint; + m_throwDirection = throwDirection; +} + +// ELF 0x1E8990 (D1; D0 0x1E89E0): the Aimer and the base only. +BAPConOkToThrowGrenade::~BAPConOkToThrowGrenade() +{ +} + +// ELF 0x1E8050. A soldier waits 10 s after a failed static attack; no friendly soldier may stand +// within 7 m of the target point (|dy| < 2.5). The throw is traced from the projectile origin to +// the apex (Aimer::getTurnPointForGrenade, only while the bot simulates artillery; otherwise three +// units along the throw direction), ignoring the bot's object; without a hit on that leg, from the +// apex to the target point, ignoring the target's object (no hit there: ok). A hit 3.5 m or more +// from the target point fails and stamps the failed static (sky) attack time. The bot's +// information and weapon are not null-checked; without the target information: false. +bool BAPConOkToThrowGrenade::evaluate(Bot* bot) +{ + BotMain* main = static_cast(bot); + Information* self = bapinline::info(bot->getCurrentEquipment()); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + Information* target = bapinline::info(m_object); + if (!target) + return false; + const unsigned int selfFlags = self->getObjectTypeFlags(); + const double now = bapinline::gameTime(); + if (now - main->getTimeOfLastFailedStaticAttack() < 10.0 && (selfFlags & 0x200000u)) + return false; + + const std::vector& players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (unsigned int i = 0; i < players.size(); ++i) { + IAIPlayer* player = players[i]; + if (!player || player->getSide() != bot->getSide()) + continue; + IAIObject* vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); + if (info && (info->getObjectTypeFlags() & 0x200000u) + && std::fabs(info->getPosition().y - m_targetPoint->m_value.y) < 2.5f) { + const Vec3 d = bapinline::sub(m_targetPoint->m_value, info->getPosition()); + if (d.x * d.x + d.y * d.y + d.z * d.z < 49.0f) + return false; + } + } + + bot->getSensedObjectFromHandle(m_object); // answer dropped (0x1E8340) + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + const Mat4& origin = weapon->getProjectileOrigin(); + + float apexTime = 0.0f; + Vec3 apex = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!main->getBotWantsToSimulateArtillery() + || !m_aimer.getTurnPointForGrenade(m_throwDirection->m_value, apex, apexTime)) { + const Vec3& d = m_throwDirection->m_value; + apex = bapinline::vec3(d.x * 3.0f, d.y * 3.0f, d.z * 3.0f); + } else { + apex.y = static_cast((static_cast(weapon->getExitVelocity()) * m_throwDirection->m_value.y * apexTime + + apex.y) * 0.5); + } + const Vec3 from = bapinline::vec3(origin.m[12], origin.m[13], origin.m[14]); + apex = bapinline::vec3(origin.m[12] + apex.x, origin.m[13] + apex.y, origin.m[14] + apex.z); + + Vec3 hit = bapinline::vec3(0.0f, 0.0f, 0.0f); + bool ok = true; + if (bapinline::collideLineIgnoring(from, apex, self->getAIObject(), hit)) { + ok = false; + } else if (bapinline::collideLineIgnoring(apex, m_targetPoint->m_value, target->getAIObject(), hit)) { + ok = false; + } + if (!ok) { + const Vec3 miss = bapinline::sub(m_targetPoint->m_value, hit); + if (12.25f <= miss.x * miss.x + miss.y * miss.y + miss.z * miss.z) { + if (!main->getBotWantsToSimulateArtillery()) { + main->setTimeOfLastFailedStaticAttack(now); + } else { + main->setTimeOfLastFailedStaticSkyAttack(now); + main->setBotIsSimulatingArtillery(false); + } + return false; + } + } + if (main->getBotWantsToSimulateArtillery() && !weapon->getIsThrown()) + main->setBotIsSimulatingArtillery(true); + return true; +} + +// ELF 0x1E88D0 +BAPConditionType BAPConOkToThrowGrenade::getConditionType() const +{ + return BAPCTOkToThrowGrenade; // 56 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h new file mode 100644 index 000000000..d63cf01b1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOKTOTHROWGRENADE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOKTOTHROWGRENADE_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "../AIBot/Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9308 (5 words), operator new 0x80, package C-actions. +class BAPConOkToThrowGrenade : public BAPConObject +{ +public: + BAPConOkToThrowGrenade(unsigned int, BAPVariable*, BAPVariable*); // 0x1E7FF0 + virtual ~BAPConOkToThrowGrenade(); // 0x1E8990 + + virtual bool evaluate(Bot*); // 0x1E8050, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E88D0, slot +0x04; from the base declaration + +private: + /* +0x0C */ Aimer m_aimer; // drag/speed/gravity set by evaluate + /* +0x78 */ BAPVariable* m_targetPoint; + /* +0x7C */ BAPVariable* m_throwDirection; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOKTOTHROWGRENADE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOpLessThan.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOpLessThan.h new file mode 100644 index 000000000..361f9d8be --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOpLessThan.h @@ -0,0 +1,62 @@ +// Comparison condition template; only is instantiated (vtable 0x4BBC38, inline in the +// image, emitted in BBPFire2d.cpp). getConditionType 0x24B7E0 returns 55. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOPLESSTHAN_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOPLESSTHAN_H + +#include + +#include "BAPCondition.h" +#include "BAPExpression.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { +namespace ai { + +template +class BAPConOpLessThan : public BAPCondition +{ +public: + // [CHOSEN, not recovered] Constructor spelling for the inline construction at + // ELF 0x246A44..0x246A7E: both optional expressions null, followed by the value pointers. + BAPConOpLessThan(BAPVariable* left, BAPVariable* right) + : m_leftExpression(0), m_left(left), m_rightExpression(0), m_right(right) {} + + // ELF 0x24B790 (). + virtual bool evaluate(Bot*) + { + if (m_leftExpression) + m_leftExpression->unimplementedExpressionSlot2(); + if (m_rightExpression) + m_rightExpression->unimplementedExpressionSlot2(); + return m_left->m_value < m_right->m_value; + } + virtual BAPConditionType getConditionType() const { return BAPCTOpLessThan; } // 0x24B7E0 + // ELF 0x24B7F0 (): streams the cached values without invoking the expressions. + virtual void streamSelf(std::ostream& out) const + { + out << m_left->m_value << " < " << m_right->m_value; + } + // ELF 0x24B850 (D1; D0 0x24B8B0). + virtual ~BAPConOpLessThan() + { + if (m_leftExpression) + delete m_leftExpression; + if (m_rightExpression) + delete m_rightExpression; + } + +private: + // [INFERRED] Operand names; expressions are owned, variables belong to the context. + /* +0x08 */ BAPExpression* m_leftExpression; + /* +0x0C */ BAPVariable* m_left; + /* +0x10 */ BAPExpression* m_rightExpression; + /* +0x14 */ BAPVariable* m_right; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOPLESSTHAN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp new file mode 100644 index 000000000..04029a0fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp @@ -0,0 +1,77 @@ +// BAPConOr: recovered by package A-core from libaidll.so (TU without a FILE symbol, 0x1F4D30..0x1F5410). +// Every body carries its ELF address. + +#include "BAPConOr.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F4D30 (C2; C1 0x1F4EA0). Copies the list and takes ownership of its conditions. +BAPConOr::BAPConOr(std::list& conditions) +{ + m_conditions = conditions; + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + (*it)->m_owner = this; +} + +// ELF 0x1F4F50 (C2; C1 0x1F4FC0). +BAPConOr::BAPConOr() +{ + m_conditions.clear(); +} + +// ELF 0x1F5030 (D2; D1 and D0 follow). Deletes the conditions (slot +0x10); the list itself goes with +// BAPBoleanOp. +BAPConOr::~BAPConOr() +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if (*it) + delete *it; + } +} + +// ELF 0x1F5250. +bool BAPConOr::evaluate(Bot* bot) +{ + for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) + { + if ((*it)->evaluate(bot)) + return true; + } + return false; +} + +// ELF 0x1F52C0: no null check. +void BAPConOr::addCondition(BAPCondition* condition) +{ + condition->m_owner = this; + m_conditions.insert(m_conditions.end(), condition); +} + +// ELF 0x1F5330. +BAPConditionType BAPConOr::getConditionType() const +{ + return BAPCTOr; +} + +// ELF 0x1F5340: "(" c1 " || " c2 ... ")". +void BAPConOr::streamSelf(std::ostream& os) const +{ + os << "("; + std::list::const_iterator it = m_conditions.begin(); + if (it != m_conditions.end()) + { + os << **it; + for (++it; it != m_conditions.end(); ++it) + os << " || " << **it; + } + os << ")"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h new file mode 100644 index 000000000..3159667e0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.h @@ -0,0 +1,40 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOR_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOR_H + +#include +#include +#include "BAPBoleanOp.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B9EE0 (6 words), operator new 0xC, package A-core. +// True when any condition is (an empty Or is false); stops at the first true. Owns its +// conditions (BAPBoleanOp::m_conditions). sizeof 0xC. +class BAPConOr : public BAPBoleanOp +{ +public: + explicit BAPConOr(std::list&); // 0x1F4EA0 + BAPConOr(); // 0x1F4FC0 + virtual ~BAPConOr(); // 0x1F50E0 + + virtual bool evaluate(Bot*); // 0x1F5250, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F5330, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F5340, slot +0x08; from the base declaration + virtual void addCondition(BAPCondition*); // 0x1F52C0, slot +0x14; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONOR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp new file mode 100644 index 000000000..84ac2171c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp @@ -0,0 +1,51 @@ +// Compares the bot's forward direction with a normalized object-position-plus-offset vector. + +// static init: ELF 0x1E8DA0 (__tcf_0 0x1E8E00, _GLOBAL__I 0x1E8E30): 's Init object only. +#include + +#include "BAPConPointAt.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E8AA0 (C1; C2 0x1E8A30) +BAPConPointAt::BAPConPointAt(unsigned int object, Vec3& offset, float angle) + : m_object(object), m_cosAngle(std::cos(angle)), m_offset(offset) +{ +} + +// ELF 0x1E8B30 (D1; D2 0x1E8B10, D0 0x1E8B50) +BAPConPointAt::~BAPConPointAt() +{ +} + +// ELF 0x1E8B90 +bool BAPConPointAt::evaluate(Bot* bot) +{ + Information* object = bapinline::info(m_object); + if (!object) + return true; + // shipped defect: the bot's position is never subtracted from this world-space point. + Vec3 direction = bapinline::add(object->getPosition(), m_offset); + bapinline::normalize(direction); + Information* self = bapinline::info(bot->getCurrentEquipment()); + const Mat4& transform = self->getTransformation(); + const Vec3 forward = bapinline::vec3(transform.m[8], transform.m[9], transform.m[10]); + return bapinline::dot(direction, forward) >= m_cosAngle; +} + +// ELF 0x1E8D90 +BAPConditionType BAPConPointAt::getConditionType() const +{ + return BAPCTPointAt; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.h new file mode 100644 index 000000000..2311deff9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.h @@ -0,0 +1,36 @@ +// Compares the bot's forward direction with a normalized object-position-plus-offset vector. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTAT_H + +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9340 (5 words), package H-deferred. +class BAPConPointAt : public BAPCondition +{ +public: + BAPConPointAt(unsigned int, Vec3&, float); // 0x1E8AA0 + virtual ~BAPConPointAt(); // 0x1E8B30 + + virtual bool evaluate(Bot*); // 0x1E8B90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E8D90, slot +0x04; from the base declaration +private: + /* +0x08 */ unsigned int m_object; + /* +0x0C */ float m_cosAngle; + /* +0x10 */ Vec3 m_offset; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp new file mode 100644 index 000000000..04ef73b4c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp @@ -0,0 +1,86 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E9400 (__tcf_0 0x1E9460, _GLOBAL__I 0x1E9490): 's Init object only. +#include + +#include "BAPConPointDistance.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E8ED0 (C1) +BAPConPointDistance::BAPConPointDistance(const Vec3& point, float maxDistance, bool flat) +{ + m_minDistanceSqr = 0.0f; + m_lastDistanceSqr = 0.0f; + m_2d = flat; + m_point = point; + m_maxDistanceSqr = maxDistance * maxDistance; +} + +// ELF 0x1E8FD0 (C1) +BAPConPointDistance::BAPConPointDistance(const Vec3& point, float minDistance, float maxDistance, bool flat) +{ + m_2d = flat; + m_lastDistanceSqr = 0.0f; + m_point = point; + m_maxDistanceSqr = maxDistance * maxDistance; + m_minDistanceSqr = minDistance * minDistance; +} + +// ELF 0x1E9070 (D0 0x1E9090) +BAPConPointDistance::~BAPConPointDistance() +{ +} + +// ELF 0x1E90D0 (the information is not null-checked) +bool BAPConPointDistance::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + float a, b; + if (!m_2d) { + const Vec3& p = self->getPosition(); + b = (m_point.z - p.z) * (m_point.z - p.z); + a = (m_point.x - p.x) * (m_point.x - p.x) + (m_point.y - p.y) * (m_point.y - p.y); + } else { + const float px = self->getPosition().x; + const float dz = m_point.z - self->getPosition().z; + a = (m_point.x - px) * (m_point.x - px); + b = dz * dz; + } + const float d = a + b; + m_lastDistanceSqr = d; + return m_minDistanceSqr <= d && d <= m_maxDistanceSqr; +} + +// ELF 0x1E9270 +BAPConditionType BAPConPointDistance::getConditionType() const +{ + return BAPCTPointDistance; // 12 +} + +// ELF 0x1E9280 (the label says "ObjectDistance" in the image) +void BAPConPointDistance::streamSelf(std::ostream& out) const +{ + out << "ObjectDistance["; + if (m_lastDistanceSqr == 0.0f) + out << "not calculated"; + else + out << static_cast(std::sqrt(m_lastDistanceSqr)); + out << "] < " << static_cast(std::sqrt(m_maxDistanceSqr)); + if (m_minDistanceSqr != 0.0f) + out << " && ObjectDistance[" << static_cast(std::sqrt(m_lastDistanceSqr)) << "] > " + << static_cast(std::sqrt(m_minDistanceSqr)); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.h new file mode 100644 index 000000000..be6adcccd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTDISTANCE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTDISTANCE_H + +#include +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9368 (5 words), operator new 0x24, package C-actions. +// min^2 <= d^2 <= max^2 from the bot's current vehicle/soldier to a point (3d, or XZ +// with the flag); the last d^2 is kept for streamSelf. +class BAPConPointDistance : public BAPCondition +{ +public: + BAPConPointDistance(const Vec3&, float, bool); // 0x1E8ED0 + BAPConPointDistance(const Vec3&, float, float, bool); // 0x1E8FD0 + virtual ~BAPConPointDistance(); // 0x1E9070 + + virtual bool evaluate(Bot*); // 0x1E90D0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E9270, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E9280, slot +0x08; from the base declaration + +private: + /* +0x08 */ float m_minDistanceSqr; // = 0 in the one-distance form + /* +0x0C */ float m_maxDistanceSqr; + /* +0x10 */ bool m_2d; + /* +0x14 */ float m_lastDistanceSqr; // = 0 ("not calculated") + /* +0x18 */ Vec3 m_point; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTDISTANCE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp new file mode 100644 index 000000000..ce58ca058 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp @@ -0,0 +1,56 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [PLATFORM] precision: the x87 build adds the scaled forward axis to the position in extended +// precision before rounding the point. + +// static init: ELF 0x1E9830 (__tcf_0 0x1E9890, _GLOBAL__I 0x1E98C0): 's Init object only. +#include + +#include "BAPConPointInFront.h" + +#include "../../../../Math/Mat4.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "BAPActionInline.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E9520 (C1; C2 0x1E94B0) +BAPConPointInFront::BAPConPointInFront(const Vec3& point, float distance, float minDot) +{ + m_distance = distance; + m_minDot = minDot; + m_point = point; +} + +// ELF 0x1E95B0 (D1 0x1E9590, D0 0x1E95D0): base only. +BAPConPointInFront::~BAPConPointInFront() +{ +} + +// ELF 0x1E9610. No information on the bot's vehicle: false. +bool BAPConPointInFront::evaluate(Bot* bot) +{ + Information* const self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + const Mat4& transformation = self->getTransformation(); + const Vec3 forward = bapinline::vec3(transformation.m[8], transformation.m[9], transformation.m[10]); + const Vec3& position = self->getPosition(); + const Vec3 ahead = bapinline::vec3(forward.x * m_distance, forward.y * m_distance, forward.z * m_distance); + const Vec3 front = bapinline::add(position, ahead); + Vec3 direction = bapinline::sub(m_point, front); + bapinline::normalize(direction); + return bapinline::dot(forward, direction) > m_minDot; +} + +// ELF 0x1E9820: ObjectInFront, as shipped. +BAPConditionType BAPConPointInFront::getConditionType() const +{ + return BAPCTObjectInFront; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.h new file mode 100644 index 000000000..bcc6a7bff --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.h @@ -0,0 +1,39 @@ +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTINFRONT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTINFRONT_H + +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9390 (5 words), operator new 0x1C, package G-vehicles. +// BAPConObjectInFront for a fixed point. getConditionType answers ObjectInFront (23), as shipped. +class BAPConPointInFront : public BAPCondition +{ +public: + BAPConPointInFront(const Vec3&, float, float); // 0x1E9520 + virtual ~BAPConPointInFront(); // 0x1E95B0 + + virtual bool evaluate(Bot*); // 0x1E9610, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E9820, slot +0x04; from the base declaration + +private: + /* +0x08 */ float m_distance; // [INFERRED] names + /* +0x0C */ float m_minDot; + /* +0x10 */ Vec3 m_point; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOINTINFRONT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp new file mode 100644 index 000000000..78f79f549 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp @@ -0,0 +1,69 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1E9CD0 (__tcf_0 0x1E9D30, _GLOBAL__I 0x1E9D60): 's Init object only. +#include + +#include "BAPConPosition.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E9950 (C1): `new Vec3(point)` (operator new 0xC) at +0x08. +BAPConPosition::BAPConPosition(const Vec3& point, float radius) +{ + setOwner(0); + Vec3* p = new Vec3(point); + m_point = &p->x; + m_is3d = true; + m_radiusSqr = radius * radius; +} + +// ELF 0x1E9A30 (C1): `new Vec2(point)` (operator new 8). +BAPConPosition::BAPConPosition(const Vec2& point, float radius) +{ + setOwner(0); + Vec2* p = new Vec2(point); + m_point = &p->x; + m_is3d = false; + m_radiusSqr = radius * radius; +} + +// ELF 0x1E9AF0 (D0 0x1E9B40): plain operator delete of the point. +BAPConPosition::~BAPConPosition() +{ + ::operator delete(m_point); +} + +// ELF 0x1E9B90: 3d `<=`, 2d (x, z against the Vec2) strict `<`. +bool BAPConPosition::evaluate(Bot* bot) +{ + Information* info = bapinline::info(bot->getCurrentEquipment()); + if (!info) + return true; + if (!m_is3d) { + const Vec3& pos = info->getPosition(); + const float dx = pos.x - m_point[0]; + const float dz = pos.z - m_point[1]; + return dz * dz + dx * dx < m_radiusSqr; + } + const Vec3& pos = info->getPosition(); + const float dx = pos.x - m_point[0]; + const float dy = pos.y - m_point[1]; + const float dz = pos.z - m_point[2]; + return dx * dx + dy * dy + dz * dz <= m_radiusSqr; +} + +// ELF 0x1E9CC0 +BAPConditionType BAPConPosition::getConditionType() const +{ + return BAPCTPosition; // 37 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.h new file mode 100644 index 000000000..17d679060 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.h @@ -0,0 +1,44 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOSITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOSITION_H + +#include "../../../../Math/Vec3.h" +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B93B8 (5 words), operator new 0x8/0x14, package C-actions. +// True while the bot's current vehicle/soldier is within the radius of a point (3d form) or +// of an XZ point (2d form, strictly inside). No information: true. +class BAPConPosition : public BAPCondition +{ +public: + BAPConPosition(const Vec3&, float); // 0x1E9950 + BAPConPosition(const Vec2&, float); // 0x1E9A30 + virtual ~BAPConPosition(); // 0x1E9AF0 + + virtual bool evaluate(Bot*); // 0x1E9B90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1E9CC0, slot +0x04; from the base declaration + +private: + /* +0x08 */ float* m_point; // new float[3] (Vec3 form) or new float[2] (Vec2 form): a heap Vec3 / Vec2 + /* +0x0C */ float m_radiusSqr; + /* +0x10 */ bool m_is3d; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONPOSITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp new file mode 100644 index 000000000..657ece67e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp @@ -0,0 +1,74 @@ +// BAPConSharedCondition: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1E9D80..0x1EA280). Every body carries its ELF address. + +#include "BAPConSharedCondition.h" + +#include "../AIUtils/checkPointer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E9D80 (C2; C1 0x1E9DF0). The cell is unchecked `operator new(8)`; no null check on the +// condition. +BAPConSharedCondition::BAPConSharedCondition(BAPCondition* condition) +{ + m_shared = new SharedValue; + m_shared->value = false; + m_shared->references = 1; + m_condition = condition; + condition->m_owner = this; +} + +// ELF 0x1E9E60 (C2; C1 0x1E9EA0): shares the cell, owns no condition. +BAPConSharedCondition::BAPConSharedCondition(const BAPConSharedCondition& other) + : BAPCondition() + , m_shared(other.m_shared) + , m_condition(0) +{ + ++m_shared->references; +} + +// ELF 0x1E9EE0 (D2; D1 0x1E9F50, D0 0x1E9FC0). +BAPConSharedCondition::~BAPConSharedCondition() +{ + if (m_condition) + delete m_condition; + if (--m_shared->references == 0) + delete m_shared; +} + +// ELF 0x1EA040. +BAPConSharedCondition* BAPConSharedCondition::getNewSharedCondition() const +{ + return checkPointer(new BAPConSharedCondition(*this)); +} + +// ELF 0x1EA190: only the original evaluates; every holder returns the cell. +bool BAPConSharedCondition::evaluate(Bot* bot) +{ + if (m_condition) + m_shared->value = m_condition->evaluate(bot); + return m_shared->value; +} + +// ELF 0x1EA1D0. +BAPConditionType BAPConSharedCondition::getConditionType() const +{ + return BAPCTSharedCondition; +} + +// ELF 0x1EA1E0: "[" condition "][" cell address "]"; a copy prints "[][" address "]". +void BAPConSharedCondition::streamSelf(std::ostream& os) const +{ + if (m_condition) + os << "[" << *m_condition << "][" << static_cast(m_shared) << "]"; + else + os << "[" << "][" << static_cast(m_shared) << "]"; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.h new file mode 100644 index 000000000..049b237ce --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.h @@ -0,0 +1,52 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSHAREDCONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSHAREDCONDITION_H + +#include +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// ELF: vtable 0x4B93E0 (5 words), operator new 0x8/0x10, package A-core. +// A condition evaluated once and read by several plan nodes: the original (built with the wrapped +// condition) evaluates it and stores the result in a shared, reference-counted cell; copies +// (getNewSharedCondition) only read the cell. sizeof 0x10. +class BAPConSharedCondition : public BAPCondition +{ +public: + explicit BAPConSharedCondition(BAPCondition*); // 0x1E9DF0 + explicit BAPConSharedCondition(const BAPConSharedCondition&); // 0x1E9EA0 + virtual ~BAPConSharedCondition(); // 0x1E9F50 + + virtual bool evaluate(Bot*); // 0x1EA190, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EA1D0, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1EA1E0, slot +0x08; from the base declaration + + BAPConSharedCondition* getNewSharedCondition() const; // 0x1EA040: checkPointer(new copy) + +private: + // `operator new(8)` in the constructor 0x1E9D80: {false, 1}. + struct SharedValue + { + bool value; + int references; + }; + + /* +0x08 */ SharedValue* m_shared; + /* +0x0C */ BAPCondition* m_condition; // owned; 0 in copies +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSHAREDCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp new file mode 100644 index 000000000..28b65b986 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp @@ -0,0 +1,115 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EA970 (__tcf_0 0x1EA9D0, _GLOBAL__I 0x1EAA00): 's Init object only. +#include + +#include "BAPConSplashDamage.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EA2F0 (C1; C2 0x1EA280) +BAPConSplashDamage::BAPConSplashDamage(unsigned int object, BAPVariable* targetPoint, + BAPVariable* variable7C, float radius) +{ + m_object = object; + m_targetPoint = targetPoint; + m_variable7C = variable7C; + m_radiusSqr = radius * radius; +} + +// ELF 0x1EAA20 (D1; D0 0x1EAA70): the Aimer and the base only. +BAPConSplashDamage::~BAPConSplashDamage() +{ +} + +// ELF 0x1EA360. Casts the shot along the weapon's projectile-origin row 2 out to the target's last +// seen position + 5 m, ignoring the bot's own object. True when it hits within the radius of the +// target point and no soldier of the bot's side stands within the radius of the hit (|dy| < 2.5). +// Without the target information or its sensed record: false. Every other false answer stamps +// BotMain::setTimeOfLastFailedSplashDamageAttack(now). The bot's information and its weapon are +// not null-checked. +bool BAPConSplashDamage::evaluate(Bot* bot) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!bapinline::info(m_object)) + return false; + SensedObject* sensed = bot->getSensedObjectFromHandle(m_object); + if (!sensed) + return false; + + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3 from = bapinline::vec3(origin.m[12], origin.m[13], origin.m[14]); + const Vec3 d = bapinline::sub(sensed->m_lastSeenPosition, from); + const float reach = std::sqrt(d.z * d.z + d.x * d.x + d.y * d.y) + 5.0f; + const Vec3 to = bapinline::vec3(origin.m[8] * reach + origin.m[12], origin.m[9] * reach + origin.m[13], + reach * origin.m[10] + origin.m[14]); + Vec3 hit = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (bapinline::collideLineIgnoring(from, to, self->getAIObject(), hit)) { + const std::vector& players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + bool friendlyInSplash = false; + for (unsigned int i = 0; i < players.size() && !friendlyInSplash; ++i) { + IAIPlayer* player = players[i]; + if (!player || player->getSide() != bot->getSide()) + continue; + IAIObject* vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); + if (info && (info->getObjectTypeFlags() & 0x200000u) && std::fabs(info->getPosition().y - hit.y) < 2.5f) { + const Vec3& p = info->getPosition(); + if ((hit.z - p.z) * (hit.z - p.z) + (hit.x - p.x) * (hit.x - p.x) + (hit.y - p.y) * (hit.y - p.y) + < m_radiusSqr) + friendlyInSplash = true; + } + } + if (!friendlyInSplash) { + const Vec3& t = m_targetPoint->m_value; + const float dx = t.x - hit.x; + const float dy = t.y - hit.y; + const float dz = t.z - hit.z; + if (dx * dx + dy * dy + dz * dz < m_radiusSqr) + return true; + } + } + static_cast(bot)->setTimeOfLastFailedSplashDamageAttack(bapinline::gameTime()); + return false; +} + +// ELF 0x1EA960 +BAPConditionType BAPConSplashDamage::getConditionType() const +{ + return BAPCTSplashDamage; // 57 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h new file mode 100644 index 000000000..2db68ce74 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h @@ -0,0 +1,44 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSPLASHDAMAGE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSPLASHDAMAGE_H + +#include "../../../../Math/Vec3.h" +#include "BAPConObject.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "../AIBot/Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9448 (5 words), operator new 0x84, package C-actions. +class BAPConSplashDamage : public BAPConObject +{ +public: + BAPConSplashDamage(unsigned int, BAPVariable*, BAPVariable*, float); // 0x1EA2F0 + virtual ~BAPConSplashDamage(); // 0x1EAA20 + + virtual bool evaluate(Bot*); // 0x1EA360, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EA960, slot +0x04; from the base declaration + +private: + /* +0x0C */ Aimer m_aimer; // only its drag/speed/gravity are set (evaluate) + /* +0x78 */ BAPVariable* m_targetPoint; // the impact must land within the radius of it + /* +0x7C */ BAPVariable* m_variable7C; // [UNRESOLVED] stored, not read by evaluate + /* +0x80 */ float m_radiusSqr; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSPLASHDAMAGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp new file mode 100644 index 000000000..6a1ce8ea7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp @@ -0,0 +1,49 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1EAC00 (__tcf_0 0x1EAC60, _GLOBAL__I 0x1EAC90): 's Init object only. +#include + +#include "BAPConStrategicObjectStatus.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIStrategicEntity/AIStrategicObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EAB00 (C1) +BAPConStrategicObjectStatus::BAPConStrategicObjectStatus(AIStrategicObject* object, int side, bool zero) +{ + m_object = object; + m_side = side; + m_zero = zero; +} + +// ELF 0x1EAB90 (D0 0x1EABB0): base only. +BAPConStrategicObjectStatus::~BAPConStrategicObjectStatus() +{ +} + +// ELF 0x1EAB40: `object->+0x70 + 4 * side` (AIStrategicObject::getStatus(side), 1-based side). +bool BAPConStrategicObjectStatus::evaluate(Bot*) +{ + const int status = static_cast(m_object->getStatus(m_side)); + return m_zero ? status == 0 : status != 0; +} + +// ELF 0x1EABF0 +BAPConditionType BAPConStrategicObjectStatus::getConditionType() const +{ + return BAPCTStrategicObjectStatus; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.h new file mode 100644 index 000000000..53767b5c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSTRATEGICOBJECTSTATUS_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSTRATEGICOBJECTSTATUS_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class Bot; + +// ELF: vtable 0x4B9470 (5 words), operator new 0x14, package C-actions. +// A strategic object's status for one side is non-zero (or, with the flag, zero). +class BAPConStrategicObjectStatus : public BAPCondition +{ +public: + BAPConStrategicObjectStatus(AIStrategicObject*, int, bool); // 0x1EAB00 + virtual ~BAPConStrategicObjectStatus(); // 0x1EAB90 + + virtual bool evaluate(Bot*); // 0x1EAB40, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EABF0, slot +0x04; from the base declaration + +private: + /* +0x08 */ AIStrategicObject* m_object; + /* +0x0C */ int m_side; // 1-based + /* +0x10 */ bool m_zero; // true: "status is 0", false: "status is not 0" +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONSTRATEGICOBJECTSTATUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp new file mode 100644 index 000000000..736933d15 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp @@ -0,0 +1,53 @@ +// BAPConTime: recovered by package A-core from libaidll.so (TU without a FILE symbol, +// 0x1EACB0..0x1EAEF0). Every body carries its ELF address. + +#include "BAPConTime.h" + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EACB0 (C2; C1 0x1EAD50). The deadline is a double: -1.0f widened, or now + duration. +BAPConTime::BAPConTime(double duration, bool flag19, bool armed, bool fireFirst) +{ + if (fireFirst) + m_deadline = -1.0f; + else + m_deadline = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime() + duration; + m_duration = duration; + m_armed = armed || fireFirst; + m_flag19 = flag19; +} + +// ELF 0x1EADF0 (D2/D1; D0 0x1EAE30): the vptr store only. +BAPConTime::~BAPConTime() +{ +} + +// ELF 0x1EAE70. `now < deadline` is the image's jb after fucomip (unordered: true -> not yet). +bool BAPConTime::evaluate(Bot*) +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!m_armed) + { + m_armed = true; + m_deadline = now + m_duration; + } + if (now < m_deadline) + return false; + m_armed = false; + return true; +} + +// ELF 0x1EAEE0. +BAPConditionType BAPConTime::getConditionType() const +{ + return BAPCTTime; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h new file mode 100644 index 000000000..d64cf47d0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTime.h @@ -0,0 +1,43 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTIME_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTIME_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9498 (5 words), operator new 0x18/0x1C, package A-core. +// True once the game time (IBFTimer::getGameTime, CommonSingletonServer::m_iBFTimer) reaches the +// deadline; then it re-arms: the next evaluate sets deadline = now + duration. sizeof 0x1C +// (`operator new(0x1C)`; 0x18 at other sites rounds the 0x1A of fields). +class BAPConTime : public BAPCondition +{ +public: + // fireFirst: the first evaluate is already true (deadline -1). armed (or fireFirst): the deadline + // counts from construction; otherwise from the first evaluate. + BAPConTime(double duration, bool flag19, bool armed, bool fireFirst); // 0x1EAD50 + virtual ~BAPConTime(); // 0x1EAE10 + + virtual bool evaluate(Bot*); // 0x1EAE70, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EAEE0, slot +0x04; from the base declaration + +private: + /* +0x08 */ double m_deadline; + /* +0x10 */ double m_duration; + /* +0x18 */ bool m_armed; // [INFERRED] name + /* +0x19 */ bool m_flag19; // first bool argument; no recovered function reads it [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTIME_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp new file mode 100644 index 000000000..8589befd3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp @@ -0,0 +1,63 @@ +// Condition: the object's ammunition, as the product of the fill fractions of its weapons, is at +// most a threshold. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body +// carries its ELF address. + +#include "BAPConTotalAmmo.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F1C30 (C1; C2 0x1F1BF0): +0x04 = 0 by the base, +0x08 = the object, +0x0C = threshold. +BAPConTotalAmmo::BAPConTotalAmmo(unsigned int object, float threshold) +{ + m_object = object; + m_threshold = threshold; +} + +// ELF 0x1F1E50 (D1; D2 0x1F1E30, D0 0x1F1E70): base only. +BAPConTotalAmmo::~BAPConTotalAmmo() +{ +} + +// ELF 0x1F1C70: false without information. Otherwise the object's weapon list is copied and every +// weapon that exists, is neither of type 1 nor 2, whose WeaponInfo slot +0x10 (getAmmo) is not -1 +// and whose maximum ammunition is not 0 multiplies the total (1 at first) by +// getCurrentAmmo / getMaxAmmo. True when the total is at most the threshold. +bool BAPConTotalAmmo::evaluate(Bot*) +{ + float total = 1.0f; + std::vector weapons; + Information* info = bapinline::info(m_object); + if (!info) + return false; + weapons = info->getArmament()->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon || weapon->getWeaponType() == 1 || weapon->getWeaponType() == 2 || weapon->getAmmo() == -1 + || weapon->getMaxAmmo() == 0) + continue; + const float current = static_cast(weapon->getCurrentAmmo()); + total *= current / static_cast(weapon->getMaxAmmo()); + } + return m_threshold >= total; +} + +// ELF 0x1F1EB0 +BAPConditionType BAPConTotalAmmo::getConditionType() const +{ + return BAPCTTotalAmmo; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.h new file mode 100644 index 000000000..44469d6fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.h @@ -0,0 +1,34 @@ +// Condition: the product of the object's ammunition fractions is at most a threshold. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTOTALAMMO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTOTALAMMO_H + +#include "BAPConObject.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9AA8 (5 words), operator new 0x10, package F-infantry. +class BAPConTotalAmmo : public BAPConObject +{ +public: + BAPConTotalAmmo(unsigned int, float); // 0x1F1C30 + virtual ~BAPConTotalAmmo(); // 0x1F1E50 + + virtual bool evaluate(Bot*); // 0x1F1C70, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F1EB0, slot +0x04; from the base declaration + +private: + /* +0x0C */ float m_threshold; // the constructor's float +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTOTALAMMO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp new file mode 100644 index 000000000..edf49a8e1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp @@ -0,0 +1,39 @@ +// Reads the borrowed triggerable's active-state byte without a null guard. + +// static init: ELF 0x1EB000 (__tcf_0 0x1EB060, _GLOBAL__I 0x1EB090): 's Init object only. +#include + +#include "BAPConTriggerableActive.h" + +#include "../../../../Game/Objects/Game/Triggerable.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1EAF20 (C1; C2 0x1EAEF0) +BAPConTriggerableActive::BAPConTriggerableActive(world::Triggerable* triggerable) + : m_triggerable(triggerable) +{ +} + +// ELF 0x1EAF90 (D1; D2 0x1EAF70, D0 0x1EAFB0) +BAPConTriggerableActive::~BAPConTriggerableActive() +{ +} + +// ELF 0x1EAF50 +bool BAPConTriggerableActive::evaluate(Bot*) +{ + return m_triggerable->m_bool16C; +} + +// ELF 0x1EAFF0 +BAPConditionType BAPConTriggerableActive::getConditionType() const +{ + return BAPCTTriggerableActive; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.h new file mode 100644 index 000000000..c4a6bad89 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.h @@ -0,0 +1,34 @@ +// Reads the borrowed triggerable's active-state byte without a null guard. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRIGGERABLEACTIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRIGGERABLEACTIVE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace world { class Triggerable; } +namespace ai { + +class Bot; + +// ELF: vtable 0x4B94E8 (5 words), operator new 0xC/0x2C, package F-infantry. +class BAPConTriggerableActive : public BAPCondition +{ +public: + explicit BAPConTriggerableActive(world::Triggerable*); // 0x1EAF20 + virtual ~BAPConTriggerableActive(); // 0x1EAF90 + + virtual bool evaluate(Bot*); // 0x1EAF50, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1EAFF0, slot +0x04; from the base declaration +private: + /* +0x08 */ world::Triggerable* m_triggerable; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRIGGERABLEACTIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp new file mode 100644 index 000000000..c290298a1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp @@ -0,0 +1,34 @@ +// BAPConTrue: recovered by ai-main from libaidll.so (0x1C18A0..0x1C1910; S0 skeleton file). +// Every body carries its ELF address. + +#include "BAPConTrue.h" + +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1C18C0 (D1, D0 0x1C18E0): only the vtable store of the (empty) BAPCondition base +// (GOT -0x1550 + 8); nothing of its own. +BAPConTrue::~BAPConTrue() +{ +} + +// ELF 0x1C18A0: `movl $0x1, %eax; ret`. +bool BAPConTrue::evaluate(Bot*) +{ + return true; +} + +// ELF 0x1C18B0: `movl $0x28, %eax; ret` (40 = BAPCTTrue). +BAPConditionType BAPConTrue::getConditionType() const +{ + return BAPCTTrue; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h new file mode 100644 index 000000000..198a92486 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.h @@ -0,0 +1,35 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRUE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRUE_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B7500 (5 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConTrue : public BAPCondition +{ +public: + virtual ~BAPConTrue(); // 0x1C18C0 + + virtual bool evaluate(Bot*); // 0x1C18A0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1C18B0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONTRUE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeapon.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeapon.h new file mode 100644 index 000000000..65ab83840 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeapon.h @@ -0,0 +1,34 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPON_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPON_H + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class WeaponInfo; +template class BAPVariable; + +class BAPConWeapon : public BAPCondition +{ +public: + // Inline in the image (no symbol); every subclass ctor stores the weapon variable at +0x08. + /* +0x08 */ BAPVariable* m_weapon; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPON_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp new file mode 100644 index 000000000..e61ebe1b2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F2260 (__tcf_0 0x1F22C0, _GLOBAL__I 0x1F22F0): 's Init object only. +#include + +#include "BAPConWeaponDetonatorIsActive.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F20E0 (C1) +BAPConWeaponDetonatorIsActive::BAPConWeaponDetonatorIsActive(BAPVariable* weapon) +{ + m_weapon = weapon; +} + +// ELF 0x1F2130 (D0 0x1F2150): base only. +BAPConWeaponDetonatorIsActive::~BAPConWeaponDetonatorIsActive() +{ +} + +// ELF 0x1F2190 +bool BAPConWeaponDetonatorIsActive::evaluate(Bot* bot) +{ + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* active = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + bool result = false; + if (m_weapon->m_value == active) + result = m_weapon->m_value->getWeaponState() == 1; + return result; +} + +// ELF 0x1F2250 +BAPConditionType BAPConWeaponDetonatorIsActive::getConditionType() const +{ + return BAPCTWeaponDetonatorIsActive; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.h new file mode 100644 index 000000000..3409fac87 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONDETONATORISACTIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONDETONATORISACTIVE_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9B08 (5 words), operator new 0xC, package C-actions. +// The variable's weapon is the active one and its weapon state is 1. +class BAPConWeaponDetonatorIsActive : public BAPConWeapon +{ +public: + explicit BAPConWeaponDetonatorIsActive(BAPVariable*); // 0x1F20E0 + virtual ~BAPConWeaponDetonatorIsActive(); // 0x1F2130 + + virtual bool evaluate(Bot*); // 0x1F2190, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2250, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONDETONATORISACTIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp new file mode 100644 index 000000000..0773fa002 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F24B0 (__tcf_0 0x1F2510, _GLOBAL__I 0x1F2540): 's Init object only. +#include + +#include "BAPConWeaponHasLockOnTarget.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2350 (C1) +BAPConWeaponHasLockOnTarget::BAPConWeaponHasLockOnTarget(BAPVariable* weapon, unsigned int unused) +{ + m_weapon = weapon; + m_unusedC = unused; +} + +// ELF 0x1F23B0 (D0 0x1F23D0): base only. +BAPConWeaponHasLockOnTarget::~BAPConWeaponHasLockOnTarget() +{ +} + +// ELF 0x1F2410: `getLockedTarget()->getInformation(bot->getSide())` (IAIObject +0xB8) resolves. +bool BAPConWeaponHasLockOnTarget::evaluate(Bot* bot) +{ + IAIObject* target = m_weapon->m_value->getLockedTarget(); + bool result = false; + if (target) + result = bapinline::info(target->getInformation(bot->getSide())) != 0; + return result; +} + +// ELF 0x1F24A0 +BAPConditionType BAPConWeaponHasLockOnTarget::getConditionType() const +{ + return BAPCTWeaponHasLockOnTarget; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h new file mode 100644 index 000000000..251ce7f32 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h @@ -0,0 +1,41 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHASLOCKONTARGET_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHASLOCKONTARGET_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9B68 (5 words), operator new 0xC/0x10, package C-actions. +// The weapon has locked a target whose information for the bot's side exists. +class BAPConWeaponHasLockOnTarget : public BAPConWeapon +{ +public: + BAPConWeaponHasLockOnTarget(BAPVariable*, unsigned int); // 0x1F2350 + virtual ~BAPConWeaponHasLockOnTarget(); // 0x1F23B0 + + virtual bool evaluate(Bot*); // 0x1F2410, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F24A0, slot +0x04; from the base declaration + +private: + /* +0x0C */ unsigned int m_unusedC; // the ctor's second argument; evaluate does not read it +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHASLOCKONTARGET_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp new file mode 100644 index 000000000..c651f73b2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp @@ -0,0 +1,62 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPConWeaponHeat.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F25A0 (C1): one limit for both. +BAPConWeaponHeat::BAPConWeaponHeat(BAPVariable* weapon, float limit) +{ + m_overheat = limit; + m_cooled = limit; + m_weapon = weapon; + m_overheated = false; +} + +// ELF 0x1F2620 (C1) +BAPConWeaponHeat::BAPConWeaponHeat(BAPVariable* weapon, float overheat, float cooled) +{ + m_weapon = weapon; + m_overheat = overheat; + m_overheated = false; + m_cooled = cooled; +} + +// ELF 0x1F2680 (D0 0x1F26A0) +BAPConWeaponHeat::~BAPConWeaponHeat() +{ +} + +// ELF 0x1F26E0: WeaponInfo::getHeat (+0x24). +bool BAPConWeaponHeat::evaluate(Bot*) +{ + if (!m_overheated) { + if (m_overheat <= m_weapon->m_value->getHeat()) { + m_overheated = true; + return false; + } + } else { + if (m_cooled < m_weapon->m_value->getHeat()) + return false; + m_overheated = false; + } + return true; +} + +// ELF 0x1F2750 +BAPConditionType BAPConWeaponHeat::getConditionType() const +{ + return BAPCTWeaponHeat; // 46 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.h new file mode 100644 index 000000000..795d26681 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.h @@ -0,0 +1,45 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHEAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHEAT_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9BC8 (5 words), operator new 0x18, package C-actions. +// Heat hysteresis: false once the heat reaches the upper limit, true again once it +// falls to the lower limit. +class BAPConWeaponHeat : public BAPConWeapon +{ +public: + BAPConWeaponHeat(BAPVariable*, float); // 0x1F25A0 + BAPConWeaponHeat(BAPVariable*, float, float); // 0x1F2620 + virtual ~BAPConWeaponHeat(); // 0x1F2680 + + virtual bool evaluate(Bot*); // 0x1F26E0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2750, slot +0x04; from the base declaration + +private: + /* +0x0C */ float m_overheat; // becomes "overheated" at heat >= this + /* +0x10 */ float m_cooled; // and recovers at heat <= this + /* +0x14 */ bool m_overheated; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONHEAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp new file mode 100644 index 000000000..cdd34ec62 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp @@ -0,0 +1,50 @@ +// Condition: the plan's weapon variable holds the bot's active weapon. Recovered from libaidll.so +// (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x1F2900 (__tcf_0 0x1F2960, _GLOBAL__I 0x1F2990): 's Init object only. +#include + +#include "BAPConWeaponIsActive.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2790 (C1; C2 0x1F2760): +0x04 = 0 by the base, +0x08 = the weapon variable. +BAPConWeaponIsActive::BAPConWeaponIsActive(BAPVariable* weapon) +{ + m_weapon = weapon; +} + +// ELF 0x1F27E0 (D1; D2 0x1F27C0, D0 0x1F2800): base only. +BAPConWeaponIsActive::~BAPConWeaponIsActive() +{ +} + +// ELF 0x1F2840: true when the variable's weapon is the WeaponInfo of the active weapon of the +// bot's current equipment. The equipment information is not null-checked, and the active weapon +// handle is fetched once without use before the compared fetch; as compiled. +bool BAPConWeaponIsActive::evaluate(Bot* bot) +{ + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* active = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + return m_weapon->m_value == active; +} + +// ELF 0x1F28F0 +BAPConditionType BAPConWeaponIsActive::getConditionType() const +{ + return BAPCTWeaponIsActive; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.h new file mode 100644 index 000000000..e571822e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.h @@ -0,0 +1,33 @@ +// Condition: the plan weapon variable holds the active weapon. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISACTIVE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISACTIVE_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9C28 (5 words), operator new 0x8/0xC, package F-infantry. +class BAPConWeaponIsActive : public BAPConWeapon +{ +public: + explicit BAPConWeaponIsActive(BAPVariable*); // 0x1F2790 + virtual ~BAPConWeaponIsActive(); // 0x1F27E0 + + virtual bool evaluate(Bot*); // 0x1F2840, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F28F0, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISACTIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp new file mode 100644 index 000000000..ce2264f2d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp @@ -0,0 +1,51 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F2B50 (__tcf_0 0x1F2BB0, _GLOBAL__I 0x1F2BE0): 's Init object only. +#include + +#include "BAPConWeaponIsZoomed.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F29E0 (C1) +BAPConWeaponIsZoomed::BAPConWeaponIsZoomed() +{ + setOwner(0); +} + +// ELF 0x1F2A30 (D0 0x1F2A50) +BAPConWeaponIsZoomed::~BAPConWeaponIsZoomed() +{ +} + +// ELF 0x1F2A90: the active weapon of the bot's current vehicle/soldier. The image calls +// getWeapon(getActiveWeapon()) twice and drops the first result; both calls are kept. The +// information and its armament are not null-checked. +bool BAPConWeaponIsZoomed::evaluate(Bot* bot) +{ + Information* info = bapinline::info(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + const unsigned int weapon = armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* weaponInfo = WeaponInfoManager::m_instance->getInformation(weapon); + return weaponInfo ? weaponInfo->isZoomed() : false; +} + +// ELF 0x1F2B40 +BAPConditionType BAPConWeaponIsZoomed::getConditionType() const +{ + return BAPCTWeaponIsZoomed; // 52 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.h new file mode 100644 index 000000000..caf0dd286 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISZOOMED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISZOOMED_H + +#include "BAPCondition.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4B9C88 (5 words), operator new 0x8/0xC, package C-actions. +// No data (operator new 8). +class BAPConWeaponIsZoomed : public BAPCondition +{ +public: + BAPConWeaponIsZoomed(); // 0x1F29E0 + virtual ~BAPConWeaponIsZoomed(); // 0x1F2A30 + + virtual bool evaluate(Bot*); // 0x1F2A90, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2B40, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONISZOOMED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp new file mode 100644 index 000000000..be4d80ba9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp @@ -0,0 +1,61 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +#include "BAPConWeaponMagAmmo.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2C40 (C1) +BAPConWeaponMagAmmo::BAPConWeaponMagAmmo(BAPVariable* weapon, BAPVariable* count, bool notEqual) +{ + m_weapon = weapon; + m_notEqual = notEqual; + m_count = count; +} + +// ELF 0x1F2D80 (D0 0x1F2DA0) +BAPConWeaponMagAmmo::~BAPConWeaponMagAmmo() +{ +} + +// ELF 0x1F2C80. Default form: no mags left counts as true, otherwise shots in mag <= n. The +// flag form: no mags: n != 0; negative mags: false; else shots in mag != n. Every getter call of +// the image is kept. +bool BAPConWeaponMagAmmo::evaluate(Bot*) +{ + WeaponInfo* weapon = m_weapon->m_value; + if (!m_notEqual) { + bool result = false; + if (weapon->getNumberOfMags() >= 0) { + result = true; + if (weapon->getNumberOfMags() != 0) { + result = false; + if (weapon->getShotsInMag(0) >= 0) + result = weapon->getShotsInMag(0) <= m_count->m_value; + } + } + return result; + } + if (weapon->getNumberOfMags() == 0) + return m_count->m_value != 0; + if (weapon->getNumberOfMags() < 0) + return false; + return weapon->getShotsInMag(0) != m_count->m_value; +} + +// ELF 0x1F2DE0 +BAPConditionType BAPConWeaponMagAmmo::getConditionType() const +{ + return BAPCTWeaponMagAmmo; // 41 +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.h new file mode 100644 index 000000000..f79a6a6dd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONMAGAMMO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONMAGAMMO_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9CE8 (5 words), operator new 0x14, package C-actions. +// Magazine test against an int variable (getNumberOfMags +0x18, getShotsInMag(0) +0x0C). +class BAPConWeaponMagAmmo : public BAPConWeapon +{ +public: + BAPConWeaponMagAmmo(BAPVariable*, BAPVariable*, bool); // 0x1F2C40 + virtual ~BAPConWeaponMagAmmo(); // 0x1F2D80 + + virtual bool evaluate(Bot*); // 0x1F2C80, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2DE0, slot +0x04; from the base declaration + +private: + /* +0x0C */ bool m_notEqual; // the ctor's bool: "shots in mag != n" form; [INFERRED] name + /* +0x10 */ BAPVariable* m_count; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONMAGAMMO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp new file mode 100644 index 000000000..795c0ab33 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp @@ -0,0 +1,52 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F2F90 (__tcf_0 0x1F2FF0, _GLOBAL__I 0x1F3020): 's Init object only. +#include + +#include "BAPConWeaponReadyToFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F2E20 (C1) +BAPConWeaponReadyToFire::BAPConWeaponReadyToFire(BAPVariable* weapon) +{ + m_weapon = weapon; +} + +// ELF 0x1F2E70 (D0 0x1F2E90): base only. +BAPConWeaponReadyToFire::~BAPConWeaponReadyToFire() +{ +} + +// ELF 0x1F2ED0 (getWeapon(getActiveWeapon()) is called twice, the first result dropped). +bool BAPConWeaponReadyToFire::evaluate(Bot* bot) +{ + IPIArmament* armament = bapinline::info(bot->getCurrentEquipment())->getArmament(); + armament->getWeapon(armament->getActiveWeapon()); + WeaponInfo* active = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + bool result = false; + WeaponInfo* weapon = m_weapon->m_value; + if (weapon == active) + result = weapon->isReadyToFire(); + return result; +} + +// ELF 0x1F2F80 +BAPConditionType BAPConWeaponReadyToFire::getConditionType() const +{ + return BAPCTWeaponReadyToFire; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.h new file mode 100644 index 000000000..6cb0e8d32 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONREADYTOFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONREADYTOFIRE_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9D48 (5 words), operator new 0xC, package C-actions. +// The variable's weapon is the active one of the bot's current vehicle/soldier and is ready to fire. +class BAPConWeaponReadyToFire : public BAPConWeapon +{ +public: + explicit BAPConWeaponReadyToFire(BAPVariable*); // 0x1F2E20 + virtual ~BAPConWeaponReadyToFire(); // 0x1F2E70 + + virtual bool evaluate(Bot*); // 0x1F2ED0, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F2F80, slot +0x04; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONREADYTOFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp new file mode 100644 index 000000000..f484120e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp @@ -0,0 +1,98 @@ +// Weapon-target reachability recovered from libaidll.so. +// static init: ELF 0x1F3910 (__tcf_0 0x1F3970, _GLOBAL__I 0x1F39A0): 's Init object only. +#include +#include "BAPConWeaponTargetReachable.h" +#include "BAPActionInline.h" +#include "../AIBot/Aimer.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F30B0 (C1; C2 0x1F3040) +BAPConWeaponTargetReachable::BAPConWeaponTargetReachable(BAPVariable* position, + BAPVariable* weapon, BAPVariable* target) + : m_target(target), m_position(position) +{ + m_weapon = weapon; + m_aimer = new Aimer; +} + +// ELF 0x1F3180 (D1; D2 0x1F3120, D0 0x1F31E0) +BAPConWeaponTargetReachable::~BAPConWeaponTargetReachable() +{ + delete m_aimer; +} + +// ELF 0x1F3250 +bool BAPConWeaponTargetReachable::evaluate(Bot* bot) +{ + static Vec3 zero = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_weapon || !m_weapon->m_value) + return false; + WeaponInfo* weapon = m_weapon->m_value; + Information* target = bapinline::info(m_target->m_value); + if (!target) + return false; + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (!self) + return false; + IPIMobile* mobile = target->getMobile(); + Vec3 targetPosition = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (mobile) + mobile->getPositionEstimate(targetPosition); + else + targetPosition = target->getPosition(); + Vec3 relative = bapinline::sub(targetPosition, self->getPosition()); + if (!bot->getSensedObjectFromHandle(m_target->m_value)) + return false; + const bool thrown = weapon->getIsThrown(); + weapon->getExplosionRadius(); + const Mat4& origin = weapon->getProjectileOrigin(); + m_aimer->m_speed = weapon->getExitVelocity(); + m_aimer->m_drag = weapon->getDrag(); + m_aimer->m_inverseDrag = m_aimer->m_drag != 0.0f ? 1.0f / m_aimer->m_drag : 0.0f; + const float gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity(); + m_aimer->m_gravity = weapon->getGravityModifier() * gravity; + if (thrown) { + Vec3 direction = bapinline::vec3(0.0f, 0.0f, 0.0f); + const double time = bapinline::gameTime(); + relative = bapinline::sub(targetPosition, self->getPosition()); + Vec3 shooterVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + m_aimer->setTargetData(relative, zero, shooterVelocity, &origin, time); + Vec3 aimPoint = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!m_aimer->getFiringDirection(time, 0.5f, true, direction, aimPoint, 0)) + return false; + bapinline::normalize(direction); + const float speed = weapon->getExitVelocity(); + direction.x *= speed; + direction.y *= speed; + direction.z *= speed; + const double extreme = m_aimer->getVerticalExtreme(); + const Vec3& position = self->getPosition(); + const float travelTime = static_cast(extreme); + Vec3 trajectory = bapinline::vec3(direction.x * travelTime + position.x, + direction.y * travelTime + position.y, direction.z * travelTime + position.z); + const float acceleration = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity(); + trajectory.y += acceleration * static_cast(extreme * extreme * 0.5); + (void)trajectory; + } + // shipped defect: the calculated trajectory is discarded and the output is the shooter's position. + m_position->m_value = self->getPosition(); + return true; +} + +// ELF 0x1F3900 +BAPConditionType BAPConWeaponTargetReachable::getConditionType() const +{ + return BAPCTWeaponTargetReachable; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.h new file mode 100644 index 000000000..08eaee3e3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.h @@ -0,0 +1,39 @@ +// Weapon/target reachability condition with an owned ballistic aimer and a position output. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTARGETREACHABLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTARGETREACHABLE_H + +#include "../../../../Math/Vec3.h" +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Aimer; +class WeaponInfo; + +// ELF: vtable 0x4B9DA8 (5 words), package H-deferred. +class BAPConWeaponTargetReachable : public BAPConWeapon +{ +public: + BAPConWeaponTargetReachable(BAPVariable*, BAPVariable*, BAPVariable*); // 0x1F30B0 + virtual ~BAPConWeaponTargetReachable(); // 0x1F3180 + + virtual bool evaluate(Bot*); // 0x1F3250, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F3900, slot +0x04; from the base declaration +private: + /* +0x0C */ BAPVariable* m_target; + /* +0x10 */ BAPVariable* m_position; + /* +0x14 */ Aimer* m_aimer; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTARGETREACHABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp new file mode 100644 index 000000000..69b9bc997 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp @@ -0,0 +1,40 @@ +// Compares current weapon ammunition with a plan variable using != or <=. + +#include "BAPConWeaponTotalAmmo.h" + +#include "../AIKnowledge/WeaponInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F3A00 (C1; C2 0x1F39C0) +BAPConWeaponTotalAmmo::BAPConWeaponTotalAmmo(BAPVariable* weapon, + BAPVariable* ammo, bool notEqual) : m_notEqual(notEqual), m_ammo(ammo) +{ + m_weapon = weapon; +} + +// ELF 0x1F3AA0 (D1; D2 0x1F3A80, D0 0x1F3AC0) +BAPConWeaponTotalAmmo::~BAPConWeaponTotalAmmo() +{ +} + +// ELF 0x1F3A40 +bool BAPConWeaponTotalAmmo::evaluate(Bot*) +{ + const int ammo = m_weapon->m_value->getCurrentAmmo(); + if (m_notEqual) + return ammo != m_ammo->m_value; + return ammo <= m_ammo->m_value; +} + +// ELF 0x1F3B00 +BAPConditionType BAPConWeaponTotalAmmo::getConditionType() const +{ + return BAPCTWeaponTotalAmmo; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.h new file mode 100644 index 000000000..c97033643 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.h @@ -0,0 +1,36 @@ +// Compares current weapon ammunition with a plan variable using != or <=. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTOTALAMMO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTOTALAMMO_H + +#include "BAPConWeapon.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4B9E08 (5 words), package H-deferred. +class BAPConWeaponTotalAmmo : public BAPConWeapon +{ +public: + BAPConWeaponTotalAmmo(BAPVariable*, BAPVariable*, bool); // 0x1F3A00 + virtual ~BAPConWeaponTotalAmmo(); // 0x1F3AA0 + + virtual bool evaluate(Bot*); // 0x1F3A40, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const; // 0x1F3B00, slot +0x04; from the base declaration +private: + /* +0x0C */ bool m_notEqual; + /* +0x10 */ BAPVariable* m_ammo; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONWEAPONTOTALAMMO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp new file mode 100644 index 000000000..5a9893979 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp @@ -0,0 +1,38 @@ +// BAPCondition: recovered by package A-core from libaidll.so (TU BAPCondition.cpp, 0x1F8090..0x1F8210). +// Every body carries its ELF address. + +// static init: ELF 0x1F8100 (__tcf_0 0x1F8160, _GLOBAL__I 0x1F8190): 's Init object only. +#include + +#include "BAPCondition.h" +#include "../Main/AIStreamOperators.h" + + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F81F0 (D1; D0 0x1F81B0): the vptr store only. +BAPCondition::~BAPCondition() +{ +} + +// ELF 0x1F8090: os << getConditionType() (slot +4) with operator<<(ostream&, BAPConditionType) +// 0x3C7AE0 (Main/AIStreamOperators.cpp). No endl. Only plan dumps reach it. +void BAPCondition::streamSelf(std::ostream& os) const +{ + os << getConditionType(); +} + +// ELF 0x1F80D0. +std::ostream& operator<<(std::ostream& os, const BAPCondition& condition) +{ + condition.streamSelf(os); + return os; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h new file mode 100644 index 000000000..6bdd70e81 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h @@ -0,0 +1,52 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDITION_H + +#include +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// Condition base. Vtable 0x4BA1C8: evaluate, getConditionType, streamSelf, D1, D0. +// ELF: vtable 0x4BA1C8 (5 words), package A-core. +class BAPCondition +{ +public: + BAPCondition() : m_owner(0) {} // inline in the image (BAPConAnd() 0x1F3D30 stores +4 = 0) + + virtual bool evaluate(Bot*) = 0; // no body, slot +0x00; from the base declaration + virtual BAPConditionType getConditionType() const = 0; // no body, slot +0x04; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F8090, slot +0x08; from the base declaration + virtual ~BAPCondition(); // 0x1F81F0 slots +0x0C/+0x10 + + // [INFERRED] inline (no symbol): statement constructors store themselves at +0x04 of their + // conditions (BAPALookAtObject 0x1D318B, BAPALookInDir 0x1D3AEB). + void setOwner(void* owner) { m_owner = owner; } + +protected: + // The owner: BAPFlowCEnd's constructor (0x1E3293) stores the owning statement here, + // BAPBoleanOp::addCondition (BAPConAnd 0x1F40CC) and the list constructors the owning condition. + // Mixed pointee types, so untyped. [INFERRED] name; public like BotScript::m_owner, because + // statements of other packages store it inline. [CHOSEN] visibility. +public: + /* +0x04 */ void* m_owner; +}; + +// ELF 0x1F80D0: condition.streamSelf(os) (slot +8); returns os. +std::ostream& operator<<(std::ostream& os, const BAPCondition& condition); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConnectedCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConnectedCondition.h new file mode 100644 index 000000000..70e4cc004 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConnectedCondition.h @@ -0,0 +1,29 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNECTEDCONDITION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNECTEDCONDITION_H + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPConnectedCondition : public BAPCondition +{ +public: +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPCONNECTEDCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPExpression.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPExpression.h new file mode 100644 index 000000000..7268ab7aa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPExpression.h @@ -0,0 +1,31 @@ +// Abstract expression interface used by the otherwise unconstructed expression paths. +// [INFERRED] Header placement beside BAPAEvaluate, whose constructor names this type. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPEXPRESSION_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPEXPRESSION_H + +namespace dice { +namespace hfe { +namespace ai { + +class BAPExpression +{ +public: + // Deletion calls ia-32 +0x04 at ELF 0x1D1E09/0x24B89D/0x24B8A7; + // amd-64 +0x08 at 0x23E32E/0x2A9870/0x2A985E establish the destructor pair. + // Neither image emits a BAPExpression constructor, destructor, vtable or descendant RTTI. + // Declaration only: there is no attested destructor body to implement. + virtual ~BAPExpression(); + + // [CHOSEN, not recovered] Name and void return under the unimplemented-slot exception. + // No vtable exists in either ELF. Calls at ia-32 0x1D1E91/0x24B7CD/0x24B7D7 + // (+0x08), amd-64 0x23E1DB/0x2A97D0/0x2A97C0 (+0x10), pass only this + // (stack / rdi) and discard the result. No expression instance is constructed. + virtual void unimplementedExpressionSlot2() = 0; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp new file mode 100644 index 000000000..a9c811cfe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp @@ -0,0 +1,96 @@ +// BAPFlowCEnd: recovered by package A-core from libaidll.so (TU without a FILE symbol, beside +// BAPFlowCIf.cpp; 0x1E3230..0x1E3550). Every body carries its ELF address. + +#include "BAPFlowCEnd.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E3230 (C2; C1 0x1E32A0). +BAPFlowCEnd::BAPFlowCEnd(int patternId, BAPFlowCEnd::EndType type, BAPCondition* condition) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_type(type) +{ + if (condition) + condition->m_owner = this; +} + +// ELF 0x1E3310 (D2; D1 0x1E3380, D0 0x1E33F0). The condition's deleting destructor is slot +0x10. +BAPFlowCEnd::~BAPFlowCEnd() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1E3460; the table is in the header. +bool BAPFlowCEnd::execute(Bot* bot, bool& ok, bool& finished) +{ + switch (static_cast(m_type)) + { + case 0: + if (m_condition == 0 || m_condition->evaluate(bot)) + { + finished = true; + ok = false; + } + else + { + finished = false; + ok = true; + } + break; + case 1: + if (m_condition == 0) + { + finished = true; + ok = false; + } + else + { + finished = m_condition->evaluate(bot); + ok = true; + } + break; + case 2: + if (m_condition == 0) + { + finished = false; + ok = false; + } + else + { + finished = !m_condition->evaluate(bot); + ok = true; + } + break; + default: + break; + } + return true; +} + +// ELF 0x1E3520. +unsigned long long BAPFlowCEnd::getControls() +{ + return 0; +} + +// ELF 0x1E3540. +BAPStatementType BAPFlowCEnd::getId() const +{ + return BAPSTPlanEnd; +} + +// ELF 0x1E3530. +bool BAPFlowCEnd::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h new file mode 100644 index 000000000..56e25a0a3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.h @@ -0,0 +1,46 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCEND_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCEND_H + +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// Plan end (execute 0x1E3460), by EndType (ok, finished): +// 0: condition true -> (false, true), false -> (true, false); no condition -> (false, true); +// 1: (true, condition); no condition -> (false, true); +// 2: (true, !condition); no condition -> (false, false); +// other values: neither flag is written. Always returns 1. +// The condition is owned. sizeof 0x1C. +// ELF: vtable 0x4B8EC0 (8 words), operator new 0x1C, package A-core. +class BAPFlowCEnd : public BAPFlowControl +{ +public: + enum EndType : int; // [UNRESOLVED] enumerators: values 0, 1, 2 are handled (see above) + BAPFlowCEnd(int patternId, BAPFlowCEnd::EndType type, BAPCondition* condition); // 0x1E32A0 + virtual ~BAPFlowCEnd(); // 0x1E3380 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E3460, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E3520, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E3540, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E3530, slot +0x14; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; // may be 0 + /* +0x18 */ EndType m_type; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCEND_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp new file mode 100644 index 000000000..d5aac4a7f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp @@ -0,0 +1,196 @@ +// BAPFlowCIf: recovered by package A-core from libaidll.so (TU BAPFlowCIf.cpp, 0x1E3550..0x1E3F80). +// Every body carries its ELF address. + +// static init: ELF 0x1E3E20 (__tcf_0 0x1E3E80, _GLOBAL__I 0x1E3EB0): 's Init object only. +#include + +#include "BAPFlowCIf.h" +#include +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" + +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E3550 (C2; C1 0x1E35F0). The condition's owner is set unconditionally, the branches' only +// when present. +BAPFlowCIf::BAPFlowCIf(BAPCondition* condition, BAPStatement* trueStatement, BAPStatement* falseStatement, + int patternId, bool reevaluate, bool keepElse) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_trueStatement(trueStatement) + , m_falseStatement(falseStatement) + , m_activeStatement(0) + , m_activeStatementDebug(0) + , m_reevaluate(reevaluate) + , m_keepElse(keepElse) +{ + condition->m_owner = this; + if (m_trueStatement) + m_trueStatement->m_owner = this; + if (m_falseStatement) + m_falseStatement->m_owner = this; +} + +// ELF 0x1E3690 (D2; D1 0x1E3720, D0 0x1E37B0). +BAPFlowCIf::~BAPFlowCIf() +{ + if (m_condition) + delete m_condition; + if (m_trueStatement) + delete m_trueStatement; + if (m_falseStatement) + delete m_falseStatement; +} + +// ELF 0x1E3850 (77 instructions); the rules are in the header. Always returns 1. +bool BAPFlowCIf::execute(Bot* bot, bool& ok, bool& finished) +{ + bool test; + if (!m_reevaluate) + test = (m_activeStatement == 0); + else if (m_keepElse && m_activeStatement == m_falseStatement) + test = (m_activeStatement == 0); + else + test = true; + + if (test) + { + m_activeStatement = m_condition->evaluate(bot) ? m_trueStatement : m_falseStatement; + m_activeStatementDebug = m_activeStatement; + if (m_activeStatement == 0) + { + ok = true; + finished = true; + return true; + } + } + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E38EA. + static_cast(bot)->getPlanInterpreter()->execute(m_activeStatement, bot, ok, finished); + if (finished) + m_activeStatement = 0; + return true; +} + +// ELF 0x1E3950: the union of both branches' controls. +unsigned long long BAPFlowCIf::getControls() +{ + unsigned long long controls = 0; + if (m_trueStatement) + controls = m_trueStatement->getControls(); + if (m_falseStatement) + controls |= m_falseStatement->getControls(); + return controls; +} + +// ELF 0x1E3F70 (emitted after the TU's initialiser). +BAPStatementType BAPFlowCIf::getId() const +{ + return BAPSTIf; +} + +// ELF 0x1E39B0. +bool BAPFlowCIf::hasDefault() +{ + return true; +} + +// ELF 0x1E3A10. +void BAPFlowCIf::debug(BotScriptDebugger::DebugLevel, std::string& text) +{ + if (m_activeStatementDebug == 0) + { + text = "If, now about to test condition..."; + return; + } + const std::string branch(m_activeStatementDebug == m_trueStatement ? "Then" : "Else"); + std::string line = "If, currently executing " + branch; + line.append(" block..."); + text = line; +} + +// ELF 0x1E3B60 (192 instructions). With +0x28 set, a tabulated "/*Force update*/" line first +// ("/*Force update, but freeze false-statement*/" with +0x29). Then tabulate, os << getId() << "(", +// "[true]"/"[false]" when a branch is active (+0x20 == +0x18 picks "[true]"), *condition when set, +// ")" endl; '{', the true branch one tab level deeper when set, '}'; and for a false branch +// (+0x1C) "else", '{', the branch one level deeper, '}', each on its own tabulated line. +void BAPFlowCIf::streamSelf(std::ostream& os) const +{ + IBotManager* const manager = IBotManager::instance; + if (m_reevaluate) + { + manager->tabulate(os); + os << (m_keepElse ? "/*Force update, but freeze false-statement*/" : "/*Force update*/") << std::endl; + } + manager->tabulate(os); + os << getId() << "("; + if (m_activeStatement) + os << (m_activeStatement == m_trueStatement ? "[true]" : "[false]"); + if (m_condition) + os << *m_condition; + os << ")" << std::endl; + manager->tabulate(os); + os << '{' << std::endl; + if (m_trueStatement) + { + manager->increaseTabLevel(); + os << *m_trueStatement; + manager->decreaseTabLevel(); + } + manager->tabulate(os); + os << '}' << std::endl; + if (m_falseStatement) + { + manager->tabulate(os); + os << "else" << std::endl; + manager->tabulate(os); + os << '{' << std::endl; + manager->increaseTabLevel(); + os << *m_falseStatement; + manager->decreaseTabLevel(); + manager->tabulate(os); + os << '}' << std::endl; + } +} + +// ELF 0x1E39C0. +BAPCondition* BAPFlowCIf::getCondition() const +{ + return m_condition; +} + +// ELF 0x1E39D0. +BAPStatement* BAPFlowCIf::getTrueStatement() const +{ + return m_trueStatement; +} + +// ELF 0x1E39E0. +BAPStatement* BAPFlowCIf::getFalseStatement() const +{ + return m_falseStatement; +} + +// ELF 0x1E39F0. +BAPStatement* BAPFlowCIf::getActiveStatement() const +{ + return m_activeStatement; +} + +// ELF 0x1E3A00. +BAPStatement* BAPFlowCIf::getActiveStatementDebug() const +{ + return m_activeStatementDebug; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h new file mode 100644 index 000000000..96ca2500b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.h @@ -0,0 +1,63 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCIF_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCIF_H + +#include +#include +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class BAPStatement; +class Bot; + +// If (execute 0x1E3850). Without reevaluate the condition is tested once, the chosen branch then +// runs until it reports finished, after which the next tick tests again. With reevaluate the +// condition is tested every tick (the branch may switch), except that with keepElse a running +// else-branch is kept until it finishes. A missing branch: ok = finished = true. The branch's +// finished drops it (the next tick tests again). Both branches and the condition are owned. +// sizeof 0x2C. +// ELF: vtable 0x4B8F40 (8 words), operator new 0x2C, package A-core. +class BAPFlowCIf : public BAPFlowControl +{ +public: + BAPFlowCIf(BAPCondition* condition, BAPStatement* trueStatement, BAPStatement* falseStatement, int patternId, + bool reevaluate, bool keepElse); // 0x1E35F0 + virtual ~BAPFlowCIf(); // 0x1E3720 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E3850, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E3950, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E3F70, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E39B0, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1E3A10, slot +0x18; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E3B60, slot +0x1C; from the base declaration + + BAPCondition* getCondition() const; // 0x1E39C0: +0x14 + BAPStatement* getTrueStatement() const; // 0x1E39D0: +0x18 + BAPStatement* getFalseStatement() const; // 0x1E39E0: +0x1C + BAPStatement* getActiveStatement() const; // 0x1E39F0: +0x20 + BAPStatement* getActiveStatementDebug() const; // 0x1E3A00: +0x24 + +private: + /* +0x14 */ BAPCondition* m_condition; + /* +0x18 */ BAPStatement* m_trueStatement; + /* +0x1C */ BAPStatement* m_falseStatement; + /* +0x20 */ BAPStatement* m_activeStatement; // 0 = test the condition next tick + /* +0x24 */ BAPStatement* m_activeStatementDebug; // last chosen branch, kept for debug()/streamSelf + /* +0x28 */ bool m_reevaluate; // [INFERRED] name + /* +0x29 */ bool m_keepElse; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCIF_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp new file mode 100644 index 000000000..1d0994646 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp @@ -0,0 +1,55 @@ +// BAPFlowCWait: recovered by package A-core from libaidll.so (TU without a FILE symbol, beside +// BAPFlowCIf.cpp; 0x1E3F80..0x1E4200). Every body carries its ELF address. + +#include "BAPFlowCWait.h" + +#include "BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E3F80 (C2; C1 0x1E3FF0). The condition's owner is set unconditionally. +BAPFlowCWait::BAPFlowCWait(BAPCondition* condition, int patternId) + : BAPFlowControl(patternId) + , m_condition(condition) +{ + condition->m_owner = this; +} + +// ELF 0x1E4060 (D2; D1 0x1E40C0, D0 0x1E4120). +BAPFlowCWait::~BAPFlowCWait() +{ + if (m_condition) + delete m_condition; +} + +// ELF 0x1E4190. +bool BAPFlowCWait::execute(Bot* bot, bool& ok, bool& finished) +{ + finished = m_condition->evaluate(bot); + ok = true; + return true; +} + +// ELF 0x1E41D0. +unsigned long long BAPFlowCWait::getControls() +{ + return 0; +} + +// ELF 0x1E41F0. +BAPStatementType BAPFlowCWait::getId() const +{ + return BAPSTWait; +} + +// ELF 0x1E41E0. +bool BAPFlowCWait::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h new file mode 100644 index 000000000..3021bb9e2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.h @@ -0,0 +1,39 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWAIT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWAIT_H + +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class Bot; + +// Wait (execute 0x1E4190): ok = true, finished = condition. The condition is owned. sizeof 0x18. +// ELF: vtable 0x4B8F80 (8 words), package A-core. +class BAPFlowCWait : public BAPFlowControl +{ +public: + BAPFlowCWait(BAPCondition* condition, int patternId); // 0x1E3FF0 + virtual ~BAPFlowCWait(); // 0x1E40C0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E4190, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E41D0, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E41F0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E41E0, slot +0x14; from the base declaration + +private: + /* +0x14 */ BAPCondition* m_condition; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWAIT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp new file mode 100644 index 000000000..fc44fb86e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp @@ -0,0 +1,155 @@ +// BAPFlowCWhile: recovered by package A-core from libaidll.so (TU BAPFlowCWhile.cpp, +// 0x1E4200..0x1E4910). Every body carries its ELF address. + +// static init: ELF 0x1E4850 (__tcf_0 0x1E48B0, _GLOBAL__I 0x1E48E0): 's Init object only. +#include + +#include "BAPFlowCWhile.h" +#include +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" + +#include "BAPCondition.h" +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1E4200 (C2; C1 0x1E4280). The condition's owner is set unconditionally, the body's only +// when present. +BAPFlowCWhile::BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, int patternId) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_loopStatement(loopStatement) + , m_break(false) + , m_testCondition(true) + , m_testOnFinish(true) +{ + condition->m_owner = this; + if (m_loopStatement) + m_loopStatement->m_owner = this; +} + +// ELF 0x1E4300 (C2; C1 0x1E4390). +BAPFlowCWhile::BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, bool testOnFinish, + int patternId) + : BAPFlowControl(patternId) + , m_condition(condition) + , m_loopStatement(loopStatement) + , m_break(false) + , m_testCondition(true) + , m_testOnFinish(testOnFinish) +{ + condition->m_owner = this; + if (m_loopStatement) + m_loopStatement->m_owner = this; +} + +// ELF 0x1E4420 (D2; D1 0x1E4490, D0 0x1E4500). +BAPFlowCWhile::~BAPFlowCWhile() +{ + if (m_condition) + delete m_condition; + if (m_loopStatement) + delete m_loopStatement; +} + +// ELF 0x1E4580 (82 instructions); the rules are in the header. Always returns 1. +bool BAPFlowCWhile::execute(Bot* bot, bool& ok, bool& finished) +{ + if (m_loopStatement == 0) + { + ok = true; + m_break = false; + finished = !m_condition->evaluate(bot); + return true; + } + + if (m_break) + { + ok = true; + finished = true; + m_break = false; + return true; + } + + if (m_testCondition && !m_condition->evaluate(bot)) + { + ok = true; + finished = true; + return true; + } + + // BotMain::getPlanInterpreter (non-virtual, 0x18A780) on the Bot*, call at 0x1E4616. + static_cast(bot)->getPlanInterpreter()->execute(m_loopStatement, bot, ok, finished); + if (m_testOnFinish) + m_testCondition = finished; + else + m_testCondition = true; + finished = false; + return true; +} + +// ELF 0x1E4690. +unsigned long long BAPFlowCWhile::getControls() +{ + if (m_loopStatement == 0) + return 0; + return m_loopStatement->getControls(); +} + +// ELF 0x1E4900 (emitted after the TU's initialiser). +BAPStatementType BAPFlowCWhile::getId() const +{ + return BAPSTWhile; +} + +// ELF 0x1E46C0. +bool BAPFlowCWhile::hasDefault() +{ + return true; +} + +// ELF 0x1E4700 (97 instructions): tabulate, os << getId() << "(" << *condition << ")" << endl (the +// condition is not null-checked), then '{', the body one tab level deeper when there is one +// (+0x18, 0x1E47CA), and '}', each on its own tabulated line. +void BAPFlowCWhile::streamSelf(std::ostream& os) const +{ + IBotManager* const manager = IBotManager::instance; + manager->tabulate(os); + os << getId() << "(" << *m_condition << ")" << std::endl; + manager->tabulate(os); + os << '{' << std::endl; + if (m_loopStatement) + { + manager->increaseTabLevel(); + os << *m_loopStatement; + manager->decreaseTabLevel(); + } + manager->tabulate(os); + os << '}' << std::endl; +} + +// ELF 0x1E46D0. +void BAPFlowCWhile::breakLoop() +{ + m_break = true; +} + +// ELF 0x1E46E0. +BAPCondition* BAPFlowCWhile::getCondition() +{ + return m_condition; +} + +// ELF 0x1E46F0. +BAPStatement* BAPFlowCWhile::getLoopStatement() +{ + return m_loopStatement; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h new file mode 100644 index 000000000..9054bb261 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.h @@ -0,0 +1,55 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWHILE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWHILE_H + +#include +#include "BAPFlowControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPCondition; +class BAPStatement; +class Bot; + +// While (execute 0x1E4580). Without a loop statement it reports ok and finished = !condition. +// Otherwise: breakLoop() ends it on the next tick (ok, finished); the condition is tested only +// when m_testCondition is set (always, or with testOnFinish only after the body reported +// finished) and a false condition ends it (ok, finished); else the body runs and the while itself +// reports not finished. Condition and body are owned. sizeof 0x20. +// ELF: vtable 0x4B9000 (8 words), operator new 0x8/0x20, package A-core. +class BAPFlowCWhile : public BAPFlowControl +{ +public: + BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, int patternId); // 0x1E4280 + BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatement, bool testOnFinish, int patternId); // 0x1E4390 + virtual ~BAPFlowCWhile(); // 0x1E4490 + + virtual bool execute(Bot*, bool&, bool&); // 0x1E4580, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1E4690, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1E4900, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1E46C0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1E4700, slot +0x1C; from the base declaration + + void breakLoop(); // 0x1E46D0: +0x1C = 1 + BAPCondition* getCondition(); // 0x1E46E0: +0x14 + BAPStatement* getLoopStatement(); // 0x1E46F0: +0x18 + +private: + /* +0x14 */ BAPCondition* m_condition; + /* +0x18 */ BAPStatement* m_loopStatement; + /* +0x1C */ bool m_break; // = false + /* +0x1D */ bool m_testCondition; // = true [INFERRED] name + /* +0x1E */ bool m_testOnFinish; // = true, or the bool argument [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCWHILE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowControl.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowControl.h new file mode 100644 index 000000000..64917c3eb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowControl.h @@ -0,0 +1,29 @@ +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. Every body carries its ELF address. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCONTROL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCONTROL_H + +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// Base of If/While/Wait/End: typeinfo only in the image (no vtable, no data; the derived +// constructors go straight from the BAPStatement vptr to their own). +// ELF: package A-core. +class BAPFlowControl : public BAPStatement +{ +protected: + BAPFlowControl() {} + explicit BAPFlowControl(int patternId) : BAPStatement(patternId) {} +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPFLOWCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp new file mode 100644 index 000000000..8702d7f63 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp @@ -0,0 +1,48 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F8540 (__tcf_0 0x1F85A0, _GLOBAL__I 0x1F85D0): 's Init object only. +#include + +#include "BAPICChangeVehicle.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F8490 (C1; C2 0x1F8440): +4/+8/+0xC = 0, +0x14 = the handle (+0x10 is not written). +BAPICChangeVehicle::BAPICChangeVehicle(unsigned int target) +{ + m_target = target; +} + +// ELF 0x1F85F0 (D0 0x1F8630): the inlined ~BAPStatement only. +BAPICChangeVehicle::~BAPICChangeVehicle() +{ +} + +// ELF 0x1F84E0: Bot vfn +0x1B8 (setChangeTarget) with +0x14; ok = finished = true. +bool BAPICChangeVehicle::execute(Bot* bot, bool& ok, bool& finished) +{ + bot->setChangeTarget(m_target); + ok = true; + finished = true; + return true; +} + +// ELF 0x1F8520 +BAPStatementType BAPICChangeVehicle::getId() const +{ + return BAPSTICChangeVehicle; // 29 +} + +// ELF 0x1F8530 +bool BAPICChangeVehicle::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.h new file mode 100644 index 000000000..93353e994 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.h @@ -0,0 +1,37 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICCHANGEVEHICLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICCHANGEVEHICLE_H + +#include "BAPInterruptControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA280 (8 words), operator new 0x18, package F-infantry. +// Interrupt control: hands the vehicle/seat handle to the bot (Bot::setChangeTarget, +0x1B8). +class BAPICChangeVehicle : public BAPInterruptControl +{ +public: + explicit BAPICChangeVehicle(unsigned int); // 0x1F8490 + virtual ~BAPICChangeVehicle(); // 0x1F85F0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F84E0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1F8520, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F8530, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_target; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICCHANGEVEHICLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp new file mode 100644 index 000000000..0a488a2c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp @@ -0,0 +1,48 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F8850 (__tcf_0 0x1F88B0, _GLOBAL__I 0x1F88E0): 's Init object only. +#include + +#include "BAPICTurnLock.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F86D0 (C1): base only, +0x10 untouched in the image (the shared base ctor zeroes it). +BAPICTurnLock::BAPICTurnLock(bool lock) +{ + m_lock = lock; +} + +// ELF 0x1F8760 (D0 0x1F87A0) +BAPICTurnLock::~BAPICTurnLock() +{ +} + +// ELF 0x1F87F0 +bool BAPICTurnLock::execute(Bot* bot, bool& ok, bool& failed) +{ + bot->setPlanLock(m_lock); + ok = true; + failed = true; + return true; +} + +// ELF 0x1F8830 +BAPStatementType BAPICTurnLock::getId() const +{ + return BAPSTICTurnLock; // 31 +} + +// ELF 0x1F8840 +bool BAPICTurnLock::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h new file mode 100644 index 000000000..e4412b4df --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICTURNLOCK_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICTURNLOCK_H + +#include "BAPInterruptControl.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA2C0 (8 words), operator new 0x18, package C-actions. +// Sets the bot's plan lock (Bot::setPlanLock, +0x6C). +class BAPICTurnLock : public BAPInterruptControl +{ +public: + explicit BAPICTurnLock(bool); // 0x1F86D0 + virtual ~BAPICTurnLock(); // 0x1F8760 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F87F0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1F8830, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F8840, slot +0x14; from the base declaration + +private: + /* +0x14 */ bool m_lock; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPICTURNLOCK_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp new file mode 100644 index 000000000..f96092e96 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp @@ -0,0 +1,92 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F6920 (__tcf_0 0x1F6980, _GLOBAL__I 0x1F69B0): 's Init object only. +#include + +#include "BAPIWChange.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F5A80 (C1; C2 0x1F59E0): BAPInfoWrapper(statement, patternId), +0x18 handle, +0x1C player id, +// then Information::bookVehicle(player id) on the handle's information (no null test), child +4 = this. +BAPIWChange::BAPIWChange(unsigned int target, BAPStatement* statement, int patternId, int playerId) + : BAPInfoWrapper(statement, patternId) +{ + m_target = target; + m_playerId = playerId; + bapinline::info(target)->bookVehicle(playerId); + m_statement->m_owner = this; +} + +// ELF 0x1F5FC0 (D1; D2 0x1F5B20, D0 0x1F6470). Cancels the booking; then, when the plan's bot +// (IBotManager::getBotFromPlayerId, +0x1C, no null test) now sits in the target: "requested" when the +// target's primary or one of its secondary seats has a player (getPlayerId >= 0) who sent message +// type 1 (receivedMessageExists) and the bot's primary is that primary; "seatsFree" starts as +// "the bot is not in the primary seat, the primary's unit is occupied, same primary" and stays set +// while no secondary seat is booked. The seat loop leaves as soon as requested && !seatsFree. +// Afterwards: seatsFree -> enqueueRadioMessage(11, 7, 3, 1.0f, -1), else requested -> (8, 7, 3, 1.0f, -1). +// Finally the child is deleted (vfn +8) and the base destructor runs. +BAPIWChange::~BAPIWChange() +{ + Information* target = bapinline::info(m_target); + if (target && target->isBooked()) + target->cancelBookVehicle(); + + Bot* bot = IBotManager::instance->getBotFromPlayerId(m_playerId); + CommunicationAgent* communication = bot->getCommunicationAgent(); + Information* equipment = bapinline::info(bot->getCurrentEquipment()); + if (target && equipment && m_target == bot->getCurrentEquipment()) { + bool requested = false; + Information* primary = bapinline::info(target->getPrimaryObject(bot->getSide())); + Information* equipmentPrimary = bapinline::info(equipment->getPrimaryObject(bot->getSide())); + int playerId = primary->getPlayerId(); + if (playerId >= 0 && communication->receivedMessageExists(static_cast(1), playerId) + && equipmentPrimary == primary) + requested = true; + bool seatsFree = false; + if (!equipment->isPrimary() && primary->getUnit()->isOccupied() && equipmentPrimary == primary) + seatsFree = true; + + int iterator; + Information* seat = bapinline::info(primary->getFirstSecondaryObject(iterator, bot->getSide())); + while (seat) { + playerId = seat->getPlayerId(); + if (playerId >= 0 && communication->receivedMessageExists(static_cast(1), playerId) + && equipmentPrimary == primary) + requested = true; + seatsFree = seatsFree && !seat->isBooked(); + if (requested && !seatsFree) + break; + seat = bapinline::info(primary->getSecondaryObject(iterator, bot->getSide())); + } + + if (seatsFree) + communication->enqueueRadioMessage(static_cast(11), static_cast(7), + 3, 1.0f, -1); + else if (requested) + communication->enqueueRadioMessage(static_cast(8), static_cast(7), + 3, 1.0f, -1); + } + + if (m_statement) + delete m_statement; +} + +// ELF 0x1F69D0: "Change" in infoTypes. +int BAPIWChange::getInfoType() const +{ + return 8; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h new file mode 100644 index 000000000..18538e421 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.h @@ -0,0 +1,38 @@ +// Package F (ai-w1-f-urgency): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWCHANGE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWCHANGE_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4B9FE0 (9 words), package F-infantry. +// Info wrapper of type "Change" (8): books the target vehicle/seat for the player while the plan +// lives; the destructor cancels the booking and radios the pickup result (messages 11 / 8). +class BAPIWChange : public BAPInfoWrapper +{ +public: + BAPIWChange(unsigned int, BAPStatement*, int, int); // 0x1F5A80 + virtual ~BAPIWChange(); // 0x1F5FC0 + + virtual int getInfoType() const; // 0x1F69D0, slot +0x20; from the base declaration + + unsigned int getTarget() const { return m_target; } // [CHOSEN] inline reader: BBPChange::createPlan reads +0x18 + +private: + /* +0x18 */ unsigned int m_target; // vehicle/seat information handle + /* +0x1C */ int m_playerId; // Bot::getPlayerId of the plan's bot +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWCHANGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp new file mode 100644 index 000000000..2035c011d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp @@ -0,0 +1,39 @@ +// Owns a mine-defusing plan and brackets its lifetime with the bot's firing/mine-target state. + +// static init: ELF 0x1F6C90 (__tcf_0 0x1F6CF0, _GLOBAL__I 0x1F6D20): 's Init object only. +#include + +#include "BAPIWDefuseMines.h" + +#include "../AIBot/BotMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F6A70 (C1; C2 0x1F69E0) +BAPIWDefuseMines::BAPIWDefuseMines(Bot* bot, unsigned int mine, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_mine(mine), m_bot(bot) +{ + m_statement->setParent(this); + bot->setIsFiring(true); + static_cast(m_bot)->setMineTarget(mine); +} + +// ELF 0x1F6B80 (D1; D2 0x1F6B00, D0 0x1F6C00) +BAPIWDefuseMines::~BAPIWDefuseMines() +{ + delete m_statement; + m_bot->setIsFiring(false); + static_cast(m_bot)->setMineTarget(0xFFFFFFFFu); +} + +// ELF 0x1F6D40 +int BAPIWDefuseMines::getInfoType() const +{ + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.h new file mode 100644 index 000000000..7c1f6309d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.h @@ -0,0 +1,35 @@ +// Owns a mine-defusing plan and brackets its lifetime with the bot's firing/mine-target state. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWDEFUSEMINES_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWDEFUSEMINES_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA020 (9 words), operator new 0x20, package F-infantry. +class BAPIWDefuseMines : public BAPInfoWrapper +{ +public: + BAPIWDefuseMines(Bot*, unsigned int, BAPStatement*, int); // 0x1F6A70 + virtual ~BAPIWDefuseMines(); // 0x1F6B80 + + virtual int getInfoType() const; // 0x1F6D40, slot +0x20; from the base declaration +private: + // [INFERRED] friendship for the inline mine reader in createPlan (ELF 0x243FB0). + friend class BBPDefuseMines; + /* +0x18 */ unsigned int m_mine; + /* +0x1C */ Bot* m_bot; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWDEFUSEMINES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp new file mode 100644 index 000000000..f73c25b61 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp @@ -0,0 +1,67 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F72F0 (__tcf_0 0x1F7350, _GLOBAL__I 0x1F7380): 's Init object only. +#include + +#include "BAPIWFire.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F6E20 (C1): Bot::setIsFiring(true) (+0x12C), setFiringTarget(target) (+0x7C), and +// BotMain::getUseStaticAttack (+0x288) is remembered. +BAPIWFire::BAPIWFire(Bot* bot, unsigned int target, bool flag24, bool flag25, int int1C, int int20, + BAPStatement* statement, int patternId) + : BAPInfoWrapper(statement, patternId) +{ + m_target = target; + m_int1C = int1C; + m_int20 = int20; + m_flag24 = flag24; + m_int28 = -1; + m_flag25 = flag25; + m_bot = bot; + m_statement->m_owner = this; + bot->setIsFiring(true); + bot->setFiringTarget(target); + m_useStaticAttack = static_cast(bot)->getUseStaticAttack(); +} + +// ELF 0x1F7040 (D1; D0 0x1F7190): deletes the child, then resets the bot (+0x12C, +0x1D0, +// +0x230, +0x1C0, +0x278, +0x7C) and clears the target player's bot "engineer target" flag (+0x1E8). +BAPIWFire::~BAPIWFire() +{ + if (m_statement) + delete m_statement; + BotMain* bot = static_cast(m_bot); + bot->setIsFiring(false); + bot->setBridgeRepairTarget(0xFFFFFFFFu); + bot->setBotIsSimulatingArtillery(false); + bot->setRepairTarget(0xFFFFFFFFu); + bot->setIsGoingForFlag(false); + bot->setFiringTarget(0xFFFFFFFFu); + if (m_target != 0xFFFFFFFFu) { + Information* info = bapinline::info(m_target); + if (info) { + Bot* other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); + if (other) + static_cast(other)->setIsEngineerTarget(false); + } + } +} + +// ELF 0x1F73A0: "Fire" +int BAPIWFire::getInfoType() const +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h new file mode 100644 index 000000000..f5fd5160b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.h @@ -0,0 +1,59 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWFIRE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWFIRE_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA060 (9 words), operator new 0x34, package C-actions. +// Fire info wrapper: marks the bot firing at the target for its lifetime and clears the +// bot's fire/repair/engineer state when the plan ends. +class BAPIWFire : public BAPInfoWrapper +{ +public: + BAPIWFire(Bot*, unsigned int, bool, bool, int, int, BAPStatement*, int); // 0x1F6E20 + virtual ~BAPIWFire(); // 0x1F7040 + + virtual int getInfoType() const; // 0x1F73A0, slot +0x20; from the base declaration + +public: + // [CHOSEN, not recovered] getters added by ai-w1-e-fire for BBPFireInfantery (inline in the image, + // createPlan 0x25F541..0x25F5D8); mapped onto the owner's (C) field names. + unsigned int getTarget() const { return m_target; } + int getWeapon() const { return m_int1C; } + bool getFlagA() const { return m_flag24; } + bool getUseStaticAttack() const { return m_useStaticAttack; } + // [CHOSEN, not recovered] accessors for BBPFire2dDriver::createPlan (0x24C100), which reads + // +0x25 and +0x28 and stores +0x28 inline (0x250D6C, 0x250D79, 0x24D4FC). + bool getFlagB() const { return m_flag25; } + int getInt28() const { return m_int28; } + void setInt28(int value) { m_int28 = value; } + +private: + /* +0x18 */ unsigned int m_target; + /* +0x1C */ int m_int1C; // ctor's first int (the weapon, per BBPFireInfantery); [UNRESOLVED] + /* +0x20 */ int m_int20; // ctor's second int; [UNRESOLVED] + /* +0x24 */ bool m_flag24; // ctor's first bool; [UNRESOLVED] + /* +0x25 */ bool m_flag25; // ctor's second bool; [UNRESOLVED] + /* +0x28 */ int m_int28; // = -1; [UNRESOLVED] + /* +0x2C */ Bot* m_bot; + /* +0x30 */ bool m_useStaticAttack; // BotMain::getUseStaticAttack at construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp new file mode 100644 index 000000000..67e5f6b5c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp @@ -0,0 +1,44 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F76E0 (__tcf_0 0x1F7740, _GLOBAL__I 0x1F7770): 's Init object only. +#include + +#include "BAPIWIdle.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7480 (C1; C2 0x1F7310 region) +BAPIWIdle::BAPIWIdle(const Vec3& position, BAPStatement* statement, int tag, Bot* bot) + : BAPInfoWrapper(statement, tag) +{ + m_position = position; + m_bot = bot; + if (bot && bot->getSquadMember()) + m_bot->getSquadMember()->setIsIdle(true); + m_statement->m_owner = this; +} + +// ELF 0x1F75D0 (D1; D2 0x1F7510 region, D0 0x1F7650): clears the idle flag, deletes the child +// (virtual D0, slot +8). +BAPIWIdle::~BAPIWIdle() +{ + if (m_bot && m_bot->getSquadMember()) + m_bot->getSquadMember()->setIsIdle(false); + if (m_statement) + delete m_statement; +} + +// ELF 0x1F7790: "Idle" +int BAPIWIdle::getInfoType() const +{ + return 4; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h new file mode 100644 index 000000000..593789c40 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWIDLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWIDLE_H + +#include "../../../../Math/Vec3.h" +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA0A0 (9 words), operator new 0x28, package C-actions. +// Idle info wrapper: marks the bot's squad member idle for its lifetime. +class BAPIWIdle : public BAPInfoWrapper +{ +public: + BAPIWIdle(const Vec3&, BAPStatement*, int, Bot*); // 0x1F7480 + virtual ~BAPIWIdle(); // 0x1F75D0 + + virtual int getInfoType() const; // 0x1F7790, slot +0x20; from the base declaration + +private: + /* +0x18 */ Vec3 m_position; + /* +0x24 */ Bot* m_bot; // may be null +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp new file mode 100644 index 000000000..37c522fee --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp @@ -0,0 +1,35 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F79A0 (__tcf_0 0x1F7A00, _GLOBAL__I 0x1F7A30): 's Init object only. +#include + +#include "BAPIWMoveTo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7820 (C1; C2 0x1F77A0 region) +BAPIWMoveTo::BAPIWMoveTo(const Vec3& position, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag) +{ + m_position = position; + m_statement->m_owner = this; +} + +// ELF 0x1F78F0 (D0 0x1F7940): deletes the child. +BAPIWMoveTo::~BAPIWMoveTo() +{ + if (m_statement) + delete m_statement; +} + +// ELF 0x1F7A50: "MoveTo" +int BAPIWMoveTo::getInfoType() const +{ + return 2; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h new file mode 100644 index 000000000..e453a9fd9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWMOVETO_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWMOVETO_H + +#include "../../../../Math/Vec3.h" +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4BA0E0 (9 words), operator new 0x24, package C-actions. +// MoveTo info wrapper; owns its child. +class BAPIWMoveTo : public BAPInfoWrapper +{ +public: + BAPIWMoveTo(const Vec3&, BAPStatement*, int); // 0x1F7820 + virtual ~BAPIWMoveTo(); // 0x1F78F0 + + virtual int getInfoType() const; // 0x1F7A50, slot +0x20; from the base declaration + + // [INFERRED] inline (no symbol): BBPGotoWaypointSoldier::createPlan 0x285E2F `fsubrs 0x18(%eax)` + // (and 0x2864F0) compares it with the new goal to keep the plan. + const Vec3& getPosition() const { return m_position; } + +private: + /* +0x18 */ Vec3 m_position; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp new file mode 100644 index 000000000..ad664551f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp @@ -0,0 +1,31 @@ +// Owns a roaming plan and retains its object handle. + +#include "BAPIWRoam.h" + + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7AC0 (C1; C2 0x1F7A60) +BAPIWRoam::BAPIWRoam(unsigned int object, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_object(object) +{ + m_statement->setParent(this); +} + +// ELF 0x1F7B70 (D1; D2 0x1F7B20, D0 0x1F7BC0) +BAPIWRoam::~BAPIWRoam() +{ + delete m_statement; +} + +// ELF 0x1F7C20 +int BAPIWRoam::getInfoType() const +{ + return 5; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h new file mode 100644 index 000000000..20a5a80d0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.h @@ -0,0 +1,33 @@ +// Owns a roaming plan and retains its object handle. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWROAM_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWROAM_H + +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4BA120 (9 words), operator new 0x1C, package H-deferred. +class BAPIWRoam : public BAPInfoWrapper +{ +public: + BAPIWRoam(unsigned int, BAPStatement*, int); // 0x1F7AC0 + virtual ~BAPIWRoam(); // 0x1F7B70 + + virtual int getInfoType() const; // 0x1F7C20, slot +0x20; from the base declaration +private: + // [INFERRED] friendship for createPlan's inline target reader (ELF 0x29BFD1). + friend class BBPRoam3d; + /* +0x18 */ unsigned int m_object; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWROAM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp new file mode 100644 index 000000000..2210cf1f6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp @@ -0,0 +1,47 @@ +// Owns a take-cover plan and stores either a fixed point or an object's initial position. + +// static init: ELF 0x1F7FD0 (__tcf_0 0x1F8030, _GLOBAL__I 0x1F8060): 's Init object only. +#include + +#include "BAPIWTakeCover.h" + +#include "BAPActionInline.h" +#include "../AIKnowledge/Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F7CB0 (C1; C2 0x1F7C30) +BAPIWTakeCover::BAPIWTakeCover(const Vec3& position, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_position(position), m_useObject(false) +{ + m_statement->setParent(this); +} + +// ELF 0x1F7E00 (C1; C2 0x1F7D30) +BAPIWTakeCover::BAPIWTakeCover(unsigned int object, BAPStatement* statement, int tag) + : BAPInfoWrapper(statement, tag), m_position(bapinline::vec3(0.0f, 0.0f, 0.0f)), + m_object(object), m_useObject(true) +{ + Information* information = bapinline::info(object); + if (information) + m_position = information->getPosition(); + m_statement->setParent(this); +} + +// ELF 0x1F7F20 (D1; D2 0x1F7ED0, D0 0x1F7F70) +BAPIWTakeCover::~BAPIWTakeCover() +{ + delete m_statement; +} + +// ELF 0x1F8080 +int BAPIWTakeCover::getInfoType() const +{ + return 7; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h new file mode 100644 index 000000000..a845be3f3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.h @@ -0,0 +1,40 @@ +// Owns a take-cover plan and stores either a fixed point or an object's initial position. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWTAKECOVER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWTAKECOVER_H + +#include "../../../../Math/Vec3.h" +#include "BAPInfoWrapper.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; + +// ELF: vtable 0x4BA160 (9 words), operator new 0x2C, package H-deferred. +class BAPIWTakeCover : public BAPInfoWrapper +{ +public: + BAPIWTakeCover(const Vec3&, BAPStatement*, int); // 0x1F7CB0 + BAPIWTakeCover(unsigned int, BAPStatement*, int); // 0x1F7E00 + virtual ~BAPIWTakeCover(); // 0x1F7F20 + + virtual int getInfoType() const; // 0x1F8080, slot +0x20; from the base declaration +private: + // [INFERRED] friendship for the inline +0x18/+0x24/+0x28 readers in BBPTakeCover::createPlan + // (ELF 0x29F98C, 0x29F9E3, 0x29FA73, 0x29FAE7, 0x29FB4F). + friend class BBPTakeCover; + // The infantry pattern repeats the same readers (ELF 0x2A664D, 0x2A669E, 0x2A6724). + friend class BBPTakeCoverInfantry; + /* +0x18 */ Vec3 m_position; + /* +0x24 */ unsigned int m_object; // initialized only by the object-taking constructor + /* +0x28 */ bool m_useObject; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPIWTAKECOVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp new file mode 100644 index 000000000..875ef2489 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp @@ -0,0 +1,85 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F5740 (__tcf_0 0x1F58D0, __tcf_1 0x1F5900, _GLOBAL__I 0x1F5970): 's Init object, then dice::hfe::ai::infoTypes. +#include + +#include "BAPInfoWrapper.h" + +#include "BAPActionInline.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x4CE220, built by the TU's static initialiser 0x1F5740 (destroyed by __tcf_1 0x1F5900). +std::string infoTypes[10] = { "Fire", "DefuseMines", "MoveTo", "Avoid", "Idle", "Roam", "Scout", + "TakeCover", "Change", "Default" }; + +// ELF 0x1F5470 (C1; C2 0x1F5410). The child's parent is set by the subclasses, not here. +BAPInfoWrapper::BAPInfoWrapper(BAPStatement* statement, int tag) +{ + m_controls = 0; + m_patternId = tag; + m_statement = statement; +} + +// ELF 0x1F5510 (D1; D2 0x1F54D0, D0 0x1F5550): base only, the child is not deleted here. +BAPInfoWrapper::~BAPInfoWrapper() +{ +} + +// ELF 0x1F55A0: `bot->getPlanInterpreter()->execute(child, bot, ok, failed)` (slot +8). +bool BAPInfoWrapper::execute(Bot* bot, bool& ok, bool& failed) +{ + PlanInterpreter* interpreter = static_cast(bot)->getPlanInterpreter(); + return interpreter->execute(m_statement, bot, ok, failed); +} + +// ELF 0x1F5990: the child's controls. +unsigned long long BAPInfoWrapper::getControls() +{ + return m_statement->getControls(); +} + +// ELF 0x1F59B0 +BAPStatementType BAPInfoWrapper::getId() const +{ + return BAPSTInfoWrapper; // 15 +} + +// ELF 0x1F59C0 +bool BAPInfoWrapper::hasDefault() +{ + return true; +} + +// ELF 0x1F5600 +void BAPInfoWrapper::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + const int type = getInfoType(); + out << "InfoWrapper(" << infoTypes[type] << ")" << std::endl; + IBotManager::instance->tabulate(out); + out << '{' << std::endl; + IBotManager::instance->increaseTabLevel(); + if (m_statement) + out << *m_statement; // operator<<(std::ostream&, const BAPStatement&) 0x1F82D0 + IBotManager::instance->decreaseTabLevel(); + IBotManager::instance->tabulate(out); + out << '}' << std::endl; +} + +// ELF 0x1F59D0: "Default" +int BAPInfoWrapper::getInfoType() const +{ + return 9; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h new file mode 100644 index 000000000..38fdf6fc9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.h @@ -0,0 +1,51 @@ +// Runs a child statement through the bot's interpreter and supplies a plan information type. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINFOWRAPPER_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINFOWRAPPER_H + +#include +#include +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// BSS 0x4CE220: "Fire", "DefuseMines", "MoveTo", "Avoid", "Idle", "Roam", "Scout", "TakeCover", +// "Change", "Default" (static initialiser 0x1F5740), indexed by getInfoType(). +extern std::string infoTypes[10]; + +// ELF: vtable 0x4B9F60 (9 words), package C-actions. +// Wraps one statement and tags it with an information type (getInfoType, an index into +// infoTypes); runs the child through the bot's plan interpreter. +class BAPInfoWrapper : public BAPStatement +{ +public: + BAPInfoWrapper(BAPStatement*, int); // 0x1F5470 + virtual ~BAPInfoWrapper(); // 0x1F5510 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F55A0, slot +0x00; from the base declaration + virtual unsigned long long getControls(); // 0x1F5990, slot +0x0C; from the base declaration + virtual BAPStatementType getId() const; // 0x1F59B0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F59C0, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F5600, slot +0x1C; from the base declaration + virtual int getInfoType() const; // 0x1F59D0, slot +0x20; [INFERRED] ELF int + + // [CHOSEN, not recovered] added by ai-w1-e-fire for BBPFireInfantery: inline in the image + // (createPlan reads +0x10, BAPStatement::m_patternId). + int getGeneratorId() const { return m_patternId; } + + /* +0x14 */ BAPStatement* m_statement; // the wrapped child; deleted by the subclasses' destructors + +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINFOWRAPPER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInterruptControl.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInterruptControl.h new file mode 100644 index 000000000..774434105 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPInterruptControl.h @@ -0,0 +1,29 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINTERRUPTCONTROL_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINTERRUPTCONTROL_H + +#include "BAPStatement.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: package C-actions. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BAPInterruptControl : public BAPStatement +{ +public: +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPINTERRUPTCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp new file mode 100644 index 000000000..0c995fc33 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp @@ -0,0 +1,47 @@ +// BAPStatement: recovered by package A-core from libaidll.so (TU BAPStatement.cpp, 0x1F8210..0x1F8440; +// getControls is weak at 0x1CDB10). Every body carries its ELF address. + +// static init: ELF 0x1F8300 (__tcf_0 0x1F8360, _GLOBAL__I 0x1F8390): 's Init object only. +#include + +#include "BAPStatement.h" +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" + + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +int BAPStatement::news = 0; +int BAPStatement::destroys = 0; + +// ~BAPStatement (0x1F83B0) and getControls (0x1CDB10) are weak in the image: inline in the header. + +// ELF 0x1F8210. +void BAPStatement::debug(BotScriptDebugger::DebugLevel, std::string& text) +{ + text = "Standard debug."; +} + +// ELF 0x1F8260: IBotManager::instance->tabulate(os) (+0x88), then os << getId() (slot +0x10) +// << endl with operator<<(ostream&, BAPStatementType) 0x3C7D90 (Main/AIStreamOperators.cpp). +void BAPStatement::streamSelf(std::ostream& os) const +{ + IBotManager::instance->tabulate(os); + os << getId() << std::endl; +} + +// ELF 0x1F82D0. +std::ostream& operator<<(std::ostream& os, const BAPStatement& statement) +{ + statement.streamSelf(os); + return os; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h new file mode 100644 index 000000000..446b87e6e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h @@ -0,0 +1,77 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPSTATEMENT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPSTATEMENT_H + +#include +#include +#include "../AIPlanInterpreter/BotScript.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// Plan statement base. Vtable 0x4BA240. Layout from BAPFlowCEnd(int, EndType, BAPCondition*) 0x1E3230, +// BAPCombinerSerial(int, int) 0x1E6150, BAPFlowCIf 0x1E3550 and BAPAIdle(BAPCondition*, u64, int) 0x1D2850: +// every constructor stores vptr, +4 = 0, +8/+0xC = 0, increments `news`, then its own vptr, and stores +// its trailing `int` constructor argument at +0x10. That argument is the creating pattern's id +// (BBPAvoidCollision2d::createPlan passes its +8, SensingAgentMouseFreeLookPattern its getId()). +// ELF: vtable 0x4BA240 (8 words), package A-core. +class BAPStatement : public BotScript +{ +public: + virtual ~BAPStatement() { ++destroys; } // 0x1F83B0, weak in the image (inline): every derived dtor inlines it + + virtual unsigned long long getControls() { return m_controls; } // 0x1CDB10 (weak), slot +0x0C + virtual BAPStatementType getId() const = 0; // no body, slot +0x10; from the base declaration + virtual bool hasDefault() = 0; // no body, slot +0x14; from the base declaration + virtual void debug(BotScriptDebugger::DebugLevel, std::string&); // 0x1F8210, slot +0x18; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1F8260, slot +0x1C; from the base declaration + + // [INFERRED] inline (no symbol): wrappers and combiners store themselves at +0x04 of their + // child statements (BAPIWIdle 0x1F7480, BAPIWMoveTo 0x1F7820). Same as writing m_owner. + void setParent(void* parent) { m_owner = parent; } + + // [INFERRED] inline (no symbol): patterns compare the current plan's +0x10 with their own id to + // keep it (BBPIdleInfantery::createPlan 0x28F718, BBPGotoWaypointSoldier::createPlan 0x2847DF). + int getPatternId() const { return m_patternId; } + +public: + static int news; // BSS 0x4CE268; every BAPStatement constructor increments it + static int destroys; // BSS 0x4CE26C; ~BAPStatement 0x1F83B0 increments it + +protected: + // [CHOSEN, not recovered] overload selector for the inline base construction in BAPWrapperFinished + // (ELF 0x1F9F00) and BAPWrapperWeapon (0x1FB050): neither stores a pattern id. + struct UninitializedPatternId {}; + explicit BAPStatement(UninitializedPatternId) : m_controls(0) { ++news; } + + // The image's BAPStatement constructor is inline (no symbol). Derived constructors either pass + // the trailing int (and the controls mask, when they take one) here or assign the fields; the + // store order inside one constructor is not observable. [CHOSEN] the two signatures. + BAPStatement() : m_controls(0), m_patternId(0) { ++news; } + explicit BAPStatement(int patternId, unsigned long long controls = 0) + : m_controls(controls), m_patternId(patternId) { ++news; } + + // +0x04 is BotScript::m_owner (the parent node or the behaviour). + /* +0x08 */ unsigned long long m_controls; // = 0; getControls 0x1CDB10 returns it; actions store their + // `unsigned long long` constructor argument (BAPAIdle 0x1D28B2) + /* +0x10 */ int m_patternId; // trailing constructor `int`: the creating pattern's id [INFERRED] name +}; + +// ELF 0x1F82D0: statement.streamSelf(os) (slot +0x1C); returns os. +std::ostream& operator<<(std::ostream& os, const BAPStatement& statement); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPSTATEMENT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h new file mode 100644 index 000000000..09848dbdc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPTypes.h @@ -0,0 +1,144 @@ +// Plan-system enums shared by the action, condition, behaviour and interpreter classes. +// [INFERRED] file placement and enumerator spellings where noted; values are attested. +// S0 skeleton (docs/macos-ai-behaviour-plan.md). Owner: package A-core. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPTYPES_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPTYPES_H + +namespace dice { +namespace hfe { +namespace ai { + +// Statement type: BAPStatement::getId. Values from every getId body; names from the 44 BAPST* +// strings the .ai files use (aiSettings.activateDefaultInterpreter). Same `: int` spelling as the +// forward declarations in Main/AIConsole.h and Main/AISettingsInterfaces.h. +// operator<<(ostream&, BAPStatementType) is libaidll.so 0x3C7D90 (a 45-case jump table). +enum BAPStatementType : int +{ + BAPSTParallel = 0, // BAPCombinerParallel + BAPSTSerial = 1, // BAPCombinerSerial + BAPSTPlanEnd = 2, // BAPFlowCEnd + BAPSTIf = 3, // BAPFlowCIf + BAPSTWait = 4, // BAPFlowCWait + BAPSTWhile = 5, // BAPFlowCWhile + BAPSTAimAt = 6, // BAPAAimAt, BAPAAimAt3d + BAPSTMoveTo = 7, // BAPAMoveTo, BAPAMoveTo3d + BAPSTMoveToDirection = 8, // BAPAMoveToDirection, BAPAMoveTo3dDirection + BAPSTMoveToObject = 9, // BAPAMoveToObject, BAPAMoveTo3dObject + BAPSTMoveAwayFromObject = 10, // BAPAMoveAwayFrom3dObject + BAPSTTrigger = 11, + BAPSTTriggerContinously = 12, + BAPSTIdle = 13, + BAPSTResetControls = 14, + BAPSTInfoWrapper = 15, + BAPSTAimingWrapper = 16, + BAPSTFinishedWrapper = 17, + BAPSTWeaponWrapper = 18, + BAPSTLookAtWrapper = 19, + BAPSTSense = 20, + BAPSTOverrideSensingAgent = 21, + BAPSTPlaceC4 = 22, + BAPSTLookAt = 23, // BAPALook + BAPSTTurn = 24, + BAPSTRoll3d = 25, + BAPSTSoldierPose = 26, + BAPSTUpdateVehicle = 27, + BAPSTChangeWeapon = 28, + BAPSTICChangeVehicle = 29, + // 30: no class returns it and the stream operator prints nothing for it. [UNRESOLVED] + BAPSTICTurnLock = 31, + BAPSTEvaluate = 32, + BAPSTNotifyBot = 33, + BAPSTPhysicsEnable = 34, + BAPSTSetSensingAgentFocus = 35, + BAPSTMergeSoldierInputs = 36, + BAPSTSendRadioMessage = 37, + BAPSTDebug = 38, + BAPSTForgetTarget = 39, + BAPSTUseFlareOnMissileLock = 40, + BAPSTRunOverObject = 41, + BAPSTHonkHorn = 42, + BAPSTEvaluateCondition = 43, + BAPSTRevive = 44 +}; + +// Condition type: BAPCondition::getConditionType. Values from the getConditionType bodies and +// operator<<(ostream&, BAPConditionType) 0x3C7AE0 (59 cases; its strings in the comments). +// [INFERRED] enumerator names (BAPCT + class stem). Retail quirks kept by the classes, not here: +// BAPConPointInFront returns 23 (ObjectInFront), ValidPitchAiming/ValidYawAiming return 32. +enum BAPConditionType : int +{ + BAPCTLookDeviation = 0, + BAPCTPrecision = 1, + BAPCTPrecision3d = 2, + BAPCTBombPrecision3d = 3, + BAPCTAnd = 4, + BAPCTEndOfPath = 5, + BAPCTFalse = 6, // "false" + BAPCTGeneric1Arg = 7, // "Generic1Arg"; no class returns it + BAPCTGeneric2Arg = 8, // "Generic2Arg"; no class returns it + BAPCTInsideBattleZone = 9, + BAPCTIteration = 10, + BAPCTLineOfFire = 11, + BAPCTPointDistance = 12, + BAPCTPointInFront = 13, + BAPCTNot = 14, + BAPCTDistanceToProj = 15, + BAPCTStrategicObjectStatus = 16, + BAPCTObjectBehind = 17, + BAPCTObjectDistance = 18, + BAPCTObjectDistanceToPoint = 19, + BAPCTObjectEnemyOccupied = 20, + BAPCTObjectExists = 21, + BAPCTObjectHealth = 22, + BAPCTObjectInFront = 23, + BAPCTObjectInLandingZone = 24, + BAPCTObjectInsideFrustum = 25, + BAPCTObjectLineOfFire = 26, + BAPCTObjectManDown = 27, + BAPCTObjectMoved = 28, + BAPCTObjectOccupied = 29, + BAPCTObjectSpeed = 30, + BAPCTObjectTouchingLand = 31, // "ObjectTouchingGround" + BAPCTObjectValidAiming = 32, + BAPCTObjectValidPosition = 33, + BAPCTObjectVisible = 34, + BAPCTOr = 35, + BAPCTPointAt = 36, + BAPCTPosition = 37, + BAPCTSharedCondition = 38, + BAPCTTime = 39, + BAPCTTrue = 40, // "true" + BAPCTWeaponMagAmmo = 41, + BAPCTWeaponTotalAmmo = 42, + BAPCTTotalAmmo = 43, // "TotalWeaponAmmo" + BAPCTWeaponReadyToFire = 44, + BAPCTWeaponTargetReachable = 45, + BAPCTWeaponHeat = 46, + BAPCTWeaponHasLockOnTarget = 47, + // 48: no class returns it and the stream operator prints nothing for it. [UNRESOLVED] + BAPCTIsTriggered = 49, + BAPCTAllowFire = 50, // "Allow fire" + BAPCTIsSprinting = 51, // "Sprinting" + BAPCTWeaponIsZoomed = 52, // "Zoomed" + BAPCTWeaponDetonatorIsActive = 53, // "Detonator active" + BAPCTWeaponIsActive = 54, // "Weapon active" + BAPCTOpLessThan = 55, // BAPConOpLessThan + BAPCTOkToThrowGrenade = 56, // "Ok to throw grenade" + BAPCTSplashDamage = 57, // "Splash damage" + BAPCTTriggerableActive = 58 // "Triggerable Active" +}; + +// Free enums seen only in mangled parameter lists. [UNRESOLVED] enumerators; the same `: int` +// forward declarations already used by Main/ and AIBot/. BotLodLevel is defined in AIBot/BotMain.h +// (operator<< 0x3C78B0 prints BLLNone/BLLLight/BLLFull/BLLMedium). +enum BotLodLevel : int; +enum AIRadioMessageType : int; +enum AIRadioChannelType : int; +enum AvoidSide : int; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPTYPES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h new file mode 100644 index 000000000..a7fd9a6c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPVariable.h @@ -0,0 +1,35 @@ +// Typed plan variable owned by a BAPContext (inline template in the image). +// Layout from the inlined constructions in BBPFireInfantery::createPlanInternal (0x2650F0): +// new 0x10 for and 0x18 for ; each new variable is pushed onto the context's +// std::list. Instantiated for bool, int, unsigned int, float, Vec3 and +// WeaponInfo* (vtables 0x4BBD38, 0x4BBC68, 0x4BBC28, 0x4BBC58, 0x4BBD28, 0x4BB908). +// S0 skeleton (docs/macos-ai-behaviour-plan.md). Owner: package A-core. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPVARIABLE_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPVARIABLE_H + +#include "../AIPlanInterpreter/BAPContext.h" + +namespace dice { +namespace hfe { +namespace ai { + +template +class BAPVariable : public BotScriptVariable +{ +public: + // [INFERRED] parameter order: the inlined stores are +4 = a pointer the caller keeps in a + // register (dereferenced before), +8 = the initial value, then the trailing word = 0. + BAPVariable(void* owner, const T& value) : m_owner(owner), m_value(value), m_tail(0) {} + virtual ~BAPVariable() {} // D1/D0 only: vptr store and BotScriptVariable + + /* +0x04 */ void* m_owner; // [UNRESOLVED] type and name + /* +0x08 */ T m_value; // bool: false, Vec3: (0, 1, 0) at the construction above + /* after */ int m_tail; // = 0; +0x0C for bool, +0x14 for Vec3 [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPVARIABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp new file mode 100644 index 000000000..15f74fcbd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp @@ -0,0 +1,251 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1F9D20 (__tcf_0 0x1F9D80, _GLOBAL__I 0x1F9DB0): 's Init object only. +#include + +#include "BAPWrapperAiming.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SensingAgent.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFPhysics.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The sensed hit point (SensedObject +0x04) through the target's transformation (Information slot +// +0x3C), spelled out in place three times in execute. +Vec3 sensedWorldPoint(Information* target, const SensedObject* sensed) +{ + const Mat4& t = target->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + return bapinline::vec3(t.m[8] * l.z + t.m[0] * l.x + t.m[4] * l.y + t.m[12], + t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13], + l.x * t.m[2] + l.y * t.m[6] + l.z * t.m[10] + t.m[14]); +} + +} // namespace + +// ELF 0x1F8C30 (C1; C2 0x1F8B70). Note the argument order: aim direction, valid flag, aim point. +BAPWrapperAiming::BAPWrapperAiming(BAPVariable* aimDirection, BAPVariable* aimValid, + BAPVariable* aimPoint, unsigned int shooter, unsigned int target, + bool continuous) +{ + m_aimDirection = aimDirection; + m_aimPoint = aimPoint; + m_aimValid = aimValid; + m_shooter = shooter; + m_target = target; + m_continuous = continuous; + m_groundQuery.x = m_groundQuery.y = m_groundQuery.z = 0.0f; + m_groundLevel = 0.0f; +} + +// ELF 0x1F9DD0 (D1; D0 0x1F9E30): the Aimer and the base only. +BAPWrapperAiming::~BAPWrapperAiming() +{ +} + +// ELF 0x1F8CF0. The ground under `pos`: a line from pos down 2 m against the world, ignoring the +// target's object; the answer is cached for the last position (FLT_EPSILON per component). No +// target information: false; no hit: false (cache untouched). +bool BAPWrapperAiming::getGroundLevelAtPos(Bot*, const Vec3& pos, float& level) +{ + Information* target = bapinline::info(m_target); + if (!target) + return false; + if (std::fabs(m_groundQuery.x - pos.x) > 1.1920929e-07f || std::fabs(m_groundQuery.y - pos.y) > 1.1920929e-07f + || std::fabs(m_groundQuery.z - pos.z) > 1.1920929e-07f) { + // pos - (0, 2, 0) (the image subtracts 0.0 from x and z). + const Vec3 below = bapinline::vec3(pos.x - 0.0f, pos.y - 2.0f, pos.z - 0.0f); + Vec3 hit = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (!bapinline::collideLineIgnoring(pos, below, target->getAIObject(), hit)) + return false; + level = hit.y; + m_groundQuery = pos; + m_groundLevel = level; + return true; + } + level = m_groundLevel; + return true; +} + +// ELF 0x1F8F40. Aims the weapon of m_shooter at m_target: overrides the sensing agent, sets up +// the Aimer from the active weapon (drag, exit velocity, scaled gravity, thrown), picks the aim +// point from the sensed record and solves for the firing direction. Explosive unguided weapons +// against a target that is out of sight use its last seen position (on the ground) or, for a +// "static" shot (BotMain::setBotWantsToSimulateArtillery(true), Aimer::getStaticFiringDirection), +// its last known position led by its velocity. Out: m_aimDirection, m_aimPoint, m_aimValid; ok; +// done unless m_continuous. Missing information, control info, armament or weapon: ok = false, +// done. +bool BAPWrapperAiming::execute(Bot* bot, bool& ok, bool& done) +{ + bot->getSensingAgent()->setOverride(true); + Information* self = bapinline::info(m_shooter); + if (!self || !self->getControlInfo() || !self->getArmament()) { + ok = false; + done = true; + return true; + } + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) { + ok = false; + done = true; + return true; + } + Information* target = bapinline::info(m_target); + if (!target) { + ok = false; + done = true; + return true; + } + // Neither primary information is null-checked in the image. + IPIMobile* targetMobile = bapinline::info(target->getPrimaryObject(bot->getSide()))->getMobile(); + IPIMobile* ownMobile = bapinline::info(self->getPrimaryObject(bot->getSide()))->getMobile(); + + const float drag = weapon->getDrag(); + m_aimer.m_drag = drag; + m_aimer.m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer.m_speed = weapon->getExitVelocity(); + const float gravityModifier = weapon->getGravityModifier(); + m_aimer.m_gravity = static_cast( + static_cast(static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity()) * gravityModifier); + m_aimer.m_grenade = weapon->getIsThrown(); + const double now = bapinline::gameTime(); + + // Soldier against soldier: short-range weapons aim 0.2 lower, others 0.3 lower at a standing + // target. + float yOffset = 0.0f; + if ((self->getObjectTypeFlags() & 0x200000u) && (target->getObjectTypeFlags() & 0x200000u)) { + if (weapon->getMaxRange() < 10.0f) + yOffset = -0.2f; + else if (target->getSoldierPose() == SPStanding) + yOffset = -0.3f; + } + + SensedObject* sensed = bot->getSensedObjectFromHandle(m_target); + if (!sensed) + return true; // ok/done untouched (0x1F91EA) + + Vec3 point = sensedWorldPoint(target, sensed); + const double now2 = bapinline::gameTime(); + const Vec3& from = self->getPosition(); + const float dy = point.y - from.y; + Vec3 toTarget = bapinline::vec3(point.x - from.x, dy, point.z - from.z); + const float len = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y + toTarget.z * toTarget.z); + if (len != 0.0f) { + const float inv = 1.0f / len; + toTarget.x *= inv; + toTarget.y *= inv; + toTarget.z = inv * toTarget.z; + } + + const bool explosive = weapon->getExplosionRadius() != 0.0f && weapon->getWeaponGuidanceType() == 0; + const bool explosiveShot = explosive && !weapon->getIsThrown(); + const bool vehicleAtSoldier = !(self->getObjectTypeFlags() & 0x200000u) + && (target->getObjectTypeFlags() & 0x200000u) && explosiveShot; + const bool highAbove = bot->getSpawnKit() != 1 && !weapon->getIsThrown() && 30.0f < dy; + const bool indirect = (sensed->m_flags & 2u) && ((sensed->m_flags & 8u) || vehicleAtSoldier || highAbove) + && explosive; + const double lastFailed = static_cast(bot)->getTimeOfLastFailedStaticSkyAttack(); + const bool staticShot = indirect && lastFailed <= sensed->m_lastPositionTime && !vehicleAtSoldier + && (!explosiveShot || 10.0f < dy || 0.6f < toTarget.y); + m_aimer.m_flag69 = indirect && !staticShot; + + if (staticShot) { + if (targetMobile) { + double sinceSeen = 999999.0; + if (sensed->m_flags & 2u) + sinceSeen = now2 - sensed->m_lastSeenTime; + point = 5.0 <= sinceSeen ? sensed->m_lastSeenPosition : sensed->m_lastPosition; + double lead = now - sensed->m_lastPositionTime; + if (1.0 < lead) { + const double scaled = (lead - 1.0) * 0.05 + 1.0; // static `factor` = 0.05 (0x4BA328) + const float limit = + 8.0f <= static_cast(now2 - bot->getTimeOfGrenadeThrown(0)) ? 2.0f : 0.5f; + lead = limit; + if (scaled < static_cast(limit)) + lead = scaled; + } + const Vec3& v = targetMobile->getSpeed(); + const float s = static_cast(lead); + point.x = v.x * s + point.x; + point.y = v.y * s + point.y; + point.z = s * v.z + point.z; + } else { + point = sensedWorldPoint(target, sensed); + } + } else if (indirect) { + point = sensed->m_lastSeenPosition; + float level; + if (getGroundLevelAtPos(bot, point, level)) + point.y = level; + } else if (!(sensed->m_flags & 2u) || (sensed->m_flags & 8u)) { + point.y = yOffset + point.y; + } else { + point = sensedWorldPoint(target, sensed); + point.y = point.y + yOffset; + } + + if (explosive && !weapon->getIsThrown() && !indirect && (target->getObjectTypeFlags() & 0x200000u)) + point.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getHeight(point.x, point.z); + if (m_aimPoint) + m_aimPoint->m_value = point; + + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3 rel = bapinline::vec3(point.x - origin.m[12], point.y - origin.m[13], point.z - origin.m[14]); + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 ownVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (ownMobile) + ownVelocity = ownMobile->getSpeed(); + if (targetMobile && !indirect) + targetVelocity = targetMobile->getSpeed(); + m_aimer.setTargetData(rel, targetVelocity, ownVelocity, &origin, now); + + Vec3 direction = bapinline::vec3(0.0f, 0.0f, 0.0f); + Vec3 aimTarget = bapinline::vec3(0.0f, 0.0f, 0.0f); + bool valid; + if (staticShot) { + static_cast(bot)->setBotWantsToSimulateArtillery(true); + valid = m_aimer.getStaticFiringDirection(direction, aimTarget); + } else { + static_cast(bot)->setBotWantsToSimulateArtillery(false); + valid = m_aimer.getFiringDirection(now, 0.5f, weapon->getIndirect(), direction, aimTarget, 0); + } + done = !m_continuous; + ok = true; + m_aimDirection->m_value = direction; + m_aimValid->m_value = valid; + return true; +} + +// ELF 0x1F9D00 +BAPStatementType BAPWrapperAiming::getId() const +{ + return BAPSTAimingWrapper; // 16 +} + +// ELF 0x1F9D10 +bool BAPWrapperAiming::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h new file mode 100644 index 000000000..65950466b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h @@ -0,0 +1,52 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERAIMING_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERAIMING_H + +#include "../../../../Math/Vec3.h" +#include "BAPStatement.h" +#include "BAPTypes.h" +#include "BAPVariable.h" +#include "../AIBot/Aimer.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA340 (8 words), operator new 0xA8, package C-actions. +class BAPWrapperAiming : public BAPStatement +{ +public: + BAPWrapperAiming(BAPVariable*, BAPVariable*, BAPVariable*, unsigned int, unsigned int, bool); // 0x1F8C30 + virtual ~BAPWrapperAiming(); // 0x1F9DD0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1F8F40, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1F9D00, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1F9D10, slot +0x14; from the base declaration + + bool getGroundLevelAtPos(Bot*, const Vec3&, float&); // 0x1F8CF0; ELF bool (`testb %al` in execute) + +private: + /* +0x14 */ Aimer m_aimer; + /* +0x80 */ BAPVariable* m_aimDirection; // out: the firing direction + /* +0x84 */ BAPVariable* m_aimPoint; // out (may be 0): the point aimed at + /* +0x88 */ BAPVariable* m_aimValid; // out: the Aimer's answer + /* +0x8C */ unsigned int m_shooter; // information handle: the bot's vehicle/soldier + /* +0x90 */ unsigned int m_target; // information handle + /* +0x94 */ bool m_continuous; // set: never done + /* +0x98 */ Vec3 m_groundQuery; // = 0; getGroundLevelAtPos' last position + /* +0xA4 */ float m_groundLevel; // = 0; its answer +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERAIMING_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp new file mode 100644 index 000000000..7de304d22 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp @@ -0,0 +1,71 @@ +// Owns a child statement and overrides its finished result after interpreter execution. + +// static init: ELF 0x1FA260 (__tcf_0 0x1FA2C0, _GLOBAL__I 0x1FA2F0): 's Init object only. +#include + +#include "BAPWrapperFinished.h" + +#include "../AIBot/BotMain.h" +#include "../AIPlanInterpreter/PlanInterpreter.h" +#include "../Main/IBotManager.h" +#include "../Main/AIStreamOperators.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1F9F00 (C1; C2 0x1F9E90) +BAPWrapperFinished::BAPWrapperFinished(BAPStatement* statement, bool finished) + : BAPStatement(UninitializedPatternId()), m_statement(statement), m_finished(finished) +{ + if (m_statement) + m_statement->setParent(this); +} + +// ELF 0x1F9FE0 (D1; D2 0x1F9F70, D0 0x1FA050) +BAPWrapperFinished::~BAPWrapperFinished() +{ + delete m_statement; +} + +// ELF 0x1FA0C0 +bool BAPWrapperFinished::execute(Bot* bot, bool& success, bool& finished) +{ + if (m_statement) + static_cast(bot)->getPlanInterpreter()->execute(m_statement, bot, success, finished); + finished = m_finished; + return true; +} + +// ELF 0x1FA130 +BAPStatementType BAPWrapperFinished::getId() const +{ + return BAPSTFinishedWrapper; +} + +// ELF 0x1FA140 +bool BAPWrapperFinished::hasDefault() +{ + return true; +} + +// ELF 0x1FA150 +void BAPWrapperFinished::streamSelf(std::ostream& out) const +{ + IBotManager::instance->tabulate(out); + out << getId() << std::endl; + IBotManager::instance->tabulate(out); + out << '{' << std::endl; + if (m_statement) { + IBotManager::instance->increaseTabLevel(); + out << *m_statement; + IBotManager::instance->decreaseTabLevel(); + } + IBotManager::instance->tabulate(out); + out << '}' << std::endl; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.h new file mode 100644 index 000000000..309657673 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.h @@ -0,0 +1,38 @@ +// Owns a child statement and overrides its finished result after interpreter execution. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERFINISHED_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERFINISHED_H + +#include +#include "BAPStatement.h" +#include "BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// ELF: vtable 0x4BA3C0 (8 words), package H-deferred. +class BAPWrapperFinished : public BAPStatement +{ +public: + BAPWrapperFinished(BAPStatement*, bool); // 0x1F9F00 + virtual ~BAPWrapperFinished(); // 0x1F9FE0 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FA0C0, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1FA130, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FA140, slot +0x14; from the base declaration + virtual void streamSelf(std::ostream&) const; // 0x1FA150, slot +0x1C; from the base declaration +private: + /* +0x14 */ BAPStatement* m_statement; + /* +0x18 */ bool m_finished; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERFINISHED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp new file mode 100644 index 000000000..9274d784b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp @@ -0,0 +1,156 @@ +// Package C (ai-w1-c-actions): recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every body. + +// static init: ELF 0x1FADB0 (__tcf_0 0x1FAE10, _GLOBAL__I 0x1FAE40): 's Init object only. +#include + +#include "BAPWrapperLookAt.h" + +#include "BAPActionInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FA390 (C1; C2 0x1FA2D0): look at an object. +BAPWrapperLookAt::BAPWrapperLookAt(unsigned int target, BAPVariable* lookPoint, bool continuous, bool lead, + BAPVariable* lookDirection, BAPVariable* valid) +{ + m_target = target; + m_lookPoint = lookPoint; + m_lookDirection = lookDirection; + m_valid = valid; + m_point.x = m_point.y = m_point.z = 0.0f; + m_continuous = continuous; + m_lead = lead; +} + +// ELF 0x1FA4B0 (C1; C2 0x1FA410): look at a fixed point. +BAPWrapperLookAt::BAPWrapperLookAt(const Vec3& point, BAPVariable* lookPoint, bool continuous, + BAPVariable* lookDirection, BAPVariable* valid) +{ + m_target = 0xFFFFFFFFu; + m_lookPoint = lookPoint; + m_lookDirection = lookDirection; + m_valid = valid; + m_point = point; + m_lead = false; + m_continuous = continuous; +} + +// ELF 0x1FAE60 (D1; D0 0x1FAEA0): base only. +BAPWrapperLookAt::~BAPWrapperLookAt() +{ +} + +// ELF 0x1FA550. Fixed point: the point, ok, done unless continuous (the direction variable is not +// written). Object: unknown information: ok = false, done. Otherwise ok, done unless continuous, +// valid = true, and when the bot senses it: the sensed hit point in world space (or, with m_lead, +// that point led by the target's velocity over the projectile's flight time from the camera, +// raised by 5% of the distance for soldiers) into m_lookPoint and the normalised direction from +// the bot into m_lookDirection. The bot's information is not null-checked. +bool BAPWrapperLookAt::execute(Bot* bot, bool& ok, bool& done) +{ + Information* self = bapinline::info(bot->getCurrentEquipment()); + if (m_target == 0xFFFFFFFFu) { + ok = true; + done = !m_continuous; + m_lookPoint->m_value = m_point; + return true; + } + Information* target = bapinline::info(m_target); + if (!target) { + ok = false; + done = true; + return true; + } + ok = true; + done = !m_continuous; + if (m_valid) + m_valid->m_value = true; + SensedObject* sensed = bot->getSensedObjectFromHandle(m_target); + if (!sensed) + return true; + + const Mat4& t = target->getTransformation(); + const Vec3& l = sensed->m_seenPosition; + const Vec3 point = bapinline::vec3(t.m[8] * l.z + t.m[0] * l.x + t.m[4] * l.y + t.m[12], + t.m[1] * l.x + t.m[5] * l.y + t.m[9] * l.z + t.m[13], + l.y * t.m[6] + l.x * t.m[2] + l.z * t.m[10] + t.m[14]); + Vec3 dir; + if (!m_lead) { + m_lookPoint->m_value = point; + if (!m_lookDirection) + return true; + dir = bapinline::sub(point, self->getPosition()); + bapinline::normalize(dir); + } else { + IPIMobile* targetMobile = target->getMobile(); + IPIArmament* armament = self->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + const Mat4& origin = weapon->getProjectileOrigin(); + Vec3 projSpeed = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool haveSpeed = armament->getProjectileSpeed(projSpeed); + Vec3 projPos = bapinline::vec3(0.0f, 0.0f, 0.0f); + armament->getProjectilePosition(projPos); + const float speedLen = std::sqrt(projSpeed.z * projSpeed.z + projSpeed.y * projSpeed.y + projSpeed.x * projSpeed.x); + const Vec3 from = (speedLen == 0.0f || !haveSpeed) ? bapinline::vec3(origin.m[12], origin.m[13], origin.m[14]) + : projPos; + Vec3 rel = bapinline::sub(point, from); + const Mat4* camera = &self->getControlInfo()->getCameraTransformation(); + Vec3 targetVelocity = bapinline::vec3(0.0f, 0.0f, 0.0f); + if (targetMobile) + targetVelocity = targetMobile->getSpeed(); + if (std::sqrt(projSpeed.z * projSpeed.z + projSpeed.y * projSpeed.y + projSpeed.x * projSpeed.x) == 0.0f) { + projSpeed.x = camera->m[8] * 20.0f; + projSpeed.y = camera->m[9] * 20.0f; + projSpeed.z = camera->m[10] * 20.0f; + } + const float closing = std::sqrt((projSpeed.z - targetVelocity.z) * (projSpeed.z - targetVelocity.z) + + (projSpeed.x - targetVelocity.x) * (projSpeed.x - targetVelocity.x) + + (projSpeed.y - targetVelocity.y) * (projSpeed.y - targetVelocity.y)); + const float distance = std::sqrt(rel.z * rel.z + rel.y * rel.y + rel.x * rel.x); + const float flight = distance / closing; + if (flight < 2.5f) { + rel.x = targetVelocity.x * flight + rel.x; + rel.z = targetVelocity.z * flight + rel.z; + rel.y = rel.y + 0.0f; + } + camera = &self->getControlInfo()->getCameraTransformation(); + if (self->getObjectTypeFlags() & 0x200000u) + rel.y = distance * 0.05f + rel.y; + m_lookPoint->m_value = bapinline::vec3(rel.x + camera->m[12], rel.y + camera->m[13], rel.z + camera->m[14]); + if (!m_lookDirection) + return true; + dir = bapinline::sub(m_lookPoint->m_value, self->getPosition()); + bapinline::normalize(dir); + } + m_lookDirection->m_value = dir; + return true; +} + +// ELF 0x1FAD90 +BAPStatementType BAPWrapperLookAt::getId() const +{ + return BAPSTLookAtWrapper; // 19 +} + +// ELF 0x1FADA0 +bool BAPWrapperLookAt::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.h new file mode 100644 index 000000000..abda262c8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERLOOKAT_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERLOOKAT_H + +#include "../../../../Math/Vec3.h" +#include "BAPStatement.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BA440 (8 words), operator new 0x34, package C-actions. +class BAPWrapperLookAt : public BAPStatement +{ +public: + BAPWrapperLookAt(unsigned int, BAPVariable*, bool, bool, BAPVariable*, BAPVariable*); // 0x1FA390 + BAPWrapperLookAt(const Vec3&, BAPVariable*, bool, BAPVariable*, BAPVariable*); // 0x1FA4B0 + virtual ~BAPWrapperLookAt(); // 0x1FAE60 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FA550, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1FAD90, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FADA0, slot +0x14; from the base declaration + +private: + /* +0x14 */ unsigned int m_target; // information handle; -1: look at m_point + /* +0x18 */ BAPVariable* m_lookPoint; // out: the point looked at + /* +0x1C */ BAPVariable* m_lookDirection; // out (may be 0): normalised, from the bot + /* +0x20 */ BAPVariable* m_valid; // out (may be 0): set when the target is known + /* +0x24 */ Vec3 m_point; // the point constructor's; = 0 otherwise + /* +0x30 */ bool m_continuous; // set: never done + /* +0x31 */ bool m_lead; // lead the target with the projectile's flight time +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERLOOKAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp new file mode 100644 index 000000000..6e009fd2d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp @@ -0,0 +1,66 @@ +// Weapon-value wrapper recovered from libaidll.so. +#include "BAPWrapperWeapon.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FB050 (C1; C2 0x1FAEF0) +BAPWrapperWeapon::BAPWrapperWeapon(ValueId id, BAPVariable* value, + BAPVariable* weapon, bool repeat) + : BAPStatement(UninitializedPatternId()), m_valueId(id), m_integer(value), + m_weapon(weapon), m_repeat(repeat) +{ + if (m_valueId != 0) + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp", 28, "") + << "Unknown integer valueId"; +} + +// ELF 0x1FB310 (C1; C2 0x1FB1B0) +BAPWrapperWeapon::BAPWrapperWeapon(ValueId id, BAPVariable* value, + BAPVariable* weapon, bool repeat) + : BAPStatement(UninitializedPatternId()), m_valueId(id), m_float(value), + m_weapon(weapon), m_repeat(repeat) +{ + if (m_valueId != 1) + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp", 50, "") + << "Unknown float valueId"; +} + +// ELF 0x1FB610 (D1; D0 0x1FB650) +BAPWrapperWeapon::~BAPWrapperWeapon() +{ +} + +// ELF 0x1FB470 +bool BAPWrapperWeapon::execute(Bot*, bool& success, bool& finished) +{ + if (m_valueId == 0) + m_integer->m_value = m_weapon->m_value->getShotsInMag(0); + else if (m_valueId == 1) + m_float->m_value = m_weapon->m_value->getHeat(); + else + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp", 68, "") + << "Unknown valueId"; + success = true; + finished = !m_repeat; + return true; +} + +// ELF 0x1FB5F0 +BAPStatementType BAPWrapperWeapon::getId() const +{ + return BAPSTWeaponWrapper; +} + +// ELF 0x1FB600 +bool BAPWrapperWeapon::hasDefault() +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.h new file mode 100644 index 000000000..6a978333f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.h @@ -0,0 +1,42 @@ +// Copies magazine ammunition or heat from a borrowed weapon into a plan variable. + +#ifndef AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERWEAPON_H +#define AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERWEAPON_H + +#include "BAPStatement.h" +#include "BAPTypes.h" +#include "BAPVariable.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class WeaponInfo; + +// ELF: vtable 0x4BA4C0 (8 words), operator new 0x28, package G-vehicles. +class BAPWrapperWeapon : public BAPStatement +{ +public: + enum ValueId : int; // [UNRESOLVED] enumerators + BAPWrapperWeapon(BAPWrapperWeapon::ValueId, BAPVariable*, BAPVariable*, bool); // 0x1FB050 + BAPWrapperWeapon(BAPWrapperWeapon::ValueId, BAPVariable*, BAPVariable*, bool); // 0x1FB310 + virtual ~BAPWrapperWeapon(); // 0x1FB610 + + virtual bool execute(Bot*, bool&, bool&); // 0x1FB470, slot +0x00; from the base declaration + virtual BAPStatementType getId() const; // 0x1FB5F0, slot +0x10; from the base declaration + virtual bool hasDefault(); // 0x1FB600, slot +0x14; from the base declaration +private: + /* +0x14 */ ValueId m_valueId; + /* +0x18 */ BAPVariable* m_integer; + /* +0x1C */ BAPVariable* m_float; + /* +0x20 */ BAPVariable* m_weapon; + /* +0x24 */ bool m_repeat; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTACTIONPLAN_BAPWRAPPERWEAPON_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp new file mode 100644 index 000000000..5070e5272 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp @@ -0,0 +1,407 @@ +// Avoid behaviour (infantry "Avoid" slot of aibehaviours.ai): a soldier scans the obstacles its +// navigation collected, predicts collisions with the moving non-soldier objects and hands the most +// urgent one to its BBPAvoidCollision pattern; a vehicle about to be bailed from is fled at urgency +// 100 per object, and a grenade warning or gas forces urgency 1000. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x1FD0B0 (__tcf_0 0x1FD110, _GLOBAL__I 0x1FD140): 's Init object only. +#include + +#include "BBAvoid.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollision.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Game/Objects/IPlayer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The sphere centre of an information in world space: the local sphere offset turned by the +// rotation rows of the transformation (row vector times matrix: x uses m[0], m[4], m[8]), plus the +// position. Inlined twice in calculateUrgency (0x1FBE28 for the bot, 0x1FC5DB per obstacle); the +// calls run getTransformation (slot +0x3C), getSphereLocalOffset (IPIPhysical +0x30), getPosition +// (+0x30) in that order. +Vec3 sphereCentre(Information* information, IPIPhysical* physical) +{ + const Mat4& transformation = information->getTransformation(); + const Vec3 offset = physical->getSphereLocalOffset(); + const float* m = transformation.m; + Vec3 rotated; + rotated.x = offset.x * m[0] + offset.y * m[4] + offset.z * m[8]; + rotated.y = offset.x * m[1] + offset.y * m[5] + offset.z * m[9]; + rotated.z = offset.x * m[2] + offset.y * m[6] + offset.z * m[10]; + const Vec3& origin = information->getPosition(); + Vec3 centre; + centre.x = rotated.x + origin.x; + centre.y = rotated.y + origin.y; + centre.z = rotated.z + origin.z; + return centre; +} + +inline float dot(const Vec3& a, const Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +} // namespace + +// ELF 0x1FB9D0 (C2) / 0x1FBA90 (C1). The base gets getMaxNBots (IAISettings slot 0); a second +// getMaxNBots sizes the +0x08 target array (plain operator new[], no checkPointer block here), and +// every bot starts with urgency 0.0f (rodata 0x49CB34) and target 0xFFFFFFFF (`movl $0xffffffff`). +BBAvoid::BBAvoid(unsigned char index, unsigned char queue, BBPAvoidCollision* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x1FBB50 (D2) / 0x1FBBA0 (D1) / 0x1FBBF0 (D0): delete[] +0x08 when set, then the base. +BBAvoid::~BBAvoid() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x1FBC40 (1,201 insns). +// Not updating: clears the changed flag and keeps the urgency while the pattern runs, else unInits. +// Updating: only a soldier (Information type flag 0x200000, byte +6 bit 5; [INFERRED] meaning: +// BBRevive picks its man-down targets with the same bit) with a mobile plug-in gets past the first +// tests. Retail quirks kept: two `!isSoldier` blocks can never run (the flag was tested earlier; the +// image reloads the same stack byte); the bot's own Information is used without a null check; so is +// the chosen target's Information before insertBehaviourInformation. +float BBAvoid::calculateUrgency(Bot* bot, bool update, float modifier) +{ + BBPAvoidCollision* const pattern = static_cast(m_pattern); + unsigned int* const targets = m_targets; + + if (!update) + { + // 0x1FBC6A: flags = 0; isInitiated (pattern slot +0x0C) keeps the stored urgency. + m_targetChanged[bot->getBotId()] = false; + if (pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + // ELF 0x4BA5A4 (d, 0x3F19999A): calculateUrgency(Bot*, bool, float)::radiusTweak. + static float radiusTweak = 0.6f; + + // 0x1FBD00: five Vec3 locals (-0x28, -0x38, -0x48, -0x58, -0x68) start at 0.0f. + Vec3 position = { 0.0f, 0.0f, 0.0f }; + Vec3 speed = { 0.0f, 0.0f, 0.0f }; + Vec3 toObstacle = { 0.0f, 0.0f, 0.0f }; + Vec3 relativeSpeed = { 0.0f, 0.0f, 0.0f }; + Vec3 collisionPoint = { 0.0f, 0.0f, 0.0f }; + + const unsigned int previousTarget = targets[bot->getBotId()]; + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + unsigned int selfPrimary; + if (self->isPrimary()) + selfPrimary = bot->getCurrentEquipment(); + else + selfPrimary = self->getPrimaryObject(bot->getSide()); + self->getName(); // 0x1FBDC1: called, result unused + + float maxUrgency = 0.0f; // -0x208 + float total = 0.0f; // -0x200 + IPIMobile* const mobile = self->getMobile(); + if (!mobile) + { + m_urgency[bot->getBotId()] = total; + return total; + } + const bool isSoldier = (self->getObjectTypeFlags() & 0x200000u) != 0; // testb $0x20, 0x6(info) + if (!isSoldier) + { + m_urgency[bot->getBotId()] = total; + return total; + } + + IPIPhysical* const physical = self->getPhysical(); + position = sphereCentre(self, physical); + const float radius = physical->getSmallestRadius(); // IPIPhysical +0x34 + speed = mobile->getSpeed(); // IPIMobile +0x1C + const float speedMagnitude = std::sqrt(dot(speed, speed)); + // 0x1FBF7E: unreachable (isSoldier is true here); getUnresolvedCollisionHandle is Bot +0x9C. + if (!isSoldier && (3.0f > speedMagnitude || bot->getUnresolvedCollisionHandle() != 0xFFFFFFFFu)) + { + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + float lookAhead = mobile->getAvoidCollisionLookAhead(); + if (self->getAIObject()) + { + if (self->getSoldierPose() == SPLying) + lookAhead += lookAhead; // 0x1FCD75: fadd %st(0), %st + else if (self->getSoldierPose() == SPCrouching) + lookAhead *= 1.5f; // rodata 0x49CDC0 + } + // 0x1FC013: (flags & 0x10) != 0, plus 2; collisionPredicted never reads it. + const int predictMode = ((self->getObjectTypeFlags() & 0x10u) != 0) + 2; + + unsigned int changeTarget = bot->getChangeTarget(); + Information* const changeInformation = informationManager->getInformation(changeTarget); + if (changeInformation && !changeInformation->isPrimary()) + changeTarget = changeInformation->getPrimaryObject(bot->getSide()); + unsigned int repairTarget = bot->getRepairTarget(); + Information* const repairInformation = informationManager->getInformation(repairTarget); + if (repairInformation && !repairInformation->isPrimary()) + repairTarget = repairInformation->getPrimaryObject(bot->getSide()); + + // 0x1FC0DF: the obstacle handles are BotNavigation +0x58 (std::vector, filled by + // updateObstacles); the count is taken once before the loop, the data pointer on every pass. + // ELF 0x1FC0DF: getBotNavigation (slot +0xFC), then `lea 0x58(%eax)`. + const std::vector& obstacles = bot->getBotNavigation()->getObstacles(); + + const unsigned int obstacleCount = static_cast(obstacles.size()); + for (unsigned int i = 0; i < obstacleCount; ++i) + { + const unsigned int handle = obstacles[i]; + Information* const obstacle = informationManager->getInformation(handle); + if (!obstacle) + continue; + IPIMobile* const obstacleMobile = obstacle->getMobile(); + if (obstacle->getObjectSpawnerHolding() + && obstacle->getObjectSpawner(bot->getSide()) == bot->getCurrentEquipment()) + continue; + unsigned int obstaclePrimary = handle; + if (!obstacle->isPrimary()) + obstaclePrimary = obstacle->getPrimaryObject(bot->getSide()); + IPIPhysical* const obstaclePhysical = obstacle->getPhysical(); + if (!obstaclePhysical || selfPrimary == obstaclePrimary || handle == repairTarget || handle == changeTarget + || handle == bot->getWantedRepairTarget() || (obstacle->getObjectTypeFlags() & 0x200000u) != 0) + continue; + + // 0x1FC5DB: obstacle sphere centre minus own centre. + const Vec3 obstacleCentre = sphereCentre(obstacle, obstaclePhysical); + toObstacle.x = obstacleCentre.x - position.x; + toObstacle.y = obstacleCentre.y - position.y; + toObstacle.z = obstacleCentre.z - position.z; + // 0x1FC737: unreachable (isSoldier): an obstacle behind a moving non-soldier is ignored. + if (!isSoldier && 0.0f > dot(toObstacle, speed)) + continue; + + Vec3 obstacleSpeed = { 0.0f, 0.0f, 0.0f }; // -0x178 + if (obstacleMobile) + obstacleSpeed = obstacleMobile->getSpeed(); + relativeSpeed.x = obstacleSpeed.x - speed.x; + relativeSpeed.y = obstacleSpeed.y - speed.y; + relativeSpeed.z = obstacleSpeed.z - speed.z; + const float relativeSpeedSq = dot(relativeSpeed, relativeSpeed); // -0x254 + float radii = radius + obstaclePhysical->getSmallestRadius(); + if (isSoldier) + radii *= radiusTweak; // fmuls 0x74E0(%ebx) + const float obstacleHealth = obstaclePhysical->getHealth(); // IPIPhysical +0x14 + const float bailValue = IBotManager::instance->getVehicleBailValue(); // +0x68 + + IPIArmament* const armament = self->getArmament(); + WeaponInfo* activeWeapon = 0; + if (armament && armament->getActiveWeapon() != -1) + activeWeapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + + // 0x1FC8B1: flee a vehicle whose health is under the bail value, or one with type flag + // 0x02000000 (byte +7 bit 1), unless the active weapon is of type 4. [INFERRED] name `flee`. + bool flee = false; + if (isSoldier) + { + if (bailValue > obstacleHealth || (obstacle->getObjectTypeFlags() & 0x02000000u) != 0) + { + if (!activeWeapon || activeWeapon->getWeaponType() != 4) + flee = true; + } + } + if (isSoldier && !flee && 4.0f > dot(obstacleSpeed, obstacleSpeed)) + continue; + + const float distance = std::sqrt(dot(toObstacle, toObstacle)); // -0x268 + // 0x1FC978: max(r, min(r + 4.0f, 10.0f)) with two getSmallestRadius calls (fcmovnbe, fcmovbe). + const float smallestRadius = obstaclePhysical->getSmallestRadius(); + float fleeDistance = obstaclePhysical->getSmallestRadius() + 4.0f; + if (fleeDistance > 10.0f) + fleeDistance = 10.0f; + if (fleeDistance <= smallestRadius) + fleeDistance = smallestRadius; + + if (flee) + { + if (fleeDistance > distance) + { + maxUrgency = 100.0f; // rodata 0x49CB5C + total += maxUrgency; + float strength = (fleeDistance - distance) / 5.0f + 0.5f; + if (strength <= 1.0f) + strength = 1.0f; + targets[bot->getBotId()] = handle; + Vec3 zeroPoint = { 0.0f, 0.0f, 0.0f }; // -0x168 + Vec3 zeroSpeed = { 0.0f, 0.0f, 0.0f }; // -0x158 + pattern->init(bot, zeroPoint, handle, zeroSpeed, strength); + } + continue; + } + + float timeToCollision = 0.0f; // -0x1EC; [CHOSEN] initialised, the image leaves it to collisionPredicted + const float predicted = collisionPredicted(toObstacle, relativeSpeed, predictMode, lookAhead, radii, + collisionPoint, timeToCollision); + if (!(predicted > 0.0f)) + continue; + // 0x1FCB3C: the image squares 3.0f at run time (flds 3; fmul %st(0), %st). + const float minRelativeSpeed = 3.0f; + if (relativeSpeedSq < minRelativeSpeed * minRelativeSpeed) + continue; + float divisor; + if (1.1920929e-07f > timeToCollision) // rodata 0x49CC7C (FLT_EPSILON) + divisor = 1.0f; + else + divisor = std::sqrt(dot(toObstacle, toObstacle)); + const float mass = obstacle->getPhysical()->getMass(); // IPIPhysical +0x4C + const float value = mass * std::sqrt(dot(relativeSpeed, relativeSpeed)) / divisor * predicted; + total += value; + if (value > maxUrgency) + { + maxUrgency = value; + targets[bot->getBotId()] = handle; + pattern->init(bot, collisionPoint, handle, relativeSpeed, timeToCollision); + } + } + + Vec3 grenadePosition = { 0.0f, 0.0f, 0.0f }; // -0x1E8 + if (isSoldier && total == 0.0f) + { + // 0x1FC577: BotNavigation::getGrenadeWarning (0x195310) answers `seta`: the warning time is + // still inside the limit at rodata 0x49CCB8 (PLT 0x17E9E0, called at 0x1FC59C, `test al`). + double grenadeTime = 0.0; + const bool grenadeWarning = bot->getBotNavigation()->getGrenadeWarning(grenadePosition, grenadeTime); + if (grenadeWarning) + { + Vec3 zero = { 0.0f, 0.0f, 0.0f }; // -0x1D8, passed twice + pattern->init(bot, zero, 0xFFFFFFFFu, zero, 0.0f); + m_urgency[bot->getBotId()] = 1000.0f; // rodata 0x49CF48 + return 1000.0f; + } + } + (void)grenadePosition; + + // 0x1FC26D: IAIPlayer +0x0C getPlayer, then world::IPlayer +0x2B8 getBlurValue, +0x140 getIsGassed. + world::IPlayer* const player = bot->getPlayer()->getPlayer(); + if (player->getBlurValue() > 0.0f && player->getIsGassed()) + { + Vec3 zero = { 0.0f, 0.0f, 0.0f }; + pattern->init(bot, zero, 0xFFFFFFFFu, zero, 0.0f); + m_urgency[bot->getBotId()] = 1000.0f; + return 1000.0f; + } + + if (total == 0.0f) + { + // 0x1FC2B6: the changed flag takes isInitiated, then unInit and urgency 0. + const bool initiated = pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + total *= bot->getMemory()->m_float8; + if ((self->getObjectTypeFlags() & 0x200000u) != 0) + { + // 0x1FC456: IBFTimer +0x08 minus the double at CommunicationAgent +0x60 (fsubl 0x60(%eax)), + // compared with 5.0f (rodata 0x49CDAC); a recent time doubles the total. + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + CommunicationAgent* const communication = bot->getCommunicationAgent(); + const double since = communication->getDouble96(); + if (now - since < 5.0f) + total += total; + } + + m_urgency[bot->getBotId()] = modifier * total; + m_targetChanged[bot->getBotId()] = previousTarget != targets[bot->getBotId()]; + // 0x1FC3DF: no null check on the target's Information (retail). + Information* const target = informationManager->getInformation(targets[bot->getBotId()]); + bot->insertBehaviourInformation(0.5f, target->getPosition(), m_index); // Bot +0x8C, rodata 0x49CB44 + return m_urgency[bot->getBotId()]; +} + +// ELF 0x1FCDF0. Closest approach of the relative motion: position `relative` (obstacle minus self), +// velocity `velocity`. Below a relative speed of 0.001 (double, rodata 0x49F4A0, squared at run +// time) there is no collision. `closestTime` is the time of closest approach; a closest distance +// inside sqrt(1.5) * radius gives the entry time t - sqrt(|d^2 - 1.5 r^2|) / |v|, written to `time`; +// inside [0, lookAhead] the entry point goes to `point` and the answer is 1.0f, else 0.0f. +float BBAvoid::collisionPredicted(Vec3& relative, Vec3& velocity, int, float lookAhead, float radius, Vec3& point, + float& time) +{ + const float radiusSq = radius * radius * 1.5f; // 0x1FCE13: stored back into the argument slot + const float speedSq = velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z; + const double minSpeed = 0.001; + if (speedSq < minSpeed * minSpeed) + return 0.0f; + const float speed = std::sqrt(speedSq); + const float inverse = 1.0f / speed; + Vec3 direction; + direction.x = velocity.x * inverse; + direction.y = velocity.y * inverse; + direction.z = velocity.z * inverse; + Vec3 back; + back.x = -relative.x; + back.y = -relative.y; + back.z = -relative.z; + const float closestTime = (direction.x * back.x + direction.y * back.y + direction.z * back.z) / speed; + if (0.0f > closestTime) + return 0.0f; + Vec3 closest; + closest.x = relative.x + velocity.x * closestTime; + closest.y = relative.y + velocity.y * closestTime; + closest.z = relative.z + velocity.z * closestTime; + const float closestSq = closest.x * closest.x + closest.y * closest.y + closest.z * closest.z; + if (closestSq >= radiusSq) + return 0.0f; + const float entryTime = closestTime - std::sqrt(std::fabs(closestSq - radiusSq)) / speed; + time = entryTime; + if (entryTime > lookAhead || 0.0f > entryTime) + return 0.0f; + point.x = velocity.x * entryTime + relative.x; + point.y = velocity.y * entryTime + relative.y; + point.z = velocity.z * entryTime + relative.z; + return 1.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h new file mode 100644 index 000000000..83ee45ea1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBAVOID_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBAVOID_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPAvoidCollision; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BA5C0 (13 words), operator new 0x24, package F-infantry. +// No members of its own: operator new 0x24 is sizeof(BotBehaviour). The base +0x08 array holds the +// handle of the obstacle each bot avoids (unsigned int per bot, 0xFFFFFFFF = none); +0x0C is the +// BBPAvoidCollision pattern. +class BBAvoid : public BotBehaviour +{ +public: + BBAvoid(unsigned char, unsigned char, BBPAvoidCollision*, UrgeCurve*, float*); // 0x1FBA90 + virtual ~BBAvoid(); // 0x1FBBA0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FBC40, slot +0x28; from the base declaration + + // float: the only caller (calculateUrgency 0x1FCB21) stores st(0) with fstps and compares it + // against 0.0f; every exit loads 0.0f or 1.0f. The int argument is never read. + float collisionPredicted(Vec3&, Vec3&, int, float, float, Vec3&, float&); // 0x1FCDF0 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBAVOID_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp new file mode 100644 index 000000000..a4f53024b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp @@ -0,0 +1,342 @@ +// Bridge-repair behaviour (infantry "BridgeRepair" slot of aibehaviours.ai): an engineer (spawn kit 4) +// picks the closest destroyed bridge segment and a valid standing point at one of its two ends. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x1FED10 (__tcf_0 0x1FED70, _GLOBAL__I 0x1FEDA0): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) +#include "BBBridgeRepair.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPBridgeRepair.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Narrow stops for callees that the tree does not declare (or declares with a different +// signature). Each is a one-line swap once the owner declares the method. + +// ai-bot: _ZN4dice3hfe2ai16SquadCoordinator17isRepairRequestedEv (ELF 0x1A49F0, PLT 0x17BB30); +// call: squad->isRepairRequested(). SquadCoordinator.h names the member (+172 m_b172) only. +bool squadIsRepairRequested(SquadCoordinator* squad) +{ + return squad->isRepairRequested(); +} + +// ai-bot: _ZN4dice3hfe2ai16SquadCoordinator19getRepairRequestPosEv (ELF 0x1A4A00, PLT 0x17DB10); +// call: squad->getRepairRequestPos(); the caller reads three floats through the returned address (+176). +const Vec3& squadGetRepairRequestPos(SquadCoordinator* squad) +{ + return squad->getRepairRequestPos(); +} + +// ai-bot: _ZN4dice3hfe2ai12SquadManager23requestResponseModifierEPNS1_11SquadMemberEjNS3_13RequestActionEi +// (ELF 0x1B0390, PLT 0x17A880); call: SquadManager::m_instance->requestResponseModifier( +// bot->getSquadMember(), segmentHandle, SquadMember::RequestAction(2), bot->getSide()); float in ST0. +float squadManagerRequestResponseModifier(SquadMember* member, unsigned int handle, int action, int side) +{ + return SquadManager::m_instance->requestResponseModifier(member, handle, action, side); +} + +// ai-strategic: _ZN4dice3hfe2ai24AIStrategicObjectManager32getClosestDestroyedBridgeSegmentENS0_4Vec3EbiRS3_Rf +// (ELF 0x349ED0, PLT 0x185180): the image returns the segment's IAIObject pointer, and this caller +// calls slot +0xD0 (IAIObject::getHandle) on it. +IAIObject* strategicClosestDestroyedBridgeSegment(AIStrategicObjectManager* manager, Vec3 position, + bool repairRequested, int side, Vec3& direction, + float& distance) +{ + return manager->getClosestDestroyedBridgeSegment(position, repairRequested, side, direction, distance); +} + +inline float lengthSquared(float x, float y, float z) +{ + return x * x + y * y + z * z; +} + +} // namespace + +// ELF 0x1FD180 (C2) / 0x1FD6C0 (C1). The base gets getMaxNBots (IAISettings slot 0); the empty +// vector at +0x24 is zeroed; three getNBattleStrengths-sized (slot +0x34) arrays go to +0x30/+0x34/ +// +0x38 (checkPointer'd, not initialised) before the index/queue/pattern stores; a getMaxNBots +// array goes to +0x08 and every base urgency (+0x10) is set to 0.0f (rodata 0x49CB34). +BBBridgeRepair::BBBridgeRepair(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_unknown30 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_unknown34 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_unknown38 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x1FDC00 (D2) / 0x1FDCB0 (D1) / 0x1FDD60 (D0): delete[] +0x08, +0x30, +0x34, +0x38 when set, +// then the vector at +0x24 (default_alloc deallocate) and the base. +BBBridgeRepair::~BBBridgeRepair() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown30) + delete[] m_unknown30; + if (m_unknown34) + delete[] m_unknown34; + if (m_unknown38) + delete[] m_unknown38; +} + +// ELF 0x1FE2E0. +float BBBridgeRepair::calculateUrgency(Bot* bot, bool update, float urgencyScale) +{ + unsigned int* const segmentHandles = m_targets; + PlanGenerator* const pattern = m_pattern; + + if (!update) + { + // 0x1FE304..0x1FE460: keep the current choice while its segment Information exists. + if (informationManager->getInformation(segmentHandles[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) // PlanGenerator slot +0x0C + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + // 0x1FE3C7: fucompi against 0.0f, setp|setne (unordered counts as changed). + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); // PlanGenerator slot +0x10 + } + return m_urgency[bot->getBotId()]; + } + + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); // Bot +0xD8 + const unsigned int botId = bot->getBotId(); + const Vec3 botPosition = info->getPosition(); // Information slot +0x30 + int weaponIndex = -1; + // 0x1FE4EF: retail quirk, getNBattleStrengths (IAISettings +0x34) is called and its result dropped. + static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + + // 0x1FE508: virtual isApplicable (slot +0x34); then the soldier (0x200000) or 0x40 type flag. + if (isApplicable(info, bot) && + ((info->getObjectTypeFlags() & 0x200000) || (info->getObjectTypeFlags() & 0x40))) + { + if ((info->getObjectTypeFlags() & 0x200000) && info->getSoldierPose() == SPSwimming) + { + // 0x1FEBF0 + m_targetChanged[botId] = true; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // 0x1FE54B: the soldier's own Information (side from Bot +0xE0 first), its weapon list + // copied, and the index of the first weapon of type 1 (-1 when none). + const int side = bot->getSide(); + Information* const soldierInfo = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(side)); + std::vector weapons = soldierInfo->getArmament()->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 1) + { + weaponIndex = i; + break; + } + } + + SquadMember* const member = bot->getSquadMember(); // Bot +0x140 + SquadCoordinator* const squad = member->getSquad(); + const bool repairRequested = squadIsRepairRequested(squad); + Vec3 direction = {0.0f, 0.0f, 0.0f}; + bool nearRequest = false; + Vec3 standPosition = {0.0f, 0.0f, 0.0f}; + Vec3 segmentEnd = {0.0f, 0.0f, 0.0f}; + float distance; + const int segmentSide = bot->getSide(); + IAIObject* const segment = strategicClosestDestroyedBridgeSegment( + AIStrategicObjectManager::getInstance(), info->getPosition(), repairRequested, segmentSide, direction, + distance); + + // 0x1FE784: continue only when |direction|^2 > 0.01f (rodata 0x49CB30; ja). + if (segment && lengthSquared(direction.x, direction.y, direction.z) > 0.01f) + { + const unsigned int segmentHandle = segment->getHandle(1); // IAIObject +0xD0 + // 0x1FE85F: retail quirk, a stale handle dereferences a null Information. + const Vec3 segmentPosition = informationManager->getInformation(segmentHandle)->getPosition(); + if (repairRequested) + { + const Vec3& requestPosition = squadGetRepairRequestPos(squad); + // 0x1FEBAE: rodata 0x49CF6C 2500.0f. + if (lengthSquared(requestPosition.x - segmentPosition.x, requestPosition.y - segmentPosition.y, + requestPosition.z - segmentPosition.z) < 2500.0f) + nearRequest = true; + } + // 0x1FE889: fcmove picks 10000.0f (rodata 0x49F4C0) near a request, else 2500.0f; + // jbe fails when limit <= distance (and when unordered). + const float limit = nearRequest ? 10000.0f : 2500.0f; + if (distance < limit && segmentHandle != 0xFFFFFFFFu) + { + standPosition = segmentPosition; + if (getBridgeCoordinate(segmentHandle, direction, bot, botPosition, standPosition, segmentEnd)) + { + // 0x1FE985: fmuls rodata 0x49CC8C 20.0f. + m_urgency[botId] = urgencyScale * 20.0f; + m_targetChanged[botId] = segmentHandles[botId] != segmentHandle; + segmentHandles[botId] = segmentHandle; + static_cast(pattern)->init(segmentHandles[botId], weaponIndex, direction, bot, + nearRequest, standPosition, segmentEnd); + float* const urgency = m_urgency; + const int responseSide = bot->getSide(); + urgency[botId] = squadManagerRequestResponseModifier(bot->getSquadMember(), segmentHandle, 2, + responseSide) * + urgency[botId]; + if (nearRequest) + m_urgency[botId] *= 2.0f; // 0x1FEAF0: fadd %st(0),%st + return m_urgency[bot->getBotId()]; + } + } + } + + // 0x1FE78E (the copied weapon list is freed after this) + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = segmentHandles[botId] != 0xFFFFFFFFu; + segmentHandles[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + return 0.0f; + } + + // 0x1FEC3B + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = segmentHandles[botId] != 0xFFFFFFFFu; + segmentHandles[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + return 0.0f; +} + +// ELF 0x1FECB0: bot->getPlayer() (+0xBC) alive (+0x24), not getManDown (+0x1B0), and the +// player's getSpawnKit (+0x44) == 4. +bool BBBridgeRepair::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + if (bot->getManDown()) + return false; + return bot->getPlayer()->getSpawnKit() == 4; +} + +// ELF 0x1FDE20: the two candidate ends of the segment are bridgePosition +/- direction * radius +// (segment Information's IPIPhysical::getRadius, slot +0x2C; a stale handle dereferences null, retail +// quirk). Each end is raised by 1.5f (rodata 0x49CDC0) and stepped along its direction up to ten +// times until the squad accepts it; the end closer to botPosition wins. bridgePosition receives the +// stand point, segmentEnd the unraised end. +bool BBBridgeRepair::getBridgeCoordinate(unsigned int segmentHandle, Vec3 direction, Bot* bot, Vec3 botPosition, + Vec3& bridgePosition, Vec3& segmentEnd) +{ + bot->getBotId(); // 0x1FDE5E: result unused (retail quirk) + const Vec3 forward = direction; + const Vec3 backward = {-forward.x, -forward.y, -forward.z}; // xorl $0x80000000 per component + const float radius = informationManager->getInformation(segmentHandle)->getPhysical()->getRadius(); + + Vec3 forwardEnd = {forward.x * radius + bridgePosition.x, forward.y * radius + bridgePosition.y, + forward.z * radius + bridgePosition.z}; + Vec3 backwardEnd = {backward.x * radius + bridgePosition.x, backward.y * radius + bridgePosition.y, + backward.z * radius + bridgePosition.z}; + const Vec3 forwardStart = forwardEnd; + const Vec3 backwardStart = backwardEnd; + + SquadMember* const member = bot->getSquadMember(); // Bot +0x140 + SquadCoordinator* const squad = member->getSquad(); + forwardEnd.y += 1.5f; + backwardEnd.y += 1.5f; + + bool forwardValid = false; + int tries = 0; + do + { + if (squad->isValidPosition(member, forwardEnd)) + forwardValid = true; + else + { + ++tries; + forwardEnd.x = forward.x + forwardEnd.x; + forwardEnd.y = forward.y + forwardEnd.y; + forwardEnd.z = forward.z + forwardEnd.z; + } + } + while (tries < 10 && !forwardValid); // 0x1FDFFB: cmpl $9; jg + + bool backwardValid = false; + tries = 0; + do + { + if (squad->isValidPosition(member, backwardEnd)) + backwardValid = true; + else + { + ++tries; + backwardEnd.x = backward.x + backwardEnd.x; + backwardEnd.y = backward.y + backwardEnd.y; + backwardEnd.z = backward.z + backwardEnd.z; + } + } + while (tries < 10 && !backwardValid); + + if (forwardValid) + { + // 0x1FE073: with both valid, the backward end wins when its squared distance to + // botPosition is <= the forward one (fucompi; jbe at 0x1FE154) [INFERRED operand order, + // read from the Ghidra decompile]. + if (backwardValid && + lengthSquared(backwardEnd.x - botPosition.x, backwardEnd.y - botPosition.y, backwardEnd.z - botPosition.z) <= + lengthSquared(forwardEnd.x - botPosition.x, forwardEnd.y - botPosition.y, + forwardEnd.z - botPosition.z)) + { + bridgePosition = backwardEnd; + segmentEnd = backwardStart; + return true; + } + bridgePosition = forwardEnd; + segmentEnd = forwardStart; + return true; + } + if (!backwardValid) + return false; + bridgePosition = backwardEnd; + segmentEnd = backwardStart; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h new file mode 100644 index 000000000..13009c316 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.h @@ -0,0 +1,53 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBBRIDGEREPAIR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBBRIDGEREPAIR_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA660 (14 words), operator new 0x3C, package F-infantry. +class BBBridgeRepair : public BotBehaviour +{ +public: + BBBridgeRepair(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x1FD6C0 + virtual ~BBBridgeRepair(); // 0x1FDCB0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FE2E0, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x1FECB0, slot +0x34; bool: 1 only for alive, not man-down, spawn kit 4 + + // ELF 0x1FDE20: bool, returns the movb $1/$0 flag in %al; the only caller tests %al. + bool getBridgeCoordinate(unsigned int, Vec3, Bot*, Vec3, Vec3&, Vec3&); + + // Base m_targets (+0x08) is unsigned int[getMaxNBots]: the bridge segment Information handle + // each bot repairs (-1 when none; calculateUrgency 0x1FE2E0). + +private: + // Constructor 0x1FD180/0x1FD6C0, destructor 0x1FDC00/0x1FDCB0/0x1FDD60. + /* +0x24 */ std::vector m_unknown24; // empty; freed as 4-byte elements; no F reader [UNRESOLVED] + /* +0x30 */ int* m_unknown30; // new [getNBattleStrengths] (IAISettings +0x34), uninitialised; no TU reader [UNRESOLVED] element type + /* +0x34 */ int* m_unknown34; // likewise [UNRESOLVED] + /* +0x38 */ int* m_unknown38; // likewise [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBBRIDGEREPAIR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp new file mode 100644 index 000000000..2f16d5f12 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp @@ -0,0 +1,156 @@ +// C4 behaviour (infantry "c4" slot of aibehaviours.ai): a bot carrying a C4 kit with charges left +// either blows its placed charge (urgency 100) or places one at an owned control point (500). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x1FF760 (__tcf_0 0x1FF7C0, _GLOBAL__I 0x1FF7F0): 's Init object only. +#include + +#include "BBC4.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadManager.h" +#include "../AIBotBehaviourPattern/BBPC4.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1FEDC0 (C2) / 0x1FEFB0 (C1): base with getMaxNBots, index/queue/pattern, then +// +0x08 = checkPointer(new[getMaxNBots]) and every base urgency = 0.0f (rodata 0x49CB34). +BBC4::BBC4(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x1FF1A0 (D2) / 0x1FF1F0 (D1) / 0x1FF240 (D0) +BBC4::~BBC4() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x1FF290 (249 insns). +float BBC4::calculateUrgency(Bot* bot, bool active, float) +{ + if (!active) + { + // 0x1FF2B9: `cmpb $0,0x10(%ebp); jne` - an inactive call only clears the slot. + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; + } + + // 0x1FF2F5: the bot's current equipment through the information pool (inlined lookup). + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + float urgency = 0.0f; // -0x168 + bool placed = false; // -0x169 + AIStrategicObject* object = 0; // -0x160 + SAI* sai = IAIMain::m_instance->getSAI(bot->getSide()); // IAIMain +0x3C + + // 0x1FF36E: `testb $0x20,0x6(%esi)` - type flag 0x200000 of the equipment, then the + // behaviour's own isApplicable (slot +0x34). + if (info && (info->getObjectTypeFlags() & 0x200000) && isApplicable(info, bot)) + { + // 0x1FF41E: the first weapon of type 4 (C4); w keeps the last lookup when none matches. + std::vector& weapons = info->getArmament()->getWeapons(); + WeaponInfo* weapon = 0; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 4) + break; + } + + // 0x1FF4A4: Bot::getC4 (+0x158) by value (sret, BotMain 0x188880). + const Bot::C4State c4 = bot->getC4(); + const Vec3 position = info->getPosition(); // slot +0x30, copied + + if (c4.placed) + { + object = c4.object; + if (c4.placementType == 0) + { + // 0x1FF505: a hostile takeover of the area the charge lies in, then no friendly + // within 15 m (rodata 0x49CDC4) of the charge: blow it. + AIStrategicObject* takeover = 0; + Vec2 takeoverPosition = { 0.0f, 0.0f }; + if (sai->hostileTakeoveInProgress(takeover, takeoverPosition) && c4.object + && c4.object->getIndex() == takeover->getIndex()) + { + if (!SquadManager::m_instance->friendliesCloseTo(c4.position, 15.0f, bot->getSide())) + { + urgency = 100.0f; // rodata 0x49CB5C + placed = true; + } + } + } + } + else + { + // 0x1FF5F0: charges left (WeaponInfo slot +0x14) and inside an owned control point + // (10 m, rodata 0x49CC88): place one, urgency 500 (rodata 0x49F500, cmovne). + placed = false; + if (weapon->getCurrentAmmo() > 0) + { + if (sai->isPosInsideOwnedControlPoint(object, position, 10.0f)) + urgency = 500.0f; + } + } + } + + // 0x1FF378: `flds 0.001; flds urgency; fxch; fucompi; jbe init` - init unless urgency < 0.001. + if (urgency < 0.001f) + m_pattern->unInit(bot); + else + static_cast(m_pattern)->init(bot, placed, object); + + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x1FF690: alive, not man down, and an armament holding a type-4 weapon with ammo. +bool BBC4::isApplicable(Information* info, Bot* bot) +{ + IPIArmament* armament = info->getArmament(); // +0x2C, read first + if (!bot->getPlayer()->getIsAlive()) + return false; + if (bot->getManDown()) + return false; + if (!armament) + return false; + + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 4 && weapon->getCurrentAmmo() > 0) + return true; + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h new file mode 100644 index 000000000..348c880ef --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBC4_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBC4_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA700 (14 words), operator new 0x24, package F-infantry. +// No members of its own: 0x24 is sizeof(BotBehaviour). +class BBC4 : public BotBehaviour +{ +public: + BBC4(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x1FEFB0 + virtual ~BBC4(); // 0x1FF1F0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FF290, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x1FF690, slot +0x34; bool: 0/1 in %edx -> %eax +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBC4_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp new file mode 100644 index 000000000..a2859121d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp @@ -0,0 +1,147 @@ +// Calls for a nearby medic according to travel time and remaining man-down time. + +// static init: ELF 0x1FFEA0 (__tcf_0 0x1FFF00, _GLOBAL__I 0x1FFF30): 's Init object only. +#include + +#include "BBCallForMedic.h" + +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPCallForMedic.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// Same-side objects carrying a weapon of type 1 or 3. No virtual destructor in the shipped table. +// [INFERRED] Source placement with its only caller; the weak body follows this TU's initializer. +class MedicatePredicate : public IAIInformationGridPredicate +{ +public: + explicit MedicatePredicate(int side) : m_side(side) {} + + // ELF 0x1FFF50 + virtual bool includeInformation(Information* information) const + { + IPIArmament* armament = information->getArmament(); + if (!armament) + return false; + const std::vector& weapons = armament->getWeapons(); + bool found = false; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon) + { + const int type = weapon->getWeaponType(); + found = false; + if (type == 3 || type == 1) + { + found = true; + break; + } + } + } + return information->getSide() == m_side && found; + } + +private: + /* +0x04 */ int m_side; +}; + +// ELF 0x1FF810 (C2), 0x1FF8E0 (C1) +BBCallForMedic::BBCallForMedic(unsigned char index, unsigned char queue, BBPCallForMedic* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targetChanged[i] = false; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x1FF9B0 (D2), 0x1FFA00 (D1), 0x1FFA50 (D0) +BBCallForMedic::~BBCallForMedic() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x1FFAA0 +float BBCallForMedic::calculateUrgency(Bot* bot, bool evaluate, float) +{ + if (!evaluate) + { + if (m_pattern->isInitiated(bot) && + informationManager->getInformation(m_targets[bot->getBotId()])) + return m_urgency[bot->getBotId()]; + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + std::vector medics; + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& position = equipment->getPosition(); + const int side = bot->getSide(); + MedicatePredicate predicate(side); + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getObjectsWithinRadius(medics, position, 50.0f, side, true, &predicate); + float nearestDistance = 50.0f; + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + for (std::vector::const_iterator i = medics.begin(); i != medics.end(); ++i) + { + Information* medic = informationManager->getInformation(*i); + const Vec3& medicPosition = medic->getPosition(); + const Vec3 delta = {position.x - medicPosition.x, position.y - medicPosition.y, + position.z - medicPosition.z}; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y + delta.z * delta.z); + if (distance < nearestDistance) + { + nearestDistance = distance; + m_targets[bot->getBotId()] = *i; + } + } + static_cast(m_pattern)->init(bot); + Information* medic = informationManager->getInformation(m_targets[bot->getBotId()]); + IPIPhysical* physical = equipment->getPhysical(); + if (medic && physical->getManDownTimeLeft() > 0.0f) + { + const float speed = medic->getMobile()->getMaxSpeed(); + const float travelTime = nearestDistance / speed; + float ratio = travelTime / physical->getManDownTimeLeft(); + if (ratio > 1.0f) + ratio = 1.0f; + const unsigned int index = bot->getBotId(); + m_urgency[index] = 1.0f - SCurve::calculate(ratio); + } + else + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.h new file mode 100644 index 000000000..0f4121d57 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.h @@ -0,0 +1,31 @@ +// Urgency for a medic call while a nearby friendly medic can reach the bot before man-down expires. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCALLFORMEDIC_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCALLFORMEDIC_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPCallForMedic; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BA7A0 (13 words), operator new 0x24, package H-deferred. +class BBCallForMedic : public BotBehaviour +{ +public: + BBCallForMedic(unsigned char, unsigned char, BBPCallForMedic*, UrgeCurve*, float*); // 0x1FF8E0 + virtual ~BBCallForMedic(); // 0x1FFA00 + + virtual float calculateUrgency(Bot*, bool, float); // 0x1FFAA0, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCALLFORMEDIC_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp new file mode 100644 index 000000000..ba92289c8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp @@ -0,0 +1,901 @@ +// Change behaviour: rates the bot's current vehicle (and its seats), getting out on foot, and every +// nearby vehicle and seat (calculateVehicleUrgency), then initialises the BBPChange pattern with the best +// one. Radio requests (message types 0 and 1) and the human player calling for a pick-up weigh in. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. Information flag bits are named by their test only: 0x10 (the +// air-vehicle tests: altitude, runway), 0x20, 0x80, 0x8000 and 0x200000 [UNRESOLVED] meanings. + +// static init: ELF 0x2038C0 (__tcf_0 0x203920, _GLOBAL__I 0x203950): 's Init object only. +#include + +#include "BBChange.h" +#include "VehicleUrgencyCalculator.h" + +#include "UrgeCurve.h" +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPChange.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIStrategicMap/BFStrategicEnvironment.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Frustum.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x203970 (W, this TU): the frustum query filter of runwayClear. +0x04 / +0x08 are the two +// informations runwayClear was given; vtable _ZTVN4dice3hfe2ai56_GLOBAL__N_AI_AIDLL_AI_AIBotBehaviour_ +// BBChange.cppI8HLwd25RunwayObstructedPredicateE. +class RunwayObstructedPredicate : public IAIInformationGridPredicate +{ +public: + RunwayObstructedPredicate(Information* vehicle, Information* other) : m_vehicle(vehicle), m_other(other) {} + + // Neither of the two; flag 0x8000 set, 0x200000 and 0x80 clear. + virtual bool includeInformation(Information* information) const + { + if (information == m_vehicle || information == m_other) + return false; + const unsigned int flags = information->getObjectTypeFlags(); + if (!(flags & 0x8000)) + return false; + if (flags & 0x200000) + return false; + if (flags & 0x80) + return false; + return true; + } + +private: + /* +0x04 */ Information* m_vehicle; + /* +0x08 */ Information* m_other; +}; + +// [CHOSEN, not recovered] helper: the image inlines this check at five sites (radio message types 0 +// and 1): the sender of the list's first message, if that player exists, is human (IAIPlayer slot +// +0x88 false), alive (+0x24) and not man-down (+0x2C). +IAIPlayer* liveHumanSender(const std::list& messages) +{ + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(messages.front().m_senderPlayerId); + if (!player || player->getIsAIPlayer() || !player->getIsAlive() || player->isManDown()) + return 0; + return player; +} + +} // namespace + +// ELF 0x200000 (C2) / 0x200240 (C1). The base gets getMaxNBots (IAISettings slot 0); +0x24/+0x30 empty +// vectors, +0x3C/+0x40 = 0; then index, queue, pattern; +0x08 = checkPointer(new unsigned int[getMaxNBots]) +// and, per bot, urgency (+0x10) = 0.0f (rodata 0x49CB34) and +0x08 = 0xFFFFFFFF. +BBChange::BBChange(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()), + m_vehicles(), m_runwayObstacles(), m_unknown3C(0), m_unknown40(0) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x200480 (D2) / 0x200530 (D1) / 0x2005E0 (D0): delete[] +0x08, delete +0x3C, delete +0x40 (each +// when set, slot +4), then the vectors (+0x30, +0x24) and the base. +BBChange::~BBChange() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown3C) + delete m_unknown3C; + if (m_unknown40) + delete m_unknown40; +} + +// ELF 0x200770. Ghidra decompile + asm (the locals carry their ELF frame offsets). +float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) +{ + unsigned int* const targets = m_targets; + PlanGenerator* const pattern = m_pattern; + + // The fire/move inclinations (Bot +0x190 / +0x18C) split into shares that sum to 1. + float fireShare = 0.0f; // -0x1B4 + float moveShare = 0.0f; // -0x1B8 + int side = bot->getSide(); // -0x1A4 (passed by reference to isMannedByEnemy) + const unsigned int botId = bot->getBotId(); // -0x1BC + bot->getSquadMember(); // ELF 0x2007DC: result unused + const float fire = bot->getFireInclination(); + const float move = bot->getMoveInclination(); + if (move > 0.0f) + { + if (fire > 0.0f) + { + fireShare = fire / (fire + move); + moveShare = move / (fire + move); + } + else + { + moveShare = 1.0f; + } + } + else if (fire > 0.0f) + { + fireShare = 1.0f; + } + else + { + fireShare = 0.5f; // ELF 0x202E03: fsts + fstps of rodata 0x49CB44 + moveShare = 0.5f; + } + + IAIStrategicEnvironment* const strategic = + static_cast(AISingletonServer::m_iaiStrategicEnvironment); + CommunicationAgent* const comm = bot->getCommunicationAgent(); // -0x1C0 + const float* const enemyTypes = strategic->getEnemyTypes(bot); // slot +0x0C, -0x1C4 + const float* const enemyStrengths = strategic->getEnemyStrengths(bot); // slot +0x08, -0x1C8 + + if (!evaluate) + { + // ---- ELF 0x200889: only re-check the bot's current choice. + const unsigned int equipment = bot->getCurrentEquipment(); + const unsigned int soldier = bot->getPlayer()->getSoldier()->getInformation(side); + const bool onFoot = soldier == equipment; // -0x1CD + + if (!onFoot && isBailAllowed(bot)) + { + Information* equipmentInfo = informationManager->getInformation(equipment); // -0x1D4 + float current = calculateVehicleUrgency(bot, equipmentInfo, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side) * 2.5f; + if (!equipmentInfo->isPrimary()) + current *= modifyForDriver( + informationManager->getInformation(equipmentInfo->getPrimaryObject(side)), false); + const float getOut = calculateVehicleUrgency(bot, informationManager->getInformation(soldier), + enemyStrengths, enemyTypes, false, equipmentInfo, + fireShare, moveShare, side) * 0.2f; + if (current > getOut) + { + // ELF 0x200A27: keep the current target while it is free and the pattern runs. + Information* target = informationManager->getInformation(targets[botId]); + if (target) + { + if (!target->getUnit()->isOccupied()) + { + if (pattern->isInitiated(bot)) + { + m_targetChanged[botId] = false; + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; + } + } + m_targetChanged[botId] = true; // ELF 0x200A80: overwritten at once below (retail) + } + } + else + { + // ELF 0x200B51: get out - the soldier itself is the target. + m_targetChanged[botId] = targets[botId] != soldier; + targets[botId] = soldier; + static_cast(m_pattern)->init(soldier, false, false, bot); + const float ratio = current != 0.0f ? getOut * 0.5f / current : getOut * 0.5f; + m_urgency[botId] = DecleiningSlopeCurve::calculate(ratio) * (scale * 4.0f); + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; + } + } + else + { + // ELF 0x200CC0 + Information* target = informationManager->getInformation(targets[botId]); + if (onFoot && target) + { + if (target->getUnit() && !target->getUnit()->isOccupied() && pattern->isInitiated(bot)) + { + m_targetChanged[botId] = false; + m_urgency[botId] = checkBookings(bot); + // ELF 0x200D88: no null test of the equipment information (retail). + Information* equipmentInfo = informationManager->getInformation(equipment); + if (equipmentInfo->getObjectTypeFlags() & 0x200000) + { + const std::list& calls = + comm->getReceivedMessages(static_cast(1)); + if (!calls.empty() && isCallingVehicle(targets[botId], calls, side)) + static_cast(m_pattern)->setGetInConfirm(true, bot); + } + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; + } + m_targetChanged[botId] = true; // ELF 0x200A80 + } + } + + // ELF 0x200A93: drop the choice. + m_targetChanged[botId] = pattern->isInitiated(bot); + targets[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // ---- ELF 0x200E68: full evaluation. + float currentUrgency = 0.0f; // -0x1EC: the current vehicle/seat's own urgency + int seatIterator = 0; // -0x19C, shared by every secondary-object walk below + Vec3 entryPos; // -0x148 + Vec3 bestEntryPos; // -0x138 + entryPos.x = entryPos.y = entryPos.z = -666.0f; // rodata 0x49CC98 + bestEntryPos.x = bestEntryPos.y = bestEntryPos.z = -666.0f; + SquadManager* const squadManager = SquadManager::m_instance; + float orderModifier = 0.0f; // -0x1F4 + bool wasCalled = false; // -0x1F9: the chosen vehicle answered a radio call + bool chooseSoldier = false; // -0x1FA: getting out won + + const unsigned int equipment = bot->getCurrentEquipment(); // -0x1D8 + Information* equipmentInfo = informationManager->getInformation(equipment); // -0x208, no null test + Vec3& pos = equipmentInfo->getPosition(); // -0x20C + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); // -0x210 + const bool isAir = (equipmentInfo->getObjectTypeFlags() & 0x200000) != 0; // -0x1FB + bool inArtillery = false; // -0x211 + double artillerySinceStart = 0.0; // -0x198 + int artillerySide = -1; // -0x190 + if (!(equipmentInfo->getObjectTypeFlags() & 0x10)) + { + // ELF 0x202D27 + if (squadManager->isInArtilleryDangerZone(pos, bot->getSide(), artillerySinceStart, artillerySide) + && artillerySinceStart > 4.0f) + inArtillery = true; + } + + if (!isAir && !isBailAllowed(bot)) + { + // ELF 0x202D10 -> 0x200AB4 + m_targetChanged[botId] = pattern->isInitiated(bot); + targets[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // ELF 0x200FB2: the current vehicle's primary object and its seats. + const unsigned int primary = equipmentInfo->getPrimaryObject(side); + Information* primaryInfo = informationManager->getInformation(primary); // -0x218 + Information* primaryInfoAgain = informationManager->getInformation(equipmentInfo->getPrimaryObject(side)); // -0x21C + unsigned int bestHandle = primary; // -0x1DC + float candidate; // -0x1E4 + int vehicleNumber; // -0x200 + if (equipment == primary) + { + // ELF 0x202C23 + candidate = 2.0f * calculateVehicleUrgency(bot, primaryInfo, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side); // fadd st,st + currentUrgency = candidate; + if (0.0f > currentUrgency) + currentUrgency = 0.0f; + vehicleNumber = -1; + if (primaryInfo->getMobile()) + { + vehicleNumber = primaryInfo->getMobile()->getVehicleNumber(); + primaryInfo->getUnit()->getEquipmentType(); // ELF 0x202CEA: result unused + } + } + else + { + candidate = 2.0f * calculateVehicleUrgency(bot, primaryInfo, enemyStrengths, enemyTypes, true, + equipmentInfo, fireShare, moveShare, side); + vehicleNumber = -1; + } + + float radioStrength; // -0x1F8 + bool upsideDown; // -0x212 + if (!isAir && isUpsideDown(primaryInfo, terrain, 0.7071f)) // rodata 0x49F580 + { + candidate = 0.0f; + upsideDown = true; + radioStrength = 1.0f; + if ((primaryInfo->getObjectTypeFlags() & 0x10) && !primaryInfo->getPhysical()->isInAir()) + { + // ELF 0x202BB9: a grounded air vehicle counts as upright again. + radioStrength = getRadioStrength(primaryInfo, bot); + upsideDown = false; + candidate *= radioStrength; + } + } + else + { + radioStrength = getRadioStrength(primaryInfo, bot); // ELF 0x202BE0 + upsideDown = false; + candidate *= radioStrength; + } + + float best = candidate; // -0x1E8 + Information* bestInfo = primaryInfo; // -0x1E0 + if (!upsideDown) + { + // ELF 0x2028A7: the current vehicle's seats. + unsigned int seatHandle = bestInfo->getFirstSecondaryObject(seatIterator, side); + Information* seat = informationManager->getInformation(seatHandle); // -0x220 + const float driverModifier = modifyForDriver(primaryInfo, primary == equipment); // -0x1F0 + while (seat) + { + if (seatHandle == equipment) + { + // ELF 0x202AE4 + candidate = 2.0f * calculateVehicleUrgency(bot, seat, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side) + * driverModifier * radioStrength; + currentUrgency = candidate; + if (0.0f > currentUrgency) + currentUrgency = 0.0f; + } + else + { + candidate = calculateVehicleUrgency(bot, seat, enemyStrengths, enemyTypes, true, + equipmentInfo, fireShare, moveShare, side) + * driverModifier * radioStrength; + } + // ELF 0x202A80: an idle flag-taking squad member prefers an unarmed (+0x2C) vehicle's seats. + if (!isAir && bot->getSquadMember()->isTakingFlag() && bot->getSquadMember()->getIsIdle() + && !primaryInfo->hasArmament()) + candidate *= 5.0f; + if (candidate > best) + { + bestHandle = seatHandle; + bestInfo = seat; + bestEntryPos = entryPos; + best = candidate; + } + seatHandle = primaryInfo->getSecondaryObject(seatIterator, side); + seat = informationManager->getInformation(seatHandle); + } + } + + // ELF 0x201175: getting out, against the radio message type 0 list. + const unsigned int soldier = bot->getPlayer()->getSoldier()->getInformation(side); + const std::list& requests = comm->getReceivedMessages(static_cast(0)); // -0x224 + bool requestValid = false; // -0x225 + if (!requests.empty() && liveHumanSender(requests)) + requestValid = true; + if (soldier != equipment) + { + Information* soldierInfo = informationManager->getInformation(soldier); // -0x22C + candidate = calculateVehicleUrgency(bot, soldierInfo, enemyStrengths, enemyTypes, false, + equipmentInfo, fireShare, moveShare, side) * 0.2f; + if (!requests.empty() && requestValid && !(equipmentInfo->getObjectTypeFlags() & 0x200000)) + candidate = 100.0f * requests.front().m_modifier * candidate; + if (!requests.empty() && requestValid && (equipmentInfo->getObjectTypeFlags() & 0x10)) + candidate = 10000.0f; // rodata 0x49F4C0 + if (inArtillery) + candidate = 10000.0f; + if (bot->isBotStuck() && soldierInfo) + { + bot->setBotStuck(false); + candidate = 10000.0f; + } + AIStrategicArea* area = bot->getSquadMember()->getSquad()->getSquadStrategicAreaAssignment(); + if (area) + { + // ELF 0x201388: getOrderPos (slot +0x14) for 0 and 1; a height step over 3 checks avoidance. + const Vec3 orderPos0 = area->getOrderPos(0, bot->getSide()); + const Vec3 orderPos1 = area->getOrderPos(1, bot->getSide()); + if (std::fabs(orderPos0.y - orderPos1.y) > 3.0f) + { + if (closeAndShouldAvoidVehicles(primaryInfoAgain, primaryInfoAgain->getSide(), bot)) + candidate = 10000.0f; + } + } + if (0.001f > currentUrgency) // rodata 0x49CC94 + candidate = 10000.0f; + soldierInfo->getMobile()->getVehicleNumber(); // ELF 0x201448: results unused + soldierInfo->getUnit()->getEquipmentType(); + if (candidate > best) + { + chooseSoldier = true; + best = candidate; + bestHandle = soldier; + bestInfo = soldierInfo; + } + } + + // ELF 0x20149A: an ordered "change" with an empty order list uses the memory's modifier (+0x08). + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + orderModifier = bot->getMemory()->m_float8; + else + orderModifier = 1.0f; + + // ELF 0x2014C7: a human (radio message type 1) asks for the vehicle the bot's target belongs to. + bool requestedByHuman = false; // -0x22D + unsigned int requestedPrimary = 0xFFFFFFFFu; // -0x234 + Information* currentTarget = informationManager->getInformation(targets[botId]); + if (currentTarget) + { + requestedPrimary = currentTarget->getPrimaryObject(side); + const std::list& calls = comm->getReceivedMessages(static_cast(1)); + if (!calls.empty() && (equipmentInfo->getObjectTypeFlags() & 0x200000)) + { + IAIPlayer* caller = liveHumanSender(calls); + if (caller && caller->getCurrentVehicle()->getPrimaryObject()->getInformation(side) == requestedPrimary) + requestedByHuman = true; + } + } + + unsigned int callingHandle = 0xFFFFFFFFu; // -0x238: the last scanned vehicle's caller state (retail) + if (!chooseSoldier && (requests.empty() || !requestValid) && !(equipmentInfo->getObjectTypeFlags() & 0x10) + && !inArtillery && !bot->getSquadMember()->isCloseToNonOwnedTarget()) + { + // ---- ELF 0x201AF9: every vehicle around. + m_vehicles.resize(0); + // ELF 0x201B6B: slot +0x14 returns the search radius in st0 (stored at -0x23C). + const float searchRadius = + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getHardware(m_vehicles, pos, bot); + bool reachable = false; // -0x241: not reset per vehicle (retail) + const std::list& calls = comm->getReceivedMessages(static_cast(1)); // -0x24C + const float searchRadiusSq = searchRadius * searchRadius; // -0x23C + Information* equipmentInfoAgain = informationManager->getInformation(bot->getCurrentEquipment()); // -0x250 + + for (std::vector::iterator it = m_vehicles.begin(); it != m_vehicles.end(); ++it) + { + callingHandle = 0xFFFFFFFFu; + unsigned int handle = *it; // -0x1A8 (passed by reference to isMannedByEnemy) + if (!calls.empty() && (equipmentInfo->getObjectTypeFlags() & 0x200000) + && isCallingVehicle(*it, calls, side)) + callingHandle = *it; + + Information* vehicle = informationManager->getInformation(handle); // -0x254 + if (!vehicle || vehicle == primaryInfoAgain || (vehicle->getObjectTypeFlags() & 0x200000)) + continue; + if (requestedByHuman && handle != requestedPrimary) + continue; + if (vehicle->getObjectTypeFlags() & 0x80) + { + // ELF 0x201CF2: only the vehicle the calling human sits in, airborne and in water. + if (calls.empty()) + continue; + IAIPlayer* caller = liveHumanSender(calls); + if (!caller) + continue; + const unsigned int callerVehicle = + caller->getCurrentVehicle()->getPrimaryObject()->getInformation(side); + Information* callerVehicleInfo = informationManager->getInformation(callerVehicle); + if (handle != callerVehicle || !callerVehicleInfo || !callerVehicleInfo->getPhysical()) + continue; + IPIPhysical* physical = callerVehicleInfo->getPhysical(); + if (!physical->isInAir() || !physical->isInWater()) + continue; + } + if (!vehicle->getAIObject()->getIsAllowedByBots()) + continue; + if (isMannedByEnemy(handle, vehicle, side)) + continue; + + Vec3& vehiclePos = vehicle->getPosition(); // -0x258 + IPIMobile* mobile = vehicle->getMobile(); // -0x248 + if (mobile && !(vehicle->getObjectTypeFlags() & 0x10)) + { + // ELF 0x202570: no valid navmesh position - only the calling human's vehicle. + const IPIMobile::ValidPos lastValid = mobile->getLastValidPosition(); + if (lastValid.quadTree == 0xFFFFFFFFu) + { + if (calls.empty()) + continue; + IAIPlayer* caller = liveHumanSender(calls); + if (!caller) + continue; + const unsigned int callerPrimary = + caller->getCurrentVehicle()->getPrimaryObject()->getInformation(side); + const unsigned int callerVehicle = caller->getCurrentVehicle()->getInformation(side); + if (handle != callerPrimary || handle != callerVehicle) + continue; + } + } + if (mobile && !(vehicle->getObjectTypeFlags() & 0x10) && !(vehicle->getObjectTypeFlags() & 0x200000) + && isUpsideDown(vehicle, terrain, 0.7071f)) + continue; + + // ELF 0x201E9A: distance falloff, 1 at the bot down to 0 beyond the search radius. + IPIUnit* unit = vehicle->getUnit(); + Vec3 delta; + delta.x = vehiclePos.x - pos.x; + delta.y = vehiclePos.y - pos.y; + delta.z = vehiclePos.z - pos.z; + const float distSq = delta.z * delta.z + delta.y * delta.y + delta.x * delta.x; // -0x240 + float falloff = (searchRadiusSq - distSq * 0.8f) / searchRadiusSq; + if (0.5f <= falloff) + falloff = 0.5f; + float distanceFactor = 0.0f; // -0x25C + if (0.0f <= falloff + 0.5f) + distanceFactor = falloff + 0.5f; + + if (vehicleNumber == -1) + { + reachable = true; // ELF 0x202530 + } + else if (unit) + { + if (unit->useNoPathfindingToGetToObject() || !vehicle->getMobile()) + { + reachable = true; // ELF 0x2024FE + entryPos = unit->getEntryPositionOfNonMobile(); + } + else + { + // ELF 0x201FA9: vehicle number 0, not vehicleNumber (retail). + const IPIMobile::ValidPos& valid = mobile->getLastValidPosition(0); + if (vehicle->getPhysical()) + { + const float radius = vehicle->getPhysical()->getRadius(); + if (equipmentInfoAgain->getPhysical()) + { + const float ownRadius = equipmentInfoAgain->getPhysical()->getRadius(); + Vec3 gap; + gap.x = vehiclePos.x - valid.position.x; + gap.y = vehiclePos.y - valid.position.y; + gap.z = vehiclePos.z - valid.position.z; + reachable = gap.x * gap.x + gap.y * gap.y + gap.z * gap.z + < (radius + ownRadius) * (radius + ownRadius); + } + } + } + } + bool usable; + if (!vehicle->getMobile() || (vehicle->getObjectTypeFlags() & 0x10)) + usable = true; + else + usable = reachable; + if (!usable || !reachable) + continue; + + // ELF 0x2020CB: the vehicle's primary seat. + radioStrength = getRadioStrength(vehicle, bot); + float urgency = calculateVehicleUrgency(bot, vehicle, enemyStrengths, enemyTypes, true, + equipmentInfo, fireShare, moveShare, side) + * distanceFactor * radioStrength; + candidate = urgency; + if (requestedByHuman) + candidate = urgency * 5.0f; + // ELF 0x2024AD: no null test of the physical plug-in here (the seat loop has one). + if (isAir && 400.0f > distSq && 0.25f > equipmentInfo->getPhysical()->getHealth()) + candidate *= 50.0f; + if (callingHandle != 0xFFFFFFFFu) + candidate *= calls.front().m_modifier; + if (candidate > best) + { + const unsigned int flags = vehicle->getObjectTypeFlags(); + if (!(flags & 0x10) || (flags & 0x20) || runwayClear(vehicle, equipmentInfo, side)) + { + bestHandle = handle; + wasCalled = callingHandle != 0xFFFFFFFFu; + best = candidate; + bestEntryPos = entryPos; + bestInfo = vehicle; + } + } + + // ELF 0x20222D: its seats. + unsigned int seatHandle = vehicle->getFirstSecondaryObject(seatIterator, side); + Information* seat = informationManager->getInformation(seatHandle); + const float driverModifier = modifyForDriver(vehicle, false); // -0x1F0 + while (seat) + { + urgency = calculateVehicleUrgency(bot, seat, enemyStrengths, enemyTypes, true, equipmentInfo, + fireShare, moveShare, side) + * radioStrength * distanceFactor * driverModifier; + candidate = urgency; + if (requestedByHuman) + candidate = urgency * 5.0f; + else if (isAir && 400.0f > distSq && equipmentInfo->getPhysical() + && 0.25f > equipmentInfo->getPhysical()->getHealth()) + candidate = candidate * 50.0f; + if (callingHandle != 0xFFFFFFFFu) + candidate *= calls.front().m_modifier; + if (candidate > best) + { + bestHandle = seatHandle; + wasCalled = callingHandle != 0xFFFFFFFFu; + bestEntryPos = entryPos; + best = candidate; + bestInfo = seat; + } + seatHandle = vehicle->getSecondaryObject(seatIterator, side); + seat = informationManager->getInformation(seatHandle); + } + } + } + + // ---- ELF 0x2015B0: commit the choice. + if (bestHandle == equipment) + { + // ELF 0x201A50: nothing better than staying - refuse a caller and drop the choice. + if (isAir && callingHandle != 0xFFFFFFFFu) + denyGetIn(equipmentInfo, callingHandle, comm); + m_targetChanged[botId] = pattern->isInitiated(bot); + targets[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + const bool samePrimary = bestInfo->getPrimaryObject(side) == equipmentInfo->getPrimaryObject(side); // -0x25D + m_targetChanged[botId] = targets[botId] != bestHandle; + targets[botId] = bestHandle; + if (isAir && callingHandle != 0xFFFFFFFFu && !botChoiceInVehicle(targets[botId], callingHandle, side)) + denyGetIn(equipmentInfo, callingHandle, comm); + static_cast(m_pattern)->init(bestHandle, bestEntryPos, samePrimary, wasCalled, bot); + + // ELF 0x2016B2: the 1.0f (rodata 0x49CB2C) is a separate factor of the scale in the image. + const float unitFactor = 1.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float ratio = currentUrgency != 0.0f ? best * 0.5f / currentUrgency : best * 0.5f; + m_urgency[botId] = DecleiningSlopeCurve::calculate(ratio) * (unitFactor * scale * 4.0f) * orderModifier; + const double sincePossessed = now - equipmentInfo->getUnit()->getLastPlayerPossesionTime(); // fstpl + if (15.0f > sincePossessed) + m_urgency[botId] *= 6.0f; + + if (chooseSoldier) + { + // ELF 0x201930: bailing out of a damaged vehicle says so on the radio. + Information* current = informationManager->getInformation(bot->getCurrentEquipment()); + if (current) + { + if (IPIPhysical* physical = current->getPhysical()) + { + const float health = physical->getHealth(); + if (IBotManager::instance->getVehicleBailValue() + 0.1f >= health) + comm->sendImmediately(static_cast(0), + static_cast(7), 10, 0); + } + m_urgency[botId] *= 5.0f; + } + } + if (isAir) + { + // ELF 0x201843 + const Vec3& bestPos = bestInfo->getPosition(); + Vec3 delta; + delta.x = bestPos.x - pos.x; + delta.y = bestPos.y - pos.y; + delta.z = bestPos.z - pos.z; + if (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z < 400.0f && equipmentInfo->getPhysical() + && equipmentInfo->getPhysical()->getHealth() < 0.25f) + m_urgency[botId] *= 5.0f; + } + + // ELF 0x2017AC: no null test of the target information (retail). + Information* target = informationManager->getInformation(targets[bot->getBotId()]); + bot->insertBehaviourInformation(0.5f, target->getPosition(), m_index); + m_urgency[botId] = checkBookings(bot); + return m_urgency[botId]; +} + +// ELF 0x2006A0: a positive urgency drops to 0 while the chosen vehicle is booked by someone else +// (Bot::getPlayerId, slot +0xB4). +float BBChange::checkBookings(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); + float urgency = m_urgency[botId]; + Information* target = informationManager->getInformation(m_targets[botId]); + if (target && target->isBooked() && !target->isBookedBy(bot->getPlayerId())) + { + if (m_urgency[botId] > 0.0f) // fcmovnbe against rodata 0x49CB34 + urgency = 0.0f; + } + return urgency; +} + +// ELF 0x202E20: a driver seat recently given up by a player (less than 15 s, rodata 0x49CDC4) keeps +// 1.0f; otherwise by flag 0x80 -> 1.0f, 0x40 -> 0.77f (rodata 0x49F58C), 0x10 -> 0.5f, else 1.0f. +float BBChange::modifyForDriver(Information* vehicle, bool current) +{ + if (!vehicle) + return 1.0f; + IPIUnit* unit = vehicle->getUnit(); + // ELF 0x202E54: the time is taken before the unit's null test (retail order). + const double sincePossessed = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime() + - vehicle->getUnit()->getLastPlayerPossesionTime(); + if (!unit) + return 1.0f; + if (!current && unit->isOccupied()) + return 1.0f; + if (!vehicle->getMobile()) + return 1.0f; + if (15.0f > sincePossessed) + return 1.0f; + const unsigned int flags = vehicle->getObjectTypeFlags(); + if (flags & 0x80) + return 1.0f; + if (flags & 0x40) + return 0.77f; + if (flags & 0x10) + return 0.5f; + return 1.0f; +} + +// ELF 0x202F00: an orthographic frustum along the aircraft's flattened forward axis (box size x/y +// times 1.2, rodata 0x49F590; near z * -0.6, rodata 0x49CFA4; far z * 12, rodata 0x49F594) must hold +// no obstacle (RunwayObstructedPredicate) for the given side. +bool BBChange::runwayClear(Information* aircraft, Information* other, int side) const +{ + LocalBoundingBox* box = const_cast(aircraft->getPhysical()->getLocalBoundingBox()); + const float sizeX = box->getSize().x; + const float sizeZ = box->getSize().z; + const float sizeY = box->getSize().y; + aircraft->getPosition(); // ELF 0x202F6F: slot +0x30, result unused + + // ELF 0x202F7D: the matrix is zeroed (16 x 0.0f) before the copy, then row 2's y is cleared and the + // rows are re-orthonormalised: row 1 receives the third axis, rows 2 and 0 are rewritten. + Mat4 transform; + for (int i = 0; i < 16; ++i) + transform.m[i] = 0.0f; + transform = aircraft->getTransformation(); + transform.m[9] = 0.0f; + reinterpret_cast(&transform.m[4])->makeOrthonormalBasis(*reinterpret_cast(&transform.m[8]), + *reinterpret_cast(&transform.m[0])); + + const float widthScale = 1.2f; + const float farScale = 12.0f; + Frustum frustum; + frustum.setOrtho(sizeX * widthScale, sizeY * widthScale, sizeZ * -0.6f, sizeZ * farScale, transform); + + m_runwayObstacles.resize(0); + RunwayObstructedPredicate predicate(aircraft, other); + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getObjectsWithinFrustum(m_runwayObstacles, frustum, side, true, &predicate); + return m_runwayObstacles.size() == 0; +} + +// ELF 0x203210: 1.0f for flag 0x200000, else 1.0f squared (fmul st,st of rodata 0x49CB2C). +float BBChange::getRadioStrength(Information* vehicle, Bot*) const +{ + const float strength = 1.0f; + if (vehicle->getObjectTypeFlags() & 0x200000) + return strength; + return strength * strength; +} + +// ELF 0x203240: a vehicle of another side (Information slot +0x44) that is occupied for our side. +bool BBChange::isMannedByEnemy(unsigned int& handle, Information* vehicle, int& side) const +{ + bool manned = false; + if (vehicle->getSide() != side && vehicleOccupied(handle, side)) + manned = true; + return manned; +} + +// ELF 0x2032A0: the transformation's m[5] (row 1, y; +0x14) below 0.01f (rodata 0x49CB30). The terrain +// and the threshold argument are not read. +bool BBChange::isUpsideDown(Information* vehicle, IAITerrain*, float) const +{ + return 0.01f > vehicle->getTransformation().m[5]; +} + +// ELF 0x2032E0: always true while the bot has its soldier information, except an air vehicle (flag +// 0x10) that is primary and between 2 and 12 (rodata 0x49CC74 / 0x49F594) above the aerial height map. +bool BBChange::isBailAllowed(Bot* bot) const +{ + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + Information* soldier = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(bot->getSide())); + if (!soldier) + return false; + if (equipment->isPrimary()) + { + // ELF 0x2033D3: the position and two unused queries, then the altitude test. + const Vec3& position = equipment->getPosition(); + equipment->getUnit()->useNoPathfindingToGetToObject(); + equipment->isPrimary(); + if (equipment->getObjectTypeFlags() & 0x10) + { + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + if (altitude > 2.0f && 12.0f > altitude) + return false; + } + } + // ELF 0x2033A1: both outcomes of the remaining tests answer true (retail). + if (equipment->getMobile()) + return true; + if (equipment->isPrimary()) + return true; + return true; +} + +// ELF 0x203460: a not-yet-handled (m_flag16) message whose sender owns the vehicle or one of its seats +// (IAIObject slot +0x148, inlined Information::getPlayerId). False when the vehicle is manned by an enemy. +bool BBChange::isCallingVehicle(unsigned int handle, const std::list& messages, int side) const +{ + Information* vehicle = informationManager->getInformation(handle); + int seatIterator = 0; + if (isMannedByEnemy(handle, vehicle, side)) + return false; + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + if (it->m_flag16) + continue; + if (vehicle->getAIObject()->getPlayerId() == it->m_senderPlayerId) + return true; + Information* seat = informationManager->getInformation(vehicle->getFirstSecondaryObject(seatIterator, side)); + while (seat) + { + if (seat->getAIObject()->getPlayerId() == it->m_senderPlayerId) + return true; + seat = informationManager->getInformation(vehicle->getSecondaryObject(seatIterator, side)); + } + } + return false; +} + +// ELF 0x203610: after a confirmed get-in request (message type 1), a caller closer than 15 (225 squared, +// rodata 0x49CF4C) hears message 7 on channel 6, priority 3, delay 1.0f, -1. +void BBChange::denyGetIn(Information* vehicle, unsigned int caller, CommunicationAgent* comm) const +{ + if (!comm->generalConfirmReceivedMessage(static_cast(1))) + return; + // ELF 0x20366C: no null test of the caller's information (retail). + const Vec3 callerPos = informationManager->getInformation(caller)->getPosition(); + const Vec3 vehiclePos = vehicle->getPosition(); + Vec3 delta; + delta.x = vehiclePos.x - callerPos.x; + delta.y = vehiclePos.y - callerPos.y; + delta.z = vehiclePos.z - callerPos.z; + if (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z < 225.0f) + comm->enqueueRadioMessage(static_cast(7), static_cast(6), 3, 1.0f, -1); +} + +// ELF 0x203740: true when the bot's target is the calling vehicle's primary object or one of its seats. +bool BBChange::botChoiceInVehicle(unsigned int target, unsigned int caller, int side) const +{ + Information* callerPrimary = + informationManager->getInformation(informationManager->getInformation(caller)->getPrimaryObject(side)); + if (callerPrimary == informationManager->getInformation(target)) + return true; + int seatIterator; // ELF -0x10: not initialised (getFirstSecondaryObject sets it) + unsigned int seatHandle = callerPrimary->getFirstSecondaryObject(seatIterator, side); + Information* seat = informationManager->getInformation(seatHandle); + while (seat) + { + if (seatHandle == target) + return true; + seatHandle = callerPrimary->getSecondaryObject(seatIterator, side); + seat = informationManager->getInformation(seatHandle); + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h new file mode 100644 index 000000000..185ae61fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.h @@ -0,0 +1,63 @@ +// Change behaviour (the "Change" slot of aibehaviours.ai): picks the vehicle or seat a bot should get +// into (or back out of) and hands it to the BBPChange pattern. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. Virtual functions are in ELF vtable slot order (vtable check). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGE_H + +#include +#include +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +struct AIRadioMessageInfo; +class Bot; +class CommunicationAgent; +class IAITerrain; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA860 (13 words), operator new 0x44, package F-infantry. +class BBChange : public BotBehaviour +{ +public: + BBChange(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x200240 + virtual ~BBChange(); // 0x200530 + + virtual float calculateUrgency(Bot*, bool, float); // 0x200770, slot +0x28; from the base declaration + + float checkBookings(Bot*); // 0x2006A0; float in st0 (flds of the urgency slot) + float modifyForDriver(Information*, bool); // 0x202E20; float in st0 (1.0f / 0.77f / 0.5f) + bool runwayClear(Information*, Information*, int) const; // 0x202F00; bool: sete + movzbl + float getRadioStrength(Information*, Bot*) const; // 0x203210; float in st0 + bool isMannedByEnemy(unsigned int&, Information*, int&) const; // 0x203240; bool byte + bool isUpsideDown(Information*, IAITerrain*, float) const; // 0x2032A0; bool: seta + movzbl + bool isBailAllowed(Bot*) const; // 0x2032E0; 0/1 in eax, both callers test %al + bool isCallingVehicle(unsigned int, const std::list&, int) const; // 0x203460; 0/1, callers test %al + void denyGetIn(Information*, unsigned int, CommunicationAgent*) const; // 0x203610; ELF void + bool botChoiceInVehicle(unsigned int, unsigned int, int) const; // 0x203740; 0/1, the caller tests %al + +private: + // The constructors zero +0x24..+0x40 and the destructors free them (ELF 0x200480 / 0x200530 / 0x2005E0). + // The base +0x08 (m_targets) is the per-bot chosen vehicle or seat (unsigned int[bot], -1 = none). + /* +0x24 */ std::vector m_vehicles; // calculateUrgency: the getHardware list + // runwayClear (a const member) resizes and refills it: [INFERRED] mutable. + /* +0x30 */ mutable std::vector m_runwayObstacles; + // [UNRESOLVED] Nothing in this TU writes these except the constructors' 0; every destructor deletes + // them through vtable slot +4 (the deleting destructor), +0x3C first. The pointee type is + // [CHOSEN, not recovered]: UrgeCurve, a polymorphic type whose delete compiles to the same call. + /* +0x3C */ UrgeCurve* m_unknown3C; + /* +0x40 */ UrgeCurve* m_unknown40; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp new file mode 100644 index 000000000..88d1e4408 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp @@ -0,0 +1,291 @@ +// Landing-craft seat selection and disembark urgency, recovered from libaidll.so. + +// static init: ELF 0x204EA0 (__tcf_0 0x204F00, _GLOBAL__I 0x204F30): 's Init object only. +#include + +#include "BBChangeLandingCraft.h" + +#include "CustomCurve.h" +#include "VehicleUrgencyCalculator.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPChange.h" +#include "../AIBotBehaviourPattern/BBPChangeLandingCraft.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategicMap/BFStrategicEnvironment.h" +#include "../Main/IBotManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2039C0 (C2) / 0x203A80 (C1); vtable GOT -0xDE0. The BBAvoid shape: the base gets getMaxNBots +// (IAISettings slot 0); a second getMaxNBots sizes the +0x08 target array (plain operator new[]), +// and every bot starts with urgency 0.0f (rodata 0x49CB34) and target 0xFFFFFFFF. +BBChangeLandingCraft::BBChangeLandingCraft(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x203B40 (D2) / 0x203B90 (D1) / 0x203BE0 (D0): delete[] +0x08 when set, then ~BotBehaviour. +BBChangeLandingCraft::~BBChangeLandingCraft() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x203DD0 +float BBChangeLandingCraft::calculateUrgency(Bot* bot, bool evaluate, float) +{ + if (!evaluate) + { + m_urgency[bot->getBotId()] = 0.0f; + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + const float urgency = checkLandingCraftBookings(bot); + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; + } + std::list unusedObjects; + float fireShare; + float moveShare; + if (bot->getMoveInclination() > 0.0f) + { + if (bot->getFireInclination() > 0.0f) + { + const float fire = bot->getFireInclination(); + const float sum = bot->getMoveInclination() + fire; + fireShare = bot->getFireInclination() / sum; + moveShare = bot->getMoveInclination() / sum; + } + else { fireShare = 0.0f; moveShare = 1.0f; } + } + else if (bot->getFireInclination() > 0.0f) + { fireShare = 1.0f; moveShare = 0.0f; } + else { fireShare = 0.5f; moveShare = 0.5f; } + + const int side = bot->getSide(); + unsigned int bestHandle = bot->getCurrentEquipment(); + Information* current = informationManager->getInformation(bestHandle); + float orderFactor = 1.0f; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->empty()) + orderFactor = bot->getMemory()->m_float8; + IAIStrategicEnvironment* strategic = static_cast(AISingletonServer::m_iaiStrategicEnvironment); + const float* types = strategic->getEnemyTypes(bot); + const float* strengths = strategic->getEnemyStrengths(bot); + Information* primary = informationManager->getInformation(current->getPrimaryObject(side)); + IPIMobile* primaryMobile = primary ? primary->getMobile() : 0; + float primaryFactor = 1.0f; + float currentFactor = 1.0f; + const float secondaryFactor = 0.25f; + if (current->isPrimary()) + primary = current; + else if (!primary->getUnit()->isOccupied() && !(current->getObjectTypeFlags() & 0x80)) + { + primaryFactor = (current->getObjectTypeFlags() & 0x10) ? 1.5f : 1.0f; + currentFactor = 0.25f; + } + const bool currentIsPrimary = current == primary; + int iterator = primary->getFirstSecondaryObjectIterator(); + unsigned int handle = current->getPrimaryObject(side); + IPIUnit* primaryUnit = primary->getUnit(); + bool invalidPosition = false; + float best = 0.0f; + float currentUrgency = 0.0f; + Information* candidate = primary; + if (candidate) + { + do + { + const bool isCurrent = current == candidate; + float urgency = calculateVehicleUrgency(bot, candidate, strengths, types, !isCurrent, + current, fireShare, moveShare, side); + urgency *= isCurrent ? currentFactor : (candidate->isPrimary() ? primaryFactor : secondaryFactor); + urgency *= orderFactor; + if (candidate == primary && !primaryUnit->isOccupied() && primaryMobile) + { + const IPIMobile::ValidPos valid = primaryMobile->getLastValidPosition(); + if (valid.quadTree == 0xFFFFFFFFu) + { urgency = 0.0f; invalidPosition = true; } + else urgency += 100.0f; + } + if (isCurrent) + currentUrgency = urgency; + if (urgency > best) + { best = urgency; bestHandle = handle; } + handle = primary->getSecondaryObject(iterator, side); + candidate = informationManager->getInformation(handle); + } while (candidate && !invalidPosition); + } + + bool disembark = false; + const bool air = (primary->getObjectTypeFlags() & 0x10) != 0; + const Vec3& position = current->getPosition(); + bool canDisembark = false; + if (air) + { + SquadMember* member = bot->getSquadMember(); + if (member && currentIsPrimary) + { + const bool close = member->isCloseToNonOwnedTarget(10000.0f, 22500.0f); + const bool alone = isOnlyPrimaryInVehicle(current, side); + if (alone) + canDisembark = member->isCloseToNonOwnedTarget(625.0f, 10000.0f); + else if (close) + { + CommunicationAgent* communication = bot->getCommunicationAgent(); + if (!communication->getSentMessage(static_cast(0))) + communication->enqueueRadioMessage(static_cast(0), + static_cast(7), 10, 0.0f, -1); + } + } + } + else if (IPIPhysical* physical = primary->getPhysical()) + { + Vec3 contact = {0.0f, 0.0f, 0.0f}; + canDisembark = !physical->isInWater() || physical->isTouchingTerrain(contact); + } + if (canDisembark) + { + IPIMobile* mobile = primary->getMobile(); + canDisembark = air || mobile->getSpeedMagnitude() < 2.0f; + const int playerSide = bot->getSide(); + bot->getPlayer()->getSoldier()->getInformation(playerSide); + if (canDisembark) + { + if (air) + disembark = true; + else + { + const Vec3& valid = mobile->getLastValidInfantryPos().position; + const float dx = valid.x - position.x; + const float dy = valid.y - position.y; + const float dz = valid.z - position.z; + disembark = 16.0f > dx * dx + dy * dy + dz * dz; + } + } + } + if (!air && !(primary->getObjectTypeFlags() & 0x200000)) + { + Vec3 normal = {0.0f, 0.0f, 0.0f}; + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + terrain->getWaterLevel(position.x, position.z); + terrain->getHeight(position.x, position.z); + terrain->getNormal(position.x, position.z, normal); + } + const std::list& messages = bot->getCommunicationAgent()->getReceivedMessages(static_cast(0)); + if (air && !messages.empty()) + disembark = true; + if (current->getPhysical()) + { + const float health = current->getPhysical()->getHealth(); + if (IBotManager::instance->getVehicleBailValue() + 0.1f >= health) + { + disembark = true; + bot->getCommunicationAgent()->sendImmediately(static_cast(0), + static_cast(7), 10, 0); + } + } + if (disembark || invalidPosition) + { + const int playerSide = bot->getSide(); + bestHandle = bot->getPlayer()->getSoldier()->getInformation(playerSide); + const unsigned int botId = bot->getBotId(); + m_targetChanged[botId] = m_targets[bot->getBotId()] != 0xFFFFFFFFu; + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + if (air) + static_cast(m_pattern)->init(bestHandle, false, false, bot); + else + static_cast(m_pattern)->init(bestHandle, false, bot); + primary->getAIObject()->getPhysical(); // ELF 0x2044FC: result discarded. + static_cast(bot)->resetAllControls(true, true, true); + m_urgency[bot->getBotId()] = 4.0f; + } + else if (bestHandle == bot->getCurrentEquipment()) + { + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + const unsigned int botId = bot->getBotId(); + m_targetChanged[botId] = m_targets[bot->getBotId()] != bestHandle; + m_targets[bot->getBotId()] = bestHandle; + if (air) + static_cast(m_pattern)->init(bestHandle, true, false, bot); + else + static_cast(m_pattern)->init(bestHandle, true, bot); + const unsigned int urgencyId = bot->getBotId(); + const float ratio = currentUrgency > 0.0f ? (best * 0.5f) / currentUrgency : best * 0.5f; + m_urgency[urgencyId] = DecleiningSlopeCurve::calculate(ratio) * 4.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double sincePossessed = now - current->getUnit()->getLastPlayerPossesionTime(); + if (15.0f > sincePossessed) + m_urgency[bot->getBotId()] *= 6.0f; + } + const float urgency = checkLandingCraftBookings(bot); + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x203C30 +float BBChangeLandingCraft::checkLandingCraftBookings(Bot* bot) +{ + const unsigned int id = bot->getBotId(); + float urgency = m_urgency[id]; + Information* target = informationManager->getInformation(m_targets[id]); + if (target && target->isBooked() && !target->isBookedBy(bot->getPlayerId())) + if (m_urgency[id] > 0.0f) + urgency = 0.0f; + return urgency; +} + +// ELF 0x203D00 +bool BBChangeLandingCraft::isOnlyPrimaryInVehicle(Information* primary, int side) +{ + int iterator; + Information* seat = informationManager->getInformation(primary->getFirstSecondaryObject(iterator, side)); + while (seat) + { + if (seat->getUnit() && seat->getUnit()->isOccupied()) + return false; + seat = informationManager->getInformation(primary->getSecondaryObject(iterator, side)); + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.h new file mode 100644 index 000000000..70f82508f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.h @@ -0,0 +1,35 @@ +// Landing-craft seat selection and disembark urgency. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGELANDINGCRAFT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGELANDINGCRAFT_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA920 (13 words), operator new 0x24, package G-vehicles. +class BBChangeLandingCraft : public BotBehaviour +{ +public: + BBChangeLandingCraft(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x203A80 + virtual ~BBChangeLandingCraft(); // 0x203B90 + + virtual float calculateUrgency(Bot*, bool, float); // 0x203DD0, slot +0x28; from the base declaration + + float checkLandingCraftBookings(Bot*); // 0x203C30 + bool isOnlyPrimaryInVehicle(Information*, int); // 0x203D00 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGELANDINGCRAFT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp new file mode 100644 index 000000000..843a50d85 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp @@ -0,0 +1,218 @@ +// Rates teleporting between the current vehicle's seats and initializes its change pattern. + +// static init: ELF 0x205D70 (__tcf_0 0x205DD0, _GLOBAL__I 0x205E00): 's Init object only. +#include + +#include "BBChangeTeleport.h" + +#include "VehicleUrgencyCalculator.h" +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPChangeTeleport.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategicMap/BFStrategicEnvironment.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x204F50 (C2) / 0x205010 (C1); vtable GOT -0x1624. The BBAvoid shape: the base gets getMaxNBots +// (IAISettings slot 0); a second getMaxNBots sizes the +0x08 target array (plain operator new[]), +// and every bot starts with urgency 0.0f (rodata 0x49CB34) and target 0xFFFFFFFF. +BBChangeTeleport::BBChangeTeleport(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x2050D0 (D2) / 0x205120 (D1) / 0x205170 (D0): delete[] +0x08 when set, then ~BotBehaviour. +BBChangeTeleport::~BBChangeTeleport() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x2051C0 +float BBChangeTeleport::calculateUrgency(Bot* bot, bool evaluate, float) +{ + if (!evaluate) + { + m_urgency[bot->getBotId()] = 0.0f; + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + return m_urgency[bot->getBotId()]; + } + std::list unused; + float fireShare; + float moveShare; + if (bot->getMoveInclination() > 0.0f) + { + if (bot->getFireInclination() > 0.0f) + { + const float fire = bot->getFireInclination(); + const float sum = bot->getMoveInclination() + fire; + fireShare = bot->getFireInclination() / sum; + moveShare = bot->getMoveInclination() / sum; + } + else + { + fireShare = 0.0f; + moveShare = 1.0f; + } + } + else if (bot->getFireInclination() > 0.0f) + { + fireShare = 1.0f; + moveShare = 0.0f; + } + else + fireShare = moveShare = 0.5f; + + const int side = bot->getSide(); + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + equipment->getPrimaryObject(side); + float orderModifier = 1.0f; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + orderModifier = bot->getMemory()->m_float8; + IAIStrategicEnvironment* strategic = + static_cast(AISingletonServer::m_iaiStrategicEnvironment); + const float* types = strategic->getEnemyTypes(bot); + const float* strengths = strategic->getEnemyStrengths(bot); + unsigned int bestHandle = bot->getCurrentEquipment(); + float currentModifier; + float secondaryModifier; + float primaryModifier; + if (equipment->isPrimary()) + { + currentModifier = 1.0f; + secondaryModifier = 0.5f; + primaryModifier = 1.0f; + } + else + { + Information* primary = informationManager->getInformation(equipment->getPrimaryObject(side)); + if (primary->getUnit()->isOccupied()) + { + currentModifier = 1.0f; + secondaryModifier = primaryModifier = 0.5f; + } + else + { + const unsigned int flags = equipment->getObjectTypeFlags(); + if (flags & 0x80) + { + currentModifier = 0.5f; + secondaryModifier = 0.65f; + primaryModifier = 1.0f; + } + else if (flags & 0x40) + { + currentModifier = 0.5f; + secondaryModifier = 0.7f; + primaryModifier = 1.0f; + } + else if (flags & 0x10) + { + currentModifier = secondaryModifier = 0.5f; + primaryModifier = 1.5f; + } + else + currentModifier = secondaryModifier = primaryModifier = 1.0f; + } + } + bool isPrimary = equipment->isPrimary(); + Information* primary = equipment; + if (!isPrimary) + { + bestHandle = equipment->getPrimaryObject(side); + primary = informationManager->getInformation(bestHandle); + } + float current = calculateVehicleUrgency(bot, primary, strengths, types, !isPrimary, + equipment, fireShare, moveShare, side); + current *= isPrimary ? currentModifier : primaryModifier; + float best = current; + if (!isPrimary) + { + best *= orderModifier; + current = 0.0f; + } + int iterator; + unsigned int handle = primary->getFirstSecondaryObject(iterator, side); + Information* seat = informationManager->getInformation(handle); + while (seat) + { + const bool other = equipment != seat; + // shipped defect: each secondary is rated using the primary information record. + float candidate = calculateVehicleUrgency(bot, primary, strengths, types, other, + equipment, fireShare, moveShare, side); + candidate *= other ? secondaryModifier : currentModifier; + if (other) + candidate *= orderModifier; + else + current = candidate; + if (candidate > best) + { + best = candidate; + bestHandle = handle; + } + handle = primary->getSecondaryObject(iterator, side); + seat = informationManager->getInformation(handle); + } + if (bestHandle == bot->getCurrentEquipment() && fireShare < 0.05f && bot->getLodLevel() != 0) + { + const unsigned int changedIndex = bot->getBotId(); + m_targetChanged[changedIndex] = m_targets[bot->getBotId()] != 0xFFFFFFFFu; + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + static_cast(m_pattern)->init(bestHandle, false, bot); + m_urgency[bot->getBotId()] = 2.0f; + } + else if (bestHandle == bot->getCurrentEquipment()) + { + const bool initiated = m_pattern->isInitiated(bot); + m_targetChanged[bot->getBotId()] = initiated; + m_pattern->unInit(bot); + m_targets[bot->getBotId()] = 0xFFFFFFFFu; + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + const unsigned int changedIndex = bot->getBotId(); + m_targetChanged[changedIndex] = m_targets[bot->getBotId()] != bestHandle; + m_targets[bot->getBotId()] = bestHandle; + static_cast(m_pattern)->init(bestHandle, true, bot); + const unsigned int urgencyIndex = bot->getBotId(); + const float ratio = current > 0.0f ? (best * 0.5f) / current : best * 0.5f; + m_urgency[urgencyIndex] = DecleiningSlopeCurve::calculate(ratio) * 4.0f; + } + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double elapsed = now - equipment->getUnit()->getLastPlayerPossesionTime(); + if (elapsed < 15.0f) + { + const unsigned int index = bot->getBotId(); + m_urgency[index] = 6.0f * m_urgency[index]; + } + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.h new file mode 100644 index 000000000..c94f3ee08 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.h @@ -0,0 +1,31 @@ +// Urgency for changing seats through the teleport change pattern. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGETELEPORT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGETELEPORT_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BA9C0 (13 words), operator new 0x24, package G-vehicles. +class BBChangeTeleport : public BotBehaviour +{ +public: + BBChangeTeleport(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x205010 + virtual ~BBChangeTeleport(); // 0x205120 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2051C0, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBCHANGETELEPORT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp new file mode 100644 index 000000000..962cb476f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp @@ -0,0 +1,260 @@ +// Defuse-mines behaviour (infantry "DefuseMines" slot of aibehaviours.ai): an engineer (spawn kit 4) +// without a mine target looks for the closest hostile mine whose pathfinding position is reachable +// within 35 m. Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x207370 (__tcf_0 0x2073D0, _GLOBAL__I 0x207400): 's Init object only. +#include + +#include "BBDefuseMines.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPDefuseMines.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMineManager.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +inline float lengthSquared(float x, float y, float z) +{ + return x * x + y * y + z * z; +} + +} // namespace + +// ELF 0x205E20 (C2) / 0x206280 (C1). The base gets getMaxNBots (IAISettings slot 0); the empty +// vector at +0x24 is zeroed; +0x30 is new [getNBattleStrengths] (slot +0x34) and +0x34 new +// [getMaxNBots], both checkPointer'd, before the index/queue/pattern stores; +0x08 is new +// [getMaxNBots]; then every base urgency (+0x10) is 0.0f (rodata 0x49CB34) and every mine target -1. +BBDefuseMines::BBDefuseMines(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_unknown30 = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_mineTarget = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_mineTarget[i] = 0xFFFFFFFFu; + } +} + +// ELF 0x2066E0 (D2) / 0x206780 (D1) / 0x206820 (D0): delete[] +0x08, +0x30, +0x34 when set, then the +// vector at +0x24 (default_alloc deallocate) and the base. +BBDefuseMines::~BBDefuseMines() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown30) + delete[] m_unknown30; + if (m_mineTarget) + delete[] m_mineTarget; +} + +// ELF 0x2068C0. Bot slots +0x1F8 setMineTarget / +0x1FC getMineTarget are virtual calls in the image, +// but the Bot interface in AIBot/BotMain.h ends at +0x1DC; [CHOSEN, not recovered] the calls go +// through BotMain (the only Bot implementation, same slots) until ai-bot extends Bot. +float BBDefuseMines::calculateUrgency(Bot* bot, bool update, float urgencyScale) +{ + PlanGenerator* const pattern = m_pattern; + + if (!update) + { + // 0x2068E4..0x206A11: keep the current choice while a mine target is set. + if (m_mineTarget[bot->getBotId()] != 0xFFFFFFFFu) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) // PlanGenerator slot +0x0C + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + // 0x206980: fucompi against 0.0f, setp|setne (unordered counts as changed). + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); // PlanGenerator slot +0x10 + } + return m_urgency[bot->getBotId()]; + } + + float baseUrgency = 0.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); // Bot +0xD8 + unsigned int mineTarget = 0xFFFFFFFFu; + const unsigned int botId = bot->getBotId(); + const Vec3 botPosition = info->getPosition(); // Information slot +0x30 + int weaponIndex = -1; + // 0x206AAB: retail quirk, getNBattleStrengths (IAISettings +0x34) is called and its result dropped. + static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + + // 0x206AC4: virtual isApplicable (slot +0x34); then the soldier (0x200000) or 0x40 type flag. + if (isApplicable(info, bot) && + ((info->getObjectTypeFlags() & 0x200000) || (info->getObjectTypeFlags() & 0x40))) + { + if ((info->getObjectTypeFlags() & 0x200000) && info->getSoldierPose() == SPSwimming) + { + // 0x207255 + m_targetChanged[botId] = true; + pattern->unInit(bot); + m_urgency[botId] = 0.0f; + return 0.0f; + } + + // 0x206B01: a bot that already has a mine target (Bot +0x1FC) keeps its urgency. + if (static_cast(bot)->getMineTarget() != 0xFFFFFFFFu) + return m_urgency[botId]; + + // 0x206B29: the soldier's own Information (side from Bot +0xE0 first), its weapon list + // copied, and the index of the first weapon of type 1 (-1 when none). + const int side = bot->getSide(); + Information* const soldierInfo = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(side)); + std::vector weapons = soldierInfo->getArmament()->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 1) + { + weaponIndex = i; + break; + } + } + + IPIMobile* const mobile = soldierInfo->getMobile(); // +0x38, read once before the loop + SquadMember* const member = bot->getSquadMember(); // Bot +0x140 + std::vector ignoredMines; + Vec3 minePosition = {0.0f, 0.0f, 0.0f}; + Vec3 mineNormal = {0.0f, 0.0f, 0.0f}; + Vec3 targetPosition = {0.0f, 0.0f, 0.0f}; + bool done = false; + bool found = false; + int tries = 0; + while (!done) + { + // 0x206CF6: cmpl $0x64; jg -- at most 100 queries. + if (++tries > 100) + break; + + bool mineFlag; // [UNRESOLVED] meaning; its negation is passed as the MineType + unsigned int mineId; + // IAIGame slot +0x18 (declared int; the caller tests %al only, 0x206D91). + if (!static_cast(static_cast(CommonSingletonServer::m_iaiGame) + ->getClosestHostileMine(member->getPlayer(), botPosition, mineFlag, + minePosition, mineNormal, mineId, + ignoredMines))) + { + done = true; + continue; + } + + found = false; + unsigned int quadTree; + unsigned int polygon; + // ELF 0x206DDB calls the const-reference getter (0x2E1720), then copies its Vec3. + minePosition = static_cast(CommonSingletonServer::m_iAIMineManager) + ->getPathfindingPositionOfMine(mineId, static_cast(!mineFlag), + quadTree, polygon); + if (quadTree != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu) + { + targetPosition = minePosition; + // 0x206E2A: fucompi |normal.y| against 0.5f (rodata 0x49CB44); jbe pulls the target + // back 0.8f (rodata 0x49CB64) along the normal, also when unordered. + if (!(std::fabs(mineNormal.y) > 0.5f)) + { + targetPosition.x = minePosition.x - mineNormal.x * 0.8f; + targetPosition.y = minePosition.y - mineNormal.y * 0.8f; + targetPosition.z = minePosition.z - mineNormal.z * 0.8f; + } + // IAIPathfinding slot +0x2C; getEquipmentType (Information +0x40 unit, reread each + // pass) is evaluated before getVehicleNumber. + const int equipmentType = soldierInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = mobile->getVehicleNumber(); + if (IAIPathfinding::instance->isValidPosition(vehicleNumber, equipmentType, targetPosition, false)) + { + // 0x206F0B: rodata 0x49F6A4 1225.0f (35 m squared); 42.0f is rodata 0x49F6A8. + if (lengthSquared(targetPosition.x - botPosition.x, targetPosition.y - botPosition.y, + targetPosition.z - botPosition.z) < 1225.0f) + { + baseUrgency = 42.0f; + found = true; + mineTarget = mineId; + done = true; + continue; + } + } + } + ignoredMines.push_back(mineId); + } + + if (found) + { + // 0x206F81: flds base; fmuls urgencyScale. + m_urgency[botId] = baseUrgency * urgencyScale; + m_targetChanged[botId] = m_mineTarget[botId] != mineTarget; + m_mineTarget[botId] = mineTarget; + static_cast(pattern)->init(mineTarget, weaponIndex, bot, minePosition, targetPosition); + if (m_urgency[botId] == 0.0f) + static_cast(bot)->setMineTarget(0xFFFFFFFFu); // Bot +0x1F8 + return m_urgency[bot->getBotId()]; + } + + // 0x207105 + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = m_mineTarget[botId] != mineTarget; + pattern->unInit(bot); + m_mineTarget[botId] = mineTarget; + static_cast(bot)->setMineTarget(0xFFFFFFFFu); + return 0.0f; + } + + // 0x207294 + m_urgency[botId] = 0.0f; + m_targetChanged[botId] = m_mineTarget[botId] != 0xFFFFFFFFu; + m_mineTarget[botId] = 0xFFFFFFFFu; + pattern->unInit(bot); + static_cast(bot)->setMineTarget(0xFFFFFFFFu); + return 0.0f; +} + +// ELF 0x207310: bot->getPlayer() (+0xBC) alive (+0x24), not getManDown (+0x1B0), and the +// player's getSpawnKit (+0x44) == 4. +bool BBDefuseMines::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + if (bot->getManDown()) + return false; + return bot->getPlayer()->getSpawnKit() == 4; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.h new file mode 100644 index 000000000..52099896b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.h @@ -0,0 +1,47 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBDEFUSEMINES_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBDEFUSEMINES_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BAA60 (14 words), operator new 0x38, package F-infantry. +class BBDefuseMines : public BotBehaviour +{ +public: + BBDefuseMines(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x206280 + virtual ~BBDefuseMines(); // 0x206780 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2068C0, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x207310, slot +0x34; bool: 1 only for alive, not man-down, spawn kit 4 + + // Base m_targets (+0x08) is new unsigned int[getMaxNBots], uninitialised; no reader in this TU. + +private: + // Constructor 0x205E20/0x206280, destructor 0x2066E0/0x206780/0x206820. + /* +0x24 */ std::vector m_unknown24; // empty; freed as 4-byte elements; no F reader [UNRESOLVED] + /* +0x30 */ int* m_unknown30; // new [getNBattleStrengths] (IAISettings +0x34), uninitialised [UNRESOLVED] + /* +0x34 */ unsigned int* m_mineTarget; // new [getMaxNBots], each -1: the mine id each bot defuses [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBDEFUSEMINES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp new file mode 100644 index 000000000..b257b0b14 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp @@ -0,0 +1,1039 @@ +// Fire behaviour base (AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x20B720 (__tcf_0 0x20B780, _GLOBAL__I 0x20B7B0): 's Init object only. +#include + +#include "BBFire.h" + +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/checkPointer.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../Main/AIMain.h" +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotNavigation.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../../../AIInterface/BFKnowledge/IWeapon.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +// [INFERRED] the inline reader of io::Input: a mapped input's value, else 0. chooseWeapon +// (0x20B278) tests the 64-bit mapping mask and reads the value directly. +float mappedInput(const io::PlayerInput* input, io::PlayerInputMap index) +{ + return ((input->mappingFlags >> index) & 1) ? input->inputs[index] : 0.0f; +} + +} // namespace + +// ELF 0x2079B0 +BBFire::BBFire(unsigned char index, unsigned char queue, BBPFire* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, settings()->getMaxNBots()) + , m_double28(0.0) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + + const int bots = settings()->getMaxNBots(); + m_targets = checkPointer(new unsigned int[bots]); + m_unknown24 = checkPointer(new unsigned int[bots]); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_unknown24[i] = static_cast(-1); + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); + m_curve = new CustomCurve(&CustomCurve::modifiedSoftStepFunc, 0.0f, 1.0f, 0.03f); +} + +// ELF 0x207E80 +BBFire::~BBFire() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown24) + delete[] m_unknown24; + if (m_curve) + delete m_curve; +} + +// ELF 0x208040 (listing block by block; Ghidra pseudo-code cross-check). Scores every sensed, +// hostile, living object as a target and keeps the best one in the per-bot target array +// (BotBehaviour +0x08), its weapon index in m_unknown24, and hands both to the pattern through +// initializeGenerator. Without a target the behaviour is un-initialised and its urgency is 0. +// +// A candidate's score is the summed strength of it and its secondary objects (the own battle +// strength against it, its information strength and its battle strength against the own +// strength type, times its armour class value, the order factor and the area factor), times +// the range factor, the best weapon's strength, the indirect-sense age factor, the approach +// factor, the attack factor, the area factor, a CustomCurve of an AIRandom draw and the +// weapon's range quality, and * 0.33 when the summed strength is at most the harmless +// threshold. The current target is kept while it scores more than 1 / 1.2 of the best. +// The weapon-score array, the up vector and several dead Vec3 temporaries are as compiled. +float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + static bool checkOpportunist = false; // .bss; nothing in the image writes it + static float enemyStrengthTweak = 2.0f; // .data + + PlanGenerator* const pattern = m_pattern; + unsigned int* const targets = m_targets; + + if (!recalculate) + { + if (!pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = false; + return m_urgency[bot->getBotId()] = 0.0f; + } + if (!informationManager->getInformation(targets[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = true; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + float areaFactor = 0.5f; + const float* const armourClassValues = settings()->getArmourClassValues(); + + // 0x20821A: once a minute, forget the feedback of objects that no longer exist. + if (now - m_double28 > 60.0) + { + std::map::iterator it = m_feedback.begin(); + while (it != m_feedback.end()) + { + if (informationManager->getInformation(it->first)) + { + ++it; + continue; + } + delete it->second; + m_feedback.erase(it++); + } + m_double28 = now; + } + + const int side = bot->getSide(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& position = equipment->getPosition(); + const unsigned int flags = equipment->getObjectTypeFlags(); + if (!(flags & 0x80) && !(flags & 0x10) && (flags & 0x200000)) + { + // 0x209FE0: a passenger seat whose soldier pose is 4 does not fire. + if (equipment->isPrimary() && equipment->getSoldierPose() == 4) + { + m_targetChanged[bot->getBotId()] = true; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + } + + IPIUnit* const unit = equipment->getUnit(); + const int equipmentType = unit->getEquipmentType(); // called before the null test (retail) + IPIArmament* const armament = equipment->getArmament(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + if (!unit || !physical || !armament || !controlInfo) + { + m_targetChanged[bot->getBotId()] = true; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + + IPIMobile* const mobile = equipment->getMobile(); + const bool exposedSoldier = unit->hasExposedSoldier(); + const int strengthType = physical->getStrengthType(); + int soldierStrengthType = 0; + if (exposedSoldier) + { + // 0x209F74: the exposed soldier's own strength type. Retail quirk: no null test. + Information* const soldier = + informationManager->getInformation(bot->getPlayer()->getSoldier()->getInformation(side)); + soldierStrengthType = soldier->getPhysical()->getStrengthType(); + } + + const float zero = 0.0f; // -0x19C: never written again + unsigned int countedOrders = 0; // -0x1A4 + WeaponInfo* bestWeaponInfo = 0; // -0x204 + const unsigned int currentTarget = targets[bot->getBotId()]; + bot->getBotId(); // called, result unused + bool keepCurrentTarget = false; // -0x1A9: the current target scored again + + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(bot->getBotId()); + AIStrategicArea* const area = + static_cast(AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea)); + if (area && !area->isInside(position)) + areaFactor = 0.85f; + + Vec3 unused; // -0x158: zeroed, never read + unused.x = zero; + unused.y = zero; + unused.z = zero; + (void)unused; + equipment->getTransformation(); // 0x2084A6: called, result unused here + float bestDistance = zero; // -0x208 + m_unknown24[bot->getBotId()] = static_cast(-1); + + float currentTargetScore = zero; // -0x1B0 + float bestScore = zero; // -0x198 + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + if (!(object->m_flags & SensedObject::SENSE_SEEN) || !(object->m_flags & SensedObject::SENSE_SIDED)) + continue; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info) + continue; + if (info->getSide() == side || info->getSide() == 0) + continue; + IPIUnit* const targetUnit = info->getUnit(); + IPIPhysical* const targetPhysical = info->getPhysical(); + if (!targetPhysical) + continue; + const unsigned int targetFlags = info->getObjectTypeFlags(); + if ((targetFlags & 0x20000) || (targetFlags & 0x100000) || (targetFlags & 0x800000)) + continue; + if (0.0f >= targetPhysical->getHealth()) // 0x208B46 jae: a NaN health is kept + continue; + if ((object->m_flags & 0x20) && object->m_fireRating < 0) + continue; + + // 0x208B63: recent fire feedback on this object needs some movement to engage again. + BBPFeedback* const feedback = getBBPFeedback(object->m_handle); + if (now - feedback->m_time < 20.0) + { + float speed = 0.0f; + if (mobile) + speed = mobile->getSpeedMagnitude(); + if (info->getMobile()) + speed = speed + info->getMobile()->getSpeedMagnitude(); + if (speed < 2.0f) + continue; + static_cast(bot)->setHadPrecisionTimeStamp(now); + } + + // 0x208BDD: an object attacking the bot weighs up to 1.5 (3x for a human soldier), fading + // to 1.0 over 30 seconds. + float attackFactor; // -0x1B4 + double attackTime; + if (static_cast(bot)->isAttacking(object->m_handle, attackTime)) + { + const float age = static_cast(now - attackTime); + float ramp = age / 30.0f; + if (0.0f > ramp) + ramp = 0.0f; + else if (ramp > 1.0f) + ramp = 1.0f; + attackFactor = 1.5f - ramp * 0.5f; + if (!IBotManager::instance->getBotFromPlayerId(info->getPlayerId()) + && (info->getObjectTypeFlags() & 0x200000)) + attackFactor = attackFactor * 3.0f; + } + else + { + attackFactor = 1.0f; + } + + Vec3 targetPosition; // -0x168 + targetPosition.x = zero; + targetPosition.y = zero; + targetPosition.z = zero; + IPIMobile* const targetMobile = info->getMobile(); + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; // -0x148 + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + if (distance > 0.0001f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + } + float indirectFactor = 1.0f; // -0x224 + if (1.0f > distance) + distance = 1.0f; + + if (object->m_flags & SensedObject::SENSE_INDIRECT) + { + // 0x208D65: an object not seen directly must stand on ground the bot's vehicle can use. + if (!mobile) + continue; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + if (!targetMobile) + continue; + const IPIMobile::ValidPos& valid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + if (valid.polygon == static_cast(-1)) + continue; + if (targetUnit->getEquipmentType() != equipmentType) + { + unsigned char material; + pathfinding->getMaterial(mobile->getVehicleNumber(), valid.quadTree, valid.polygon, material); + if (!settings()->isValidMaterial(equipmentType, material)) + continue; + } + const float age = static_cast(now - object->m_firstSeenTime); + indirectFactor = 1.0f / (age * 0.05f + 1.5f); + } + else if (!mobile) + { + // 0x209D64: a static weapon needs the seen part inside its camera's range of directions. + Vec3 cameraBase; + cameraBase.x = zero; + cameraBase.y = zero; + cameraBase.z = zero; + controlInfo->getCameraBasePos(cameraBase); + Vec3 seen; + seen.x = zero; + seen.y = zero; + seen.z = zero; + const Mat4& transformation = info->getTransformation(); + const Vec3& local = object->m_seenPosition; + // 0x209DC3..0x209DEC: ((m4*y + m0*x) + m8*z) + m12. + seen.x = transformation.m[4] * local.y + transformation.m[0] * local.x + + transformation.m[8] * local.z + transformation.m[12]; + seen.y = transformation.m[1] * local.x + transformation.m[5] * local.y + + transformation.m[9] * local.z + transformation.m[13]; + seen.z = local.x * transformation.m[2] + local.y * transformation.m[6] + + local.z * transformation.m[10] + transformation.m[14]; + const unsigned int ownFlags = equipment->getObjectTypeFlags(); + if (!(ownFlags & 0x10) || (ownFlags & 0x20)) + { + if (!controlInfo->validateCameraDirectionByPos(seen)) + continue; + } + } + + // 0x208E82: the strongest usable weapon against the target's strength type, and the + // longest range of all weapons. + float bestWeaponScore = 0.0f; // -0x238 + int bestWeapon = -1; // -0x234 + float maxRange = 0.0f; // -0x230 + float weaponScores[8]; // -0x138 + std::vector& weapons = armament->getWeapons(); + int i; + for (i = 0; static_cast(i) < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + { + weaponScores[i] = 0.0f; + continue; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + const int weaponType = weapon->getWeaponType(); + if (weaponType != 0 && weaponType != 4 && weaponType != 3) + { + weaponScores[i] = 0.0f; + continue; + } + if (weaponType == 4 && targetMobile) + { + // Retail: the skipped weapon's score is left unwritten. + const Vec3 faceing = equipment->getFaceing(); + const Vec3& speed = targetMobile->getSpeed(); + if (std::fabs(speed.y * faceing.y + speed.x * faceing.x + speed.z * faceing.z) > 4.0f) + continue; + } + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + if (ammo > 0) + weaponScores[i] = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + else + weaponScores[i] = 0.0f; + if (i == armament->getActiveWeapon()) + weaponScores[i] = weaponScores[i] * 1.03f; + if (weaponScores[i] > bestWeaponScore) + { + bestWeapon = i; + bestWeaponScore = weaponScores[i]; + bestWeaponInfo = weapon; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestWeaponScore == 0.0f) + continue; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + + Vec3 targetSpeed; // -0x118 + targetSpeed.x = 0.0f; + targetSpeed.y = 0.0f; + targetSpeed.z = 0.0f; + if (targetMobile) + targetSpeed = targetMobile->getSpeed(); + const float targetSpeedMagnitude = std::sqrt(targetSpeed.x * targetSpeed.x + targetSpeed.y * targetSpeed.y + + targetSpeed.z * targetSpeed.z); + + float targetAreaFactor = areaFactor; // -0x1A0 + if (mobile && !(equipment->getObjectTypeFlags() & 0x10) && area && !area->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.85f; + + // 0x209247: the approach factor (-0x258). + float approachFactor; + bool closing = true; // falls through to the closing-speed estimate below + if (info->getObjectTypeFlags() & 0x10) + { + // 0x209C55: an aircraft target. + const int antiAircraft = armament->isAntiAircraft(); + if (!antiAircraft) + { + if (info->getAltitude() > 5.0f) + continue; + if (distance > maxRange * 0.5f || targetSpeedMagnitude > 5.0f) // 0x209D15 ja, 0x209D21 jbe + { + approachFactor = 0.0f; + closing = false; + } + } + else + { + if (checkOpportunist && antiAircraft == 2) + { + const Mat4& transformation = equipment->getTransformation(); + if (direction.y * transformation.m[5] + direction.x * transformation.m[4] + + direction.z * transformation.m[6] + > 0.5f) + continue; + } + if (maxRange * 0.9f > distance) // 0x209C8D jbe + { + approachFactor = 1.0f; + closing = false; + } + } + } + if (closing) + { + if (!targetMobile || !(distance > maxRange)) + { + approachFactor = 1.0f; + targetAreaFactor = 0.5f; + } + else + { + // 0x20927A: out of range; how fast the target can close in or cross. + float ownMaxSpeed = 0.0f; + Vec3 ownSpeed; // -0x108 + ownSpeed.x = 0.0f; + ownSpeed.y = 0.0f; + ownSpeed.z = 0.0f; + if (mobile) + { + ownMaxSpeed = mobile->getMaxSpeed(); + ownSpeed = mobile->getSpeed(); + } + if (targetMobile->getMaxSpeed() - ownMaxSpeed > 5.0f) + { + Vec3 up; // -0xD8 + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + Vec3 across; // -0xF8: up x direction + across.x = up.y * direction.z - up.z * direction.y; + across.y = up.z * direction.x - up.x * direction.z; + across.z = up.x * direction.y - up.y * direction.x; + const Vec3& speed = targetMobile->getSpeed(); + float towards = (direction.x * speed.x + direction.y * speed.y + direction.z * speed.z) + - (direction.x * ownSpeed.x + direction.y * ownSpeed.y + direction.z * ownSpeed.z); + float sideways = (across.x * speed.x + across.y * speed.y + across.z * speed.z) + - (ownSpeed.x * across.x + ownSpeed.y * across.y + ownSpeed.z * across.z); + if (0.0f > towards) // 0x209BB4 fcmovbe keeps a NaN + towards = 0.0f; + if (0.0f > sideways) + sideways = 0.0f; + const float speedMagnitude = std::sqrt(speed.x * speed.x + speed.y * speed.y + speed.z * speed.z); + approachFactor = 0.25f / (towards + towards + up.y + (sideways + sideways) + + speedMagnitude * 0.5f); + } + else + { + approachFactor = 0.25f; + } + } + } + + if (distance > maxRange) + { + // 0x209325: out of range; the bot must be able to drive to the target in 5 seconds. + if (!targetMobile || !mobile) + continue; + const IPIMobile::ValidPos& valid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + if (valid.polygon == static_cast(-1)) + continue; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + if (targetUnit->getEquipmentType() != equipmentType) + { + unsigned char material; + pathfinding->getMaterial(mobile->getVehicleNumber(), valid.quadTree, valid.polygon, material); + if (!settings()->isValidMaterial(equipmentType, material)) + continue; + } + if (distance - maxRange > mobile->getMaxSpeed() * 5.0f) + continue; + } + + // 0x209461: the strength of the object and its secondary objects (seats). + if (!info->getUnit() || !vehicleOccupied(object->m_handle, side)) + continue; + float strengthSum = 0.0f; // -0x278 + float score = 0.0f; // -0x194 + unsigned int partHandle = object->m_handle; + Information* part = info; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + do + { + IPIUnit* partUnit = part->getUnit(); + const unsigned int occupied = partUnit->getOccupiedObject(side); + if (occupied != static_cast(-1)) + { + Information* const occupier = informationManager->getInformation(occupied); + if (occupier) + partUnit = occupier->getUnit(); + } + strengthSum = strengthSum + partUnit->getBattleStrengths()[strengthType]; + bool ordered = false; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->size() > countedOrders) + { + if (bot->getOrderList(m_index)->end() + != std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), + partHandle)) + ordered = true; + } + float orderFactor; + if (ordered) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + else + { + orderFactor = 1.0f; + } + float strength; + if (!exposedSoldier) + strength = partUnit->getBattleStrengths()[strengthType]; + else + strength = std::max(partUnit->getBattleStrengths()[strengthType], + partUnit->getBattleStrengths()[soldierStrengthType]); + if (!(info->getObjectTypeFlags() & 0x200000)) + strength = strength * enemyStrengthTweak; + score = (strength + part->getStrength() + unit->getBattleStrengths()[targetStrengthType]) + * armourClassValues[targetStrengthType] * orderFactor * targetAreaFactor + + score; + partHandle = info->getSecondaryObject(secondary, side); + part = informationManager->getInformation(partHandle); + } + while (part); + + // 0x209667 + float rangeFactor = 1.0f - distance / (maxRange * 1.2f); + if (!(rangeFactor > 0.0f)) + rangeFactor = 0.0f; + score = rangeFactor * bestWeaponScore * indirectFactor * approachFactor * attackFactor * targetAreaFactor + * score; + const float weaponMaxRange = bestWeaponInfo->getMaxRange(); + const float weaponMinRange = bestWeaponInfo->getMinRange(); + const float rangeQuality = ((weaponMaxRange - weaponMinRange) * 0.1f + weaponMinRange) / distance; + score = m_curve->calculate(AIRandom::m_instance->nextFloat(), true) * score * rangeQuality; + if (strengthSum <= static_cast(static_cast(bot)->getHarmlessThrsh())) + score = score * 0.33f; + if (!info->getUnit()) + continue; + if (currentTarget == it->first) + { + currentTargetScore = score; + keepCurrentTarget = true; + } + if (score > bestScore) + { + bestScore = score; + targets[bot->getBotId()] = it->first; + m_unknown24[bot->getBotId()] = bestWeapon; + bestDistance = distance; + } + } + + float scale = 1.0f; // -0x298 + if (bestScore > 0.0f) + { + if (keepCurrentTarget) + currentTargetScore = currentTargetScore * 1.2f; + if (keepCurrentTarget && currentTargetScore > bestScore) + { + if (targets[bot->getBotId()] != currentTarget) + { + // 0x20877F: stay with the current target; its distance replaces the best one. + targets[bot->getBotId()] = currentTarget; + Information* const target = informationManager->getInformation(currentTarget); + const Vec3& from = equipment->getPosition(); + const Vec3& to = target->getPosition(); + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + bestDistance = std::sqrt(dx * dx + dy * dy + dz * dz); + } + } + else + { + bot->getBotId(); // called, result unused + keepCurrentTarget = false; + } + const int weapon = chooseWeapon(bot, targets[bot->getBotId()], bestDistance); + if (weapon != -1) + m_unknown24[bot->getBotId()] = weapon; + initializeGenerator(static_cast(bot), m_unknown24[bot->getBotId()], false, false); + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !keepCurrentTarget; + scale = scale * modifier; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * scale; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + // 0x2088A8. -0x19C is never written after its 0.0, so the second branch (0x208936) is dead + // code in the image; it is kept as compiled. + m_targetChanged[bot->getBotId()] = !keepCurrentTarget; + float indirectScore = zero; + if (!(indirectScore > 0.0f)) + { + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(static_cast(bot), -1, false, false); + const float weighted = scale * indirectScore; + indirectScore = indirectScore + indirectScore; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(indirectScore + indirectScore) * weighted; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + m_urgency[bot->getBotId()] = m_urgency[bot->getBotId()] * bot->getMemory()->m_float8; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x20A090 +void BBFire::initializeGenerator(BotMain* bot, int mode, bool a, bool b) +{ + unsigned int* const targets = m_targets; + bot->setFiringTarget(targets[bot->getBotId()]); + static_cast(m_pattern)->init(bot, targets[bot->getBotId()], mode, a, b); +} + +// ELF 0x20A120 +void BBFire::initializeGenerator(unsigned int target, const Vec3& position, BotMain* bot, int mode) +{ + bot->setFiringTarget(target); + static_cast(m_pattern)->init(bot, target, position, mode); +} + +// ELF 0x20A180 +BBFire::BBPFeedback* BBFire::getBBPFeedback(unsigned int target) +{ + std::map::iterator it = m_feedback.find(target); + if (it != m_feedback.end()) + return it->second; + BBPFeedback* const feedback = checkPointer(new BBPFeedback); + m_feedback.insert(std::make_pair(target, feedback)); + return feedback; +} + +// ELF 0x20A350 (listing block by block; Ghidra pseudo-code cross-check). The index of the +// bot's weapon that scores best against the target at `distance`, or -1. A weapon scores its +// strength against the target's strength type, scaled down outside its range band and by 0.33 +// with an empty magazine. Against a soldier the bot may pick a close-quarters weapon +// (spawn-kit dependent slot 0 or 5) and returns it at once when the pathfinding trace to the +// target's last valid position succeeds; a splash-damage weapon may be chosen for a static +// attack (score * 100, setUseStaticAttack(true)) when the target is in its band, not recently +// failed and not near the flag the bot is going for. setUseStaticAttack(false) comes first. +int BBFire::chooseWeapon(Bot* bot, unsigned int target, float distance) +{ + static bool allowMultipleC4 = false; // .bss; nothing in the image writes it + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const bool ownIsSoldier = (equipment->getObjectTypeFlags() & 0x200000) != 0; + IPIArmament* const armament = equipment->getArmament(); + static_cast(bot)->setUseStaticAttack(false); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + int bestWeapon = -1; + float bestScore = 0.0f; + + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return -1; + const bool targetIsSoldier = (targetInfo->getObjectTypeFlags() & 0x200000) != 0; + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + IPIMobile* const targetMobile = targetInfo->getMobile(); + if (!targetPhysical) + return -1; + + // 0x20A478: the bot's active weapon. closeQuartersActive: a soldier holding the slot the + // close-quarters weapon of its kit sits in; ownMagazineEmpty: the active magazine is empty. + bool closeQuartersActive = false; // -0x199 + bool ownMagazineEmpty = false; // -0x19A + IPIArmament* const ownArmament = equipment->getArmament(); + if (ownArmament && ownArmament->getActiveWeapon() != -1) + { + const int active = ownArmament->getActiveWeapon(); + WeaponInfo* const activeInfo = WeaponInfoManager::m_instance->getInformation(ownArmament->getWeapon(active)); + if (!activeInfo) + return -1; + IWeapon* const activeWeapon = activeInfo->getWeapon(); + if (ownIsSoldier + && ((bot->getSpawnKit() != 5 && active == 0) || (bot->getSpawnKit() == 5 && active == 5))) + closeQuartersActive = true; + ownMagazineEmpty = false; + if (activeWeapon->getAmmoInMag(0) == 0 && !closeQuartersActive) + ownMagazineEmpty = true; + } + + // 0x20A511: the target's active weapon and whether its magazine is empty. + bool targetMagazineEmpty = false; // -0x19B + WeaponInfo* targetWeapon = 0; + IPIArmament* const targetArmament = targetInfo->getArmament(); + if (targetArmament && targetArmament->getActiveWeapon() != -1) + { + targetWeapon = WeaponInfoManager::m_instance->getInformation( + targetArmament->getWeapon(targetArmament->getActiveWeapon())); + if (targetWeapon) + targetMagazineEmpty = targetWeapon->getWeapon()->getAmmoInMag(0) == 0; + } + + // 0x20A57D: whether the target fights the bot: a bot whose firing target is this bot's + // player, or a human who attacked the bot (any recorded attack: within 9995 seconds). + bool targetEngagesBot = false; // -0x19C + Bot* const targetBot = IBotManager::instance->getBotFromPlayerId(targetInfo->getPlayerId()); + if (!targetBot) + { + if (targetWeapon) + { + double attackTime; + static_cast(bot)->isAttacking(target, attackTime); + targetEngagesBot = now - attackTime < 9995.0; + } + } + else + { + Information* const firingTarget = informationManager->getInformation(targetBot->getFiringTarget()); + if (firingTarget && firingTarget->getPlayerId() == bot->getPlayerId()) + targetEngagesBot = true; + } + bool soldierAgainstSoldier = false; // -0x19D + if (targetIsSoldier && ownIsSoldier) + soldierAgainstSoldier = true; + const bool targetIsHuman = !IBotManager::instance->getBotFromPlayerId(targetInfo->getPlayerId()); // -0x19E + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); + + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + const int weaponType = weapon->getWeaponType(); + if (weaponType != 0 && weaponType != 4 && weaponType != 3) + continue; + + bool closeQuarters = false; // -0x1B1 + bool meleeAttack = false; // -0x1B2 + bool splash = false; // -0x1C8: a vehicle's explosive weapon against a soldier + if (!ownIsSoldier && (targetInfo->getObjectTypeFlags() & 0x200000)) + { + if (weapon->getWeaponGuidanceType() == 0 && weapon->getExplosionRadius() != 0.0f) + splash = true; + } + if (!weapon->getFiresThroughTransparent() && !(sensed->m_flags & SensedObject::SENSE_INDIRECT) + && !(sensed->m_flags & SensedObject::SENSE_FLAG40)) + continue; + if (ownIsSoldier + && ((bot->getSpawnKit() != 5 && i == 0) || (bot->getSpawnKit() == 5 && i == 5))) + closeQuarters = true; + if (targetInfo->getArmament() && targetInfo->getArmament()->getActiveWeapon() == 0) + closeQuarters = false; + if (weaponType == 4) + { + // 0x20B520: C4 once, and not against a target moving across the bot's facing. + if (bot->isC4Placed() && !allowMultipleC4) + continue; + if (targetMobile) + { + const Vec3 faceing = equipment->getFaceing(); + const Vec3& speed = targetMobile->getSpeed(); + if (std::fabs(speed.y * faceing.y + speed.x * faceing.x + speed.z * faceing.z) > 4.0f) + continue; + } + } + + if (closeQuarters && ownIsSoldier && targetInfo->getMobile() && equipment->getMobile()) + { + // 0x20B41F: no close quarters with a target off its last valid position or inside + // an obstacle radius; that also ends soldierAgainstSoldier for the later weapons. + const IPIMobile::ValidPos& valid = + targetInfo->getMobile()->getLastValidPosition(equipment->getMobile()->getVehicleNumber()); + const Vec3& targetPosition = targetInfo->getPosition(); + Vec3 offset; + offset.x = 0.0f; + offset.y = 0.0f; + offset.z = 0.0f; + offset.x = targetPosition.x - valid.position.x; + offset.y = targetPosition.y - valid.position.y; + offset.z = targetPosition.z - valid.position.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z > 1.0f + || bot->getBotNavigation()->pointWithinObstacleRadius(targetInfo->getPosition())) + { + soldierAgainstSoldier = false; + continue; + } + } + + // 0x20A810 + bool closeAndActive = false; // -0x1D1 + if (closeQuartersActive && 10.0f > distance) + closeAndActive = true; + const float stamina = targetMobile ? targetMobile->getSprintStamina() : 0.0f; + if ((stamina > 0.5f || (closeAndActive && stamina > 0.0f)) && closeQuarters + && (targetMagazineEmpty || closeAndActive) && (ownMagazineEmpty || closeQuartersActive) + && soldierAgainstSoldier && targetIsHuman && 20.0f > distance + && (targetEngagesBot || closeQuartersActive)) + meleeAttack = true; + + int ammo = weapon->getAmmo(); + bool staticAttack = false; // -0x1D2 + if (ammo == -1) + ammo = 0x10000; + if (!(ammo > 0) && weaponType != 3 && !meleeAttack) + continue; + float score = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + if (score == 0.0f) + continue; + if (ownIsSoldier && targetIsSoldier && score != 0.0f && 3.0f > distance && closeQuarters) + meleeAttack = true; + + if (meleeAttack) + { + // 0x20B300: take the close-quarters weapon when the target's last valid position + // can be reached. + const IPIMobile::ValidPos& valid = + targetInfo->getMobile()->getLastValidPosition(equipment->getMobile()->getVehicleNumber()); + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + Vec3 end; + end.x = 0.0f; + end.y = 0.0f; + end.z = 0.0f; + unsigned int polygon; + const int equipmentType = equipment->getUnit()->getEquipmentType(); + if (pathfinding->trace(bot->getBotNavigation(), false, valid.position, end, polygon, equipmentType, -1, + 0.0f, 0, 0)) + return static_cast(i); + } + + if ((ownIsSoldier || splash) && (targetInfo->getObjectTypeFlags() & 0x200000) + && weapon->getWeaponGuidanceType() == 0 && weapon->getExplosionRadius() != 0.0f) + { + // 0x20ABCC: splash damage, unless the bot or the target is at the flag the bot goes for. + bool goingForFlag = static_cast(bot)->getIsGoingForFlag(); // -0x1D9 + bool targetNearFlag = false; // -0x1DA + if (!splash) + { + AIStrategicObject* const closest = AIStrategicObjectManager::getInstance()->getClosestObject( + equipment->getPosition(), bot->getSide(), false); + Vec3 orderPosition; + orderPosition.x = 0.0f; + orderPosition.y = 0.0f; + orderPosition.z = 0.0f; + if (closest) + { + orderPosition = closest->getOrderPos(equipment->getMobile()->getVehicleNumber(), bot->getSide()); + float radius = closest->m_size[bot->getSide()]; + Vec3 flag; + flag.x = 0.0f; + flag.y = 0.0f; + flag.z = 0.0f; + vec2ToVec3XZ(closest->getPosition(bot->getSide()), flag); + radius = radius * radius; + flag.y = orderPosition.y; + Vec3 offset; + offset.x = flag.x - orderPosition.x; + offset.y = flag.y - orderPosition.y; + offset.z = flag.z - orderPosition.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius) + { + const float nearRadius = 40.0f; + if (closest->getStatus(bot->getSide()) != 0) + { + const Vec3& position = equipment->getPosition(); + offset.x = position.x - orderPosition.x; + offset.y = position.y - orderPosition.y; + offset.z = position.z - orderPosition.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z + < nearRadius * nearRadius) + { + const io::PlayerInput* const input = bot->getInput(); + if (mappedInput(input, io::PIThrottle) != 0.0f || mappedInput(input, io::PIYaw) != 0.0f + || mappedInput(input, io::PISprint) != 0.0f) + goingForFlag = true; + } + } + } + const Vec3& targetPosition = targetInfo->getPosition(); + offset.x = flag.x - targetPosition.x; + offset.y = flag.y - targetPosition.y; + offset.z = flag.z - targetPosition.z; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius) + targetNearFlag = true; + } + } + if ((!goingForFlag && !targetNearFlag) || splash) + { + // 0x20AC13: the target in the weapon's band, not just failed, seen within the + // window, and no grenade thrown in the last 10 seconds. + const float heightDifference = targetInfo->getPosition().y - equipment->getPosition().y; + float minRange = weapon->getMinRange(); + if (!splash) + { + minRange = 5.0f; + if (!(heightDifference > 3.0f)) + minRange = 10.0f; + } + float maxRange = weapon->getMaxRange(); + if (heightDifference > 5.0f && !weapon->getIsThrown()) + maxRange = heightDifference * 1.25f + maxRange; + if (static_cast(bot)->getBotWantsToSimulateArtillery()) + { + minRange = minRange - 1.0f; + maxRange = 1.0f + maxRange; + } + bool aboveTarget = false; // -0x208 + if (bot->getSpawnKit() != 1 && !weapon->getIsThrown() && heightDifference > 30.0f) + aboveTarget = true; + aboveTarget = aboveTarget || splash; + double seenWindow = 10.0; + if (splash) + seenWindow = 5.0; + int grenades = 1; + if (!weapon->getIsThrown()) + { + if (weapon->getBurst()) + grenades = 3; + } + const double sinceSeen = now - sensed->m_lastSeenTime; + const double sinceGrenade = now - bot->getTimeOfGrenadeThrown(grenades - 1); + const bool staticFailed = + now - static_cast(bot)->getTimeOfLastFailedStaticAttack() < 10.0; + bool recentlyFailed = + now - static_cast(bot)->getTimeOfLastFailedSplashDamageAttack() < 5.0; + const bool inBand = distance >= minRange && maxRange >= distance; + if (!splash) + recentlyFailed = staticFailed; + if (inBand && !recentlyFailed && (sensed->m_flags & SensedObject::SENSE_SEEN) + && ((sensed->m_flags & SensedObject::SENSE_INDIRECT) || aboveTarget) && seenWindow > sinceSeen + && (sinceGrenade > 10.0 || splash)) + { + staticAttack = true; + score = score * 100.0f; + static_cast(bot)->setUseStaticAttack(true); + } + } + } + + // 0x20A9E1: an empty magazine that reloads slowly is nearly worthless. + IWeapon* const iweapon = weapon->getWeapon(); + if (iweapon->getAmmoInMag(0) == 0 && weapon->getReloadTime() > 1.9f && weapon->hasAutoReload()) + { + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); // result unused + if (iweapon->getWeaponGuidingSystem() == 0) + score = 0.1f; + else if (!iweapon->getProjectile()) + score = 0.1f; + } + const float maxRange = weapon->getMaxRange(); + const float minRange = weapon->getMinRange(); + if (!staticAttack) + { + if (minRange > distance) + { + float shortfall = (minRange - distance) / 5.0f; + if (shortfall > 1.0f) + shortfall = 1.0f; + score = ((1.0f - 0.9f) - shortfall * 0.09f) * score; + } + else if (distance > maxRange) + { + float excess = (distance - maxRange) / 5.0f; + if (excess > 1.0f) + excess = 1.0f; + score = (1.0f - excess * 0.9f) * score; + } + } + if (iweapon->getAmmoInMag(0) == 0) + score = score * 0.33f; + if (score > bestScore) + { + bestScore = score; + bestWeapon = static_cast(i); + } + } + return bestWeapon; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h new file mode 100644 index 000000000..2e09c5750 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.h @@ -0,0 +1,58 @@ +// Fire behaviour base: urgency of engaging the bot's chosen target, weapon choice, and the target +// handed to the fire pattern (BBPFire) through initializeGenerator. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFire; +class Bot; +class BotMain; +class CustomCurve; +class UrgeCurve; + +// ELF: vtable 0x4BAB00 (15 words), operator new 0x40, package D-behaviours. +class BBFire : public BotBehaviour +{ +public: + // Per-target feedback from the fire pattern, kept by target handle (new(8) in getBBPFeedback). + struct BBPFeedback + { + BBPFeedback() : m_time(-10000.0) {} + /* +0 */ double m_time; // [UNRESOLVED] meaning; -10000 = never + }; + + BBFire(unsigned char index, unsigned char queue, BBPFire* pattern, UrgeCurve* curve, float* modifiers); // 0x2079B0 + virtual ~BBFire(); // 0x207E80 + + virtual float calculateUrgency(Bot*, bool, float); // 0x208040, slot +0x28 + // Hands the bot's current target (BotBehaviour +0x08 [botId]) to the pattern and to the bot. + virtual void initializeGenerator(BotMain*, int, bool, bool); // 0x20A090, slot +0x34 + virtual void initializeGenerator(unsigned int target, const Vec3& position, BotMain*, int); // 0x20A120, slot +0x38 + + BBPFeedback* getBBPFeedback(unsigned int target); // 0x20A180: find, or insert a new one + int chooseWeapon(Bot*, unsigned int, float); // 0x20A350; [INFERRED] ELF int, callers {'int': 1} + +protected: + /* +0x24 */ unsigned int* m_unknown24; // per bot slot, constructed -1 [UNRESOLVED] meaning + /* +0x28 */ double m_double28; // constructed 0.0 [UNRESOLVED] meaning + /* +0x30 */ std::map m_feedback; // never freed (retail leak) + /* +0x3C */ CustomCurve* m_curve; // CustomCurve(modifiedSoftStepFunc, 0, 1, 0.03) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp new file mode 100644 index 000000000..50d7ecce1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp @@ -0,0 +1,539 @@ +// Aircraft fire behaviour, recovered from the symbolized Linux 1.50 libaidll.so. + +// static init: ELF 0x20E060 (__tcf_0 0x20E0C0, _GLOBAL__I 0x20E0F0): 's Init object only. +#include + +#include "BBFire3d.h" + +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20BB00 (C2) / 0x20BCF0 (C1); vtable GOT -0x964. The base gets getMaxNBots; +0x28 = 0.0 +// (fld of the 0.0f constant, fstpl), the empty map at +0x30 (a 0x18-byte header node); a second +// getMaxNBots sizes the +0x08 and +0x24 arrays (plain operator new[], no checkPointer); every bot +// starts with urgency 0.0f and both slots -1; the pattern gets this behaviour as its urgency +// generator. Unlike BBFire, no CustomCurve. +BBFire3d::BBFire3d(unsigned char index, unsigned char queue, BBPFire* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) + , m_double28(0.0) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = new unsigned int[bots]; + m_unknown24 = new unsigned int[bots]; + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_unknown24[i] = static_cast(-1); + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); +} + +// ELF 0x20BE30 (D2) / 0x20BEF0 (D1) / 0x20BFB0 (D0): delete[] +0x08, then +0x24 (each when set), +// then the map's destructor (_M_erase of the nodes; the BBPFeedback objects are not deleted) and +// ~BotBehaviour. +BBFire3d::~BBFire3d() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown24) + delete[] m_unknown24; +} + +// ELF 0x20C070 +float BBFire3d::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + if (!recalculate) + { + if (!m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = false; + return m_urgency[bot->getBotId()] = 0.0f; + } + if (!informationManager->getInformation(m_targets[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now - m_double28 > 60.0) + { + std::map::iterator it = m_feedback.begin(); + while (it != m_feedback.end()) + { + if (informationManager->getInformation(it->first)) + ++it; + else + { + delete it->second; + m_feedback.erase(it++); + } + } + m_double28 = now; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIUnit* const unit = equipment->getUnit(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIArmament* const armament = equipment->getArmament(); + IPIMobile* const mobile = equipment->getMobile(); + IPIControlInfo* const controls = equipment->getControlInfo(); + const unsigned long long aimControls = controls->getAimControls(); + const unsigned long long driveControls = controls->getDriveControls(); + if ((aimControls & driveControls) && !bot->isAirBorn()) + { + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + + const int strengthType = physical->getStrengthType(); + float indirectScore = 0.0f; // never updated in the shipped body + float bestScore = 0.0f; + float currentScore = 0.0f; + unsigned int countedOrders = 0; + int bestWeapon = -1; + const int side = bot->getSide(); + const unsigned int currentTarget = m_targets[bot->getBotId()]; + const int currentWeapon = m_unknown24[bot->getBotId()]; + bool keepCurrent = false; + std::vector unusedObjects; + unusedObjects.push_back(equipment->getAIObject()); + unusedObjects.push_back(0); + + const Vec3& position = equipment->getPosition(); + const unsigned int botId = bot->getBotId(); + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(botId); + AIStrategicObject* const area = AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea); + const float areaFactor = area ? (static_cast(area)->isInside(position) ? 1.0f : 0.75f) : 1.0f; + equipment->getTransformation(); // result unused + Vec3 indirectPosition; + indirectPosition.x = indirectPosition.y = indirectPosition.z = 0.0f; + + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + if (!(object->m_flags & 2) && !(object->m_flags & 4)) + continue; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info) + continue; + Bot* const other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); + if (other && (info->getObjectTypeFlags() & 0x10)) + { + Information* const otherTarget = informationManager->getInformation(other->getFiringTarget()); + if (otherTarget && otherTarget->getPlayerId() == bot->getPlayerId()) + continue; + } + if (20.0 > now - getBBPFeedback(object->m_handle)->m_time) + continue; + int weapon = -1; + const double seenTime = (object->m_flags & 8) ? object->m_firstSeenTime : 0.0; + const float score = updateUrgencyWithTarget(object->m_handle, info, seenTime, now, weapon, + static_cast(bot), position, equipment, armament, mobile, unit, strengthType, + areaFactor, area, countedOrders); + if (currentTarget == object->m_handle) + { + keepCurrent = true; + currentScore = score; + } + if (score > bestScore) + { + bestScore = score; + m_targets[bot->getBotId()] = object->m_handle; + bestWeapon = weapon; + } + } + + if (!keepCurrent) + { + std::vector enemies; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getEnemyObjects(enemies, bot, -1.0f); + for (std::vector::const_iterator it = enemies.begin(); it != enemies.end(); ++it) + { + if (20.0 > now - getBBPFeedback(*it)->m_time) + continue; + Information* const info = informationManager->getInformation(*it); + if (!info) + continue; + Bot* const other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); + if (other && (info->getObjectTypeFlags() & 0x10)) + { + Information* const otherTarget = informationManager->getInformation(other->getFiringTarget()); + if (otherTarget && otherTarget->getPlayerId() == bot->getPlayerId()) + continue; + } + int weapon = -1; + const float score = updateUrgencyWithTarget(*it, info, 0.0, now, weapon, + static_cast(bot), position, equipment, armament, mobile, unit, strengthType, + areaFactor, area, countedOrders); + if (currentTarget == *it) + { + keepCurrent = true; + currentScore = score; + } + if (score > bestScore) + { + bestScore = score; + m_targets[bot->getBotId()] = *it; + bestWeapon = weapon; + } + } + } + + float scale = 1.0f; + // The point-target branch survives in ia-32, but its handle remains -1. + const unsigned int indirectTarget = static_cast(-1); + if (indirectTarget != static_cast(-1)) + { + m_urgency[bot->getBotId()] = 5.0f; + m_targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(indirectTarget, indirectPosition, static_cast(bot), + m_unknown24[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + if (bestScore > 0.0f) + { + if (keepCurrent) + currentScore = currentScore * 1.2f; + if (keepCurrent && currentScore > bestScore && currentWeapon == bestWeapon) + { + // Shipped quirk: restore the target, but keep the best candidate's score. + m_targets[bot->getBotId()] = currentTarget; + m_unknown24[bot->getBotId()] = bestWeapon; + } + else + { + bot->getBotId(); // result unused + m_unknown24[bot->getBotId()] = bestWeapon; + keepCurrent = false; + } + initializeGenerator(static_cast(bot), bestWeapon, false, false); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !keepCurrent; + scale = scale * modifier; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * scale; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + m_targetChanged[bot->getBotId()] = !keepCurrent; + if (!(indirectScore > 0.0f)) + { + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + m_targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(static_cast(bot), -1, false, false); + const float weighted = scale * indirectScore; + indirectScore = indirectScore + indirectScore; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(indirectScore + indirectScore) * weighted; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + m_urgency[bot->getBotId()] = m_urgency[bot->getBotId()] * bot->getMemory()->m_float8; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x20D0A0 +void BBFire3d::initializeGenerator(BotMain* bot, int weapon, bool a, bool b) +{ + bot->setFiringTarget(m_targets[bot->getBotId()]); + static_cast(m_pattern)->init(bot, m_targets[bot->getBotId()], weapon, a, b); +} + +// ELF 0x20D130 +void BBFire3d::initializeGenerator(unsigned int target, const Vec3& position, BotMain* bot, int weapon) +{ + bot->setFiringTarget(target); + static_cast(m_pattern)->init(bot, target, position, weapon); +} + +// ELF 0x20D190 +BBFire3d::BBPFeedback* BBFire3d::getBBPFeedback(unsigned int target) +{ + std::map::iterator it = m_feedback.find(target); + if (it != m_feedback.end()) + return it->second; + BBPFeedback* const feedback = new BBPFeedback; + feedback->m_time = -10000.0; + m_feedback.insert(std::make_pair(target, feedback)); + return feedback; +} + +// ELF 0x20D230 +float BBFire3d::updateUrgencyWithTarget(unsigned int target, Information* info, double seenTime, + double now, int& bestWeapon, BotMain* bot, const Vec3& position, Information* equipment, + IPIArmament* armament, IPIMobile* mobile, IPIUnit* unit, int strengthType, float areaFactor, + AIStrategicObject* area, unsigned int& countedOrders) +{ + if (!info || info->getSide() == bot->getSide()) + return 0.0f; + Information* const primary = informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + IPIPhysical* const physical = info->getPhysical(); + if (!physical || (info->getObjectTypeFlags() & 0x20000) || (info->getObjectTypeFlags() & 0x100000) + || (info->getObjectTypeFlags() & 0x800000) || 0.0f >= physical->getHealth()) + return 0.0f; + + float attackFactor = 1.0f; + double attackTime; + if (bot->isAttacking(target, attackTime)) + { + float ramp = static_cast(now - attackTime) / 30.0f; + if (0.0f > ramp) + ramp = 0.0f; + else if (ramp > 1.0f) + ramp = 1.0f; + attackFactor = 1.5f - ramp * 0.5f; + } + + IPIMobile* const targetMobile = primary->getMobile(); + Vec3 targetPosition; + targetPosition.x = targetPosition.y = targetPosition.z = 0.0f; + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = primary->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (0.5f > distance) + distance = 0.5f; + if (distance > 0.00001f) + { + const float reciprocal = 1.0f / distance; + direction.x = direction.x * reciprocal; + direction.y = direction.y * reciprocal; + direction.z = direction.z * reciprocal; + } + + float weaponScores[8]; // shipped body has no upper bound on the weapon count + float bestStrength = 0.0f; + float maxRange = 0.0f; + const std::vector& weapons = armament->getWeapons(); + unsigned int i = 0; + for (; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + { + weaponScores[i] = 0.0f; + continue; + } + const float strength = static_cast(weapon->getStrength(physical->getStrengthType())); + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + weaponScores[i] = ammo > 0 ? strength : 0.0f; + if (weaponScores[i] > bestStrength) + { + bestWeapon = i; + bestStrength = weaponScores[i]; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestStrength == 0.0f) + return 0.0f; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + + float ageFactor = 1.0f; + if (seenTime > 0.0) + { + const float age = static_cast(now - seenTime); + ageFactor = 1.0f / (age * 0.05f + 1.0f); + } + Vec3 targetSpeed; + targetSpeed.x = targetSpeed.y = targetSpeed.z = 0.0f; + if (targetMobile) + targetSpeed = targetMobile->getSpeed(); + const float speed = std::sqrt(targetSpeed.x * targetSpeed.x + targetSpeed.y * targetSpeed.y + + targetSpeed.z * targetSpeed.z); + + bool calculateApproach = true; + float approachFactor = 1.0f; + if (primary->getObjectTypeFlags() & 0x10) + { + if (armament->isAntiAircraft() == 0) + { + if (primary->getAltitude() > 5.0f) + return 0.0f; + if (distance > maxRange * 0.5f || speed > 15.0f) + { + approachFactor = 0.0f; + calculateApproach = false; + } + } + else if (!(equipment->getObjectTypeFlags() & 0x10) && maxRange * 0.9f > distance) + { + calculateApproach = false; + } + } + if (calculateApproach && targetMobile) + { + if (distance > maxRange) + { + float maxSpeed = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + if (mobile) + { + maxSpeed = mobile->getMaxSpeed(); + ownSpeed = mobile->getSpeed(); + } + if (targetMobile->getMaxSpeed() - maxSpeed > 5.0f) + { + Vec3 lateral; + lateral.x = direction.z - direction.y * 0.0f; + lateral.y = direction.x * 0.0f - direction.z * 0.0f; + lateral.z = direction.y * 0.0f - direction.x; + const Vec3& velocity = targetMobile->getSpeed(); + float radial = (direction.x * velocity.x + direction.y * velocity.y + direction.z * velocity.z) + - (direction.x * ownSpeed.x + direction.y * ownSpeed.y + direction.z * ownSpeed.z); + if (0.0f > radial) + radial = 0.0f; + float transverse = (lateral.x * velocity.x + lateral.y * velocity.y + lateral.z * velocity.z) + - (lateral.x * ownSpeed.x + lateral.y * ownSpeed.y + lateral.z * ownSpeed.z); + if (0.0f > transverse) + transverse = 0.0f; + const float targetSpeedMagnitude = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + + velocity.z * velocity.z); + approachFactor = 0.25f / (radial * 2.0f + 1.0f + transverse * 2.0f + + targetSpeedMagnitude * 0.5f); + } + else + approachFactor = 0.25f; + } + else + { + const Vec3& velocity = targetMobile->getSpeed(); + approachFactor = 1.0f / (std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + + velocity.z * velocity.z) * 0.5f + 1.0f); + } + } + + float targetAreaFactor = areaFactor; + if (mobile && !(equipment->getObjectTypeFlags() & 0x10) && area + && !static_cast(area)->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.75f; + if (!info->getUnit() || !vehicleOccupied(target, bot->getSide())) + return 0.0f; + + float strengthSum = 0.0f; + float score = 0.0f; + unsigned int partHandle = target; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + const float* const armourValues = static_cast(CommonSingletonServer::m_iaiSettings)->getArmourClassValues(); + Information* part = info; + do + { + IPIUnit* const partUnit = part->getUnit(); + strengthSum = strengthSum + partUnit->getBattleStrengths()[strengthType]; + float orderFactor = 1.0f; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && countedOrders < bot->getOrderList(m_index)->size()) + { + std::list::iterator end = bot->getOrderList(m_index)->end(); + std::list::iterator begin = bot->getOrderList(m_index)->begin(); + std::list::iterator searchEnd = bot->getOrderList(m_index)->end(); + std::list::iterator found = std::find(begin, searchEnd, partHandle); + if (found != end) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + } + score = (partUnit->getBattleStrengths()[strengthType] + part->getStrength() + + unit->getBattleStrengths()[targetStrengthType]) * armourValues[targetStrengthType] + * orderFactor * targetAreaFactor + score; + partHandle = info->getSecondaryObject(secondary, bot->getSide()); + part = informationManager->getInformation(partHandle); + } + while (part); + + float rangeFactor; + if (primary->getObjectTypeFlags() & 0x10) + { + rangeFactor = 1.0f - distance / (maxRange * 1.5f); + if (!(rangeFactor > 0.0f)) + rangeFactor = 0.0f; + if (armament->isAntiAircraft()) + score = score + score; + } + else + { + float fraction = distance / (maxRange * 3.0f); + if (fraction > 1.0f) + fraction = 1.0f; + rangeFactor = 1.0f - fraction; + } + const Mat4& transformation = equipment->getTransformation(); + float facing = direction.x * transformation.m[8] + direction.y * transformation.m[9] + + direction.z * transformation.m[10] + 1.0f; + if (!(facing > 0.5f)) + facing = 0.5f; + rangeFactor = facing * 0.5f * rangeFactor; + rangeFactor = bestStrength * rangeFactor; + rangeFactor = rangeFactor * ageFactor; + rangeFactor = rangeFactor * approachFactor; + score = rangeFactor * attackFactor * score; + if (strengthSum <= static_cast(bot->getHarmlessThrsh())) + score = score * 0.01f; + return score; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h new file mode 100644 index 000000000..f99edb204 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.h @@ -0,0 +1,56 @@ +// Aircraft fire behaviour. Scores sensed and spatial-query targets and initializes BBPFire. +// Recovered from the symbolized Linux 1.50 libaidll.so; offsets refer to the ia-32 image. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE3D_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class BBPFire; +class Bot; +class BotMain; +class IPIArmament; +class IPIMobile; +class IPIUnit; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BABA0 (13 words), operator new 0x3C, package G-vehicles. +class BBFire3d : public BotBehaviour +{ +public: + struct BBPFeedback + { + // ELF 0x20D190 initializes the sole double to -10000.0. + double m_time; + }; + BBFire3d(unsigned char, unsigned char, BBPFire*, UrgeCurve*, float*); // 0x20BCF0 + virtual ~BBFire3d(); // 0x20BEF0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x20C070, slot +0x28; from the base declaration + + void initializeGenerator(BotMain*, int, bool, bool); // 0x20D0A0 + void initializeGenerator(unsigned int, const Vec3&, BotMain*, int); // 0x20D130 + BBPFeedback* getBBPFeedback(unsigned int); // 0x20D190: find or allocate a feedback record + float updateUrgencyWithTarget(unsigned int, Information*, double, double, int&, BotMain*, const Vec3&, Information*, IPIArmament*, IPIMobile*, IPIUnit*, int, float, AIStrategicObject*, unsigned int&); // 0x20D230 + + // Fields from the constructor 0x20BCF0 and destructor 0x20BEF0 (operator new 0x3C). + /* +0x24 */ unsigned int* m_unknown24; // per-bot weapon index; initialized to -1 + /* +0x28 */ double m_double28; // last feedback cleanup time; initialized to 0.0 + /* +0x30 */ std::map m_feedback; // target -> feedback; the destructor only frees the nodes [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp new file mode 100644 index 000000000..527a6912a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp @@ -0,0 +1,80 @@ +// Artillery driver fire behaviour, recovered from the symbolized Linux 1.50 libaidll.so. + +// static init: ELF 0x20F070 (__tcf_0 0x20F0D0, _GLOBAL__I 0x20F100): 's Init object only. +#include + +#include "BBFireArtilleryDriver.h" + +#include "BBFireLargeBore.h" +#include "BBFireUnarmed.h" +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20E3F0 (C2), 0x20E870 (C1) +BBFireArtilleryDriver::BBFireArtilleryDriver(unsigned char index, unsigned char queue, BBPFire* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_unarmed = checkPointer(new BBFireUnarmed(index, queue)); + m_gunner = checkPointer(new BBFireLargeBore(index, queue, pattern, curve, modifiers, false)); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[bots]); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); +} + +// ELF 0x20ECF0 (D2), 0x20ED70 (D1), 0x20EDF0 (D0) +BBFireArtilleryDriver::~BBFireArtilleryDriver() +{ + if (m_targets) + delete[] m_targets; + if (m_unarmed) + delete m_unarmed; + if (m_gunner) + delete m_gunner; + // Shipped defect: the gunner and this behaviour both own the same pattern through their bases. +} + +// ELF 0x20EE70 +float BBFireArtilleryDriver::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + int secondary; + Information* const gunner = informationManager->getInformation(equipment->getFirstSecondaryObject(secondary, bot->getSide())); + // Shipped defect: neither the secondary object nor its unit is checked for null. + if (gunner->getUnit()->isOccupied()) + { + const float urgency = m_gunner->calculateUrgency(bot, recalculate, modifier, gunner, equipment->getMobile()); + m_urgency[bot->getBotId()] = urgency; + const bool changed = m_gunner->hasChangedTarget(bot); + m_targetChanged[bot->getBotId()] = changed; + } + else + { + m_targetChanged[bot->getBotId()] = false; + const float urgency = m_unarmed->calculateUrgency(bot, recalculate, modifier); + m_urgency[bot->getBotId()] = urgency; + } + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.h new file mode 100644 index 000000000..e1d3727dc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.h @@ -0,0 +1,38 @@ +// Artillery driver fire behaviour: delegates to the occupied gun seat or the unarmed behaviour. +// Recovered from the symbolized Linux 1.50 libaidll.so; offsets refer to the ia-32 image. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREARTILLERYDRIVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREARTILLERYDRIVER_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFire; +class BBFireLargeBore; +class BBFireUnarmed; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BAC40 (13 words), operator new 0x2C, package H-deferred. +class BBFireArtilleryDriver : public BotBehaviour +{ +public: + BBFireArtilleryDriver(unsigned char, unsigned char, BBPFire*, UrgeCurve*, float*); // 0x20E870 + virtual ~BBFireArtilleryDriver(); // 0x20ED70 + + virtual float calculateUrgency(Bot*, bool, float); // 0x20EE70, slot +0x28; from the base declaration + +private: + /* +0x24 */ BBFireUnarmed* m_unarmed; + /* +0x28 */ BBFireLargeBore* m_gunner; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREARTILLERYDRIVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp new file mode 100644 index 000000000..725a92fe2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp @@ -0,0 +1,36 @@ +// Fire behaviour of infantry (AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x20F310 (__tcf_0 0x20F370, _GLOBAL__I 0x20F3A0): 's Init object only. +#include + +#include "BBFireInfantery.h" + +#include "../AIBotBehaviourPattern/BBPFireInfantery.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20F190 +BBFireInfantery::BBFireInfantery(unsigned char index, unsigned char queue, BBPFireInfantery* pattern, + UrgeCurve* curve, float* modifiers) + : BBFire(index, queue, pattern, curve, modifiers) + , m_infantryPattern(pattern) +{ +} + +// ELF 0x20F240 +BBFireInfantery::~BBFireInfantery() +{ +} + +// ELF 0x20F2C0: forwards to BBFire's. +void BBFireInfantery::initializeGenerator(BotMain* bot, int i, bool a, bool b) +{ + BBFire::initializeGenerator(bot, i, a, b); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.h new file mode 100644 index 000000000..acf718dd6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.h @@ -0,0 +1,38 @@ +// Fire behaviour of infantry: BBFire with the infantry fire pattern (BBPFireInfantery, package E). +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREINFANTERY_H + +#include "BBFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFireInfantery; +class BotMain; +class UrgeCurve; + +// ELF: vtable 0x4BACA0 (15 words), operator new 0x44, package D-behaviours. +class BBFireInfantery : public BBFire +{ +public: + BBFireInfantery(unsigned char index, unsigned char queue, BBPFireInfantery* pattern, UrgeCurve* curve, + float* modifiers); // 0x20F190 + virtual ~BBFireInfantery(); // 0x20F240 + + virtual void initializeGenerator(BotMain*, int, bool, bool); // 0x20F2C0, slot +0x34 + +private: + // The constructor's pattern argument again, typed (BBFire keeps it as the generic pattern at +0x0C). + /* +0x40 */ BBPFireInfantery* m_infantryPattern; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp new file mode 100644 index 000000000..09e810097 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp @@ -0,0 +1,672 @@ +// Large-bore fire behaviour, recovered from the symbolized Linux 1.50 libaidll.so. + +// static init: ELF 0x212EA0 (__tcf_0 0x212F00, _GLOBAL__I 0x212F30): 's Init object only. +#include + +#include "BBFireLargeBore.h" + +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPFire.h" +#include "../AIBotBehaviourPattern/BBPFire2d.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x20F3C0 (C2) / 0x20F7E0 (C1); vtable GOT -0x1514. As BBFire3d's, plus the bool at +0x3C, +// and both per-bot arrays go through the inlined checkPointer: +0x08 targets, then +0x24; every bot +// starts with urgency 0.0f and both slots -1; the pattern gets this behaviour as its urgency +// generator. +BBFireLargeBore::BBFireLargeBore(unsigned char index, unsigned char queue, BBPFire* pattern, + UrgeCurve* curve, float* modifiers, bool flag) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) + , m_double28(0.0) +{ + m_flag3C = flag; + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[bots]); + m_unknown24 = checkPointer(new unsigned int[bots]); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_unknown24[i] = static_cast(-1); + m_targets[i] = static_cast(-1); + } + pattern->setUrgencyGenerator(this); +} + +// ELF 0x20FB80 (D2) / 0x20FC40 (D1) / 0x20FD00 (D0): delete[] +0x08, then +0x24 (each when set), +// then the map's destructor (nodes only) and ~BotBehaviour. +BBFireLargeBore::~BBFireLargeBore() +{ + if (m_targets) + delete[] m_targets; + if (m_unknown24) + delete[] m_unknown24; +} + +// ELF 0x20FDC0 +float BBFireLargeBore::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + return calculateUrgency(bot, recalculate, modifier, equipment, equipment->getMobile()); +} + +// ELF 0x212BE0 +void BBFireLargeBore::initializeGenerator(BotMain* bot, int weapon, bool a, bool b, bool spatial) +{ + bot->setFiringTarget(m_targets[bot->getBotId()]); + BBPFire* const pattern = static_cast(m_pattern); + if (pattern->getImplementationType() == 2) + static_cast(m_pattern)->init(bot, m_targets[bot->getBotId()], weapon, a, b, spatial); + else + pattern->init(bot, m_targets[bot->getBotId()], weapon, a, b); +} + +// ELF 0x20FE50 +float BBFireLargeBore::calculateUrgency(Bot* bot, bool recalculate, float modifier, + Information* equipment, IPIMobile* mobile) +{ + if (!recalculate) + { + if (!m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = false; + return m_urgency[bot->getBotId()] = 0.0f; + } + if (!informationManager->getInformation(m_targets[bot->getBotId()])) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + bool bestSpatial = false; + bool secondarySpatial = false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float* const armourValues = static_cast(CommonSingletonServer::m_iaiSettings)->getArmourClassValues(); + const int equipmentType = equipment->getUnit()->getEquipmentType(); + if (now - m_double28 > 60.0) + { + std::map::iterator it = m_feedback.begin(); + while (it != m_feedback.end()) + { + if (informationManager->getInformation(it->first)) + ++it; + else + { + delete it->second; + m_feedback.erase(it++); + } + } + m_double28 = now; + } + + IPIUnit* const unit = equipment->getUnit(); + IPIControlInfo* const controls = equipment->getControlInfo(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIArmament* armament; + if (m_flag3C) + { + int secondary; + Information* const gunner = informationManager->getInformation( + equipment->getFirstSecondaryObject(secondary, bot->getSide())); + armament = gunner->getArmament(); // shipped: no secondary-object null guard + } + else + armament = equipment->getArmament(); + const int strengthType = physical->getStrengthType(); + const Vec3 position = equipment->getPosition(); + float deadScore = 0.0f; // never written again in the image + float bestScore = 0.0f; + float secondaryScore = 0.0f; + float currentScore = 0.0f; + int bestWeapon = -1; + int secondaryWeapon = -1; + unsigned int secondaryTarget = static_cast(-1); + unsigned int countedOrders = 0; + WeaponInfo* selectedWeaponInfo = 0; + const int side = bot->getSide(); + const unsigned int currentTarget = m_targets[bot->getBotId()]; + const unsigned int currentWeapon = m_unknown24[bot->getBotId()]; + bool keepCurrent = false; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + const unsigned int botId = bot->getBotId(); + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(botId); + AIStrategicArea* const area = static_cast( + AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea)); + const float areaFactor = area ? (area->isInside(position) ? 1.0f : 0.75f) : 1.0f; + IAIObjectEnvironment* const environment = static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + + // [INFERRED] local helper names for repeated inline expansions in this body. + // ELF 0x212AA2 / 0x211830: attacking-target bonus, fading from 1.5 to 1 over 30 seconds. + const auto attackFactorFor = [&](unsigned int handle) -> float + { + double attackTime; + if (!static_cast(bot)->isAttacking(handle, attackTime)) + return 1.0f; + float ramp = static_cast(now - attackTime) / 30.0f; + if (0.0f > ramp) + ramp = 0.0f; + else if (ramp > 1.0f) + ramp = 1.0f; + return 1.5f - ramp * 0.5f; + }; + + // ELF 0x211CE0..0x211E25 / 0x212588..0x21289E, and 0x210CCD..0x210E1E / + // 0x211318..0x211632: moving-target and anti-aircraft weights. + const auto approachFactorFor = [&](Information* info, IPIMobile* targetMobile, + const Vec3& direction, float distance, float maxRange, + bool sensed) -> float + { + Vec3 targetSpeed; + targetSpeed.x = targetSpeed.y = targetSpeed.z = 0.0f; + if (targetMobile) + targetSpeed = targetMobile->getSpeed(); + const float speed = std::sqrt(targetSpeed.x * targetSpeed.x + targetSpeed.y * targetSpeed.y + + targetSpeed.z * targetSpeed.z); + if (!(equipment->getObjectTypeFlags() & 0x10) && (info->getObjectTypeFlags() & 0x10)) + { + if (armament->isAntiAircraft() == 0) + { + if (distance > maxRange * 0.5f || speed > 15.0f) + return 0.0f; + } + else if (maxRange * 0.9f > distance) + return 1.0f; + } + if (!targetMobile) + return 1.0f; + if (!(distance > maxRange)) + { + const Vec3& velocity = targetMobile->getSpeed(); + return 1.0f / (std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + + velocity.z * velocity.z) * 0.5f + 1.0f); + } + float maxSpeed = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + if (mobile) + { + maxSpeed = mobile->getMaxSpeed(); + ownSpeed = mobile->getSpeed(); + } + if (!(targetMobile->getMaxSpeed() - maxSpeed > 5.0f)) + return 0.25f; + Vec3 lateral; + lateral.x = direction.z - direction.y * 0.0f; + lateral.y = direction.x * 0.0f - direction.z * 0.0f; + lateral.z = direction.y * 0.0f - direction.x; + const Vec3& velocity = targetMobile->getSpeed(); + float radial = (direction.x * velocity.x + direction.y * velocity.y + direction.z * velocity.z) + - (direction.x * ownSpeed.x + direction.y * ownSpeed.y + direction.z * ownSpeed.z); + if (0.0f > radial) + radial = 0.0f; + float transverse = (lateral.x * velocity.x + lateral.y * velocity.y + lateral.z * velocity.z) + - (lateral.x * ownSpeed.x + lateral.y * ownSpeed.y + lateral.z * ownSpeed.z); + if (0.0f > transverse) + transverse = 0.0f; + const float magnitude = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z); + const float relative = sensed ? transverse * 2.0f + radial * 2.0f + 1.0f + : radial * 2.0f + 1.0f + transverse * 2.0f; + return 0.25f / (relative + magnitude * 0.5f); + }; + + // ELF 0x211F0F..0x212063 and 0x210F05..0x21106E: target plus secondary-seat strengths. + const auto strengthsFor = [&](Information* info, unsigned int target, float targetAreaFactor, + float& strengthSum) -> float + { + float score = 0.0f; + strengthSum = 0.0f; + unsigned int partHandle = target; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + Information* part = info; + do + { + IPIUnit* const partUnit = part->getUnit(); + strengthSum = strengthSum + partUnit->getBattleStrengths()[strengthType]; + bool ordered = false; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && countedOrders < bot->getOrderList(m_index)->size()) + { + const std::list::iterator end = bot->getOrderList(m_index)->end(); + const std::list::iterator begin = bot->getOrderList(m_index)->begin(); + const std::list::iterator searchEnd = bot->getOrderList(m_index)->end(); + ordered = std::find(begin, searchEnd, partHandle) != end; + } + float orderFactor = 1.0f; + if (ordered) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + score = (partUnit->getBattleStrengths()[strengthType] + part->getStrength() + + unit->getBattleStrengths()[targetStrengthType]) * armourValues[targetStrengthType] + * orderFactor * targetAreaFactor + score; + partHandle = info->getSecondaryObject(secondary, side); + part = informationManager->getInformation(partHandle); + } + while (part); + return score; + }; + + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + Information* const info = informationManager->getInformation(it->first); + if (!info || info->getSide() == side) + continue; + IPIPhysical* const targetPhysical = info->getPhysical(); + if (!targetPhysical || (info->getObjectTypeFlags() & 0x20000) || (info->getObjectTypeFlags() & 0x100000) + || (info->getObjectTypeFlags() & 0x800000) || 0.0f >= targetPhysical->getHealth()) + continue; + if ((object->m_flags & 0x20) && object->m_fireRating < 0) + continue; + if (20.0 > now - getBBPFeedback(object->m_handle)->m_time) + continue; + const float attackFactor = attackFactorFor(object->m_handle); + IPIMobile* const targetMobile = info->getMobile(); + Vec3 targetPosition; + targetPosition.x = targetPosition.y = targetPosition.z = 0.0f; + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (0.5f > distance) + distance = 0.5f; + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = direction.z * inverse; + + int weaponIndex = -1; + float maxRange = 0.0f; + float bestStrength = 0.0f; + float weaponScores[8]; // shipped: no bound on the weapon count + const std::vector& weapons = armament->getWeapons(); + unsigned int i = 0; + for (; i < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + { + weaponScores[i] = 0.0f; + continue; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + if (ammo > 0) + { + float strength = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + if (!(weapon->getMaxRange() >= distance)) + strength = strength * 0.25f; + weaponScores[i] = strength; + } + else + weaponScores[i] = 0.0f; + if (weapon->getMinRange() > distance) + weaponScores[i] = 0.0f; + if (weaponScores[i] > bestStrength) + { + weaponIndex = i; + bestStrength = weaponScores[i]; + selectedWeaponInfo = weapon; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestStrength == 0.0f) + continue; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + + float ageFactor = 1.0f; + if (object->m_flags & 8) + { + const float age = static_cast(now - object->m_firstSeenTime); + ageFactor = 1.0f / (age * 0.05f + 1.0f); + } + else if (!mobile) + { + Vec3 unusedCameraPosition; + unusedCameraPosition.x = unusedCameraPosition.y = unusedCameraPosition.z = 0.0f; + controls->getCameraBasePos(unusedCameraPosition); + const Mat4& transform = info->getTransformation(); + const Vec3& local = object->m_seenPosition; + Vec3 point; + point.x = local.x * transform.m[0] + local.y * transform.m[4] + local.z * transform.m[8] + transform.m[12]; + point.y = local.x * transform.m[1] + local.y * transform.m[5] + local.z * transform.m[9] + transform.m[13]; + point.z = local.x * transform.m[2] + local.y * transform.m[6] + local.z * transform.m[10] + transform.m[14]; + const Vec3& weaponPosition = selectedWeaponInfo->getPosition(); + Vec3 aim; + aim.x = point.x - weaponPosition.x; + aim.y = point.y - weaponPosition.y; + aim.z = point.z - weaponPosition.z; + if (!controls->validateCameraDirectionYaw(aim)) + continue; + } + + const float approachFactor = approachFactorFor(info, targetMobile, direction, distance, maxRange, true); + if (distance > maxRange * 0.89f) + { + if (!mobile) + continue; + const Vec3& target = info->getPosition(); + const int vehicle = mobile->getVehicleNumber(); + if (pathfinding->isValidPosition(vehicle, equipmentType, target, true)) + continue; + } + else if (!mobile) + { + Vec3 from; + from.x = from.y = from.z = 0.0f; + Vec3 to; + to.x = to.y = to.z = 0.0f; + const Mat4* const camera = static_cast(bot->getPlayer()->getCameraTransformation()); + from.x = camera->m[12]; + from.y = camera->m[13]; + from.z = camera->m[14]; + std::vector ignored; + ignored.push_back(equipment->getAIObject()); + ignored.push_back(info->getAIObject()); + const Mat4& transform = info->getTransformation(); + const Vec3& local = object->m_seenPosition; + to.x = local.x * transform.m[0] + local.y * transform.m[4] + local.z * transform.m[8] + transform.m[12]; + to.y = local.x * transform.m[1] + local.y * transform.m[5] + local.z * transform.m[9] + transform.m[13]; + to.z = local.x * transform.m[2] + local.y * transform.m[6] + local.z * transform.m[10] + transform.m[14]; + if (targetMobile) + { + Vec3 estimate; + estimate.x = estimate.y = estimate.z = 0.0f; + targetMobile->getPositionEstimate(now, estimate); + const Vec3& currentPosition = info->getPosition(); + to.x = (estimate.x - currentPosition.x) + to.x; + to.y = (estimate.y - currentPosition.y) + to.y; + to.z = (estimate.z - currentPosition.z) + to.z; + } + bool hit; + if (environment->collideLineWithWorld(from, to, ignored, false, 0.7f, false, hit)) + continue; + } + float targetAreaFactor = areaFactor; + if (mobile && area && !area->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.75f; + if (!info->getUnit() || !vehicleOccupied(object->m_handle, side)) + continue; + float strengthSum; + float score = strengthsFor(info, object->m_handle, targetAreaFactor, strengthSum); + float fraction = (distance * 1.5f) / maxRange; + if (!(fraction > 0.1f)) + fraction = 0.1f; + if (fraction > 1.0f) + fraction = 1.0f; + score = (1.0f - fraction) * bestStrength * ageFactor * approachFactor * attackFactor * score; + if (strengthSum <= static_cast(static_cast(bot)->getHarmlessThrsh())) + score = score * 0.33f; + if (info->getUnit() && score > secondaryScore) + { + secondaryScore = score; + secondaryTarget = it->first; + secondaryWeapon = weaponIndex; + } + } + + if (armament->isAntiAircraft() == 0) + { + std::vector enemies; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getEnemyObjects(enemies, bot, 850.0f); + for (std::vector::const_iterator it = enemies.begin(); it != enemies.end(); ++it) + { + Information* const info = informationManager->getInformation(*it); + if (!info || info->getSide() == side) + continue; + IPIPhysical* const targetPhysical = info->getPhysical(); + if (!targetPhysical || (info->getObjectTypeFlags() & 0x20000) || (info->getObjectTypeFlags() & 0x100000) + || (info->getObjectTypeFlags() & 0x800000) || 0.0f >= targetPhysical->getHealth()) + continue; + if (20.0 > now - getBBPFeedback(*it)->m_time) + continue; + const float attackFactor = attackFactorFor(*it); + if (!mobile) + { + Vec3 cameraPosition; + cameraPosition.x = cameraPosition.y = cameraPosition.z = 0.0f; + controls->getCameraBasePos(cameraPosition); + const Vec3& target = info->getPosition(); + Vec3 aim; + aim.x = target.x - cameraPosition.x; + aim.y = target.y - cameraPosition.y; + aim.z = target.z - cameraPosition.z; + const float lengthSquared = aim.x * aim.x + aim.y * aim.y + aim.z * aim.z; + if (!(std::fabs(lengthSquared - 1.0f) < 1.19209290e-7f)) + { + if (std::fabs(lengthSquared) < 1.19209290e-7f) + aim.x = aim.y = aim.z = 0.0f; + else + { + const float reciprocal = 1.0f / std::sqrt(lengthSquared); + aim.x = aim.x * reciprocal; + aim.y = aim.y * reciprocal; + aim.z = aim.z * reciprocal; + } + } + if (!controls->validateCameraDirectionYaw(aim)) + continue; + } + IPIMobile* const targetMobile = info->getMobile(); + Vec3 targetPosition; + targetPosition.x = targetPosition.y = targetPosition.z = 0.0f; + if (targetMobile) + targetMobile->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (0.5f > distance) + distance = 0.5f; + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = direction.z * inverse; + int weaponIndex = -1; + float maxRange = 0.0f; + float bestStrength = 0.0f; + float weaponScores[8]; // shipped: no upper bound on weapons.size() + const std::vector& weapons = armament->getWeapons(); + unsigned int i = 0; + for (; i < weapons.size(); ++i) + { + if (!WeaponInfoManager::m_instance->getInformation(weapons[i])) + { + weaponScores[i] = 0.0f; + continue; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + const float strength = static_cast(weapon->getStrength(targetPhysical->getStrengthType())); + int ammo = weapon->getAmmo(); + if (ammo == -1) + ammo = 0x10000; + weaponScores[i] = ammo > 0 ? strength / (10.0f / static_cast(ammo) + 1.0f) : 0.0f; + if (weaponScores[i] > bestStrength) + { + bestStrength = weaponScores[i]; + weaponIndex = i; + } + if (weapon->getMaxRange() > maxRange) + maxRange = weapon->getMaxRange(); + } + if (bestStrength == 0.0f) + continue; + for (; i < 8; ++i) + weaponScores[i] = 0.0f; + const float approachFactor = approachFactorFor(info, targetMobile, direction, distance, maxRange, false); + if (distance > maxRange * 0.89f) + { + if (!mobile) + continue; + const Vec3& target = info->getPosition(); + const int vehicle = mobile->getVehicleNumber(); + if (pathfinding->isValidPosition(vehicle, equipmentType, target, true)) + continue; + } + float targetAreaFactor = areaFactor; + if (mobile && area && !area->isInside(targetPosition)) + targetAreaFactor = targetAreaFactor * 0.75f; + if (!info->getUnit() || !vehicleOccupied(*it, side)) + continue; + float strengthSum; + float score = strengthsFor(info, *it, targetAreaFactor, strengthSum); + float fraction = distance / (maxRange * 1.5f); + if (!(fraction > 0.1f)) + fraction = 0.1f; + if (fraction > 1.0f) + fraction = 1.0f; + score = (1.0f - fraction) * bestStrength * approachFactor * attackFactor * 0.75f * score; + if (!(strengthSum > static_cast(static_cast(bot)->getHarmlessThrsh()))) + { + if (score > secondaryScore) + { + secondaryScore = score; + secondaryWeapon = weaponIndex; + secondaryTarget = *it; + secondarySpatial = true; + } + } + else + { + if (currentTarget == *it) + { + currentScore = score; + keepCurrent = true; + } + if (score > bestScore) + { + bestScore = score; + m_targets[bot->getBotId()] = *it; + bestWeapon = weaponIndex; + bestSpatial = true; + } + } + } + } + + float scale = 1.0f; + if (bestScore > 0.0f) + { + if (keepCurrent) + currentScore = currentScore * 1.2f; + if (keepCurrent && currentScore > bestScore) + { + m_targets[bot->getBotId()] = currentTarget; + m_unknown24[bot->getBotId()] = currentWeapon; + } + else + { + bot->getBotId(); // result unused + // Shipped defect: load the previous slot instead of storing the newly selected weapon. + bestWeapon = m_unknown24[bot->getBotId()]; + keepCurrent = false; + } + initializeGenerator(static_cast(bot), bestWeapon, false, false, bestSpatial); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !keepCurrent; + scale = scale * modifier; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * scale; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + m_targetChanged[bot->getBotId()] = !keepCurrent; + if (secondaryScore > 0.0f) + { + m_targets[bot->getBotId()] = secondaryTarget; + initializeGenerator(static_cast(bot), secondaryWeapon, false, false, secondarySpatial); + } + else if (deadScore > 0.0f) + { + m_targets[bot->getBotId()] = static_cast(-1); + initializeGenerator(static_cast(bot), -1, true, true, false); + } + else + { + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_targets[bot->getBotId()] = static_cast(-1); + return 0.0f; + } + // Shipped quirk: the secondary/dead-score path omits the caller's modifier. + const float weighted = scale * (secondaryScore > 0.0f ? secondaryScore : deadScore); + secondaryScore = secondaryScore + deadScore; + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(secondaryScore + secondaryScore) * weighted; + bot->addToFireInclination(m_urgency[bot->getBotId()]); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + m_urgency[bot->getBotId()] = m_urgency[bot->getBotId()] * bot->getMemory()->m_float8; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x212CD0 +BBFireLargeBore::BBPFeedback* BBFireLargeBore::getBBPFeedback(unsigned int target) +{ + std::map::iterator it = m_feedback.find(target); + if (it != m_feedback.end()) + return it->second; + BBPFeedback* const feedback = checkPointer(new BBPFeedback); + feedback->m_time = -10000.0; + m_feedback.insert(std::make_pair(target, feedback)); + return feedback; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h new file mode 100644 index 000000000..87edbf03a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.h @@ -0,0 +1,51 @@ +// Large-bore fire behaviour, including driver-controlled and stationary guns. +// Recovered from the symbolized Linux 1.50 libaidll.so; offsets refer to the ia-32 image. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRELARGEBORE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRELARGEBORE_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPFire; +class Bot; +class BotMain; +class IPIMobile; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BAD40 (14 words), operator new 0x40, package G-vehicles. +class BBFireLargeBore : public BotBehaviour +{ +public: + struct BBPFeedback + { + double m_time; // ELF 0x212CD0: sole member, initialized to -10000.0 + }; + BBFireLargeBore(unsigned char, unsigned char, BBPFire*, UrgeCurve*, float*, bool); // 0x20F7E0 + virtual ~BBFireLargeBore(); // 0x20FC40 + + virtual float calculateUrgency(Bot*, bool, float); // 0x20FDC0, slot +0x28; from the base declaration + virtual void initializeGenerator(BotMain*, int, bool, bool, bool); // 0x212BE0, slot +0x34; [INFERRED] ELF void + + float calculateUrgency(Bot*, bool, float, Information*, IPIMobile*); // 0x20FE50; [INFERRED] ELF float, callers {'float': 1} + BBPFeedback* getBBPFeedback(unsigned int); // 0x212CD0 + + // Fields from the constructor 0x20F7E0 and destructor 0x20FC40 (operator new 0x40). + /* +0x24 */ unsigned int* m_unknown24; // per-bot weapon slot; initialized to -1 + /* +0x28 */ double m_double28; // last feedback cleanup time; initialized to 0.0 + /* +0x30 */ std::map m_feedback; // the destructor only frees the nodes [INFERRED] name + /* +0x3C */ bool m_flag3C; // use the first secondary object's armament +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIRELARGEBORE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp new file mode 100644 index 000000000..d828338eb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp @@ -0,0 +1,300 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +// static init: ELF 0x214A60 (__tcf_0 0x214AC0, _GLOBAL__I 0x214AF0): 's Init object only. +#include + +#include "BBFireUnarmed.h" + +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../Main/AIMain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +#include +#include +#include +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x213230 (C2) / 0x213570 (C1); vtable GOT -0x1158. BotBehaviour(null modifiers, null +// curve, getMaxNBots); +0x24 = checkPointer(new float[n]), then the +0x08 targets = +// checkPointer(new unsigned int[n]) (operator new 0x28), no pattern (+0x0C = 0); every bot +// starts with urgency and +0x24 at 0.0f and target -1. +BBFireUnarmed::BBFireUnarmed(unsigned char index, unsigned char queue) + : BotBehaviour(0, 0, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_value24 = checkPointer(new float[bots]); + m_targets = checkPointer(new unsigned int[bots]); + m_pattern = 0; + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 0.0f; + m_value24[i] = 0.0f; + m_targets[i] = static_cast(-1); + } +} + +// ELF 0x2138B0 (D2) / 0x213910 (D1) / 0x213970 (D0): delete[] +0x08, then +0x24 (each when set), +// then ~BotBehaviour. +BBFireUnarmed::~BBFireUnarmed() +{ + if (m_targets) + delete[] m_targets; + if (m_value24) + delete[] m_value24; +} + +// ELF 0x2139E0 (Ghidra; listing for the constants and the return). Always returns 0.0; the +// urgency goes to +0x24 and to the bot's fire inclination (+0x188). +// Without `evaluate`: a target that no longer resolves marks the change and clears +0x24; +// otherwise the stored +0x24 is fed to the fire inclination again. +// With it: every sided sensed object of another side with a physical part, alive, not of the +// three excluded type bits (0x20000 / 0x100000 / 0x800000) and within 250 (distance floored at +// 0.5) of the equipment's position is weighed when it has a unit and its vehicle is occupied +// for this side: over it and its secondary objects, (battle strength against the own strength +// type + the information's strength) * armour class of its strength type * the order factor +// (the memory's +0x08 while the object is in the bot's order list, counted at most once per order) +// * the area factor (0.75 outside the ordered area, again 0.75 when a mobile bot's target is +// outside it), then * time factor (1 / (age * 0.05 + 1) for indirect senses) / max(0.1, +// distance * 1.5 * 0.2), and * 0.33 when the summed strength is at most the harmless threshold. +// The best becomes the target, unless the current target scored and stays within 1.2 of it. +// A two-entry ignore list (the equipment's AI object, null) is built and never used, and the +// normalised direction is computed and dropped, as compiled. +float BBFireUnarmed::calculateUrgency(Bot* bot, bool evaluate, float modifier) +{ + if (!evaluate) + { + Information* const target = informationManager->getInformation(m_targets[bot->getBotId()]); + if (!target) + { + m_targetChanged[bot->getBotId()] = true; + m_value24[bot->getBotId()] = 0.0f; + return 0.0f; + } + m_targetChanged[bot->getBotId()] = false; + bot->addToFireInclination(m_value24[bot->getBotId()]); + return 0.0f; + } + + const float* const armourClass = + static_cast(CommonSingletonServer::m_iaiSettings)->getArmourClassValues(); // +0x94 + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const ownMobile = equipment->getMobile(); + const int ownStrengthType = equipment->getPhysical()->getStrengthType(); + const Vec3 position = equipment->getPosition(); + float currentTargetScore = 0.0f; + unsigned int countedOrders = 0; + const int side = bot->getSide(); + const unsigned int currentTarget = m_targets[bot->getBotId()]; + bool currentTargetScored = false; + std::vector ignore; + ignore.push_back(equipment->getAIObject()); + ignore.push_back(0); + + const unsigned int botId = bot->getBotId(); + const int orderedArea = IAIMain::m_instance->getSAI(side)->getBotOrderedPos(botId); + AIStrategicArea* const area = + static_cast(AIStrategicObjectManager::getInstance()->getStrategicObject(orderedArea)); + float areaFactor; + if (!area) + areaFactor = 1.0f; + else + areaFactor = area->isInside(position) ? 1.0f : 0.75f; + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + float bestScore = currentTargetScore; + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const object = it->second; + if (!(object->m_flags & SensedObject::SENSE_SIDED)) + continue; + Information* const info = informationManager->getInformation(object->m_handle); + if (!info || info->getSide() == side || !info->getPhysical()) + continue; + const unsigned int typeFlags = info->getObjectTypeFlags(); + if ((typeFlags & 0x20000) || (typeFlags & 0x100000) || (typeFlags & 0x800000)) + continue; + if (!(info->getPhysical()->getHealth() > 0.0f)) + continue; + + Vec3 targetPosition; + targetPosition.x = 0.0f; + targetPosition.y = 0.0f; + targetPosition.z = 0.0f; + if (info->getMobile()) + info->getMobile()->getPositionEstimate(targetPosition); + else + targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + float distance = std::sqrt(direction.z * direction.z + direction.x * direction.x + + direction.y * direction.y); + if (!(0.5f <= distance)) + distance = 0.5f; + if (distance > 250.0f) + continue; + + float timeFactor = 1.0f; + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + (void)direction; + if (object->m_flags & SensedObject::SENSE_INDIRECT) + { + const float age = static_cast(now - object->m_firstSeenTime); + timeFactor = 1.0f / (age * 0.05f + 1.0f); + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->size() > countedOrders) + { + if (bot->getOrderList(m_index)->end() + != std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), + object->m_handle)) + ++countedOrders; + } + + float targetAreaFactor = areaFactor; + if (ownMobile && area && !area->isInside(targetPosition)) + targetAreaFactor = areaFactor * 0.75f; + + if (!info->getUnit() || !vehicleOccupied(object->m_handle, side)) + continue; + + float strengthSum = 0.0f; + const unsigned int handle = object->m_handle; + int secondary = info->getFirstSecondaryObjectIterator(); + const int targetStrengthType = info->getPhysical()->getStrengthType(); + Information* part = info; + float score = strengthSum; + do + { + IPIUnit* const unit = part->getUnit(); + strengthSum = strengthSum + unit->getBattleStrengths()[ownStrengthType]; + bool ordered = false; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && bot->getOrderList(m_index)->size() > countedOrders) + { + if (bot->getOrderList(m_index)->end() + != std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), + handle)) + ordered = true; + } + float orderFactor; + if (ordered) + { + ++countedOrders; + orderFactor = bot->getMemory()->m_float8; + } + else + { + orderFactor = 1.0f; + } + score = (unit->getBattleStrengths()[ownStrengthType] + part->getStrength()) + * armourClass[targetStrengthType] * orderFactor * targetAreaFactor + + score; + part = informationManager->getInformation(info->getSecondaryObject(secondary, side)); + } + while (part); + + float distanceFactor = distance * 1.5f * 0.2f; + if (distanceFactor <= 0.1f) + distanceFactor = 0.1f; + score = score * (timeFactor / distanceFactor); + if (strengthSum <= static_cast(static_cast(bot)->getHarmlessThrsh())) + score = score * 0.33f; + if (info->getUnit()) + { + if (currentTarget == object->m_handle) + { + currentTargetScore = score; + currentTargetScored = true; + } + if (bestScore < score) + { + bestScore = score; + m_targets[bot->getBotId()] = object->m_handle; + } + } + } + + if (bestScore <= 0.0f) + { + m_targetChanged[bot->getBotId()] = !currentTargetScored; + m_value24[bot->getBotId()] = 0.0f; + m_value24[bot->getBotId()] += getIncomingFireUrgency(static_cast(bot)); + bot->addToFireInclination(m_value24[bot->getBotId()]); + return 0.0f; + } + + if (!currentTargetScored || currentTargetScore * 1.2f <= bestScore) + { + bot->getBotId(); // called, result unused + currentTargetScored = false; + } + else + { + m_targets[bot->getBotId()] = currentTarget; + } + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + m_targetChanged[bot->getBotId()] = !currentTargetScored; + m_value24[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore + bestScore) * (modifier * 1.0f); + m_value24[bot->getBotId()] += getIncomingFireUrgency(static_cast(bot)); + bot->addToFireInclination(m_value24[bot->getBotId()]); + return 0.0f; +} + +// ELF 0x214800 (Ghidra). Ten times the strongest incoming fire against the equipment's strength +// type, over a copy of the bot's incoming-fire list (the type asked for once per entry). +float BBFireUnarmed::getIncomingFireUrgency(BotMain* bot) +{ + float strongest = 0.0f; + const std::list > incoming = *bot->getIncommingFire(); // +0xA0 + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* const physical = equipment->getPhysical(); + for (std::list >::const_iterator it = incoming.begin(); + it != incoming.end(); ++it) + { + const float strength = it->first->getBattleStrength(physical->getStrengthType()); + strongest = (strength <= strongest) ? strongest : strength; + } + return strongest * 10.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h new file mode 100644 index 000000000..31826114a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.h @@ -0,0 +1,39 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREUNARMED_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREUNARMED_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotMain; + +// ELF: vtable 0x4BADE0 (13 words), operator new 0x28, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBFireUnarmed : public BotBehaviour +{ +public: + BBFireUnarmed(unsigned char, unsigned char); // 0x213570 + virtual ~BBFireUnarmed(); // 0x213910 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2139E0, slot +0x28; from the base declaration + + float getIncomingFireUrgency(BotMain*); // 0x214800; [INFERRED] ELF float, callers {'float': 2} + + /* +0x24 */ float* m_value24; // per bot, 0.0f; calculateUrgency stores a float there (fsts 0x213AD9) [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBFIREUNARMED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp new file mode 100644 index 000000000..34c11f044 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp @@ -0,0 +1,339 @@ +// Idle behaviour (AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp in the image). Recovered from libaidll.so +// (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. +// Radio message and channel numbers are kept as the image's integers: the enumerator names of +// AIRadioMessageType/AIRadioChannelType are not recoverable from either binary ([UNRESOLVED]). + +// static init: ELF 0x215C30 (__tcf_0 0x215C90, _GLOBAL__I 0x215CC0): 's Init object only. +#include + +#include "BBIdle.h" + +#include "BBPendingCalls.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBotBehaviourPattern/BBPIdle.h" +#include "../AIBotBehaviourPattern/BBPIdle2d.h" +#include "../AIBotBehaviourPattern/BBPIdle3d.h" +#include "../AIBotBehaviourPattern/BBPIdleInfantery.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +// Information::m_objectTypeFlags bits read here ([UNRESOLVED] names): 0x10 and 0x20 select the +// larger pickup radius, 0x200000 marks an object that can carry passengers (the pickup vehicle). +const unsigned int kTypeFlag10 = 0x10; +const unsigned int kTypeFlag20 = 0x20; +const unsigned int kTypeFlagCarrier = 0x200000; + +// The sender id that means "anyone" in a pickup request; a real one makes the request personal. +const int kAnySender = 0xFF; + +} // namespace + +// ELF 0x214C10 +BBIdle::BBIdle(unsigned char index, unsigned char queue, BBPIdle* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, settings()->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + + const int bots = settings()->getMaxNBots(); + m_waitStartTime = new double[bots]; + m_waitingForPickup = new bool[bots]; + m_healthAtWaitStart = new float[bots]; + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 1.0f; + m_targetChanged[i] = false; + m_waitStartTime[i] = 0.0; + m_waitingForPickup[i] = false; + m_healthAtWaitStart[i] = 0.0f; + } + m_targets = 0; +} + +// ELF 0x214D90 +BBIdle::~BBIdle() +{ + if (m_waitStartTime) + delete[] m_waitStartTime; + if (m_waitingForPickup) + delete[] m_waitingForPickup; + if (m_healthAtWaitStart) + delete[] m_healthAtWaitStart; +} + +// ELF 0x215BA0. Retail quirk: it resets every bot slot, not only the bot it is given, and it does +// not call BotBehaviour::reset. +void BBIdle::reset(Bot*) +{ + const int bots = settings()->getMaxNBots(); + for (int i = 0; i < bots; ++i) + { + m_urgency[i] = 1.0f; + m_targetChanged[i] = false; + m_waitStartTime[i] = 0.0; + m_waitingForPickup[i] = false; + m_healthAtWaitStart[i] = 0.0f; + } + m_targets = 0; +} + +// ELF 0x214E90 +float BBIdle::calculateUrgency(Bot* bot, bool, float modifier) +{ + BBPIdle* const pattern = static_cast(m_pattern); + const unsigned int equipment = bot->getCurrentEquipment(); + Information* const info = informationManager->getInformation(equipment); + info->getPrimaryObject(bot->getSide()); // 0x214F1D: called, result unused + IPIMobile* const mobile = info->getMobile(); + + bool active = false; + float urgency = modifier; + int pickupPlayerId = -1; + + if (info->isPrimary() && !(info->getObjectTypeFlags() & kTypeFlagCarrier) && mobile) + { + bool moving = false; + if (bot->isAirBorn()) + moving = true; + else if ((info->getObjectTypeFlags() & kTypeFlag10) && mobile->getSpeedMagnitude() > 3.0f) + moving = true; + + IPIPhysical* const physical = info->getPhysical(); + bool damaged = false; + if (physical && physical->getHealth() < 0.9f) + damaged = true; + + bool waitForRepairs = false; + if (!moving && damaged) + { + BotMain* const main = static_cast(bot); + if (main->getIsRepaired() || main->getIsEngineerTarget()) + waitForRepairs = true; + } + static_cast(bot)->setShouldWaitForRepairs(waitForRepairs); + + if (!waitForRepairs) + { + // 0x215581: a repair that ended with a real gain is acknowledged once. + if (m_healthAtWaitStart[bot->getBotId()] > 0.0f && physical) + { + const float gained = physical->getHealth() - m_healthAtWaitStart[bot->getBotId()]; + if (gained > 0.25f) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(8), + static_cast(6), 3, 1.0f, + -1); + m_healthAtWaitStart[bot->getBotId()] = 0.0f; + } + } + } + + const std::list& messages = + bot->getCommunicationAgent()->getReceivedMessages(static_cast(11)); + bool hadMessages = false; + if (waitForRepairs) + { + double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (m_waitingForPickup[bot->getBotId()] == true || m_waitStartTime[bot->getBotId()] == 0.0) + { + m_waitStartTime[bot->getBotId()] = now; + m_healthAtWaitStart[bot->getBotId()] = physical->getHealth(); + } + now = now - m_waitStartTime[bot->getBotId()]; + if (now > 3.0) + static_cast(bot)->setIsRepaired(false); + if (!messages.empty()) + hadMessages = true; + m_waitingForPickup[bot->getBotId()] = false; + urgency = modifier * 60.0f; + active = true; + } + else + { + waitForPickup(bot, equipment, info, pattern, moving, modifier, urgency, pickupPlayerId, active); + } + + // 0x21515F: answer the senders of message 11 that are in the bot's own vehicle. + if (!messages.empty() + && bbpending::generalConfirmReceivedMessage(bot->getCommunicationAgent(), + static_cast(11)) + && pickupPlayerId != kAnySender) + { + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + IAIPlayer* const player = + static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(it->m_senderPlayerId); + if (!player) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const vehicleInfo = informationManager->getInformation(vehicle->getHandle(bot->getSide())); + if (!vehicleInfo) + continue; + Information* const ownPrimary = + informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + Information* const senderPrimary = + informationManager->getInformation(vehicleInfo->getPrimaryObject(bot->getSide())); + if (senderPrimary != ownPrimary) + continue; + if (!hadMessages) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(7), 3, 1.0f, + -1); + active = false; + } + else + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(7), + static_cast(7), 3, 1.0f, + -1); + } + } + } + } + + // 0x215170 + if (!active) + { + static_cast(bot)->setIsRepaired(false); + static_cast(bot)->setShouldWaitForRepairs(false); + m_waitStartTime[bot->getBotId()] = 0.0; + m_waitingForPickup[bot->getBotId()] = false; + m_healthAtWaitStart[bot->getBotId()] = 0.0f; + urgency = modifier; + } + + m_urgency[bot->getBotId()] = urgency; + if (pattern->getType() == 1) + static_cast(pattern)->init(bot, pickupPlayerId); + else if (pattern->getType() == 2) + static_cast(pattern)->init(50.0f, bot, pickupPlayerId); + else if (pattern->getType() == 3) + static_cast(pattern)->init(bot); + return urgency; +} + +// ELF 0x2156C0. Walks the bot's received pickup offers (message 2) and accepts the first that +// fits: a carrier vehicle close enough to the bot's own (primary) object. +void BBIdle::waitForPickup(Bot* bot, unsigned int equipment, Information* equipmentInfo, BBPIdle* pattern, + bool moving, float modifier, float& urgency, int& pickupPlayerId, bool& active) +{ + const std::list& messages = + bot->getCommunicationAgent()->getReceivedMessages(static_cast(2)); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + + for (std::list::const_iterator it = messages.begin(); it != messages.end(); ++it) + { + Bot* const sender = IBotManager::instance->getBotFromPlayerId(it->m_senderPlayerId); + Information* const primary = + informationManager->getInformation(equipmentInfo->getPrimaryObject(bot->getSide())); + const int primaryPlayerId = primary->getAIObject()->getPlayerId(); + CommunicationAgent* const senderAgent = sender ? sender->getCommunicationAgent() : 0; + const bool fromAnyone = it->m_senderPlayerId == kAnySender; + + if (pickupPlayerId >= 0 && !fromAnyone) + continue; + if (equipmentInfo->getObjectTypeFlags() & kTypeFlagCarrier) + continue; + // 0x21584E: `cmpl 0x5C(agent), primaryPlayerId` (CommunicationAgent +0x5C). + if (senderAgent && bbpending::communicationAgentInt92(senderAgent) != primaryPlayerId) + continue; + + IAIPlayer* const player = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(it->m_senderPlayerId); + if (!player) + continue; + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const vehicleInfo = informationManager->getInformation(vehicle->getHandle(bot->getSide())); + if (!vehicleInfo) + continue; + if (!(vehicleInfo->getObjectTypeFlags() & kTypeFlagCarrier)) + continue; + + const unsigned int flags = equipmentInfo->getObjectTypeFlags(); + float maxDistanceSqr; + if ((flags & kTypeFlag20) || (flags & kTypeFlag10) || fromAnyone) + maxDistanceSqr = 2500.0f; + else + maxDistanceSqr = 625.0f; + + // Information slot +0x3C (getTransformation); the translation row is m[12..14]. + const Mat4& own = primary->getTransformation(); + const Mat4& carrier = vehicleInfo->getTransformation(); + Vec3 delta; + delta.x = own.m[12] - carrier.m[12]; + delta.y = own.m[13] - carrier.m[13]; + delta.z = own.m[14] - carrier.m[14]; + const float distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + + bool decline; + if (fromAnyone) + decline = !pattern->freePosition(equipment, bot->getSide()) || distanceSqr > maxDistanceSqr || moving; + else + decline = distanceSqr > maxDistanceSqr || moving; + if (decline) + { + // 0x21598F + if (!bbpending::confirmReceivedMessage(bot->getCommunicationAgent(), *it)) + continue; + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(7), + static_cast(6), 3, 1.0f, -1); + return; + } + + // 0x215A00 + if (!m_waitingForPickup[bot->getBotId()] || m_waitStartTime[bot->getBotId()] == 0.0) + m_waitStartTime[bot->getBotId()] = now; + const double waited = now - m_waitStartTime[bot->getBotId()]; + if (!(vehicleInfo->getObjectTypeFlags() & kTypeFlagCarrier) || primary != equipmentInfo) + continue; + if (!equipmentInfo->getMobile() || (equipmentInfo->getObjectTypeFlags() & kTypeFlagCarrier) || moving) + continue; + if (!(waited < 10.0)) + continue; + if (pickupPlayerId >= 0 && !fromAnyone) + continue; + + urgency = modifier * it->m_modifier; + active = true; + pickupPlayerId = it->m_senderPlayerId; + m_waitingForPickup[bot->getBotId()] = true; + if (pickupPlayerId == kAnySender) + return; + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h new file mode 100644 index 000000000..318e654e4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.h @@ -0,0 +1,45 @@ +// Idle behaviour: the fallback every vehicle type gets (aibehaviours.ai `setVehicleDefaultBehaviour`). +// Its urgency is the modifier, raised while a bot waits for repairs or for a pickup it was offered. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBIDLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBIDLE_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPIdle; +class Bot; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BAE80 (13 words), operator new 0x30, package D-behaviours. +class BBIdle : public BotBehaviour +{ +public: + BBIdle(unsigned char index, unsigned char queue, BBPIdle* pattern, UrgeCurve* curve, float* modifiers); // 0x214C10 + virtual ~BBIdle(); // 0x214D90 + + virtual void reset(Bot*); // 0x215BA0, slot +0x24 + virtual float calculateUrgency(Bot*, bool, float); // 0x214E90, slot +0x28 + + void waitForPickup(Bot* bot, unsigned int equipment, Information* equipmentInfo, BBPIdle* pattern, + bool moving, float modifier, float& urgency, int& pickupPlayerId, bool& active); // 0x2156C0 + +private: + // The three per-bot arrays (one entry per bot slot, IAISettings::getMaxNBots), from the constructor. + /* +0x24 */ double* m_waitStartTime; // 0.0 = not waiting; the game time the current wait began + /* +0x28 */ bool* m_waitingForPickup; // set when a pickup offer was accepted (waitForPickup) + /* +0x2C */ float* m_healthAtWaitStart; // vehicle health when a repair wait began; 0 = none +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp new file mode 100644 index 000000000..471bbb2f3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp @@ -0,0 +1,739 @@ +// Medic/support assist behaviour (infantry "MedicAssist" slot of aibehaviours.ai). A medic +// (IAIPlayer::getSpawnKit 5) heals and an engineer (kit 4) repairs the friendly unit with the best +// strength / (curve(1 - health) * distance) score; a support soldier (kit 3) hands out ammunition +// (calculateGiveAmmoUrgency). The chosen target goes to the pattern through BBPMedicAssist::init. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. +// +// Float constants (rodata): 0x49CB34 0.0f, 0x49CB2C 1.0f, 0x49F818 75.0f, 0x49CB54 0.75f, +// 0x49F81C 0.99f, 0x49F580 0.7071f, 0x49CB5C 100.0f, 0x49CCA8 50.0f, 0x49CC88 10.0f, +// 0x49CDC0 1.5f, 0x49CC90 3.0f, 0x49CC84 4.0f, 0x49F820 0.49f, 0x49F824 0.74f, 0x49CF6C 2500.0f, +// 0x49F828 0.9 (double, fldl). + +// static init: ELF 0x219240 (__tcf_0 0x2192A0, _GLOBAL__I 0x2192D0): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) +#include "BBMedicAssist.h" + +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotBehaviourPattern/BBPMedicAssist.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Narrow stops for callees the tree does not declare yet (owner ai-bot). Each is a one-line swap +// to the real call once the owner declares it. + +// ELF 0x1C47F0 _ZNK4dice3hfe2ai18CommunicationAgent18getReceivedMessageERNS1_18AIRadioMessageInfoENS1_18AIRadioMessageTypeEi +// (PLT 0x185930). Swap to: return agent->getReceivedMessage(info, type, playerId); +bool communicationAgentGetReceivedMessage(const CommunicationAgent* agent, AIRadioMessageInfo& info, + AIRadioMessageType type, int playerId) +{ + return agent->getReceivedMessage(info, type, playerId); +} + +// ELF 0x1C4A00 _ZN4dice3hfe2ai18CommunicationAgent21receivedMessageExistsENS1_18AIRadioMessageTypeEi +// (PLT 0x17E1F0). Swap to: return agent->receivedMessageExists(type, playerId); +bool communicationAgentReceivedMessageExists(CommunicationAgent* agent, AIRadioMessageType type, + int playerId) +{ + return agent->receivedMessageExists(type, playerId); +} + +// ELF _ZN4dice3hfe2ai12SquadManager23requestResponseModifierEPNS1_11SquadMemberEjNS3_13RequestActionEi +// (PLT 0x17A880): float SquadManager::requestResponseModifier(SquadMember*, unsigned int target, +// SquadManager::RequestAction, int side), called on SquadManager::m_instance; the x87 result is +// multiplied into the urgency. Swap to: +// return SquadManager::m_instance->requestResponseModifier(member, target, +// static_cast(action), side); +float squadManagerRequestResponseModifier(SquadMember* member, unsigned int target, int action, int side) +{ + return SquadManager::m_instance->requestResponseModifier(member, target, action, side); +} + +const unsigned int kNoTarget = 0xFFFFFFFFu; + +inline IAIPlayer* playerFromId(int id) +{ + return static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(id); +} + +// The inlined Vec3 subtraction followed by the x87 length (fsqrt, sqrtf on NaN). +inline float distance(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +inline float distanceSqr(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return dx * dx + dy * dy + dz * dz; +} + +} // namespace + +// ELF 0x215CE0 (C2) / 0x216220 (C1). The base gets getMaxNBots (IAISettings slot 0); the +// vector at +0x24 is zeroed (three words); +0x30/+0x34/+0x38 are new[getNBattleStrengths] +// (slot +0x34, called once per array, each checkPointer'd); then index/queue/pattern; +0x08 is +// new[getMaxNBots] (not initialised) and every base urgency is 0.0f (rodata 0x49CB34). +BBMedicAssist::BBMedicAssist(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + IAISettings* settings = static_cast(CommonSingletonServer::m_iaiSettings); + m_bestWeaponIndex = checkPointer(new int[settings->getNBattleStrengths()]); + m_bestWeaponRange = checkPointer(new float[settings->getNBattleStrengths()]); + m_bestWeaponStrength = checkPointer(new int[settings->getNBattleStrengths()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = settings->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); // per-bot chosen target handle + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x216760 (D2) / 0x216810 (D1) / 0x2168C0 (D0): delete[] +0x08, +0x30, +0x34, +0x38 when +// set, then the vector's storage, then the base. +BBMedicAssist::~BBMedicAssist() +{ + if (m_targets) + delete[] m_targets; + if (m_bestWeaponIndex) + delete[] m_bestWeaponIndex; + if (m_bestWeaponRange) + delete[] m_bestWeaponRange; + if (m_bestWeaponStrength) + delete[] m_bestWeaponStrength; +} + +// ELF 0x216980. Primary object of `info` for `side`, then its secondary objects: the first unit +// that is occupied by a player whom IAIPlayerFactory::getPlayerFromId (+0x20) knows and whose +// getIsAIPlayer (+0x88) is false answers true. +bool BBMedicAssist::isHumanInTarget(Information* info, int side) +{ + bool human = false; + if (info) + { + Information* primary = informationManager->getInformation(info->getPrimaryObject(side)); + if (primary) + { + IPIUnit* unit = primary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = playerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + return true; + } + int iterator; + for (Information* secondary = + informationManager->getInformation(primary->getFirstSecondaryObject(iterator, side)); + secondary; + secondary = informationManager->getInformation(primary->getSecondaryObject(iterator, side))) + { + unit = secondary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = playerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + { + human = true; + break; + } + } + } + } + } + return human; +} + +// ELF 0x216B40. +float BBMedicAssist::calculateUrgency(Bot* bot, bool recalculate, float urgencyScale) +{ + unsigned int* targets = m_targets; + PlanGenerator* pattern = m_pattern; + + if (!recalculate) + { + // Keep the current target while it is still on the bot's side (Information slot +0x44 + // getSide vs Bot +0xE0); a pattern that is no longer initiated (+0x0C) drops the urgency. + Information* target = informationManager->getInformation(targets[bot->getBotId()]); + if (target && target->getSide() == bot->getSide()) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); + } + return m_urgency[bot->getBotId()]; + } + + // ELF 0x216CE9: cmpl $0x3 on IAIPlayer::getSpawnKit (+0x44) - support soldiers hand out ammo. + if (bot->getPlayer()->getSpawnKit() == 3) + return calculateGiveAmmoUrgency(bot, urgencyScale); + + const int nStrengths = static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + int bestPlayerId = -1; // -0x198 + int bestWeaponIndex = -1; // -0x194 + Vec3 normal = {0.0f, 0.0f, 0.0f}; + const int kit = bot->getPlayer()->getSpawnKit(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& selfPosition = self->getPosition(); // retail: no null check + + for (int i = 0; i < nStrengths; ++i) + { + m_bestWeaponIndex[i] = -1; + m_bestWeaponStrength[i] = 0; + } + + IPIArmament* armament = self->getArmament(); + IPIMobile* selfMobile = self->getMobile(); + int vehicleNumber = -2; + if (selfMobile) + { + vehicleNumber = selfMobile->getVehicleNumber(); + self->getUnit()->getEquipmentType(); // ELF 0x216E1A: result unused + } + + // The bot's own healing/repair weapons (WeaponInfo::getWeaponType 1): per strength type the + // strongest one, its index and its max range. + std::vector weapons = armament->getWeapons(); + for (unsigned int w = 0; w < weapons.size(); ++w) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[w]); + if (!weapon || weapon->getWeaponType() != 1) + continue; + for (int i = 0; i < nStrengths; ++i) + { + if (weapon->getStrength(i) > m_bestWeaponStrength[i]) + { + m_bestWeaponIndex[i] = static_cast(w); + m_bestWeaponStrength[i] = weapon->getStrength(i); + m_bestWeaponRange[i] = weapon->getMaxRange(); + } + } + } + + float bestScore = 0.0f; + // ELF -0x188: the same stack slot is the new size of the resize below and the counter of + // ordered targets met in the loop. [INFERRED] one source variable. + unsigned int orderedCount = 0; + // ELF 0x216FA5..0x216FC9 / 0x217E18: size > 0 -> erase(begin, end), else + // _M_fill_insert(end, 0, 0): the inlined vector::resize(0). + m_friendlies.resize(orderedCount); + // IAIInformationEnvironment slot +0x0C: getFriendlyAndNeutralUnits(out, position, bot, 75.0f). + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getFriendlyAndNeutralUnits(m_friendlies, selfPosition, bot, 75.0f); + + unsigned int bestTarget = kNoTarget; // -0x1BC + CommunicationAgent* agent = bot->getCommunicationAgent(); + const std::list& medicCalls = agent->getReceivedMessages(static_cast(3)); + const std::list& repairCalls = agent->getReceivedMessages(static_cast(4)); + bool canAnswerMedicCall = !medicCalls.empty(); + bool canAnswerRepairCall = !repairCalls.empty(); + if (bot->isAirBorn()) + { + canAnswerMedicCall = false; + canAnswerRepairCall = false; + } + // ELF 0x21708D: a 1.0f local that multiplies every score (fmuls -0x1A0). + const float scoreModifier = 1.0f; + + // Squad queries whose results are not used (ELF 0x2170C5..0x21710C). + Vec3 squadPosition = {0.0f, 0.0f, 0.0f}; + SquadCoordinator* squad = bot->getSquadMember()->getSquad(); + squad->getSquadPosition(squadPosition); + Vec3 squadGotoPosition = squad->getSquadGotoPos(); + (void)squadGotoPosition; + squad->getSquadLeader(); + + float bestDistance = 100.0f; + bool bestIsHuman = false; // -0x1DA + bool bestHasNoBot = false; // -0x1DB: set by any 3x candidate, not only the best (retail) + + for (std::vector::iterator it = m_friendlies.begin(); it != m_friendlies.end(); ++it) + { + float healthThreshold = 0.75f; + bool isHuman = false; + Information* info = informationManager->getInformation(*it); + if (!info || !info->getPhysical()) + continue; + // A firing medic does not treat itself. + if (info == self && bot->getPlayer()->getSpawnKit() == 5 && bot->isFiring()) + continue; + // Object-type flag 0x80 (testb $-0x80, +0x04): only when a human is in it. + if ((info->getObjectTypeFlags() & 0x80) && !isHumanInTarget(info, bot->getSide())) + continue; + if (info == self && bot->getPlayer()->getSpawnKit() == 5 && armament->getActiveWeapon() != -1) + { + // A medic holding its healing weapon (type 1) skips itself. + WeaponInfo* active = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (active && active->getWeaponType() == 1) + continue; + } + + IPIPhysical* physical = info->getPhysical(); + const int strengthType = physical->getStrengthType(); + if (physical->getManDown()) + continue; + if (isHumanInTarget(info, bot->getSide())) + { + healthThreshold = 0.99f; + isHuman = true; + } + if (m_bestWeaponIndex[strengthType] == -1) + continue; + + const float health = physical->getHealth(); + int occupant = -1; + if (info->getUnit()) + occupant = info->getUnit()->getOccupyingPlayerId(info->getSide()); + + AIRadioMessageInfo medicCall; + bool medicCalled = false; + if (canAnswerMedicCall) + medicCalled = communicationAgentGetReceivedMessage(agent, medicCall, static_cast(3), + occupant); + // Retail: repairCall is never filled, so its sender stays -1 (the constructor's value). + AIRadioMessageInfo repairCall; + bool repairCalled = false; + if (canAnswerRepairCall) + repairCalled = vehicleRequestsEngineer(info, info->getSide(), agent); + if (!repairCalled && bot->getPlayer()->getSpawnKit() == 4 && + bot->getSquadMember()->isCloseToNonOwnedTarget()) + continue; + + // ucomiss: needs treatment (0 < health < threshold) or a call for it. + if (!(healthThreshold > health && health > 0.0f) && !medicCalled && !repairCalled) + continue; + if (health > healthThreshold) + continue; + + // Only units standing on ground flatter than 45 degrees (terrain normal . object up row). + const Vec3& position = info->getPosition(); + static_cast(CommonSingletonServer::m_iaiTerrain)->getNormal(position.x, position.z, normal); + const Mat4& transformation = info->getTransformation(); + if (normal.x * transformation.m[4] + normal.y * transformation.m[5] + normal.z * transformation.m[6] < + 0.7071f) + continue; + + IPIUnit* unit = info->getUnit(); + if (unit->getAlwaysTargetSoldier()) + continue; + if (distance(selfPosition, position) > m_bestWeaponRange[strengthType]) + { + if (!selfMobile) + continue; + if (!unit->useNoPathfindingToGetToObject() && info->getMobile()) + { + // Retail: skips the target when the bot's last valid position is within range. + const Vec3& lastValid = selfMobile->getLastValidPosition(vehicleNumber).position; + const float range = m_bestWeaponRange[strengthType]; + if (distanceSqr(lastValid, position) < range * range) + continue; + } + } + const float targetDistance = info == self ? 1.0f : distance(selfPosition, position); + + float strength; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && + orderedCount < bot->getOrderList(m_index)->size() && + std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), *it) != + bot->getOrderList(m_index)->end()) + { + ++orderedCount; + strength = info->getStrength() * bot->getMemory()->m_float8; + } + else + { + strength = info->getStrength(); + } + + // fdivp (AT&T: st(1) = st(0) / st(1)): strength / (curve(1 - health) * distance). + float score = strength / (DecleiningSlopeCurve::calculate(1.0f - health) * targetDistance); + if ((medicCalled && medicCall.m_senderPlayerId == occupant && kit == 5) || + (repairCalled && repairCall.m_senderPlayerId == occupant && kit == 4)) + { + // IBotManager slot +0x1C: a caller without a bot (a human) triples the score. + if (IBotManager::instance->getBotFromPlayerId(occupant)) + { + score = score * 1.5f; + } + else + { + score = score * 3.0f; + bestHasNoBot = true; + } + } + if (score * scoreModifier > bestScore) + { + bestIsHuman = isHuman; + bestDistance = targetDistance; + bestWeaponIndex = m_bestWeaponIndex[strengthType]; + bestScore = score * scoreModifier; + bestTarget = *it; + bestPlayerId = occupant; + } + } + + const unsigned int id = bot->getBotId(); + if (bestTarget == kNoTarget) + { + m_urgency[id] = 0.0f; + m_targetChanged[id] = targets[id] != kNoTarget; + targets[id] = kNoTarget; + pattern->unInit(bot); + return 0.0f; + } + + // An ordered behaviour with an empty order list scales the score by BotMemory +0x08. + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + + if (bestIsHuman && bestHasNoBot && bestDistance < 50.0f) + { + m_urgency[id] = 100.0f; + } + else if (bestIsHuman) + { + m_urgency[id] = DecleiningSlopeCurve::calculate(bestScore) * 10.0f * urgencyScale; + } + else + { + // fadd %st(0), %st: curve + curve. + const float curve = DecleiningSlopeCurve::calculate(bestScore); + m_urgency[id] = (curve + curve) * urgencyScale; + } + + m_targetChanged[id] = targets[id] != bestTarget; + targets[id] = bestTarget; + static_cast(m_pattern)->init(targets[id], bestWeaponIndex, bestPlayerId, bot); + + if (kit == 5) + { + // RequestAction 1 (ELF 0x217452 movl $0x1). + m_urgency[id] = squadManagerRequestResponseModifier(bot->getSquadMember(), bestTarget, 1, bot->getSide()) * + m_urgency[id]; + } + else if (kit == 4) + { + // RequestAction 2 (ELF 0x2173A2 movl $0x2); Bot +0x1C8 setWantedRepairTarget. + m_urgency[id] = squadManagerRequestResponseModifier(bot->getSquadMember(), bestTarget, 2, bot->getSide()) * + m_urgency[id]; + bot->setWantedRepairTarget(m_urgency[id] == 0.0f ? kNoTarget : bestTarget); + } + return m_urgency[bot->getBotId()]; +} + +// ELF 0x217E70. A bot that is man down never applies; otherwise the information's armament must +// hold a weapon of type 1 (heal/repair) or 2 (ammo): `decl; cmpl $0x1; jbe`. +bool BBMedicAssist::isAplicable(Information* info, Bot* bot) +{ + IPIArmament* armament = info->getArmament(); + if (bot->getManDown() || !armament) + return false; + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && static_cast(weapon->getWeaponType() - 1) <= 1) + return true; + } + return false; +} + +// ELF 0x217F10. A repair request (message type 4) from the information's player, or from the +// player of any of its secondary objects for `side`. +bool BBMedicAssist::vehicleRequestsEngineer(Information* info, int side, CommunicationAgent* agent) const +{ + if (info && communicationAgentReceivedMessageExists(agent, static_cast(4), info->getPlayerId())) + return true; + // Retail: also reached with a null info (getFirstSecondaryObject is called on it). + int iterator; + for (Information* secondary = informationManager->getInformation(info->getFirstSecondaryObject(iterator, side)); + secondary; secondary = informationManager->getInformation(info->getSecondaryObject(iterator, side))) + { + if (communicationAgentReceivedMessageExists(agent, static_cast(4), + secondary->getPlayerId())) + return true; + } + return false; +} + +// ELF 0x218020. The support soldier's version of calculateUrgency: weapon type 2 (ammo), friendly +// units low on ammunition, message type 10, SCurve of the ammo ratio, RequestAction 4. +float BBMedicAssist::calculateGiveAmmoUrgency(Bot* bot, float urgencyScale) +{ + unsigned int* targets = m_targets; + PlanGenerator* pattern = m_pattern; + + const int nStrengths = static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + int bestPlayerId = -1; // -0x190 + int bestWeaponIndex = -1; // -0x18C + Vec3 normal = {0.0f, 0.0f, 0.0f}; + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& selfPosition = self->getPosition(); // retail: no null check + + for (int i = 0; i < nStrengths; ++i) + { + m_bestWeaponIndex[i] = -1; + m_bestWeaponStrength[i] = 0; + } + + IPIArmament* armament = self->getArmament(); + IPIMobile* selfMobile = self->getMobile(); + int vehicleNumber = -2; + if (selfMobile) + { + vehicleNumber = selfMobile->getVehicleNumber(); + self->getUnit()->getEquipmentType(); // ELF 0x21815A: result unused + } + + // The bot's own ammo weapons (type 2). + std::vector weapons = armament->getWeapons(); + for (unsigned int w = 0; w < weapons.size(); ++w) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weapons[w]); + if (!weapon || weapon->getWeaponType() != 2) + continue; + for (int i = 0; i < nStrengths; ++i) + { + if (weapon->getStrength(i) > m_bestWeaponStrength[i]) + { + m_bestWeaponIndex[i] = static_cast(w); + m_bestWeaponStrength[i] = weapon->getStrength(i); + m_bestWeaponRange[i] = weapon->getMaxRange(); + } + } + } + + float bestScore = 0.0f; + unsigned int orderedCount = 0; // same slot as the resize size, see calculateUrgency + m_friendlies.resize(orderedCount); + // IAIInformationEnvironment slot +0x08: getFriendlyUnits(out, position, bot, 75.0f). + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getFriendlyUnits(m_friendlies, selfPosition, bot, 75.0f); + + const float scoreModifier = 1.0f; // ELF 0x218340 (-0x198) + unsigned int bestTarget = kNoTarget; // -0x1B4 + CommunicationAgent* agent = bot->getCommunicationAgent(); + bool canAnswerAmmoCall = !agent->getReceivedMessages(static_cast(10)).empty(); + if (canAnswerAmmoCall && bot->isAirBorn()) + canAnswerAmmoCall = false; + + std::vector targetWeapons; + Vec3 squadPosition = {0.0f, 0.0f, 0.0f}; + SquadMember* member = bot->getSquadMember(); + member->getSquad()->getSquadPosition(squadPosition); + Vec3 squadGotoPosition = member->getSquad()->getSquadGotoPos(); + (void)squadGotoPosition; + Vec3 memberPosition = {0.0f, 0.0f, 0.0f}; + + for (std::vector::iterator it = m_friendlies.begin(); it != m_friendlies.end(); ++it) + { + float ammoThreshold = 0.49f; + Information* info = informationManager->getInformation(*it); + if (!info || !info->getPhysical()) + continue; + + IPIUnit* occupiedUnit = info->getUnit(); + if (occupiedUnit && occupiedUnit->isOccupied()) + { + // An occupied unit: skipped when an AI player is in it. + IAIPlayer* player = playerFromId(occupiedUnit->getOccupyingPlayerId(info->getSide())); + if (player && player->getIsAIPlayer()) + continue; + } + else if (member->getPosition(memberPosition) && + distanceSqr(memberPosition, info->getPosition()) > 2500.0f) + { + // An empty unit more than 50 m from the bot's own squad-member position. + continue; + } + + if (info == self && bot->getPlayer()->getSpawnKit() == 3 && armament->getActiveWeapon() != -1) + { + // A support soldier holding its ammo weapon (type 2) skips itself. + WeaponInfo* active = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (active && active->getWeaponType() == 2) + continue; + } + + IPIPhysical* physical = info->getPhysical(); + if (physical->getManDown()) + continue; + const int strengthType = physical->getStrengthType(); + if (m_bestWeaponIndex[strengthType] == -1) + continue; + + // The ammo ratio over the target's weapons except heal/repair (1) and ammo (2) ones, with + // getAmmo (+0x10) != -1 and getMaxAmmo != 0. Needs ammo when a weapon has more magazines + // (+0x18 getNumberOfMags) than int(getCurrentAmmo (+0x14) / getMaxAmmoInMag) + 1. + targetWeapons = info->getArmament()->getWeapons(); + float ammoRatio = 1.0f; + bool needsAmmo = false; + // Retail: the bound is the bot's own weapon count (-0x168/-0x164), the index goes into + // the target's copy (-0x158). + for (unsigned int w = 0; w < weapons.size(); ++w) + { + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(targetWeapons[w]); + if (!weapon || weapon->getWeaponType() == 1 || weapon->getWeaponType() == 2 || weapon->getAmmo() == -1 || + weapon->getMaxAmmo() == 0) + continue; + const float currentAmmo = static_cast(weapon->getCurrentAmmo()); + ammoRatio = currentAmmo / static_cast(weapon->getMaxAmmo()) * ammoRatio; + const int mags = weapon->getNumberOfMags(); + const float fullMags = currentAmmo / static_cast(weapon->getMaxAmmoInMag()); // fstps, cvttss2si + if (static_cast(fullMags) + 1 < mags) + needsAmmo = true; + } + if (!needsAmmo) + continue; + + int occupant = -1; + if (info->getUnit()) + occupant = info->getUnit()->getOccupyingPlayerId(info->getSide()); + AIRadioMessageInfo ammoCall; + bool ammoCalled = false; + if (canAnswerAmmoCall) + ammoCalled = communicationAgentGetReceivedMessage(agent, ammoCall, static_cast(10), + occupant); + if (isHumanInTarget(info, bot->getSide())) + ammoThreshold = 0.74f; // cmovnel of the bit pattern + + if (!(ammoThreshold > ammoRatio && ammoRatio > 0.0f)) + { + if (!ammoCalled) + continue; + if (!(ammoRatio < 0.9)) // fldl 0x49F828: double compare + continue; + } + + const Vec3& position = info->getPosition(); + terrain->getNormal(position.x, position.z, normal); + const Mat4& transformation = info->getTransformation(); + if (normal.x * transformation.m[4] + normal.y * transformation.m[5] + normal.z * transformation.m[6] < + 0.7071f) + continue; + + IPIUnit* unit = info->getUnit(); + if (unit->getAlwaysTargetSoldier()) + continue; + if (distance(selfPosition, position) > m_bestWeaponRange[strengthType]) + { + if (!selfMobile) + continue; + if (!unit->useNoPathfindingToGetToObject() && info->getMobile()) + { + const Vec3& lastValid = selfMobile->getLastValidPosition(vehicleNumber).position; + const float range = m_bestWeaponRange[strengthType]; + if (distanceSqr(lastValid, position) < range * range) + continue; + } + } + const float targetDistance = info == self ? 1.0f : distance(selfPosition, position); + + float strength; + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && + orderedCount < bot->getOrderList(m_index)->size() && + std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), *it) != + bot->getOrderList(m_index)->end()) + { + ++orderedCount; + strength = info->getStrength() * bot->getMemory()->m_float8; + } + else + { + strength = info->getStrength(); + } + + float score = strength / (SCurve::calculate(ammoRatio) * targetDistance); + if (ammoCalled) + { + // Looked up by the message's sender (-0x114), not the occupant. + if (IBotManager::instance->getBotFromPlayerId(ammoCall.m_senderPlayerId)) + score = score * 1.5f; + else + score = score * 3.0f; + } + if (score * scoreModifier > bestScore) + { + bestWeaponIndex = m_bestWeaponIndex[strengthType]; + bestScore = score * scoreModifier; + bestTarget = *it; + bestPlayerId = occupant; + } + } + + if (bestTarget == kNoTarget) + { + m_urgency[bot->getBotId()] = 0.0f; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != kNoTarget; + targets[bot->getBotId()] = kNoTarget; + pattern->unInit(bot); + return 0.0f; + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore = bestScore * bot->getMemory()->m_float8; + + m_urgency[bot->getBotId()] = DecleiningSlopeCurve::calculate(bestScore) * 4.0f * urgencyScale; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != bestTarget; + targets[bot->getBotId()] = bestTarget; + static_cast(m_pattern)->init(targets[bot->getBotId()], bestWeaponIndex, bestPlayerId, bot); + // RequestAction 4 (ELF 0x218680 movl $0x4). + const unsigned int id = bot->getBotId(); + m_urgency[id] = squadManagerRequestResponseModifier(bot->getSquadMember(), bestTarget, 4, bot->getSide()) * + m_urgency[id]; + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.h new file mode 100644 index 000000000..7e5bd9a2c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.h @@ -0,0 +1,58 @@ +// Medic/support assist behaviour (infantry): a medic (kit 5) or engineer (kit 4) picks the most +// urgent friendly unit near it to heal or repair; a support soldier (kit 3) instead looks for a +// friendly unit that needs ammunition (calculateGiveAmmoUrgency). Recovered from libaidll.so +// (Linux 1.5.3153, ia-32); F-urgency package, see docs/macos-ai-behaviour-plan.md. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMEDICASSIST_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMEDICASSIST_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class CommunicationAgent; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BAF20 (13 words), operator new 0x3C, package F-infantry. +class BBMedicAssist : public BotBehaviour +{ +public: + BBMedicAssist(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x216220 + virtual ~BBMedicAssist(); // 0x216810 + + virtual float calculateUrgency(Bot*, bool, float); // 0x216B40, slot +0x28; from the base declaration + virtual bool isAplicable(Information*, Bot*); // 0x217E70, slot +0x30; bool: 0/1 in %edx + + // ELF bool (movzbl of a 0/1 local); true when a human (non-AI) player occupies the + // information's primary object or one of its secondary objects for that side. + bool isHumanInTarget(Information*, int); // 0x216980 + // ELF returns 0/1 in %eax (movl $0x1, %edx); every caller tests the low byte, so bool. + bool vehicleRequestsEngineer(Information*, int, CommunicationAgent*) const; // 0x217F10 + // ELF float: both returns leave the urgency on the x87 stack (flds). + float calculateGiveAmmoUrgency(Bot*, float); // 0x218020 + +private: + // The friendly units of the last calculation, filled by IAIInformationEnvironment + // getFriendlyAndNeutralUnits / getFriendlyUnits (75 m around the bot). + /* +0x24 */ std::vector m_friendlies; + // Three per-battle-strength-type arrays (new[IAISettings::getNBattleStrengths]); for each + // strength type the bot's own healing/repair (weapon type 1) or ammo (type 2) weapon with the + // highest strength against it: its index in IPIArmament::getWeapons, its max range, its strength. + /* +0x30 */ int* m_bestWeaponIndex; // -1 = none + /* +0x34 */ float* m_bestWeaponRange; // WeaponInfo::getMaxRange + /* +0x38 */ int* m_bestWeaponStrength; // WeaponInfo::getStrength(type) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMEDICASSIST_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp new file mode 100644 index 000000000..d6c09d9e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp @@ -0,0 +1,126 @@ +// MoveTo behaviour (AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x219960 (__tcf_0 0x2199C0, _GLOBAL__I 0x2199F0): 's Init object only. +#include + +#include "BBMoveTo.h" + +#include "BBPendingCalls.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadFormation.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypoint.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x2193A0 +BBMoveTo::BBMoveTo(unsigned char index, unsigned char queue, BBPGotoWaypoint* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, settings()->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_targets = 0; + m_pattern = pattern; + + const int bots = settings()->getMaxNBots(); + for (int i = 0; i < bots; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x219490 +BBMoveTo::~BBMoveTo() +{ +} + +// ELF 0x219510 +float BBMoveTo::calculateUrgency(Bot* bot, bool recalculate, float modifier) +{ + BBPGotoWaypoint* const pattern = static_cast(m_pattern); + + // A squad member that holds its formation slot does not move until the squad moves out. + SquadMember* const member = bot->getSquadMember(); + if (bbpending::isAtFormationSlot(member) + && !member->getSquad()->getSquadFormation()->shouldSquadMoveOut()) + { + return m_urgency[bot->getBotId()] = 0.0f; + } + + if (!recalculate) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) + m_urgency[bot->getBotId()] = 0.0f; + bot->addToMoveInclination(m_urgency[bot->getBotId()]); + return m_urgency[bot->getBotId()]; + } + + float factor = 1.0f; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + { + const float weight = bot->getMemory()->m_float8; + m_urgency[bot->getBotId()] = weight * bot->getWaypoints()->getUrgency(equipment->getPosition(), bot); + } + else + { + m_urgency[bot->getBotId()] = bot->getWaypoints()->getUrgency(equipment->getPosition(), bot); + } + + const int side = bot->getSide(); + Vec3 position = equipment->getPosition(); + double sinceStart; + int artillerySide; + if (SquadManager::m_instance->isInArtilleryDangerZone(position, side, sinceStart, artillerySide)) + { + SquadMember* const avoiding = bot->getSquadMember(); + if (avoiding && avoiding->isAvoidingArtillery()) + m_urgency[bot->getBotId()] = 1000.0f; + } + + factor = factor * modifier; + m_urgency[bot->getBotId()] = factor * m_urgency[bot->getBotId()]; + if (m_urgency[bot->getBotId()] <= 0.0f) + { + m_targetChanged[bot->getBotId()] = pattern->isInitiated(bot); + pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + m_targetChanged[bot->getBotId()] = bot->getWaypoints()->m_flag4; + pattern->init(bot); + bot->addToMoveInclination(m_urgency[bot->getBotId()]); + + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + if (bot->getWaypoints()->getGoalPoint(position)) + bot->insertBehaviourInformation(0.5f, position, m_index); + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h new file mode 100644 index 000000000..679881d3f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.h @@ -0,0 +1,33 @@ +// MoveTo behaviour: follow the bot's waypoint list; the urgency comes from the waypoints. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETO_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETO_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPGotoWaypoint; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BAF80 (13 words), operator new 0x24, package D-behaviours. No members of its own. +class BBMoveTo : public BotBehaviour +{ +public: + BBMoveTo(unsigned char index, unsigned char queue, BBPGotoWaypoint* pattern, UrgeCurve* curve, float* modifiers); // 0x2193A0 + virtual ~BBMoveTo(); // 0x219490 + + virtual float calculateUrgency(Bot*, bool, float); // 0x219510, slot +0x28 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp new file mode 100644 index 000000000..cff3c7f82 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp @@ -0,0 +1,99 @@ +// Fixed move-to behaviour (AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp in the image). Recovered +// from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x21A1A0 (__tcf_0 0x21A200, _GLOBAL__I 0x21A230): 's Init object only. +#include + +#include "BBMoveToFixed.h" + +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/WaypointList.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../Main/AIMain.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x219A10 (C2) / 0x219C20 (C1); vtable GOT -0x1190. BotBehaviour(null modifiers, null curve, +// getMaxNBots); no targets and no pattern (+0x08 = +0x0C = 0); +0x24 = checkPointer(new +// float[getMaxNBots()]) (operator new 0x28); every bot starts with urgency and +0x24 at 0.0f. +BBMoveToFixed::BBMoveToFixed(unsigned char index, unsigned char queue) + : BotBehaviour(0, 0, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_targets = 0; + m_pattern = 0; + m_queue = queue; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_value24 = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_value24[i] = 0.0f; + } +} + +// ELF 0x219E30 (D2) / 0x219E80 (D1) / 0x219ED0 (D0): delete[] +0x24 when set, then ~BotBehaviour. +BBMoveToFixed::~BBMoveToFixed() +{ + if (m_value24) + delete[] m_value24; +} + +// ELF 0x219F20 (Ghidra; listing cross-check). Always returns 0.0; the urgency goes to +0x24 and to +// the bot's move inclination. With `recalculate` it is the waypoint list's urgency at the +// equipment's position (times the memory's +0x08 for an ordered behaviour); while positive, the +// target-changed flag follows the list's +0x04 flag and the list's goal point is reported to the +// sensing agent with weight 0.5. The SAI of the bot's side is fetched and not used, and a zero +// Vec3 is built and never read, as compiled. +float BBMoveToFixed::calculateUrgency(Bot* bot, bool recalculate, float) +{ + if (!recalculate) + { + m_targetChanged[bot->getBotId()] = false; + bot->addToMoveInclination(m_value24[bot->getBotId()]); + return 0.0f; + } + + Vec3 unused; + unused.x = 0.0f; + unused.y = 0.0f; + unused.z = 0.0f; + (void)unused; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IAIMain::m_instance->getSAI(bot->getSide()); // result unused + const Vec3& position = equipment->getPosition(); + m_value24[bot->getBotId()] = bot->getWaypoints()->getUrgency(position, bot); + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + m_value24[bot->getBotId()] = m_value24[bot->getBotId()] * bot->getMemory()->m_float8; + if (0.0f < m_value24[bot->getBotId()]) + { + m_targetChanged[bot->getBotId()] = bot->getWaypoints()->m_flag4; + bot->addToMoveInclination(m_value24[bot->getBotId()]); + Vec3 goal; + goal.x = 0.0f; + goal.y = 0.0f; + goal.z = 0.0f; + if (bot->getWaypoints()->getGoalPoint(goal)) + bot->insertBehaviourInformation(0.5f, goal, m_index); + } + else + { + m_targetChanged[bot->getBotId()] = false; + } + return 0.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h new file mode 100644 index 000000000..50fdc0b0e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETOFIXED_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETOFIXED_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BAFE0 (13 words), operator new 0x28, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBMoveToFixed : public BotBehaviour +{ +public: + BBMoveToFixed(unsigned char, unsigned char); // 0x219C20 + virtual ~BBMoveToFixed(); // 0x219E80 + + virtual float calculateUrgency(Bot*, bool, float); // 0x219F20, slot +0x28; from the base declaration + + /* +0x24 */ float* m_value24; // per bot, 0.0f; calculateUrgency stores and compares it [UNRESOLVED] meaning +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBMOVETOFIXED_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBPendingCalls.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBPendingCalls.h new file mode 100644 index 000000000..06203d62c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBPendingCalls.h @@ -0,0 +1,68 @@ +// [TEMP] [CHOSEN, not recovered] package D's stand-ins (since ai-bot eeb9049 they forward to the +// recovered callees; call sites may call them directly and this file go) for calls whose callee is not declared in +// this tree yet. Each wrapper names the image's call (ELF address of the callee) and stops by name, +// so D's recovered bodies stay complete and read like the image; when the owner's declaration +// lands, the wrapper body becomes the real call (or the call site calls it directly). +// [RETIRE-WHEN: ai-w1-d-pending-calls] every callee below is declared and linked (coord/ai-requests.md). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBPENDINGCALLS_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBPENDINGCALLS_H + +#include "../AIBotActionPlan/BAPStatement.h" +#include "../Main/AIDllFrontier.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WPCloseTo.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class BotScript; +class CommunicationAgent; +class SquadMember; +class WaypointList; +struct AIRadioMessageInfo; +enum AIRadioMessageType : int; + +namespace bbpending { + +// --- ai-bot ------------------------------------------------------------------------------- +inline bool isAtFormationSlot(SquadMember* member) // SquadMember::isAtFormationSlot 0x1B5540 +{ + return member->isAtFormationSlot(); +} + + +// WPCloseTo +0x10: the handle of the object to close in on (getId() 0), read inline by +// BBPGotoWaypointSoldier::createPlan 0x284EEC. WPCloseTo is not declared in this tree. +inline unsigned int closeToTarget(WaypointList* waypoints) +{ + return static_cast(waypoints)->getTarget(); +} + +// CommunicationAgent::generalConfirmReceivedMessage(AIRadioMessageType) +inline bool generalConfirmReceivedMessage(CommunicationAgent* agent, AIRadioMessageType type) +{ + return agent->generalConfirmReceivedMessage(type); +} + +// CommunicationAgent::confirmReceivedMessage(const AIRadioMessageInfo&) +inline bool confirmReceivedMessage(CommunicationAgent* agent, const AIRadioMessageInfo& info) +{ + return agent->confirmReceivedMessage(info); +} + +// CommunicationAgent +0x5C (m_int92, private), read inline by BBIdle::waitForPickup 0x21584E. +inline int communicationAgentInt92(CommunicationAgent* agent) +{ + return agent->getInt92(); +} + +} // namespace bbpending +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBPENDINGCALLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp new file mode 100644 index 000000000..83e86c53c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp @@ -0,0 +1,191 @@ +// Random behaviour (infantry "Random" slot of aibehaviours.ai). Despite the name it reacts to a +// grenade warning: once BotNavigation reports one, the behaviour wins with urgency 1000 until +// 5 s after the grenade's time has passed. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +#include "BBRandom.h" + +// static init: ELF 0x21AB30, 0x21AC40, 0x21AC70 (iostream Init, then the local color table). +#include + +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPRandom.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIUtils/checkPointer.h" +#include "../AIBot/BotNavigation.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace world { +namespace { + +// [CHOSEN, not recovered] Type, component names and constructor spelling for the +// three-float elements stored by ELF 0x21AB30. No original type name is attested. +struct DebugMeshMaterialColor +{ + float r, g, b; + + DebugMeshMaterialColor(float red, float green, float blue) : r(red), g(green), b(blue) {} +}; + +static_assert(sizeof(DebugMeshMaterialColor) == 12, "color element stride"); +static_assert(offsetof(DebugMeshMaterialColor, r) == 0 && + offsetof(DebugMeshMaterialColor, g) == 4 && + offsetof(DebugMeshMaterialColor, b) == 8, "color component offsets"); +static_assert(std::is_trivially_destructible::value, + "the color table has no registered teardown"); + +} // anonymous namespace + +// ELF 0x4CE300, local symbol, ten elements. __tcf_0 destroys only iostream Init. +// [CHOSEN, not recovered] Retain the unreferenced retail object with modern compilers. +#if defined(__GNUC__) +__attribute__((used)) +#endif +static DebugMeshMaterialColor debugMeshMaterialColors[10] = { + {0.66f, 0.66f, 0.185f}, + {0.185f, 0.66f, 0.185f}, + {0.185f, 0.185f, 0.66f}, + {0.185f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.185f}, + {0.66f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.66f}, + {0.185f, 0.185f, 0.185f}, + {1.0f, 1.0f, 1.0f}, + {0.0f, 0.0f, 0.0f} +}; +static_assert(sizeof(debugMeshMaterialColors) == 0x78, "local color table extent"); + +} // namespace world +namespace ai { + +// ELF 0x21A250 (C2) / 0x21A470 (C1). +BBRandom::BBRandom(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_grenadePosition.x = 0.0f; // 0x21A2BF: rodata 0x49CB34 into +0x38/+0x3C/+0x40 + m_grenadePosition.y = 0.0f; + m_grenadePosition.z = 0.0f; + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; + m_grenadeWarning = false; // 0x21A341 + m_warningTime = 0.0; // 0x21A345: fstl / fstpl of the same 0.0f + m_grenadeTime = 0.0; +} + +// ELF 0x21A690 (D2) / 0x21A6E0 (D1) / 0x21A730 (D0) +BBRandom::~BBRandom() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x21A780 (261 insns). +float BBRandom::calculateUrgency(Bot* bot, bool active, float) +{ + PlanGenerator* pattern = m_pattern; + if (!active) + { + // 0x21AA90: an initiated pattern keeps the stored urgency; otherwise uninit and 0. + if (pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + pattern->unInit(bot); + return m_urgency[bot->getBotId()] = 0.0f; // `fsts` - the stored value is returned + } + + float urgency = 0.0f; + Vec3 grenadePosition; // -0x28, zeroed + grenadePosition.x = 0.0f; + grenadePosition.y = 0.0f; + grenadePosition.z = 0.0f; + + if (!m_grenadeWarning) + { + // 0x21A7CC: BotNavigation::getGrenadeWarning(Vec3&, double&) returns bool (`testb %al`), + // then BotNavigation's bool at +0x114 (m_flag276) must be set too. + // 0x21A7E8 call, 0x21A87B `cmpb $0x0, 0x114(%eax)` on a second getBotNavigation. + double grenadeTime; // -0x60 + if (bot->getBotNavigation()->getGrenadeWarning(grenadePosition, grenadeTime) + && bot->getBotNavigation()->getGrenadeFlag()) + { + m_grenadeWarning = true; + m_warningTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_grenadeTime = grenadeTime; + m_grenadePosition = grenadePosition; + } + } + else + { + // 0x21A8C8: `fldl +0x30; faddl +0x28; fucomi; jbe` - nothing until the grenade's time has + // passed; 5 s (rodata 0x49CDAC, a float) after it the warning is dropped, but this tick + // still answers it. + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double end = m_grenadeTime + m_warningTime; + if (now > end) + { + if (now > end + 5.0f) + m_grenadeWarning = false; + + // 0x21A8FF: ignore the bot's own equipment object (no null check in the image) and + // trace from one metre above it to the grenade; the result is not used (retail). + std::vector ignore; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + ignore.push_back(info->getAIObject()); + IAIObjectEnvironment* environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + const Vec3& position = info->getPosition(); + Vec3 up; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + Vec3 from; + from.x = position.x + up.x; + from.y = position.y + up.y; + from.z = position.z + up.z; + bool hit; // -0x65 + environment->collideLineWithWorld(from, m_grenadePosition, ignore, false, 0.7f, false, hit); // slot +0x40 + + static_cast(m_pattern)->init(bot); + m_urgency[bot->getBotId()] = 1000.0f; // rodata 0x49CF48 + return 1000.0f; // the local, not a reload (0x21AA42) + } + } + + // 0x21A7F1: `flds 0.001; flds urgency; fxch; fucompi; jbe init` - init unless below 0.001. + if (urgency < 0.001f) + pattern->unInit(bot); + else + static_cast(m_pattern)->init(bot); + m_urgency[bot->getBotId()] = urgency; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x21AAF0: alive bots answer getManDown (+0x1B0). +bool BBRandom::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + return bot->getManDown(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h new file mode 100644 index 000000000..f827b93e1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.h @@ -0,0 +1,48 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRANDOM_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRANDOM_H + +#include "BotBehaviour.h" + +#include "../../../../Math/Vec3.h" // Vec3 is a typedef; never forward-declare + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB080 (14 words), operator new 0x44, package F-infantry. +class BBRandom : public BotBehaviour +{ +public: + BBRandom(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x21A470 + virtual ~BBRandom(); // 0x21A6E0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21A780, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x21AAF0, slot +0x34; bool: getManDown or 0 + +private: + // Constructor 0x21A250: +0x24 = false, +0x28/+0x30 = 0.0, +0x38 = (0,0,0). One grenade + // warning is kept for the whole behaviour object, not per bot (retail; the object is shared + // by every bot of the vehicle type). [INFERRED] names. + /* +0x24 */ bool m_grenadeWarning; + /* +0x28 */ double m_warningTime; // IBFTimer::getGameTime when the warning was taken + /* +0x30 */ double m_grenadeTime; // BotNavigation::getGrenadeWarning's time + /* +0x38 */ Vec3 m_grenadePosition; // BotNavigation::getGrenadeWarning's position +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRANDOM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp new file mode 100644 index 000000000..42f584a82 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp @@ -0,0 +1,302 @@ +// Revive behaviour (infantry "Revive" slot of aibehaviours.ai): a bot carrying a revive weapon +// (WeaponInfo type 3) looks for man-down friendly soldiers within 40 m and picks the one it can +// reach soonest relative to the man-down time left; ordered targets and human players weigh more. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x21C8A0 (__tcf_0 0x21C900, _GLOBAL__I 0x21C930): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) +#include "BBRevive.h" + +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPRevive.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21AC90 (C2) / 0x21B220 (C1). Base with getMaxNBots; the vector is empty; then +0x30, +0x34, +// +0x38 = checkPointer(new[getNBattleStrengths]) (IAISettings +0x34, called once per array); the +// index, queue and pattern; +0x08 = checkPointer(new unsigned int[getMaxNBots]) (not initialised); +// every bot starts with urgency 0.0f (rodata 0x49CB34) and changed flag false. +BBRevive::BBRevive(unsigned char index, unsigned char queue, BBPRevive* pattern, UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()), + m_friendlyUnits() +{ + m_bestWeapon = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_rangeSq = checkPointer(new float[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_bestStrength = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targetChanged[i] = false; + } +} + +// ELF 0x21B7B0 (D2) / 0x21B860 (D1) / 0x21B910 (D0): delete[] +0x08, +0x30, +0x34, +0x38 when set, +// the vector, then the base. +BBRevive::~BBRevive() +{ + if (m_targets) + delete[] m_targets; + if (m_bestWeapon) + delete[] m_bestWeapon; + if (m_rangeSq) + delete[] m_rangeSq; + if (m_bestStrength) + delete[] m_bestStrength; +} + +// ELF 0x21B9D0 (958 insns). +// Not updating: a target still on the bot's side keeps the urgency while the pattern runs; +// otherwise the changed flag records a non-zero urgency, which drops to 0, and the pattern unInits. +// Updating: candidates are man-down soldiers (type flag 0x200000) with physical and mobile +// plug-ins, not swimming and not under more than 0.75 of water, whose strength type the bot has a +// revive weapon for and whose man-down time left is at least 0.001. Retail: the bot's own +// Information and its armament are used without a null check. +float BBRevive::calculateUrgency(Bot* bot, bool update, float modifier) +{ + BBPRevive* const pattern = static_cast(m_pattern); + unsigned int* const targets = m_targets; + + if (!update) + { + // 0x21B9FA: Information slot +0x44 (getSide) against Bot +0xE0. + Information* const target = informationManager->getInformation(targets[bot->getBotId()]); + if (target && target->getSide() == bot->getSide()) + { + m_targetChanged[bot->getBotId()] = false; + if (!pattern->isInitiated(bot)) + m_urgency[bot->getBotId()] = 0.0f; + } + else + { + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); + } + return m_urgency[bot->getBotId()]; + } + + const int strengthCount = static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); + for (int i = 0; i < strengthCount; ++i) + { + m_bestWeapon[i] = -1; + m_bestStrength[i] = 0; + } + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = self->getArmament(); + const Vec3& position = self->getPosition(); + // 0x21BC15: the inlined resize(0) (erase when non-empty, _M_fill_insert of 0 elements else). + m_friendlyUnits.resize(0); + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getFriendlyUnits(m_friendlyUnits, position, bot, 40.0f); // slot +0x08, rodata 0x49CFD4 + if (m_friendlyUnits.empty()) + { + m_targetChanged[bot->getBotId()] = m_urgency[bot->getBotId()] != 0.0f; + m_urgency[bot->getBotId()] = 0.0f; + pattern->unInit(bot); + return 0.0f; + } + + // 0x21BC7F: a copy of the weapon list (allocate + memmove), freed on every exit. + const std::vector weapons = armament->getWeapons(); + const int kit = bot->getPlayer()->getSpawnKit(); // IAIPlayer +0x44 + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon || weapon->getWeaponType() != 3) + continue; + for (int s = 0; s < strengthCount; ++s) + { + if (weapon->getStrength(s) > m_bestStrength[s]) + { + m_bestWeapon[s] = static_cast(i); + m_bestStrength[s] = weapon->getStrength(s); + const float range = weapon->getMaxRange(); + m_rangeSq[s] = range * range; + } + } + } + + float bestScore = 0.0f; // -0x1A0 + unsigned int orderedCount = 0; // -0x1A4 + int bestWeapon = -1; // -0x1A8 + unsigned int bestTarget = 0xFFFFFFFFu; // -0x1AC + const float maxSpeed = self->getMobile()->getMaxSpeed(); + float bestDistance = 100.0f; // -0x1B4, rodata 0x49CB5C + + for (std::vector::iterator it = m_friendlyUnits.begin(); it != m_friendlyUnits.end(); ++it) + { + Information* const unit = informationManager->getInformation(*it); + if (!unit) + continue; + IPIPhysical* const physical = unit->getPhysical(); + if (!physical || unit == self || !unit->hasMobile() || (unit->getObjectTypeFlags() & 0x200000u) == 0) + continue; + if (!physical->getManDown()) // IPIPhysical +0x5C + continue; + if (unit->getSoldierPose() == SPSwimming) + continue; + // 0x21C30D: IAITerrain +0x30 getWaterLevel and +0x08 getHeight at the unit's x, z. + const Vec3& unitPosition = unit->getPosition(); + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float waterLevel = terrain->getWaterLevel(unitPosition.x, unitPosition.z); + const float height = terrain->getHeight(unitPosition.x, unitPosition.z); + if (waterLevel + 0.5f > unitPosition.y && waterLevel - height > 0.75f) // rodata 0x49CB44, 0x49CB54 + continue; + const int strengthType = physical->getStrengthType(); // IPIPhysical +0x44 + if (m_bestWeapon[strengthType] == -1) + continue; + const float timeLeft = physical->getManDownTimeLeft(); // IPIPhysical +0x54 + if (0.001f > timeLeft) // rodata 0x49CC94 + continue; + + Vec3 offset; + offset.x = unitPosition.x - position.x; + offset.y = unitPosition.y - position.y; + offset.z = unitPosition.z - position.z; + const float distance = std::sqrt(offset.x * offset.x + offset.y * offset.y + offset.z * offset.z); + float score = distance / maxSpeed / timeLeft; + if (score > 1.0f) + score = 1.0f; + score = 1.0f - score; + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) + { + // 0x21C5D0: the old std::list::size walk, then std::find over the order list; each + // further one-time order match multiplies by BotMemory +0x08. + if (bot->getOrderList(m_index)->size() > orderedCount) + { + const std::list::iterator end = bot->getOrderList(m_index)->end(); + if (std::find(bot->getOrderList(m_index)->begin(), bot->getOrderList(m_index)->end(), *it) != end) + { + ++orderedCount; + score *= bot->getMemory()->m_float8; + } + } + } + + IPIUnit* const unitPlugIn = unit->getUnit(); + if (unitPlugIn && unitPlugIn->isOccupied()) + { + // IAIPlayerFactory +0x20 getPlayerFromId, IAIPlayer +0x88 getIsAIPlayer: humans weigh x10. + IAIPlayer* const occupant = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(unitPlugIn->getOccupyingPlayerId(unit->getSide())); + if (occupant && !occupant->getIsAIPlayer()) + score *= 10.0f; // rodata 0x49CC88 + } + if (score > bestScore) + { + bestDistance = distance; + bestScore = score; + bestWeapon = m_bestWeapon[strengthType]; + bestTarget = *it; + } + } + + if (bestTarget == 0xFFFFFFFFu) + { + m_urgency[bot->getBotId()] = 0.0f; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != 0xFFFFFFFFu; + targets[bot->getBotId()] = 0xFFFFFFFFu; + pattern->unInit(bot); + return 0.0f; + } + + Information* const target = informationManager->getInformation(bestTarget); + bool humanTarget = false; + if (target && target->getUnit() && target->getUnit()->isOccupied()) + { + IAIPlayer* const occupant = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(target->getUnit()->getOccupyingPlayerId(target->getSide())); + if (occupant && !occupant->getIsAIPlayer()) + humanTarget = true; + } + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + bestScore *= bot->getMemory()->m_float8; + + // 0x21BF7C: a human closer than 50 m gets 100.0f flat (no modifier); otherwise the declining + // slope of the best score, x5 for a human and x2 (fadd %st(0), %st) for a bot, times the modifier. + float urgency; + if (humanTarget) + { + if (50.0f > bestDistance) // rodata 0x49CCA8 + urgency = 100.0f; + else + urgency = DecleiningSlopeCurve::calculate(bestScore) * 5.0f * modifier; + } + else + { + const float slope = DecleiningSlopeCurve::calculate(bestScore); + urgency = (slope + slope) * modifier; + } + m_urgency[bot->getBotId()] = urgency; + m_targetChanged[bot->getBotId()] = targets[bot->getBotId()] != bestTarget; + targets[bot->getBotId()] = bestTarget; + pattern->init(targets[bot->getBotId()], bestWeapon, bot); + + if (kit == 5) + { + // 0x21C0BC: m_urgency[id] = SquadManager::requestResponseModifier(SquadManager::m_instance, + // bot->getSquadMember() (Bot +0x140), bestTarget, RequestAction 1, bot->getSide()) * m_urgency[id] + // (x87 result, fmuls of the stored urgency). + m_urgency[bot->getBotId()] = SquadManager::m_instance->requestResponseModifier( + bot->getSquadMember(), bestTarget, 1, bot->getSide()) + * m_urgency[bot->getBotId()]; + } + return m_urgency[bot->getBotId()]; +} + +// ELF 0x21C810: true when the information's armament (+0x2C) lists a weapon of type 3; the list +// (IPIArmament +0x20 getWeapons) is re-measured on every pass. +bool BBRevive::isAplicable(Information* information, Bot*) +{ + IPIArmament* const armament = information->getArmament(); + if (armament) + { + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getWeaponType() == 3) + return true; + } + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h new file mode 100644 index 000000000..ad4067dd0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.h @@ -0,0 +1,50 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBREVIVE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBREVIVE_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPRevive; +class Bot; +class Information; +class UrgeCurve; + +// ELF: vtable 0x4BB120 (13 words), operator new 0x3C, package F-infantry. +// The base +0x08 array holds the handle of the man-down soldier each bot goes to revive +// (unsigned int per bot, 0xFFFFFFFF = none); +0x0C is the BBPRevive pattern. +class BBRevive : public BotBehaviour +{ +public: + BBRevive(unsigned char, unsigned char, BBPRevive*, UrgeCurve*, float*); // 0x21B220 + virtual ~BBRevive(); // 0x21B860 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21B9D0, slot +0x28; from the base declaration + virtual bool isAplicable(Information*, Bot*); // 0x21C810, slot +0x30; bool: `movl $0x1` / `xorl` into %eax + +private: + // Constructor 0x21B220: the vector is constructed empty before the vptr store; the three + // arrays are new[getNBattleStrengths] (IAISettings +0x34), checkPointer'd. calculateUrgency + // refills them per update from the bot's revive weapons (WeaponInfo type 3). + /* +0x24 */ std::vector m_friendlyUnits; // getFriendlyUnits result, radius 40 [INFERRED] name + /* +0x30 */ int* m_bestWeapon; // per strength type: index into the weapon list, -1 = none + /* +0x34 */ float* m_rangeSq; // per strength type: that weapon's getMaxRange squared (not read here) + /* +0x38 */ int* m_bestStrength; // per strength type: that weapon's getStrength +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBREVIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp new file mode 100644 index 000000000..ca59b9496 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp @@ -0,0 +1,157 @@ +// Run-over behaviour (AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x21D3B0 (__tcf_0 0x21D410, _GLOBAL__I 0x21D440): 's Init object only. +#include + +#include "BBRunOverSoldier.h" + +#include "../Main/AIDllFrontier.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPRunOverSoldier.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21C950 (C2) / 0x21CB40 (C1); vtable GOT -0xA20. The base gets getMaxNBots; a second +// getMaxNBots sizes the +0x08 target array (not initialised) through the inlined checkPointer +// (Debug type 6, line 46); every bot starts with urgency 0.0f. +BBRunOverSoldier::BBRunOverSoldier(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x21CD30 (D2) / 0x21CD80 (D1) / 0x21CDD0 (D0): delete[] +0x08 when set, then ~BotBehaviour. +BBRunOverSoldier::~BBRunOverSoldier() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x21CE20 (Ghidra; listing for the trace arguments and the constants). A bot whose vehicle +// moves at least minSpeed runs over the first living enemy soldier it sees directly that lies +// ahead (direction against the transformation's third row at least minDot) within maxDistance +// (distance floored at 1) and that the pathfinding trace from the vehicle's last valid +// position reaches: urgency 65, target in +0x08. The pattern is initialised with the stored +// target even when none was found this time. +float BBRunOverSoldier::calculateUrgency(Bot* bot, bool recalculate, float) +{ + static float minSpeed = 10.0f; // .data + static float minDot = 0.85f; // .data + static float maxDistance = 50.0f; // .data + + if (!recalculate) + { + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + m_urgency[bot->getBotId()] = 0.0f; + const int equipmentType = equipment->getUnit()->getEquipmentType(); + IPIMobile* const mobile = equipment->getMobile(); + if (!(minSpeed <= mobile->getSpeedMagnitude())) + { + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; + } + + const Vec3& position = equipment->getPosition(); + const std::map& sensed = bot->getSensedObjects(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + const unsigned int flags = it->second->m_flags; + if (!(flags & SensedObject::SENSE_SEEN) || !(flags & SensedObject::SENSE_SIDED) + || (flags & SensedObject::SENSE_INDIRECT)) + continue; + Information* const info = informationManager->getInformation(it->second->m_handle); + if (!info || !(info->getObjectTypeFlags() & 0x200000)) + continue; + if (info->getSide() == bot->getSide() || info->getSide() == 0) + continue; + IPIPhysical* const physical = info->getPhysical(); + IPIMobile* const targetMobile = info->getMobile(); + if (!physical || !(physical->getHealth() > 0.0f) || !targetMobile) + continue; + const Vec3& targetPosition = info->getPosition(); + Vec3 direction; + direction.x = targetPosition.x - position.x; + direction.y = targetPosition.y - position.y; + direction.z = targetPosition.z - position.z; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + if (!(length > 0.0001f)) + continue; + const float inverse = 1.0f / length; + direction.x = direction.x * inverse; + float distance = 1.0f; + if (1.0f <= length) + distance = length; + direction.y = direction.y * inverse; + direction.z = inverse * direction.z; + const Mat4& transformation = equipment->getTransformation(); + if (minDot > transformation.m[10] * direction.z + transformation.m[8] * direction.x + + transformation.m[9] * direction.y) + continue; + if (distance > maxDistance) + continue; + const IPIMobile::ValidPos& targetValid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); + if (targetValid.quadTree == static_cast(-1) || targetValid.polygon == static_cast(-1)) + continue; + const IPIMobile::ValidPos& valid = mobile->getLastValidPosition(); + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + Vec3 end; + end.x = 0.0f; + end.y = 0.0f; + end.z = 0.0f; + unsigned int endPolygon; + if (pathfinding->trace(valid.polygon, valid.quadTree, mobile->getVehicleNumber(), valid.position, + targetValid.position, end, endPolygon, equipmentType, -1, 0.0f, 5, 0)) + { + m_targets[bot->getBotId()] = it->first; + m_urgency[bot->getBotId()] = 65.0f; + break; + } + } + static_cast(m_pattern)->init(bot, m_targets[bot->getBotId()]); + return m_urgency[bot->getBotId()]; +} + +// ELF 0x21D360 (Ghidra). Applicable while the bot's player is alive and not man down. +bool BBRunOverSoldier::isApplicable(Information*, Bot* bot) +{ + bool applicable = false; + if (bot->getPlayer()->getIsAlive()) + applicable = !bot->getManDown(); + return applicable; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.h new file mode 100644 index 000000000..9f3495c16 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRUNOVERSOLDIER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRUNOVERSOLDIER_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB1C0 (14 words), operator new 0x24, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBRunOverSoldier : public BotBehaviour +{ +public: + BBRunOverSoldier(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x21CB40 + virtual ~BBRunOverSoldier(); // 0x21CD80 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21CE20, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x21D360, slot +0x34; [INFERRED] ELF int +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBRUNOVERSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp new file mode 100644 index 000000000..a545422b4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp @@ -0,0 +1,57 @@ +// Suicide urgency is the remaining fraction of the current equipment's man-down interval. + +// static init: ELF 0x21D740 (__tcf_0 0x21D7A0, _GLOBAL__I 0x21D7D0): 's Init object only. +#include + +#include "BBSuicide.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/BBPSuicide.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21D460 (C2), 0x21D510 (C1) +BBSuicide::BBSuicide(unsigned char index, unsigned char queue, BBPSuicide* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + for (int i = 0; i < count; ++i) + { + m_urgency[i] = 0.0f; + m_targetChanged[i] = false; + } +} + +// ELF 0x21D5C0 (D2), 0x21D600 (D1), 0x21D640 (D0) +BBSuicide::~BBSuicide() +{ +} + +// ELF 0x21D680 +float BBSuicide::calculateUrgency(Bot* bot, bool, float) +{ + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* physical = equipment->getPhysical(); + const unsigned int index = bot->getBotId(); + const float remaining = physical->getManDownTimeLeft(); + const float maximum = physical->getMaxManDownTime(); + m_urgency[index] = remaining / maximum; + static_cast(m_pattern)->init(bot); + return m_urgency[bot->getBotId()]; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h new file mode 100644 index 000000000..2aeb2019b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.h @@ -0,0 +1,31 @@ +// Man-down suicide urgency and pattern initialization. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBSUICIDE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBSUICIDE_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BBPSuicide; +class Bot; +class UrgeCurve; + +// ELF: vtable 0x4BB220 (13 words), operator new 0x24, package H-deferred. +class BBSuicide : public BotBehaviour +{ +public: + BBSuicide(unsigned char, unsigned char, BBPSuicide*, UrgeCurve*, float*); // 0x21D510 + virtual ~BBSuicide(); // 0x21D600 + + virtual float calculateUrgency(Bot*, bool, float); // 0x21D680, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBSUICIDE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp new file mode 100644 index 000000000..1503f53e3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp @@ -0,0 +1,387 @@ +// Cover urgency from directional threat strengths and reachable cover geometry. + +// static init: ELF 0x2204C0 (__tcf_0 0x220520, _GLOBAL__I 0x220550): 's Init object only. +#include + +#include "BBTakeCover.h" + +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPTakeCover.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/DangerObject.h" +#include "../AIKnowledge/IPICover.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../AIUtils/VehicleOccupancy.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../../Math/LocalBoundingBox.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x21D7F0 (C2), 0x21DC00 (C1) +BBTakeCover::BBTakeCover(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_dangers = checkPointer(new DangerObject*[m_count]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + m_targets = checkPointer(new unsigned int[m_count]); + // shipped defect: the first danger-pointer array is overwritten and leaked. + m_dangers = checkPointer(new DangerObject*[m_count]); + for (int i = 0; i < m_count; ++i) + { + m_targets[i] = 0xFFFFFFFFu; + m_urgency[i] = 0.0f; + m_dangers[i] = 0; + } +} + +// ELF 0x21E010 (D2), 0x21E090 (D1), 0x21E110 (D0) +BBTakeCover::~BBTakeCover() +{ + // DangerObject has no destructor slot; the shipped bodies deallocate these trivial wrappers. + for (int i = 0; i < m_count; ++i) + ::operator delete(m_dangers[i]); + if (m_targets) + delete[] m_targets; + if (m_dangers) + delete[] m_dangers; +} + +// ELF 0x220440 +void BBTakeCover::reset(Bot* bot) +{ + BotBehaviour::reset(bot); + if (m_dangers[bot->getBotId()]) + ::operator delete(m_dangers[bot->getBotId()]); + m_dangers[bot->getBotId()] = 0; +} + +// ELF 0x21E190 +float BBTakeCover::calculateUrgency(Bot* bot, bool evaluate, float scale) +{ + if (!evaluate) + { + m_targetChanged[bot->getBotId()] = false; + if (m_pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + // [INFERRED] local packaging of the repeated inlined pattern-clear block. + const auto clearPattern = [&]() + { + if (m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + } + // shipped defect: this overwrites the changed-target flag just set above. + m_targetChanged[bot->getBotId()] = false; + m_urgency[bot->getBotId()] = 0.0f; + }; + + const int side = bot->getSide(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* physical = self->getPhysical(); + IPIMobile* mobile = self->getMobile(); + const int equipmentType = self->getUnit()->getEquipmentType(); + const auto& sensed = bot->getSensedObjects(); + const auto* incoming = bot->getIncommingFire(); + if (sensed.empty() && incoming->empty()) + { + clearPattern(); + return 0.0f; + } + + float total = 0.0f; + float sums[8] = {}; + float maxima[8] = {}; + DangerObject* dangers[8] = {}; + const Vec3 axisX = {1.0f, 0.0f, 0.0f}; + const Vec3 axisZ = {0.0f, 0.0f, 1.0f}; + const Vec3 diagonalA = {0.70710677f, 0.0f, -0.70710677f}; + const Vec3 diagonalB = {0.70710677f, 0.0f, 0.70710677f}; + const Vec3 position = self->getPosition(); + const int strengthType = physical->getStrengthType(); + const auto dot = [](const Vec3& a, const Vec3& b) + { + return a.x * b.x + a.y * b.y + a.z * b.z; + }; + const auto quadrants = [&](const Vec3& delta, int& first, int& second) + { + const float x = dot(axisX, delta); + const float z = dot(axisZ, delta); + first = !(z < 0.0f) ? int(!(x < 0.0f)) : 2 + int(x < 0.0f); + const float a = dot(diagonalA, delta); + const float b = dot(diagonalB, delta); + second = !(b < 0.0f) ? 4 + int(!(a < 0.0f)) : 6 + int(a < 0.0f); + }; + for (const auto& entry : *incoming) + { + FireObject* fire = entry.first; + const Vec3& origin = fire->getOrigin(); + const Vec3 delta = {origin.x - position.x, origin.y - position.y, origin.z - position.z}; + int first, second; + quadrants(delta, first, second); + float strength = fire->getBattleStrength(strengthType); + if (!fire->isDirect()) + strength *= 0.8f; + sums[first] += strength; + sums[second] += strength; + total += strength; + if (strength > maxima[first]) + { + maxima[first] = strength; + if (!dangers[first]) + dangers[first] = checkPointer(new FireDanger(fire)); + else + static_cast(dangers[first])->m_fire = fire; + } + if (strength > maxima[second]) + { + // shipped defect: the second quadrant's maximum is never updated for fire. + if (!dangers[second]) + dangers[second] = checkPointer(new FireDanger(fire)); + else + static_cast(dangers[second])->m_fire = fire; + } + } + + Information* ownSector = informationManager->getInformation(mobile->getSector()); + unsigned int matchedOrders = 0; + const auto weightOrder = [&](unsigned int handle, float& rating) + { + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && + matchedOrders < bot->getOrderList(m_index)->size()) + { + const auto end = bot->getOrderList(m_index)->end(); + const auto begin = bot->getOrderList(m_index)->begin(); + const auto last = bot->getOrderList(m_index)->end(); + if (end != std::find(begin, last, handle)) + { + ++matchedOrders; + rating *= bot->getMemory()->m_float8; + } + } + }; + for (const auto& entry : sensed) + { + Information* target = informationManager->getInformation(entry.first); + if (!target || target->getSide() != 0 || !vehicleOccupied(entry.first, side) || !target->getUnit()) + continue; + const Vec3& at = target->getPosition(); + const Vec3 delta = {at.x - position.x, at.y - position.y, at.z - position.z}; + int first, second; + quadrants(delta, first, second); + float distance = vehiclecontrol::distanceVec3(position, target->getPosition()); + distance = distance > 5.0f ? distance : 5.0f; + IPIMobile* targetMobile = target->getMobile(); + if (targetMobile && ownSector) + { + Information* targetSector = informationManager->getInformation(targetMobile->getSector()); + if (targetSector && ownSector->getAIObject() == targetSector->getAIObject()) + distance *= 0.5f; + } + int iterator = target->getFirstSecondaryObjectIterator(); + unsigned int next = target->getSecondaryObject(iterator, side); + Information* seat = target; + float rating; + do + { + // shipped defects: overwrite rather than accumulate, skip the first secondary seat, + // and match the next seat's handle against orders while rating the current seat. + rating = seat->getUnit()->getBattleStrengths()[strengthType] / distance; + weightOrder(next, rating); + next = target->getSecondaryObject(iterator, side); + seat = informationManager->getInformation(next); + } while (seat); + sums[first] += rating; + sums[second] += rating; + total += rating; + const auto setInformationDanger = [&](int quadrant) + { + if (rating > maxima[quadrant]) + { + maxima[quadrant] = rating; + if (dangers[quadrant] && dangers[quadrant]->isInformation()) + static_cast(dangers[quadrant])->m_information = entry.first; + else + { + ::operator delete(dangers[quadrant]); + dangers[quadrant] = checkPointer(new InfoDanger(entry.first)); + } + } + }; + setInformationDanger(first); + setInformationDanger(second); + } + + Vec3 coverPosition = {}; + DangerObject* previous = 0; + if (total > 0.0f) + { + IAIPathfinding* pathfinding = IAIPathfinding::instance; + previous = m_dangers[bot->getBotId()]; + m_dangers[bot->getBotId()] = 0; + float bestQuadrant = 0.0f; + for (int i = 0; i < 8; ++i) + { + if (sums[i] > bestQuadrant) + { + bestQuadrant = sums[i]; + ::operator delete(m_dangers[bot->getBotId()]); + m_dangers[bot->getBotId()] = dangers[i]; + } + else + ::operator delete(dangers[i]); + } + if (!m_dangers[bot->getBotId()]) + { + clearPattern(); + if (previous) + ::operator delete(previous); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + Information* threatSector = 0; + DangerObject* danger = m_dangers[bot->getBotId()]; + if (danger->isInformation()) + { + Information* threat = informationManager->getInformation(static_cast(danger)->m_information); + if (threat && threat->getMobile()) + threatSector = informationManager->getInformation(threat->getMobile()->getSector()); + } + Vec3 threatPosition = {}; + if (!m_dangers[bot->getBotId()]->getPosition(threatPosition)) + { + clearPattern(); + if (previous) + ::operator delete(previous); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + + float multiplier = 1.0f; + float bestCover = 0.0f; + LocalBoundingBox* bounds = const_cast(physical->getLocalBoundingBox()); + const float sizeX = bounds->getSize().x; + const float sizeZ = bounds->getSize().z; + const float width = sizeZ > sizeX ? sizeZ : sizeX; + const float height = bounds->getSize().y; + std::vector covers; + static_cast(AISingletonServer::m_iaiInformationEnvironment)->getCover(*bot, covers); + for (unsigned int handle : covers) + { + Information* cover = informationManager->getInformation(handle); + if (!cover) + continue; + IPIPhysical* coverPhysical = cover->getPhysical(); + IPICover* plugin = cover->getCover(); + if (!coverPhysical || !plugin || + (threatSector && threatSector->getAIObject() == cover->getAIObject())) + continue; + const Vec3 at = cover->getPosition(); + Vec3 direction = {at.x - threatPosition.x, at.y - threatPosition.y, at.z - threatPosition.z}; + vehiclecontrol::normalizeVec3(direction); + const Vec3 start = vehiclecontrol::alongFrom(at, direction, coverPhysical->getRadius() * 0.75f); + const Vec3 end = vehiclecontrol::alongFrom(at, direction, coverPhysical->getRadius() * 3.0f); + Vec3 valid = {}; + unsigned int polygon, island; + if (!pathfinding->findClosestValidPolygon(polygon, island, valid, mobile->getVehicleNumber(), + start, end, 10, equipmentType)) + continue; + LocalBoundingBox* coverBounds = const_cast(coverPhysical->getLocalBoundingBox()); + const float coverX = coverBounds->getSize().x; + const float coverZ = coverBounds->getSize().z; + const float coverWidth = coverZ > coverX ? coverZ : coverX; + const float coverHeight = coverBounds->getSize().y; + float widthFactor = (coverWidth / width) * 0.2f; + float heightFactor = (coverHeight / height) * 0.5f; + if (widthFactor < 0.0f) widthFactor = 0.0f; + if (heightFactor < 0.0f) heightFactor = 0.0f; + if (widthFactor > 1.0f) widthFactor = 1.0f; + if (heightFactor > 1.0f) heightFactor = 1.0f; + const float factor = widthFactor * 0.25f + heightFactor * 0.75f; + float denominator = vehiclecontrol::distanceVec3(cover->getPosition(), position) * factor; + if (plugin->getPortalCount()) + denominator *= 0.1f; + float rating = plugin->getCoverValue() / denominator; + weightOrder(handle, rating); + if (rating > bestCover) + { + bestCover = rating; + m_targets[bot->getBotId()] = handle; + coverPosition = valid; + multiplier *= 1.3f; + } + else if (rating > 0.0f) + multiplier *= (rating / bestCover) * 0.3f + 1.0f; + } + total = bestCover > 0.0f ? total * multiplier : 0.0f; + } + + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + total *= bot->getMemory()->m_float8; + // The final x87 comparison takes the positive arm for unordered values as well. + if (!(total <= 0.0f)) + { + const unsigned int coverHandle = m_targets[bot->getBotId()]; + if (m_dangers[bot->getBotId()]) + { + const unsigned int changedIndex = bot->getBotId(); + m_targetChanged[changedIndex] = previous != m_dangers[bot->getBotId()]; + m_urgency[bot->getBotId()] = 0.0f; + if (previous) + ::operator delete(previous); + BBPTakeCover* pattern = static_cast(m_pattern); + DangerObject* danger = m_dangers[bot->getBotId()]; + Vec3 threatPosition = {}; + danger->getPosition(threatPosition); + if (danger->isInformation()) + pattern->init(bot, static_cast(danger)->m_information, coverPosition, coverHandle); + else + pattern->init(bot, threatPosition, coverPosition, coverHandle); + float distance = vehiclecontrol::distanceVec3(threatPosition, self->getPosition()); + distance = (distance > 10.0f ? distance : 10.0f) * 0.1f; + const unsigned int urgencyIndex = bot->getBotId(); + float* urgency = m_urgency; + const float strengthCurve = DecleiningSlopeCurve::calculate(total); + const float distanceCurve = SCurve::calculate(distance); + const float result = (distanceCurve * strengthCurve - 0.19f) * 1.0f * scale; + urgency[urgencyIndex] = result; + return result; + } + bot->getBotId(); + m_targetChanged[bot->getBotId()] = false; + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + clearPattern(); + if (previous) + ::operator delete(previous); + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h new file mode 100644 index 000000000..352ac1655 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.h @@ -0,0 +1,38 @@ +// Rates cover against incoming shots and sensed occupied vehicles, retaining one threat per bot. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class PlanGenerator; +class UrgeCurve; +class DangerObject; + +// ELF: vtable 0x4BB2C0 (13 words), operator new 0x2C, package H-deferred. +class BBTakeCover : public BotBehaviour +{ +public: + BBTakeCover(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x21DC00 + virtual ~BBTakeCover(); // 0x21E090 + + virtual void reset(Bot*); // 0x220440, slot +0x24; from the base declaration + virtual float calculateUrgency(Bot*, bool, float); // 0x21E190, slot +0x28; from the base declaration + +private: + // [INFERRED] names; both constructors and reset/destruction establish these owned arrays. + /* +0x24 */ int m_count; + /* +0x28 */ DangerObject** m_dangers; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp new file mode 100644 index 000000000..313a1d087 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp @@ -0,0 +1,81 @@ +// Aircraft cover urgency from missile-lock status. + +// static init: ELF 0x220BC0 (__tcf_0 0x220C20, _GLOBAL__I 0x220C50): 's Init object only. +#include + +#include "BBTakeCover3d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBotBehaviourPattern/BBPTakeCover3d.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x220750 (C2), 0x220810 (C1) +BBTakeCover3d::BBTakeCover3d(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + // The allocated target elements are left uninitialized by the shipped constructor. + m_targets = new unsigned int[count]; + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; +} + +// ELF 0x2208D0 (D2), 0x220920 (D1), 0x220970 (D0) +BBTakeCover3d::~BBTakeCover3d() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x2209C0 +float BBTakeCover3d::calculateUrgency(Bot* bot, bool, float scale) +{ + Information* equipment = informationManager->getInformation(bot->getCurrentEquipment()); + float urgency = 0.0f; + switch (equipment->getUnit()->getMissileLockStatus()) + { + case 1: + case 2: + urgency = 0.0f; + break; + case 3: + urgency = 20.0f; + break; + default: + break; + } + if (urgency > 0.0f) + { + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + urgency *= bot->getMemory()->m_float8; + m_urgency[bot->getBotId()] = urgency * scale; + m_targetChanged[bot->getBotId()] = false; + static_cast(m_pattern)->init(bot); + return m_urgency[bot->getBotId()]; + } + m_pattern->unInit(bot); + if (m_pattern->isInitiated(bot)) + m_targetChanged[bot->getBotId()] = true; + else + m_targetChanged[bot->getBotId()] = false; + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h new file mode 100644 index 000000000..a69fe803d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.h @@ -0,0 +1,31 @@ +// Aircraft cover urgency and initialization of its evasion pattern. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER3D_H + +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB3E0 (13 words), operator new 0x24, package H-deferred. +class BBTakeCover3d : public BotBehaviour +{ +public: + BBTakeCover3d(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x220810 + virtual ~BBTakeCover3d(); // 0x220920 + + virtual float calculateUrgency(Bot*, bool, float); // 0x2209C0, slot +0x28; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVER3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp new file mode 100644 index 000000000..5cc2a0fc9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp @@ -0,0 +1,543 @@ +// Infantry cover selection and per-quadrant threat bookkeeping. + +#include "BBTakeCoverInfantry.h" +#include "CustomCurve.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotMemory.h" +#include "../AIBot/SensedObject.h" +#include "../AIBotBehaviourPattern/BBPTakeCoverInfantry.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/DangerObject.h" +#include "../AIKnowledge/IPICover.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/AIMain.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Math/BoundingBox.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Core/Debug.h" + +#include "../../../../Math/Vec3.h" + +#include +#include +#include +#include +// static init: ELF 0x2247B0, 0x2248A0, 0x2248D0: iostream Init and four direction vectors. + +namespace dice { +namespace hfe { +namespace ai { +namespace { +const Vec3 north = {0.0f, 0.0f, 1.0f}; +const Vec3 east = {1.0f, 0.0f, 0.0f}; +const Vec3 northEast = {0.707106769f, 0.0f, 0.707106769f}; +const Vec3 southEast = {0.707106769f, 0.0f, -0.707106769f}; + +// ELF 0x220C70. +void computeQuadrants(int& first, int& second, const Vec3& position, const Vec3& target) +{ + const Vec3 delta = {target.x - position.x, target.y - position.y, target.z - position.z}; + const float ne = delta.x * northEast.x + delta.y * northEast.y + delta.z * northEast.z; + const float se = delta.x * southEast.x + delta.y * southEast.y + delta.z * southEast.z; + first = ne < 0.0f ? (se < 0.0f ? 3 : 1) : (!(se < 0.0f) ? 2 : 0); + second = delta.z < 0.0f ? (!(delta.x < 0.0f) ? 6 : 5) : (delta.x < 0.0f ? 7 : 4); +} + +// ELF 0x220D80: the direction is not normalized here. +int closestQuadFromDirection(Vec3 direction) +{ + direction.y = 0.0f; + const Vec3 candidates[] = {north, {0.0f, 0.0f, -1.0f}, east, {-1.0f, 0.0f, 0.0f}, + northEast, {-0.707106769f, 0.0f, -0.707106769f}, + southEast, {-0.707106769f, 0.0f, 0.707106769f}}; + for (int i = 0; i < 8; ++i) + if (direction.x * candidates[i].x + direction.y * candidates[i].y + + direction.z * candidates[i].z >= 0.906307817f) + return i; + return -1; +} + +// ELF 0x220F70. +Vec3 getQuadRecommendedLookDirection(Information* information, int quadrant) +{ + Vec3 direction = {}; + switch (quadrant) + { + case 0: direction = {-1.0f, 0.0f, 0.0f}; break; + case 1: direction = {1.0f, 0.0f, 0.0f}; break; + case 2: direction = {0.0f, 0.0f, 1.0f}; break; + case 3: direction = {0.0f, 0.0f, -1.0f}; break; + case 4: direction = {-0.707106769f, 0.0f, 0.707106769f}; break; + case 5: direction = {0.707106769f, 0.0f, -0.707106769f}; break; + case 6: direction = {0.707106769f, 0.0f, 0.707106769f}; break; + case 7: direction = {-0.707106769f, 0.0f, -0.707106769f}; break; + default: return direction; + } + const Mat4& transform = information->getTransformation(); + const Vec3 up = {transform.m[4], transform.m[5], transform.m[6]}; + const Vec3 result = {up.y * direction.z - up.z * direction.y, + up.z * direction.x - up.x * direction.z, + up.x * direction.y - up.y * direction.x}; + return result; +} + +// ELF 0x221090. A threatening neighbour still returns the current area's position. +bool getDangerPositionFromSAI(Bot* bot, Vec2& position) +{ + ISAI* const sai = IAIMain::m_instance->getSAI(bot->getSide()); + const int current = sai->getBotCurrentPos(static_cast(bot->getBotId())); + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(current); + if (!object || object->getType() != 0) + return false; + AIStrategicArea* const area = static_cast(object); + const int status = static_cast(area->getStatus(bot->getSide())); + if (status == 1 || status == 2) + { + position = area->getPosition(bot->getSide()); + return true; + } + if (status != 0) + return false; + for (auto it = area->m_neighbouringObjects.begin(); it != area->m_neighbouringObjects.end(); ++it) + { + AIStrategicObject* const neighbour = *it; + if (neighbour && neighbour->getType() == 0) + { + const int neighbourStatus = static_cast(neighbour->getStatus(bot->getSide())); + if (neighbourStatus == 1 || neighbourStatus == 2) + { + // shipped defect: this is the current area, not the threatening neighbour. + position = area->getPosition(bot->getSide()); + return true; + } + } + } + return false; +} + +// [INFERRED] local packaging of repeated inline clamps; unordered input is retained. +float clampCoverWeight(float value) +{ + if (value < 0.0f) return 0.0f; + if (value > 1.0f) return 1.0f; + return value; +} +} // namespace + +// ELF 0x221230 (C2), 0x2218F0 (C1). +BBTakeCoverInfantry::BBTakeCoverInfantry(unsigned char index, unsigned char queue, PlanGenerator* pattern, + UrgeCurve* curve, float* modifiers) + : BotBehaviour(modifiers, curve, + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_dangers = checkPointer(new DangerObject*[ + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_index = index; + m_queue = queue; + m_pattern = pattern; + m_targets = checkPointer(new unsigned int[m_count]); + // shipped defect: the first pointer array is overwritten and leaked. + m_dangers = checkPointer(new DangerObject*[m_count]); + m_fireDangers = checkPointer(new FireDanger[m_count]); + m_infoDangers = checkPointer(new InfoDanger[m_count]); + for (int i = 0; i < m_count; ++i) + { + m_targets[i] = 0xFFFFFFFFu; + m_urgency[i] = 0.0f; + m_dangers[i] = 0; + } +} + +// ELF 0x221FB0 (D2), 0x2220A0 (D1), 0x222190 (D0). +BBTakeCoverInfantry::~BBTakeCoverInfantry() +{ + // shipped defect: selected pointers can point inside the separately owned wrapper arrays. + for (int i = 0; i < m_count; ++i) + ::operator delete(m_dangers[i]); + if (m_targets) delete[] m_targets; + if (m_dangers) delete[] m_dangers; + if (m_fireDangers) delete[] m_fireDangers; + if (m_infoDangers) delete[] m_infoDangers; +} + +// ELF 0x222340 +float BBTakeCoverInfantry::calculateUrgency(Bot* bot, bool evaluate, float /*scale*/) +{ + if (!evaluate) + { + m_targetChanged[bot->getBotId()] = false; + if (m_pattern->isInitiated(bot)) + return m_urgency[bot->getBotId()]; + m_urgency[bot->getBotId()] = 0.0f; + return 0.0f; + } + const int side = bot->getSide(); + const unsigned int id = bot->getBotId(); + InformationManager* const manager = informationManager; + Information* const self = manager->getInformation(bot->getCurrentEquipment()); + IPIPhysical* const physical = self->getPhysical(); + InformationManager* const sectorManager = informationManager; + Information* const sector = sectorManager->getInformation(self->getMobile()->getSector()); + FireDanger fireDangers[8]; + InfoDanger infoDangers[8]; + DangerObject* dangers[8] = {}; + float sums[8] = {}, maxima[8] = {}; + float total = 0.0f; + unsigned int matchedOrders = 0; + const Vec3 selfPosition = self->getPosition(); + const int strengthType = physical->getStrengthType(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const auto* incoming = bot->getIncommingFire(); + m_lastIncomingFireTime = 0.0; + for (auto it = incoming->begin(); it != incoming->end(); ++it) + { + FireObject* const fire = it->first; + int first, second; + computeQuadrants(first, second, selfPosition, fire->getOrigin()); + const float distance = vehiclecontrol::distanceVec3(selfPosition, fire->getTarget()); + const float divisor = distance <= 0.0f ? 0.1f : distance; + const float attenuation = clampCoverWeight(4.0f / divisor); + float strength = fire->getBattleStrength(strengthType) * attenuation * 15.0f; + m_lastIncomingFireTime = fire->getTime(); + if (fire->isDirect()) strength += strength; + sums[first] += strength; + sums[second] += strength; + total += strength; + if (strength > maxima[first]) + { + maxima[first] = strength; + if (!dangers[first]) dangers[first] = &fireDangers[first]; + static_cast(dangers[first])->m_fire = fire; + } + if (strength > maxima[second]) + { + // shipped defect: the second quadrant's maximum is not updated for fire. + if (!dangers[second]) dangers[second] = &fireDangers[second]; + static_cast(dangers[second])->m_fire = fire; + } + } + // [INFERRED] local packaging of the repeated order-list search. + const auto weightOrder = [&](unsigned int handle, float& strength) + { + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() + && matchedOrders < bot->getOrderList(m_index)->size()) + { + const auto comparisonEnd = bot->getOrderList(m_index)->end(); + const auto begin = bot->getOrderList(m_index)->begin(); + const auto searchEnd = bot->getOrderList(m_index)->end(); + if (std::find(begin, searchEnd, handle) != comparisonEnd) + { + ++matchedOrders; + strength *= bot->getMemory()->m_float8; + } + } + }; + const auto& sensed = bot->getSensedObjects(); + for (auto it = sensed.begin(); it != sensed.end(); ++it) + { + SensedObject* const sensedObject = it->second; + const unsigned int handle = sensedObject->m_handle; + Information* const information = informationManager->getInformation(handle); + if (!information || information->getSide() != 0 || !information->getUnit() + || !information->getUnit()->isOccupied()) + continue; + IPIUnit* const unit = information->getUnit(); + WeaponInfo* weapon = 0; + if (information->getArmament()) weapon = information->getArmament()->getLastFiredWeapon(); + int first, second; + computeQuadrants(first, second, selfPosition, information->getPosition()); + const float measured = vehiclecontrol::distanceVec3(selfPosition, information->getPosition()); + const float distance = measured > 2.0f ? measured : 2.0f; + float strength = 0.0f; + if (sensedObject->m_flags & 2) + { + int iterator = information->getFirstSecondaryObjectIterator(); + unsigned int secondary = information->getSecondaryObject(iterator, side); + Information* current = information; + do + { + const float battleStrength = current->getUnit()->getBattleStrengths()[strengthType]; + float part = battleStrength * battleStrength / distance; + // The first contribution is the primary's but uses the first secondary's handle. + weightOrder(secondary, part); + strength += part; + secondary = information->getSecondaryObject(iterator, side); + current = informationManager->getInformation(secondary); + } while (current); + if (sensedObject->m_flags & 8) + { + const double age = now - sensedObject->m_firstSeenTime; + const float fraction = static_cast((age < 30.0 ? age : 30.0) / 30.0); + strength *= (1.0f - fraction) * 0.5f + 0.5f; + } + } + else if (sensedObject->m_flags & 1) + strength = information->getSecurity() * unit->getBattleStrengths()[strengthType] / distance; + if ((sensedObject->m_flags & 3) && weapon) + { + if (distance >= weapon->getMaxRange()) continue; + strength *= 1.0f - SCurve::calculate(distance / weapon->getMaxRange()); + } + if (bot->isOrderedObject(handle, this)) + { + ++matchedOrders; + strength *= bot->getMemory()->m_float8; + } + // shipped defect: both additions target the first quadrant. + sums[first] += strength; + sums[first] += strength; + total += strength; + const int quadrants[] = {first, second}; + for (int q : quadrants) + if (strength > maxima[q]) + { + maxima[q] = strength; + if (!dangers[q] || !dangers[q]->isInformation()) dangers[q] = &infoDangers[q]; + static_cast(dangers[q])->m_information = handle; + } + } + bool changed = true; + unsigned int cover = 0xFFFFFFFFu; + Vec3 coverPosition = {}; + float projection = 0.0f, multiplier; + if (total > 0.0f) + { + DangerObject* strongest = 0; + float maximum = 0.0f; + for (int q = 0; q < 8; ++q) + if (sums[q] > maximum) { maximum = sums[q]; strongest = dangers[q]; } + if (!strongest) { unInit(bot); return 0.0f; } + if (m_dangers[id]) changed = !(*m_dangers[id] == *strongest); + if (strongest->isInformation()) + { + m_dangers[id] = &m_infoDangers[id]; + m_infoDangers[id].m_information = static_cast(strongest)->m_information; + } + else + { + m_dangers[id] = &m_fireDangers[id]; + m_fireDangers[id].m_fire = static_cast(strongest)->m_fire; + } + Information* threat = 0; + DangerObject* const danger = m_dangers[id]; + if (danger->isInformation()) + { + Information* const information = informationManager->getInformation( + static_cast(danger)->m_information); + if (information && information->getMobile()) + threat = informationManager->getInformation(information->getMobile()->getSector()); + } + Vec3 threatPosition = {}; + if (!m_dangers[id]->getPosition(threatPosition) + || !getCoverObject(bot, threatPosition, threat, false, cover, coverPosition, projection, multiplier, false)) + { unInit(bot); return 0.0f; } + } + if (total <= 0.0f) { unInit(bot); return 0.0f; } + if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders() && bot->getOrderList(m_index)->empty()) + total *= bot->getMemory()->m_float8; + m_targetChanged[id] = changed || cover == 0xFFFFFFFFu || cover != m_targets[id]; + m_targets[id] = cover; + DangerObject* const danger = m_dangers[id]; + if (danger->isInformation()) + { + Information* const information = informationManager->getInformation( + static_cast(danger)->m_information); + std::vector ignore; + ignore.push_back(self->getAIObject()); + ignore.push_back(information->getAIObject()); + const bool coarse = bot->getLodLevel() != BotLodFull; + const Vec3& to = information->getPosition(); + const Vec3& from = self->getPosition(); + bool hit; + if (static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->collideLineWithWorld(from, to, ignore, coarse, 1.0f, true, hit)) + { m_urgency[id] = 0.0f; return 0.0f; } + } + if (m_targetChanged[id]) + { + BBPTakeCoverInfantry* const pattern = static_cast(m_pattern); + Vec3 unused = {}; + danger->getPosition(unused); + if (danger->isInformation()) + pattern->init(bot, static_cast(danger)->m_information, coverPosition, m_targets[id]); + else + { + Vec3 threatPosition = {}; + danger->getPosition(threatPosition); + pattern->init(bot, threatPosition, coverPosition, m_targets[id]); + } + m_urgency[id] = total; + if (sector) m_urgency[id] *= 0.5f; + } + else + { + const float x = self->getPosition().x; + const float z = self->getPosition().z; + const float dx = coverPosition.x - x; + const float dz = coverPosition.z - z; + if (dx * dx + dz * dz < 4.0f) + m_urgency[id] = 0.0f; + else + { + const float age = static_cast(now - m_lastIncomingFireTime); + m_urgency[id] *= clampCoverWeight(5.0f / age); + } + } + if (m_urgency[id] < 0.2f) m_urgency[id] = 0.0f; + return m_urgency[id]; +} + +// ELF 0x222290 +void BBTakeCoverInfantry::unInit(Bot* bot) +{ + if (m_pattern->isInitiated(bot)) + { + m_targetChanged[bot->getBotId()] = true; + m_pattern->unInit(bot); + } + // shipped defect: the changed flag just set above is immediately cleared again. + m_targetChanged[bot->getBotId()] = false; + m_urgency[bot->getBotId()] = 0.0f; + m_dangers[bot->getBotId()] = 0; +} + +// ELF 0x223920 +bool BBTakeCoverInfantry::getCoverObject(Bot* bot, const Vec3& threatPosition, Information* threat, + bool unrestricted, unsigned int& cover, Vec3& position, + float& projection, float& multiplier, bool restrictToArea) +{ + InformationManager* const manager = informationManager; + Information* const self = manager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + LocalBoundingBox* const selfBox = const_cast(self->getPhysical()->getLocalBoundingBox()); + const float selfX = selfBox->getSize().x; + const float selfZ = selfBox->getSize().z; + const float selfWidth = selfZ > selfX ? selfZ : selfX; + const float selfHeight = selfBox->getSize().y; + ISAI* const sai = IAIMain::m_instance->getSAI(bot->getSide()); + AIStrategicObjectManager* const strategic = AIStrategicObjectManager::getInstance(); + AIStrategicObject* const ordered = strategic->getStrategicObject( + sai->getBotOrderedPos(static_cast(bot->getBotId()))); + multiplier = 1.0f; + cover = 0xFFFFFFFFu; + Vec2 coverPosition = {}, from = {}, to = {}; + vec3ToVec2XZ(self->getPosition(), from); + vec3ToVec2XZ(threatPosition, to); + if (CoverPositionManager::m_instance->getClosestAttackCoverPosition(from, to, 30.0f, -1.0f, coverPosition)) + { + vec2ToVec3XZ(coverPosition, position); + cover = 0; + return true; + } + std::vector candidates; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getCover(*bot, candidates); + float best = 0.0f; + for (auto it = candidates.begin(); it != candidates.end(); ++it) + { + Information* const candidate = informationManager->getInformation(*it); + // shipped defect: getName is called before the null check. + candidate->getName(); + if (!candidate || !candidate->getPhysical() || !candidate->getCover()) + continue; + IPIPhysical* const physical = candidate->getPhysical(); + IPICover* const coverInfo = candidate->getCover(); + if (threat && threat->getAIObject() == candidate->getAIObject()) + continue; + const Vec3 candidatePosition = candidate->getPosition(); + const Vec3& selfFirst = self->getPosition(); + const Vec3 towardThreat = {threatPosition.x - selfFirst.x, threatPosition.y - selfFirst.y, + threatPosition.z - selfFirst.z}; + const Vec3& selfSecond = self->getPosition(); + const Vec3 towardCover = {candidatePosition.x - selfSecond.x, candidatePosition.y - selfSecond.y, + candidatePosition.z - selfSecond.z}; + const float threatDistance = std::sqrt(towardThreat.x * towardThreat.x + towardThreat.y * towardThreat.y + + towardThreat.z * towardThreat.z); + const float coverDistance = std::sqrt(towardCover.x * towardCover.x + towardCover.y * towardCover.y + + towardCover.z * towardCover.z); + const float dot = towardThreat.x * towardCover.x + towardThreat.y * towardCover.y + + towardThreat.z * towardCover.z; + if (!unrestricted && dot / coverDistance > threatDistance * 0.5f) + continue; + Vec3 goal = {}; + if (coverInfo->getPortalCount()) + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp", 1087, "") + << "What portals? They have been removed for BF2."; + coverInfo->getPortalCount(); + Vec3 away = {candidatePosition.x - threatPosition.x, candidatePosition.y - threatPosition.y, + candidatePosition.z - threatPosition.z}; + vehiclecontrol::normalizeVec3(away); + const float nearRadius = physical->getRadius() * 0.75f; + const Vec3 near = vehiclecontrol::alongFrom(candidatePosition, away, nearRadius); + const float farRadius = physical->getRadius() * 2.0f; + const Vec3 far = vehiclecontrol::alongFrom(candidatePosition, away, farRadius); + const int equipmentType = self->getUnit()->getEquipmentType(); + const int vehicle = mobile->getVehicleNumber(); + unsigned int island, polygon; + if (!IAIPathfinding::instance->findClosestValidPolygon(island, polygon, goal, vehicle, + near, far, 10, equipmentType)) + continue; + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const float boxX = box->getSize().x; + const float boxZ = box->getSize().z; + const float width = boxZ > boxX ? boxZ : boxX; + const float height = box->getSize().y; + const float horizontal = clampCoverWeight(width / selfWidth * 0.2f); + const float vertical = clampCoverWeight(height / selfHeight * 0.5f); + const float sizeRating = horizontal * 0.25f + vertical * 0.75f; + float overlap = 1.0f; + if (restrictToArea && ordered) + { + AIStrategicArea* const area = static_cast(ordered); + Vec2 unused = {}; + const Vec2 centre = area->getPosition(bot->getSide()); + const Vec2 maximum = getBoxMaxCorner(area->m_centre, centre, unused); + BoundingBox worldBox = {}; + worldBox.initWithLocalBoundingBox(*box); + worldBox.transform(candidate->getTransformation()); + const Vec3 minimum3 = worldBox.getMin(); + const Vec3 maximum3 = worldBox.getMax(); + const Vec2 minimum2 = {minimum3.x, minimum3.z}; + const Vec2 maximum2 = {maximum3.x, maximum3.z}; + Vec2 intersectionMin = {}, intersectionMax = {}; + overlap = ::dice::hfe::getBoxIntersections(area->m_centre, maximum, minimum2, maximum2, + intersectionMin, intersectionMax) ? 1.0f : 0.0f; + } + const Vec3& selfThird = self->getPosition(); + const Vec3& candidateAgain = candidate->getPosition(); + const float distance = vehiclecontrol::distanceVec3(candidateAgain, selfThird); + float rating = coverInfo->getCoverValue() * sizeRating / distance * overlap; + if (bot->isOrderedObject(*it, this)) + rating *= bot->getMemory()->m_float8; + if (rating > best) + { + best = rating; + cover = *it; + position = goal; + projection = dot; + multiplier *= 1.3f; + } + else if (rating > 0.0f) + multiplier *= rating / best * 0.3f + 1.0f; + } + return cover != 0xFFFFFFFFu; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.h new file mode 100644 index 000000000..c0fa1fb17 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.h @@ -0,0 +1,47 @@ +// Rates infantry cover against incoming shots and sensed occupied objects. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVERINFANTRY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVERINFANTRY_H + +#include "../../../../Math/Vec3.h" +#include "BotBehaviour.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; +class DangerObject; +class FireDanger; +class InfoDanger; + +// ELF: vtable 0x4BB480 (13 words), operator new 0x3C, package H-deferred. +class BBTakeCoverInfantry : public BotBehaviour +{ +public: + BBTakeCoverInfantry(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x2218F0 + virtual ~BBTakeCoverInfantry(); // 0x2220A0 + + virtual float calculateUrgency(Bot*, bool, float); // 0x222340, slot +0x28; from the base declaration + + void unInit(Bot*); // 0x222290; [INFERRED] ELF void + bool getCoverObject(Bot*, const Vec3&, Information*, bool, unsigned int&, Vec3&, float&, float&, bool); // 0x223920; [INFERRED] ELF int, callers {'bool': 1} + +private: + // [INFERRED] names; constructors and urgency bookkeeping establish the array types. + /* +0x24 */ int m_count; + /* +0x28 */ DangerObject** m_dangers; + /* +0x2C */ FireDanger* m_fireDangers; + /* +0x30 */ InfoDanger* m_infoDangers; + /* +0x34 */ double m_lastIncomingFireTime; // shared by all bots, not initialized by construction +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTAKECOVERINFANTRY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp new file mode 100644 index 000000000..21fc47db8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp @@ -0,0 +1,121 @@ +// Triggerable behaviour (infantry "Triggerable" slot of aibehaviours.ai): a man-down bot is the +// only one it applies to; its urgency is always 0 here, so it is never chosen by urgency alone. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +#include "BBTriggerable.h" + +// static init: ELF 0x224F30, 0x2250A0, 0x2250D0, 0x225140 (iostream Init, colors, triggerables). +#include + +#include "../AIBot/BotMain.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace world { +namespace { + +// [CHOSEN, not recovered] Type, component names and constructor spelling for the +// three-float elements stored by ELF 0x224F30. No original type name is attested. +struct DebugMeshMaterialColor +{ + float r, g, b; + + DebugMeshMaterialColor(float red, float green, float blue) : r(red), g(green), b(blue) {} +}; + +static_assert(sizeof(DebugMeshMaterialColor) == 12, "color element stride"); +static_assert(offsetof(DebugMeshMaterialColor, r) == 0 && + offsetof(DebugMeshMaterialColor, g) == 4 && + offsetof(DebugMeshMaterialColor, b) == 8, "color component offsets"); +static_assert(std::is_trivially_destructible::value, + "the color table has no registered teardown"); + +} // anonymous namespace + +// ELF 0x4CE3E0, a separate local table. __tcf_1 destroys only the triggerables map. +// [CHOSEN, not recovered] Retain the unreferenced retail object with modern compilers. +#if defined(__GNUC__) +__attribute__((used)) +#endif +static DebugMeshMaterialColor debugMeshMaterialColors[10] = { + {0.66f, 0.66f, 0.185f}, + {0.185f, 0.66f, 0.185f}, + {0.185f, 0.185f, 0.66f}, + {0.185f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.185f}, + {0.66f, 0.66f, 0.66f}, + {0.66f, 0.185f, 0.66f}, + {0.185f, 0.185f, 0.185f}, + {1.0f, 1.0f, 1.0f}, + {0.0f, 0.0f, 0.0f} +}; +static_assert(sizeof(debugMeshMaterialColors) == 0x78, "local color table extent"); + +} // namespace world +namespace ai { + +// ELF 0x224F30 constructs this map after the colors; __tcf_1 ELF 0x2250D0 destroys +// its nodes and sentinel, without deleting the stored Triggerable pointers. +std::map BBTriggerable::m_triggerables; + +// ELF 0x2248F0 (C2) / 0x224AF0 (C1). The base gets getMaxNBots (IAISettings slot 0) as its +// per-bot count, then a second getMaxNBots sizes the +0x08 array (checkPointer'd, not +// initialised) and every base urgency (+0x10) is set to 0.0f (rodata 0x49CB34). +BBTriggerable::BBTriggerable(unsigned char index, unsigned char queue, PlanGenerator* pattern, UrgeCurve* curve, + float* modifiers) + : BotBehaviour(modifiers, curve, static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()) +{ + m_index = index; + m_queue = queue; + m_pattern = pattern; + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_targets = checkPointer(new unsigned int[count]); + for (int i = 0; i < count; ++i) + m_urgency[i] = 0.0f; + m_unknown24 = 0; +} + +// ELF 0x224CF0 (D2) / 0x224D40 (D1) / 0x224D90 (D0): delete[] +0x08 when set, then the base. +BBTriggerable::~BBTriggerable() +{ + if (m_targets) + delete[] m_targets; +} + +// ELF 0x224DE0: m_urgency[bot->getBotId()] = 0.0f, return it (flds of the same slot). +float BBTriggerable::calculateUrgency(Bot* bot, bool, float) +{ + m_urgency[bot->getBotId()] = 0.0f; + return m_urgency[bot->getBotId()]; +} + +// ELF 0x224E40: bot->getPlayer() (+0xBC) ->getIsAlive() (+0x24); alive bots answer getManDown (+0x1B0). +bool BBTriggerable::isApplicable(Information*, Bot* bot) +{ + if (!bot->getPlayer()->getIsAlive()) + return false; + return bot->getManDown(); +} + +// ELF 0x224E80: drops the bot's entry from m_triggerables (find + erase), then the pattern +// (+0x0C) unInit(bot) through PlanGenerator slot +0x10. +void BBTriggerable::unInitialise(Bot* bot) +{ + std::map::iterator it = m_triggerables.find(bot->getBotId()); + if (it != m_triggerables.end()) + m_triggerables.erase(it); + m_pattern->unInit(bot); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.h new file mode 100644 index 000000000..fc2863290 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.h @@ -0,0 +1,50 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTRIGGERABLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTRIGGERABLE_H + +#include "BotBehaviour.h" + +#include + +namespace dice { +namespace hfe { + +namespace world { class Triggerable; } + +namespace ai { + +class Bot; +class Information; +class PlanGenerator; +class UrgeCurve; + +// ELF: vtable 0x4BB520 (14 words), operator new 0x28, package F-infantry. +class BBTriggerable : public BotBehaviour +{ +public: + BBTriggerable(unsigned char, unsigned char, PlanGenerator*, UrgeCurve*, float*); // 0x224AF0 + virtual ~BBTriggerable(); // 0x224D40 + + virtual float calculateUrgency(Bot*, bool, float); // 0x224DE0, slot +0x28; from the base declaration + virtual bool isApplicable(Information*, Bot*); // 0x224E40, slot +0x34; bool: returns Bot::getManDown or 0 + + void unInitialise(Bot*); // 0x224E80; ELF void (no result register is set) + + // The triggerable each bot works on, keyed by Bot::getBotId (ELF 0x4CE3C0, B; static + // initialiser 0x225140 is _GLOBAL__I__ZN4dice3hfe2ai13BBTriggerable14m_triggerablesE). + static std::map m_triggerables; + +private: + /* +0x24 */ unsigned int m_unknown24; // = 0 in the constructor; no other F.1 reader [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BBTRIGGERABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp new file mode 100644 index 000000000..73f501c36 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp @@ -0,0 +1,177 @@ +// BotBehaviour: recovered by package A-core from libaidll.so (TU BotBehaviour.cpp, 0x225250..0x2260D0; +// the two weak members sit at 0x1FD160). Every body carries its ELF address. + +// static init: ELF 0x226040 (__tcf_0 0x2260A0, _GLOBAL__I 0x2260D0): 's Init object only. +#include + +#include "BotBehaviour.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBotBehaviourPattern/PlanGenerator.h" +#include "../AIPlanInterpreter/BotScript.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x225250 (C2; C1 0x225610). Three checkPointer'd arrays, then the init loop. The urgency array +// is not initialised here; reset() and the derived calculateUrgency write it. +BotBehaviour::BotBehaviour(float* modifiers, UrgeCurve* urgeCurve, int count) + : m_targets(0) + , m_pattern(0) +{ + m_urgency = checkPointer(new float[count]); + m_modifiers = modifiers; + m_targetChanged = checkPointer(new bool[count]); + m_activeUrgency = checkPointer(new float[count]); + m_urgeCurve = urgeCurve; + for (int i = 0; i < count; ++i) + { + m_activeUrgency[i] = 1e-5f; // rodata 0x49D588 + m_targetChanged[i] = true; + } +} + +// ELF 0x2259D0 (C2; C1 0x225A20). No arrays. +BotBehaviour::BotBehaviour(float* modifiers, UrgeCurve* urgeCurve) + : m_targets(0) + , m_pattern(0) + , m_urgency(0) + , m_modifiers(modifiers) + , m_targetChanged(0) + , m_activeUrgency(0) + , m_urgeCurve(urgeCurve) +{ +} + +// [TEMP] S0 skeleton default constructor (see the header). +BotBehaviour::BotBehaviour() +{ + BF2_AI_FRONTIER("dice::hfe::ai::BotBehaviour::BotBehaviour (S0 skeleton default constructor: a derived constructor is not recovered)"); +} + +// ELF 0x225A70 (D2; D1 0x225B00, D0 0x225B90). The pattern is owned (deleting destructor, slot +4); +// the modifier row, the curve and m_targets are not freed here. +BotBehaviour::~BotBehaviour() +{ + delete[] m_urgency; + delete[] m_targetChanged; + delete[] m_activeUrgency; + delete m_pattern; +} + +// ELF 0x225D70. +float BotBehaviour::getUrgency(Bot* bot) +{ + return m_urgency[bot->getBotId()]; +} + +// ELF 0x225DA0. +float BotBehaviour::getActiveUrgency(Bot* bot) +{ + return m_activeUrgency[bot->getBotId()]; +} + +// ELF 0x225DD0: the current urgency becomes the active one and is returned (fsts). +float BotBehaviour::updateActiveUrgency(Bot* bot) +{ + return m_activeUrgency[bot->getBotId()] = m_urgency[bot->getBotId()]; +} + +// ELF 0x225E20. +bool BotBehaviour::hasChangedTarget(Bot* bot) +{ + return m_targetChanged[bot->getBotId()]; +} + +// ELF 0x225E50. With no active urgency: changed when the new one is positive. With a zero new +// urgency: changed. Otherwise the ratio new/active (`fdivp %st,%st(1)` = de f1, st(1) = st(0)/st(1) +// with st(0) = urgency) must lie inside [low, high]. The comparisons are the unordered-false +// forms of the image (ja / jbe after fucomip). +bool BotBehaviour::quotientChanged(Bot* bot, float low, float high) +{ + if (m_activeUrgency[bot->getBotId()] == 0.0f) + return m_urgency[bot->getBotId()] > 0.0f; + + if (m_urgency[bot->getBotId()] == 0.0f) + return true; + + const float quotient = m_urgency[bot->getBotId()] / m_activeUrgency[bot->getBotId()]; + return low > quotient || quotient > high; +} + +// ELF 0x225F30: both through the vtable (+0x14, +0x18). +bool BotBehaviour::hasChanged(Bot* bot, float low, float high) +{ + return hasChangedTarget(bot) && quotientChanged(bot, low, high); +} + +// ELF 0x1FD160 (weak). +UrgencyGenerator* BotBehaviour::getChosenGenerator() +{ + return this; +} + +// ELF 0x225F90. Note the 1e-4f here against the constructor's 1e-5f (rodata 0x49D578 / 0x49D588). +void BotBehaviour::reset(Bot* bot) +{ + if (m_pattern) + m_pattern->unInit(bot); + m_urgency[bot->getBotId()] = 0.0f; + m_activeUrgency[bot->getBotId()] = 1e-4f; + m_targetChanged[bot->getBotId()] = true; + if (m_targets) + m_targets[bot->getBotId()] = 0xFFFFFFFFu; +} + +// ELF 0x225C30 (105 instructions). +// * A locked plan (Bot +0x68) is kept: the current plan (+0x60) is returned. +// * An initiated pattern builds a new plan. The old plan is first re-owned by the pattern, the new +// one by this behaviour; when a different old plan exists it is re-owned by this behaviour too +// and the sensing agent is told something new was sensed (SensingAgent +0x78 = 1). +// The new plan is returned (the caller replaces and frees the old one). +// * A pattern that is not initiated: the current plan is deleted (slot +8), the plan is cleared +// (+0x64) and 0 is returned. +BotScript* BotBehaviour::generatePlan(Bot* bot) +{ + if (bot->getPlanLock()) + return bot->getPlan(); + + if (!m_pattern->isInitiated(bot)) + { + if (bot->getPlan() != 0) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + if (bot->getPlan() != 0) + bot->getPlan()->m_owner = m_pattern; + + BotScript* plan = m_pattern->createPlan(bot); + if (plan != 0) + { + plan->m_owner = this; + if (bot->getPlan() != 0 && bot->getPlan() != plan) + { + bot->getPlan()->m_owner = this; + bot->getSensingAgent()->setSensedNewObject(); + } + } + return plan; +} + +// ELF 0x1FD170 (weak). +bool BotBehaviour::isAplicable(Information*, Bot*) +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h new file mode 100644 index 000000000..b293943e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h @@ -0,0 +1,85 @@ +// Behaviour base: per-bot urgency bookkeeping and plan generation through the behaviour's pattern. +// Recovered by package A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order +// is checked by tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H + +#include "UrgencyMerger.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class PlanGenerator; +class Information; +class UrgeCurve; +class UrgencyGenerator; + +// Behaviour base. Vtable 0x4BB580 (13 words). One object per vehicle type and behaviour (built at +// map load by BotBehaviourManager), shared by every bot of that vehicle: the per-bot state is in +// arrays indexed by Bot::getBotId() (+0xE8). +// ELF: vtable 0x4BB580 (13 words), package A-core. +class BotBehaviour : public UrgencyGenerator +{ +public: + BotBehaviour(float*, UrgeCurve*, int); // 0x225610 + BotBehaviour(float*, UrgeCurve*); // 0x225A20 + virtual ~BotBehaviour(); // 0x225B00 + + virtual float getUrgency(Bot*); // 0x225D70, slot +0x08; from the base declaration + virtual float getActiveUrgency(Bot*); // 0x225DA0, slot +0x0C; from the base declaration + virtual float updateActiveUrgency(Bot*); // 0x225DD0, slot +0x10; from the base declaration + virtual bool hasChangedTarget(Bot*); // 0x225E20, slot +0x14; from the base declaration + virtual bool quotientChanged(Bot*, float, float); // 0x225E50, slot +0x18; from the base declaration + virtual bool hasChanged(Bot*, float, float); // 0x225F30, slot +0x1C; from the base declaration + virtual UrgencyGenerator* getChosenGenerator(); // 0x1FD160, slot +0x20; from the base declaration + virtual void reset(Bot*); // 0x225F90, slot +0x24; from the base declaration + virtual float calculateUrgency(Bot*, bool, float) = 0; // no body, slot +0x28; from the base declaration + virtual BotScript* generatePlan(Bot*); // 0x225C30, slot +0x2C; from the base declaration + virtual bool isAplicable(Information*, Bot*); // 0x1FD170, slot +0x30; from the base declaration + + // BotMain::decisionMaking (0x1893D0) reads +4, +5 and +0x14 inline; the image has no accessor. + // [CHOSEN, not recovered] inline getters so AIBot needs no friend access. + unsigned char getIndex() const { return m_index; } + unsigned char getQueueGroup() const { return m_queue; } + float* getModifiers() const { return m_modifiers; } + // [INFERRED] inline reader of +0x0C for BotMain::updateBot (ELF 0x18BF50 reads it inline). + PlanGenerator* getPattern() const { return m_pattern; } + // [INFERRED] inline reader of +0x20 for BotMemory::modifyBehaviourUrgency (ELF 0x18F2F8 reads it inline). + UrgeCurve* getUrgeCurve() const { return m_urgeCurve; } + +protected: + // [TEMP] [CHOSEN, not recovered] S0 only: lets the generated derived constructor stubs compile; + // it stops by name. [RETIRE-WHEN: ai-behaviour-skeleton-ctors] every derived constructor is recovered. + BotBehaviour(); + +protected: + // BotBehaviour(float*, UrgeCurve*, int count) 0x225250: +8 = +0xC = 0, the three arrays of + // `count` (checkPointer each), activeUrgency[i] = 1e-5f, targetChanged[i] = true; urgency[] is + // left uninitialised. BotBehaviour(float*, UrgeCurve*) 0x2259D0: all three arrays 0. + // +0x04/+0x05 are bytes the BB* constructors store (behaviour index, queue group) [INFERRED]. + /* +0x04 */ unsigned char m_index; + /* +0x05 */ unsigned char m_queue; + // +0x08: per-bot handle array that only some behaviours allocate (BBTriggerable); reset 0x22601E + // writes 0xFFFFFFFF when present. [INFERRED] name and element type. + /* +0x08 */ unsigned int* m_targets; + // +0x0C: the behaviour's pattern (BBCreateFunction passes `new BBP(id)`), owned: the + // destructor deletes it (0x225AC6). generatePlan calls isInitiated (+0xC) and createPlan (+8), + // reset calls unInit (+0x10). + /* +0x0C */ PlanGenerator* m_pattern; + /* +0x10 */ float* m_urgency; // [bot]: getUrgency 0x225D70 + /* +0x14 */ float* m_modifiers; // constructor argument 1 (the behaviour-modifier row), not owned + /* +0x18 */ bool* m_targetChanged; // [bot]: hasChangedTarget 0x225E20 returns it [INFERRED] name + /* +0x1C */ float* m_activeUrgency; // [bot]: updateActiveUrgency 0x225DD0 copies urgency into it + /* +0x20 */ UrgeCurve* m_urgeCurve; // constructor argument 2, not owned +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp index 7c1f7e3e1..ad4c4c13f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp @@ -2,7 +2,11 @@ #include "CustomCurve.h" +#include // CustomCurve: the image asserts + #include // isfinite - SCurve's guard only +#include +// static init: ELF 0x36E0E0, 0x36E140, 0x36E170: CustomCurve.cpp's iostream Init only. namespace dice { namespace hfe { @@ -454,6 +458,162 @@ void DecleiningSlopeCurve::init() } +// ELF 0x36D630 +CustomCurve::CustomCurve(Function function, float min, float max, float step) + : m_function(function) + , m_table(0) + , m_min(min) + , m_max(max) + , m_step(step) +{ + init(); +} + +// ELF 0x36D7D0 +CustomCurve::~CustomCurve() +{ + if (m_table) + delete[] m_table; +} + +// ELF 0x36D800. The image asserts (expression "0") when x is outside [min, max] and when the +// interpolated index has no successor. +float CustomCurve::calculate(float x, bool interpolate) const +{ + if (m_min > x || x > m_max) + assert(0); + // The image keeps the step, offset and fraction on the x87 stack; doubles stand in for that. + const double step = (static_cast(m_max) - m_min) / static_cast(static_cast(m_size)); + const double offset = static_cast(x) - m_min; + const int index = static_cast(static_cast(offset / step)); + if (!interpolate) + return m_table[index]; + const double fraction = (offset - static_cast(static_cast(index)) * step) / step; + if (index >= m_size) + assert(0); + return static_cast(m_table[index] + (static_cast(m_table[index + 1]) - m_table[index]) * fraction); +} + +// ELF 0x36DFB0. Samples m_size + 1 points, then writes the two ends again from min and max exactly. +void CustomCurve::init() +{ + if (0.0f >= m_step) + assert(0); + if (m_table) + delete[] m_table; + m_size = static_cast(static_cast((static_cast(m_max) - m_min) / m_step)); + m_table = new float[m_size + 1]; + const double delta = (static_cast(m_max) - m_min) / static_cast(static_cast(m_size)); + for (int i = 0; i <= m_size; ++i) + m_table[i] = m_function(m_min + static_cast(i * delta)); + m_table[0] = m_function(m_min); + m_table[m_size] = m_function(m_max); +} + +// ELF 0x36D680 (C2), 0x36D6D0 (C1): resamples the function instead of copying table entries. +CustomCurve::CustomCurve(const CustomCurve& other) + : m_function(other.m_function), m_table(0), m_min(other.m_min), m_max(other.m_max), m_step(other.m_step) +{ + init(); +} + +// ELF 0x36D720. Shipped quirk: returns a new, resampled curve by value, even on self-assignment. +CustomCurve CustomCurve::operator=(const CustomCurve& other) +{ + if (this != &other) + { + if (m_table) delete[] m_table; + m_table = 0; + m_function = other.m_function; + m_min = other.m_min; + m_max = other.m_max; + m_step = other.m_step; + init(); + } + return *this; +} + +// ELF 0x36D8F0: zero-valued function samples contribute no error but still count in the divisor. +float CustomCurve::testAccuracy(float density, bool interpolate) const +{ + if (0.0f >= density) assert(0); + float error = 0.0f; + const float width = m_max - m_min; + const int count = static_cast(static_cast(m_size) * density); + const float divisor = static_cast(count); + const float step = width / divisor; + for (int i = 0; i < count; ++i) + { + const float position = m_min + static_cast(i) * step; + const float actual = m_function(position); + const float estimated = calculate(position, interpolate); + if (actual != 0.0f) error += std::fabs(estimated - actual); + } + return error / divisor; +} + +// ELF 0x36DA40. Shipped defect: the second pass also asks for interpolation. +bool CustomCurve::testBounds(float density, float minimum, float maximum) const +{ + if (0.0f >= density) assert(0); + bool valid = true; + for (float position = m_min; position < m_max; + position += (m_max - m_min) / (static_cast(m_size) * density)) + { + const float value = calculate(position, true); + if (value < minimum || value > maximum) + { + std::cout << "Interpolated value[" << position << "] = " << value + << " is out of boundary (" << minimum << "," << maximum << ")\n"; + valid = false; + } + } + for (float position = m_min; position < m_max; + position += (m_max - m_min) / (static_cast(m_size) * density)) + { + const float value = calculate(position, true); + if (value < minimum || value > maximum) + { + std::cout << "Non-interpolated value[" << position << "] = " << value + << " is out of boundary (" << minimum << "," << maximum << ")\n"; + valid = false; + } + } + if (valid) + std::cout << "All values are within bounds (" << minimum << "," << maximum << ")\n"; + else + std::cout << "BOUNDS CHECK : Failed\n"; + return valid; +} + +// ELF 0x36DD60. +void CustomCurve::accuracyTest(float density) const +{ + std::cout << "\nACCURACY TESTS:\n"; + const float interpolated = testAccuracy(density, true); + const float direct = testAccuracy(density, false); + std::cout << "Curve is " << (1.0f - direct) * 100.0f << "% accurate without interpolation\n"; + std::cout << "Curve is " << (1.0f - interpolated) * 100.0f << "% accurate with interpolation\n"; +} + +// ELF 0x36DE60: the fourth argument is unused; the byte estimate omits the final table element. +void CustomCurve::getStatistics(float density, float minimum, float maximum, int /*flags*/) const +{ + std::cout << "\nCUSTOMCURVE STATISTICS\n----------------------\n"; + std::cout << "Curve has " << m_size << " elements and uses a total of " + << sizeof(CustomCurve) + m_size * sizeof(float) << " bytes.\n\n"; + testBounds(density, minimum, maximum); + accuracyTest(density); +} + +// ELF 0x36DF50: preserves negative zero and unordered values. +float CustomCurve::calculateEstimation(float value, bool& nonnegative) const +{ + if (value < 0.0f) { nonnegative = false; return -value; } + nonnegative = true; + return value; +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h index b33ed43e5..8186b6b52 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h @@ -5,6 +5,8 @@ #ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H // [INFERRED] guard style #define AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H +#include + namespace dice { namespace hfe { namespace ai { @@ -41,6 +43,46 @@ class DecleiningSlopeCurve // dice's spelling static float* curveValues; }; +// A function sampled into a table over [min, max] (AI/AIDLL/AI/AIUtils/CustomCurve.cpp in the image). +// Recovered by ai-w1-d-behaviours for BBFire (its constructor builds one); libaidll.so addresses. +class CustomCurve +{ +public: + typedef float (*Function)(float); + + CustomCurve(Function function, float min, float max, float step); // 0x36D630 + ~CustomCurve(); // 0x36D7D0 + + // Table lookup of x in [min, max] (asserts outside), linearly interpolated when asked. + float calculate(float x, bool interpolate) const; // 0x36D800 + float testAccuracy(float density, bool interpolate) const; + bool testBounds(float density, float minimum, float maximum) const; + void accuracyTest(float density) const; + void getStatistics(float density, float minimum, float maximum, int flags) const; + float calculateEstimation(float value, bool& nonnegative) const; + + // Weak in BBFire.cpp (0x20BAB0): powf(2x - 0.95, 21) * 1.012 + 1. + static float modifiedSoftStepFunc(float x); + +private: + CustomCurve(const CustomCurve&); // 0x36D680 + CustomCurve operator=(const CustomCurve&); // 0x36D720: returns a resampled copy by value + + void init(); // 0x36DFB0 + + /* +0x00 */ Function m_function; + /* +0x04 */ float* m_table; // m_size + 1 samples + /* +0x08 */ int m_size; + /* +0x0C */ float m_min; + /* +0x10 */ float m_max; + /* +0x14 */ float m_step; +}; + +inline float CustomCurve::modifiedSoftStepFunc(float x) +{ + return std::pow(x + x - 0.95f, 21.0f) * 1.012f + 1.0f; +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp index 443ab2095..028364e51 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp @@ -1,6 +1,10 @@ // [INFERRED] Source placement. #include "UrgeCurve.h" +#include +// Original UCLinear.cpp and UCXInverse.cpp are combined here; both only initialized iostreams. +// static init: ELF 0x226350, 0x2263B0, 0x2263E0 +// static init: ELF 0x226530, 0x226590, 0x2265C0 #include // std::max - see the argument-order note in the header diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp index 50b9a8cc3..a25e41e3f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp @@ -1,10 +1,11 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining UrgencyMerger operations. +// static init: ELF 0x1B5CD0 (__tcf_0 0x1B5D30, _GLOBAL__I 0x1B5D60): 's Init object only. +#include + #include "UrgencyMerger.h" -#include "../Main/AIDllFrontier.h" namespace dice { namespace hfe { @@ -27,58 +28,104 @@ UrgencyMerger::UrgencyMerger(int count, float* weights, UrgencyGenerator** gener { } +// ELF 0x1B5930: only the vptr store; the generators belong to the caller. UrgencyMerger::~UrgencyMerger() { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::~UrgencyMerger"); } -// [FRONTIER] Bot-specific urgency and modifier operations remain unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when the corresponding merger behavior is recovered. - -float UrgencyMerger::getUrgency(Bot*) +// ELF 0x1B59B0. The chosen generator's urgency, 0 when none is chosen. +float UrgencyMerger::getUrgency(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getUrgency"); + if (m_chosen == 0) + return 0.0f; + return m_chosen->getUrgency(bot); } -float UrgencyMerger::getActiveUrgency(Bot*) +// ELF 0x1B5A00. +float UrgencyMerger::getActiveUrgency(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getActiveUrgency"); + if (m_chosen == 0) + return 0.0f; + return m_chosen->getActiveUrgency(bot); } -void UrgencyMerger::updateActiveUrgency(Bot*) +// ELF 0x1B5A40. Updates every generator; the strictly most urgent one's own chosen generator +// becomes this merger's. Returns that urgency (0 when none is positive). The weights are not read. +float UrgencyMerger::updateActiveUrgency(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::updateActiveUrgency"); + float best = 0.0f; + m_chosen = 0; + for (int i = 0; i < m_count; ++i) + { + const float urgency = + m_generators[i] != 0 ? m_generators[i]->updateActiveUrgency(bot) : 0.0f; + if (urgency > best) + { + best = urgency; + m_chosen = m_generators[i]->getChosenGenerator(); + } + } + return best; } -bool UrgencyMerger::hasChangedTarget(Bot*) +// ELF 0x1B5AF0. True while every present generator reports a changed target (stops at the first +// that does not); true with no generators. +bool UrgencyMerger::hasChangedTarget(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::hasChangedTarget"); + bool changed = true; + for (int i = 0; i < m_count && changed; ++i) + { + if (m_generators[i] != 0) + changed = m_generators[i]->hasChangedTarget(bot); + } + return changed; } -bool UrgencyMerger::quotientChanged(Bot*, float, float) +// ELF 0x1B5B60. The same conjunction over quotientChanged. +bool UrgencyMerger::quotientChanged(Bot* bot, float lower, float upper) { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::quotientChanged"); + bool changed = true; + for (int i = 0; i < m_count && changed; ++i) + { + if (m_generators[i] != 0) + changed = m_generators[i]->quotientChanged(bot, lower, upper); + } + return changed; } -bool UrgencyMerger::hasChanged(Bot*, float, float) +// ELF 0x1B5BE0. True as soon as one present generator's quotient or target changed. +bool UrgencyMerger::hasChanged(Bot* bot, float lower, float upper) { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::hasChanged"); + bool changed = false; + for (int i = 0; i < m_count && !changed; ++i) + { + if (m_generators[i] != 0) + changed = m_generators[i]->quotientChanged(bot, lower, upper) || + m_generators[i]->hasChangedTarget(bot); + } + return changed; } +// ELF 0x1A2850. UrgencyGenerator* UrgencyMerger::getChosenGenerator() { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getChosenGenerator"); + return m_chosen; } -void UrgencyMerger::reset(Bot*) +// ELF 0x1B5C80. Resets every present generator. +void UrgencyMerger::reset(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::reset"); + for (int i = 0; i < m_count; ++i) + { + if (m_generators[i] != 0) + m_generators[i]->reset(bot); + } } +// ELF 0x1B59F0. int UrgencyMerger::getSize() { - BF2_AI_FRONTIER("dice::hfe::ai::UrgencyMerger::getSize"); + return m_count; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h index d9f6dba58..128d4367d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h @@ -1,5 +1,4 @@ // Combines per-behavior urgency generators for a bot. -// [FRONTIER] Remaining merger behavior requires implementation. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_URGENCYMERGER_H // [INFERRED] guard style @@ -11,7 +10,9 @@ namespace ai { class Bot; -// UrgencyGenerator - the abstract base. vtable off_4B6E88: , , then nine pure virtuals. +// UrgencyGenerator - the abstract base. vtable ELF 0x4B6E80: the two destructors, then eight pure +// virtuals (+0x08..+0x24). Slot +0x28 belongs to the subclasses: UrgencyMerger's getSize, a +// different pure virtual in BotBehaviour. // Its destructor body is one instruction - the vptr store C++ emits - so the class // owns nothing. It is an interface with a virtual destructor and no state. class UrgencyGenerator @@ -21,13 +22,12 @@ class UrgencyGenerator virtual float getUrgency(Bot* bot) = 0; // +0x08 virtual float getActiveUrgency(Bot* bot) = 0; // +0x0C - virtual void updateActiveUrgency(Bot* bot) = 0; // +0x10 + virtual float updateActiveUrgency(Bot* bot) = 0; // +0x10 virtual bool hasChangedTarget(Bot* bot) = 0; // +0x14 virtual bool quotientChanged(Bot* bot, float a, float b) = 0; // +0x18 virtual bool hasChanged(Bot* bot, float a, float b) = 0; // +0x1C virtual UrgencyGenerator* getChosenGenerator() = 0; // +0x20 virtual void reset(Bot* bot) = 0; // +0x24 - virtual int getSize() = 0; // +0x28 }; // UrgencyMerger - (`operator new(0x14)` in BotManager's loop). @@ -40,20 +40,21 @@ class UrgencyMerger : public UrgencyGenerator virtual float getUrgency(Bot* bot); virtual float getActiveUrgency(Bot* bot); - virtual void updateActiveUrgency(Bot* bot); + virtual float updateActiveUrgency(Bot* bot); virtual bool hasChangedTarget(Bot* bot); virtual bool quotientChanged(Bot* bot, float a, float b); virtual bool hasChanged(Bot* bot, float a, float b); virtual UrgencyGenerator* getChosenGenerator(); virtual void reset(Bot* bot); - virtual int getSize(); + virtual int getSize(); // +0x28, introduced here -private: +protected: + // RandomSquareMerger (AIBot/RandomSquareMerger.cpp) reads every field. /* 0 */ // vptr - off_4B6E48 /* 4 */ int m_count; // the generator count; getSize returns it /* 8 */ float* m_weights; // null from BotManager's pool /* 12 */ UrgencyGenerator** m_generators; - /* 16 */ void* m_chosen; // = 0 [INFERRED] from getChosenGenerator's offset + /* 16 */ UrgencyGenerator* m_chosen; // = 0; the winner of the last updateActiveUrgency }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp new file mode 100644 index 000000000..f2f911011 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp @@ -0,0 +1,680 @@ +// VehicleUrgencyCalculator: libaidll.so TU VehicleUrgencyCalculator.cpp (0x2265E0..0x228EF0), the +// vehicle scoring behind BBChange (which vehicle / seat a bot should take). Recovered by ai-bot +// (coordinator assignment 2026-11-01) from the ELF bodies; the strength rows are IPIUnit +8 +// (getBattleStrengths), indexed by the IPIPhysical strength type (vtable +0x44). + +// static init: ELF 0x228E60 (__tcf_0 0x228EC0, _GLOBAL__I 0x228EF0): 's Init object only. +#include + +#include "VehicleUrgencyCalculator.h" + +#include +#include +#include +#include +#include + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/AIObjectUnit.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +const int kMaxStrengths = 64; // [CHOSEN] stack row size (the image's frame holds 15 / 83 floats) + +Information* infoOf(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +int strengthCount() +{ + return static_cast(CommonSingletonServer::m_iaiSettings)->getNBattleStrengths(); +} + +// The bot's soldier's information for `side` (Bot +0xBC getPlayer, IAIPlayer +0x4C getSoldier, +// IAIObject +0xB8 getInformation). +Information* soldierInfo(Bot* bot, int side) +{ + return infoOf(bot->getPlayer()->getSoldier()->getInformation(side)); +} + +// The inline Vec3 normalisation: unchanged within FLT_EPSILON of unit length; false (left as is) +// within FLT_EPSILON of zero, where the image skips the camera test. +bool normalise(Vec3& v) +{ + const float lengthSq = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSq - 1.0f) < 1.1920929e-07f) + return true; + if (std::fabs(lengthSq) < 1.1920929e-07f) + return false; + const float inverse = 1.0f / std::sqrt(lengthSq); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; + return true; +} + +// The armament's weapon range envelope: max of the maximum ranges (from 50), min of the minimum +// ranges (from 0.1); `guided` when any weapon has a guidance type. +void weaponRanges(IPIArmament* armament, float& maxRange, float& minRange, bool* guided) +{ + std::vector& weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + if (guided && weapon->getWeaponGuidanceType() != 0) + *guided = true; + const float maxR = weapon->getMaxRange(); + const float minR = weapon->getMinRange(); + if (maxRange < maxR) + maxRange = maxR; + if (minR < minRange) + minRange = minR; + } +} + +// The occupied seats' fire strength added to `strengths`: 0.4 of the primary object's row when it +// is occupied, plus `share` (0.4; 0.9 for an unarmed primary) of every occupied secondary's row. +// Inline in calculateVehicleFireUrgency and calculateFireStrength. +void addSeatStrengths(float* strengths, int n, Information* vehicle, int side, bool flag, + Information* current) +{ + Information* primary; + float share = 0.4f; + if (!vehicle->isPrimary()) + { + primary = infoOf(vehicle->getPrimaryObject(side)); + IPIUnit* const unit = primary->getUnit(); + if ((primary != current || !flag) && unit->isOccupied()) + { + for (int i = 0; i < n; ++i) + strengths[i] = unit->getBattleStrengths()[i] * 0.4f + strengths[i]; + } + } + else + { + primary = vehicle; + if (!vehicle->hasArmament()) + share = 0.9f; + } + int iterator; + Information* secondary = infoOf(primary->getFirstSecondaryObject(iterator, side)); + while (secondary) + { + if (secondary != vehicle) + { + IPIUnit* const unit = secondary->getUnit(); + if ((secondary != current || !flag) && unit->isOccupied()) + { + for (int i = 0; i < n; ++i) + strengths[i] = share * unit->getBattleStrengths()[i] + strengths[i]; + } + } + secondary = infoOf(primary->getSecondaryObject(iterator, side)); + } +} + +bool closeAndShouldAvoidVehiclesImpl(Information* vehicle, int side, Bot* bot); + +// [CHOSEN, not recovered] No GNU unused attribute: these external helpers also compile on MSVC. +// ELF 0x226C90 (no caller in the image): sum over six components of a*b (b where a is 0), x0.25. +float sqrDistance(const float* a, const float* b) +{ + float sum = 0.0f; + for (int i = 0; i < 6; ++i) + sum = sum + (a[i] != 0.0f ? a[i] * b[i] : b[i]); + return sum * 0.25f; +} + +// ELF 0x226CF0 (no caller in the image): 1 / the (larger, when `both`) strength, capped at 10. +float vulnerability(const float* strengths, int type, bool both, int other) +{ + float s = strengths[type]; + if (both && !(strengths[other] <= strengths[type])) + s = strengths[other]; + if (s == 0.0f) + return 10.0f; + const float inverse = 1.0f / s; + return 10.0f < inverse ? 10.0f : inverse; +} + +// ELF 0x226D60 (no caller in the image): the squared strongest seat strength against an enemy +// type with weight > 0, minus the enemy's strength against the vehicle (and its exposed soldier). +float calculateVehicleFireUrgency(Bot* bot, Information* vehicle, + const float* enemyStrengths, const float* weights, + int, bool flag, Information* current, int side) +{ + const int n = strengthCount(); + IPIUnit* const unit = vehicle->getUnit(); + const int ownType = vehicle->getPhysical()->getStrengthType(); + const bool exposed = unit->hasExposedSoldier(); + if (closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + return 0.0f; + int soldierType = 0; + if (exposed) + soldierType = soldierInfo(bot, side)->getPhysical()->getStrengthType(); + const bool usable = vehicle != current || !flag; + float strengths[kMaxStrengths]; + for (int i = 0; i < n; ++i) + strengths[i] = usable ? unit->getBattleStrengths()[i] : 0.0f; + addSeatStrengths(strengths, n, vehicle, side, flag, current); + float best = 0.0f; + for (int i = 0; i < n; ++i) + { + if (0.0f < weights[i]) + { + const float sq = strengths[i] * strengths[i]; + if (best < sq) + best = sq; + } + } + if (!exposed) + return best - enemyStrengths[ownType]; + const float threat = enemyStrengths[soldierType] <= enemyStrengths[ownType] ? enemyStrengths[ownType] + : enemyStrengths[soldierType]; + return best - threat; +} + +// ELF 0x227150. Vehicles the bot should avoid are worth nothing. A primary mobile vehicle: max +// speed x5. A seat of a mobile primary: an empty primary is worth x4 faded over the 15 s after a +// player of this side last possessed it (0 otherwise); a primary a bot drives x2.5 when that bot +// is ordered elsewhere than this one (SAI +0xB8 getBotOrderedPos), else x4. +float calculateVehicleMoveUrgency(Information* vehicle, int side, Bot* bot, bool flag, Information* current) +{ + if (closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + return 0.0f; + const unsigned int botId = bot->getBotId(); + if (!vehicle->isPrimary()) + { + Information* const primary = infoOf(vehicle->getPrimaryObject(side)); + IPIMobile* const mobile = primary->getMobile(); + if (mobile && (primary != current || !flag)) + { + IPIUnit* const unit = primary->getUnit(); + if (!unit->isOccupied()) + { + float urgency = 0.0f; + if (primary->getSide() == side) + { + const double now = + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double since = now - unit->getLastPlayerPossesionTime(); + if (since < 15.0) + urgency = (1.0f - static_cast(since / 15.0)) * (mobile->getMaxSpeed() * 4.0f); + } + return urgency; + } + Bot* const driver = IBotManager::instance->getBot(primary->getAIObject()); + SAI* const sai = IAIMain::m_instance->getSAI(side); + if (driver) + { + const int mine = sai->getBotOrderedPos(botId); + if (mine != sai->getBotOrderedPos(driver->getBotId())) + return mobile->getMaxSpeed() * 2.5f; + } + return mobile->getMaxSpeed() * 4.0f; + } + } + else if (vehicle->getMobile()) + { + return vehicle->getMobile()->getMaxSpeed() * 5.0f; + } + return 0.0f; +} + +// ELF 0x2273B0 (1814 instructions). The fire value of taking `vehicle`: +// * a static emplacement without guided or anti-aircraft weapons is worth nothing beyond 12 m / 2 m +// of height of the current equipment; +// * with sensed objects: the best sided target (static: within weapon range, not an indirect sighting +// younger than 20 s) the seat out-guns the current equipment against, s^2 minus the target's +// strength against the vehicle; x4 unless the vehicle should be avoided; no target engaged in a +// driven vehicle falls back to the raw value; +// * nothing sensed, undriven: the best enemy object in weapon range (validity test as above); no +// enemy at all: 0 unless no neighbouring area of the bot's ordered area is in camera reach; +// * the raw value (fallback): the best weighted row strength minus the threat. +float calculateFireStrength(Bot* bot, Information* vehicle, int side, const float* enemyStrengths, + const float* weights, bool flag, Information* current) +{ + const std::map& sensed = bot->getSensedObjects(); + const int n = strengthCount(); + float fireThreat = 0.0f; + bool engaged = false; + const Vec3& position = vehicle->getPosition(); + float maxRange = 50.0f; + IPIUnit* const unit = vehicle->getUnit(); + float minRange = 0.1f; + IPIPhysical* const physical = vehicle->getPhysical(); + IPIControlInfo* const control = vehicle->getControlInfo(); + IPIArmament* armament = vehicle->getArmament(); + + bool skipProximity = false; + if (armament) + { + const int antiAircraft = armament->isAntiAircraft(); + bool guided = false; + weaponRanges(armament, maxRange, minRange, &guided); + skipProximity = guided || antiAircraft == 1; + } + if (!skipProximity && vehicle->isPrimary() && !vehicle->hasMobile()) + { + const Vec3& here = current->getPosition(); + const float dx = position.x - here.x; + const float dy = position.y - here.y; + const float dz = position.z - here.z; + if (144.0f < dx * dx + dy * dy + dz * dz + || 2.0f < std::fabs(current->getPosition().y - position.y)) + return 0.0f; + } + + const bool usable = vehicle != current || !flag; + IPIMobile* driven; // -0x1D8: the mobile of the vehicle / a manned primary + bool noMobile; // -0x1F1 + if (!vehicle->isPrimary()) + { + Information* const primary = infoOf(vehicle->getPrimaryObject(bot->getSide())); + if (!primary->getUnit() || current == primary || !primary->getUnit()->isOccupied()) + { + noMobile = true; + driven = 0; + } + else + { + driven = primary->getMobile(); + noMobile = false; + } + } + else + { + driven = vehicle->getMobile(); + noMobile = driven == 0; + } + const int ownType = physical->getStrengthType(); + const bool exposed = unit->hasExposedSoldier(); + int soldierType = 0; + if (exposed) + soldierType = soldierInfo(bot, side)->getPhysical()->getStrengthType(); + + // A seat that must borrow the soldier's weapons scores with the soldier's row and ranges. + IAIObject* const object = vehicle->getAIObject(); + IPIUnit* strengthUnit = unit; + if (usable && object->getUnit()->mustBorrowArmament(object)) + { + Information* const soldier = soldierInfo(bot, side); + maxRange = 50.0f; + strengthUnit = soldier->getUnit(); + minRange = 0.1f; + armament = soldier->getArmament(); + if (armament) + weaponRanges(armament, maxRange, minRange, 0); + } + float strengths[kMaxStrengths]; + for (int i = 0; i < n; ++i) + strengths[i] = usable ? strengthUnit->getBattleStrengths()[i] : 0.0f; + addSeatStrengths(strengths, n, vehicle, side, flag, current); + + if (sensed.empty()) + { + if (driven == 0) + { + float reach = 0.0f; + if (!armament && !object->getUnit()->mustBorrowArmament(object)) + return 0.0f; + if (!armament) + armament = soldierInfo(bot, side)->getArmament(); + const std::vector weapons = armament->getWeapons(); + for (unsigned int i = 0; i < weapons.size(); ++i) + { + if (weapons[i] == 0xFFFFFFFFu) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + const float r = weapon->getMaxRange(); + if (reach < r) + reach = r; + } + std::vector objects; + static_cast(AISingletonServer::m_iaiInformationEnvironment) + ->getEnemyObjects(objects, bot, reach); + float value = 0.0f; + float best = 0.0f; + if (!objects.empty()) + { + for (unsigned int k = 0; k < objects.size(); ++k) + { + Information* const target = infoOf(objects[k]); + if (!target) + continue; + const Vec3& p = target->getPosition(); + const float dx = p.x - position.x; + const float dy = p.y - position.y; + const float dz = p.z - position.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (!(distance <= maxRange && minRange <= distance)) + continue; + IPIUnit* const targetUnit = target->getUnit(); + IPIPhysical* const targetPhysical = + target->isPrimary() ? target->getPhysical() + : infoOf(target->getPrimaryObject(side))->getPhysical(); + if (!targetUnit || !targetPhysical) + continue; + bool valid = false; + Vec3 direction; + direction.x = target->getPosition().x - position.x; + direction.y = target->getPosition().y - position.y; + direction.z = target->getPosition().z - position.z; + if (normalise(direction) && control->validateCameraDirection(direction)) + valid = true; + // 0x227D1D..0x227D5E: the same row entry compared with itself - taken unless NaN. + const float s = strengths[targetPhysical->getStrengthType()]; + if ((valid && s > strengths[targetPhysical->getStrengthType()]) + || s == strengths[targetPhysical->getStrengthType()]) + { + const float* const theirs = targetUnit->getBattleStrengths(); + if (!exposed) + value = s * s - theirs[ownType]; + else + value = s * s - (theirs[soldierType] <= theirs[ownType] ? theirs[ownType] + : theirs[soldierType]); + } + if (best < value) + best = value; + } + return best; + } + // No enemy in reach: the bot's ordered area (SAI +0xB8; looked up with -1 only when the + // current one, +0xB4, is -1 too). + SAI* const sai = IAIMain::m_instance->getSAI(side); + const int ordered = sai->getBotOrderedPos(bot->getBotId()); + if (ordered != -1 || sai->getBotCurrentPos(bot->getBotId()) == -1) + { + AIStrategicObject* const area = AIStrategicObjectManager::getInstance()->getStrategicObject(ordered); + if (area) + { + const Vec2 from = area->getPosition(side); + const std::vector& neighbours = + static_cast(area)->m_neighbours; // +0x11C + for (unsigned int k = 0; k < neighbours.size(); ++k) + { + AIStrategicObject* const neighbour = neighbours[k]; + if (static_cast(neighbour->getStatus(side)) == 0) + continue; + const Vec2& to = neighbour->getPosition(side); + Vec2 offset; + offset.x = to.x - from.x; + offset.y = to.y - from.y; + Vec3 direction; + direction.x = 0.0f; + direction.y = 0.0f; + direction.z = 0.0f; + vec2ToVec3XZ(offset, direction); + if (normalise(direction) && control->validateCameraDirection(direction)) + noMobile = false; + } + } + } + if (!noMobile) + return 0.0f; + } + } + else + { + bool valid = true; + float best = 0.0f; + IPIUnit* const currentUnit = current->getUnit(); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + for (std::map::const_iterator it = sensed.begin(); it != sensed.end(); ++it) + { + Information* const target = infoOf(it->first); + const SensedObject* const record = it->second; + if (!target || (record->m_flags & SensedObject::SENSE_SIDED) == 0) + continue; + if (!vehicle->hasMobile() && armament) + { + const Vec3& p = target->getPosition(); + const float dx = p.x - position.x; + const float dy = p.y - position.y; + const float dz = p.z - position.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (maxRange < distance || distance < minRange + || ((record->m_flags & SensedObject::SENSE_INDIRECT) && now < record->m_firstSeenTime + 20.0)) + continue; + } + IPIUnit* const targetUnit = target->getUnit(); + IPIPhysical* const targetPhysical = + target->isPrimary() ? target->getPhysical() : infoOf(target->getPrimaryObject(side))->getPhysical(); + if (!targetUnit || !targetPhysical) + continue; + if (driven == 0) + { + valid = false; + Vec3 direction; + direction.x = target->getPosition().x - position.x; + direction.y = target->getPosition().y - position.y; + direction.z = target->getPosition().z - position.z; + if (normalise(direction) && control->validateCameraDirection(direction)) + { + noMobile = false; + valid = true; + } + } + const int type = targetPhysical->getStrengthType(); + const float s = strengths[type]; + float value = 0.0f; + if (valid && currentUnit->getBattleStrengths()[type] <= unit->getBattleStrengths()[type]) + { + engaged = true; + const float* const theirs = targetUnit->getBattleStrengths(); + if (!exposed) + value = s * s - theirs[ownType]; + else + value = s * s - (theirs[soldierType] <= theirs[ownType] ? theirs[ownType] : theirs[soldierType]); + } + if (value <= best) + value = best; + best = value; + } + + // The strongest incoming fire against the vehicle's type, over a copy of the list (the image's + // sensed-object find and the two side reads per entry have no effect). + const std::list > fire = *bot->getIncommingFire(); + for (std::list >::const_iterator it = fire.begin(); it != fire.end(); ++it) + { + const float strength = it->first->getBattleStrength(ownType); + if (fireThreat < strength) + fireThreat = strength; + } + if (driven != 0 || !noMobile) + { + if (!(!engaged && driven != 0)) + { + if (!closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + return best * 4.0f; + return 0.0f; + } + // not engaged in a driven vehicle: the raw value below + } + else + { + return 0.0f; + } + } + + // The raw fire value: the best weighted strength (x6 for weights <= 0.5, else x3 x weight; a + // running maximum) against an enemy type with weight > 0, minus the threat to the vehicle. + if ((!vehicle->isPrimary() || vehicle->hasMobile()) && !closeAndShouldAvoidVehiclesImpl(vehicle, side, bot)) + { + float best = 0.0f; + float running = 0.0f; + for (int i = 0; i < n; ++i) + { + const float w = weights[i]; + float v = w <= 0.5f ? strengths[i] * 6.0f : strengths[i] * 3.0f * w; + if (v <= running) + v = running; + if (0.0f < w && best < v) + best = v; + running = v; + } + if (best <= 0.0f) + return running; + float threat; + if (!exposed) + threat = fireThreat + enemyStrengths[ownType]; + else + threat = (enemyStrengths[soldierType] <= enemyStrengths[ownType] ? enemyStrengths[ownType] + : enemyStrengths[soldierType]) + + fireThreat; + return best - threat; + } + return 0.0f; +} + +// ELF 0x2265E0. A ground vehicle (primary not a soldier, not flags 0x10 / 0x20) while the bot's +// squad holds a takeable area whose order position is outside its control point radius: avoided +// when the bot already uses it (same primary) within 25 m of the order position (unless the bot +// is in an armed primary and the side's SAI has owned control points, +0x74), or when the vehicle +// or the squad is within 70 m of the control point. +bool closeAndShouldAvoidVehiclesImpl(Information* vehicle, int side, Bot* bot) +{ + bool avoid = false; + Information* const primary = infoOf(vehicle->getPrimaryObject(side)); + const unsigned int flags = primary->getObjectTypeFlags(); + if ((flags & 0x200000u) || (flags & 0x10u) || (flags & 0x20u)) + return false; + IPIMobile* const mobile = primary->getMobile(); + AIStrategicArea* const area = bot->getSquadMember()->getSquad()->getSquadStrategicAreaAssignment(); + if (!area || !area->isAreaTakeable() || !mobile) + return false; + if (!area->isOrderPosOutsideCpRadius(mobile->getVehicleNumber(), side)) + return false; + Vec3 squad; + squad.x = 0.0f; + squad.y = 0.0f; + squad.z = 0.0f; + if (!bot->getSquadMember()->getPosition(squad)) + return false; + Information* const equipment = infoOf(bot->getCurrentEquipment()); + if (equipment->getPrimaryObject(side) == primary->getPrimaryObject(side)) + { + const Vec3 order = area->getOrderPos(mobile->getVehicleNumber(), side); + const float dx = squad.x - order.x; + const float dy = squad.y - order.y; + const float dz = squad.z - order.z; + if (dx * dx + dy * dy + dz * dz < 625.0f) + { + avoid = true; + if (equipment->isPrimary() && equipment->hasArmament() + && IAIMain::m_instance->getSAI(side)->haveAnyOwnedCps(side)) + avoid = false; + } + } + else + { + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + float radius = 1.0f; + bool active; + static_cast(CommonSingletonServer::m_iaiGame) + ->getControlPointInfo(area->m_controlPointId, centre, radius, active); + const Vec3& p = primary->getPosition(); + if ((p.z - centre.z) * (p.z - centre.z) + (p.x - centre.x) * (p.x - centre.x) + + (p.y - centre.y) * (p.y - centre.y) < 4900.0f + || (centre.x - squad.x) * (centre.x - squad.x) + (centre.y - squad.y) * (centre.y - squad.y) + + (centre.z - squad.z) * (centre.z - squad.z) < 4900.0f) + avoid = true; + } + return avoid; +} + +} // namespace + +// ELF 0x2265E0. +bool closeAndShouldAvoidVehicles(Information* vehicle, int side, Bot* bot) +{ + return closeAndShouldAvoidVehiclesImpl(vehicle, side, bot); +} + +// ELF 0x2269E0 (static double allowedTimeDiff = 15.0 at 0x4BB688). Nothing for a vehicle booked by +// another player, more than 8 m above ground (unless flag 0x10 or the current one), occupied (with +// `flag`) or not team-locked to the side. Otherwise fire + move value (+ 4 x the strength when +// above 0.01), scaled by health when it is at least the bail value (x0.3 for the current primary; +// soldiers always), and faded over 15 s after the side last possessed it. The two floats are unread. +float calculateVehicleUrgency(Bot* bot, Information* vehicle, const float* strengths, const float* weights, + bool flag, Information* current, float, float, int side) +{ + static double allowedTimeDiff = 15.0; + + IPIPhysical* const physical = vehicle->getPhysical(); + IPIUnit* const unit = vehicle->getUnit(); + if (vehicle->isBooked() && !vehicle->isBookedBy(bot->getPlayerId())) + return 0.0f; + if (vehicle != current && (vehicle->getObjectTypeFlags() & 0x10u) == 0) + { + if (8.0f < static_cast(CommonSingletonServer::m_iaiTerrain) + ->getAltitude(vehicle->getPosition())) + return 0.0f; + } + if ((flag && unit->isOccupied()) || !unit->isTeamLocked(side)) + return 0.0f; + const float fire = calculateFireStrength(bot, vehicle, side, strengths, weights, flag, current); + const float move = calculateVehicleMoveUrgency(vehicle, side, bot, flag, current); + float urgency = move + fire; + if (0.01f < urgency) + urgency = vehicle->getStrength() * 4.0f + urgency; + const float health = physical->getHealth(); + float bail = IBotManager::instance->getVehicleBailValue(); + if ((vehicle->getObjectTypeFlags() & 0x200000u) == 0 && vehicle->isPrimary() + && vehicle->getHandle() == current->getHandle()) + bail = bail * 0.3f; + if (!(bail <= health) && (vehicle->getObjectTypeFlags() & 0x200000u) == 0) + return 0.0f; + urgency = urgency * health; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (vehicle->getSide() == side) + { + const double since = now - unit->getLastPlayerPossesionTime(); + if (since < allowedTimeDiff) + urgency = static_cast(1.0 / allowedTimeDiff * since) * urgency; + } + return urgency; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.h new file mode 100644 index 000000000..39c7a743a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.h @@ -0,0 +1,28 @@ +// Vehicle urgency helpers shared by the change/enter-vehicle behaviours (BBChange). Package A-core +// (docs/macos-ai-behaviour-plan.md); TU VehicleUrgencyCalculator.cpp, libaidll.so 0x2265E0..0x228EF0. +// The image has no header symbol; the free functions are in namespace dice::hfe::ai. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_VEHICLEURGENCYCALCULATOR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOUR_VEHICLEURGENCYCALCULATOR_H + +namespace dice { +namespace hfe { +namespace ai { + +class Bot; +class Information; + +// ELF 0x2265E0 (318 instructions; returns `al`). +bool closeAndShouldAvoidVehicles(Information* vehicle, int side, Bot* bot); + +// ELF 0x2269E0 (175 instructions; x87 float return). Callers: BBChange (9 sites, 0x20096F..0x202C7C). +// The two `const float*` are per-weapon-class rows indexed by IAISettings slot +0x34 counts; +// [UNRESOLVED] parameter names. +float calculateVehicleUrgency(Bot* bot, Information* vehicle, const float* strengths, const float* weights, + bool flag, Information* current, float a, float b, int side); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOUR_VEHICLEURGENCYCALCULATOR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp new file mode 100644 index 000000000..f61ceee82 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp @@ -0,0 +1,46 @@ +// Base of the avoid-collision patterns (BBPAvoidCollisionInfantery, BBPAvoidCollision2d, 3d): the +// per-bot arrays their init (slot +0x18) fills from BBAvoid's calculateUrgency. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x2297F0 (__tcf_0 0x229850, _GLOBAL__I 0x229880): 's Init object only. +#include + +#include "BBPAvoidCollision.h" + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x229090 (C2) / 0x229440 (C1). One getMaxNBots (IAISettings slot 0) sizes all three arrays: +// +0x0C new[n] of 4 bytes, +0x10 new[n * 12] with every Vec3 zeroed (rodata 0x49CB34) before the +// check, +0x14 new[n] of 4 bytes; each is checkPointer'd. +0x08 is left to the subclasses. +BBPAvoidCollision::BBPAvoidCollision() + : BBPPattern() +{ + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_obstacle = checkPointer(new unsigned int[count]); + m_relativeSpeed = checkPointer(new Vec3[count]()); + m_value = checkPointer(new float[count]); +} + +// ELF 0x228F10 (D2) / 0x228F90 (D1) / 0x229010 (D0): delete[] +0x0C, +0x10, +0x14 when set, then +// ~BBPPattern. +BBPAvoidCollision::~BBPAvoidCollision() +{ + if (m_obstacle) + delete[] m_obstacle; + if (m_relativeSpeed) + delete[] m_relativeSpeed; + if (m_value) + delete[] m_value; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.h new file mode 100644 index 000000000..8214154a9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BB6A0 (7 words), package F-infantry. sizeof 0x18 (BBPAvoidCollisionInfantery's +// own members start at +0x18). The per-bot arrays are what init (slot +0x18) stores; BBAvoid's +// calculateUrgency passes (bot, collision point, obstacle handle, relative speed, time to +// collision) or zero vectors and a flee strength. +class BBPAvoidCollision : public BBPPattern +{ +public: + BBPAvoidCollision(); // 0x229440 + virtual ~BBPAvoidCollision(); // 0x228F90 + + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float) = 0; // no body, slot +0x18; void: BBPAvoidCollisionInfantery::init 0x22C870 sets no result register + +protected: + /* +0x08 */ int m_id; // not written here; the concrete constructors store their argument + /* +0x0C */ unsigned int* m_obstacle; // per bot: init's handle [INFERRED] name + /* +0x10 */ Vec3* m_relativeSpeed; // per bot, zeroed: init's second Vec3 [INFERRED] name + /* +0x14 */ float* m_value; // per bot: init's float (time to collision or flee strength) [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp new file mode 100644 index 000000000..a1e69e556 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp @@ -0,0 +1,192 @@ +// Vehicle collision-avoidance plans, recovered from libaidll.so. + +// static init: ELF 0x22AFD0 (__tcf_0 0x22B030, _GLOBAL__I 0x22B060): 's Init object only. +#include + +#include "BBPAvoidCollision2d.h" + +#include "../AIUtils/checkPointer.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAHonkHorn.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" +#include "../../../../Math/Mat4.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x229AD0: BBPAvoidCollision(), the vtable store (GOT -0xF48 + 8), the argument at +0x08, +// then `new Vec2[getMaxNBots()]` (IAISettings slot 0; 8 bytes each, both words zeroed from the +// 0.0f constant) through the inlined checkPointer (Debug type 6, line 46) into +0x1C. The same +// body as BBPAvoidCollisionInfantery's. +BBPAvoidCollision2d::BBPAvoidCollision2d(int id) + : BBPAvoidCollision() +{ + m_id = id; + m_pointXZ = checkPointer(new Vec2[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); +} + +// ELF 0x229C70 (D2) / 0x229CC0 (D1) / 0x229D10 (D0): delete[] +0x1C when set, then +// ~BBPAvoidCollision. +BBPAvoidCollision2d::~BBPAvoidCollision2d() +{ + if (m_pointXZ) + delete[] m_pointXZ; +} + +// ELF 0x229E20 +BotScript* BBPAvoidCollision2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + const unsigned int obstacleHandle = m_obstacle[bot->getBotId()]; + Information* obstacle = informationManager->getInformation(obstacleHandle); + if (!obstacle) + return 0; + IPIMobile* obstacleMobile = obstacle->getMobile(); + if (!obstacleMobile) + return 0; + const float time = m_value[bot->getBotId()]; + const Vec2 collisionPoint = m_pointXZ[bot->getBotId()]; + const Vec3 relativeSpeed = m_relativeSpeed[bot->getBotId()]; + (void)collisionPoint; + (void)relativeSpeed; + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile = self->getMobile(); + IPIControlInfo* controls = self->getControlInfo(); + const Vec3& position = self->getPosition(); + const Vec2 ownXZ = {position.x, position.z}; + const Vec3& obstaclePosition = obstacle->getPosition(); + const Vec2 obstacleXZ = {obstaclePosition.x, obstaclePosition.z}; + Vec2 velocity; + velocity.x = mobile->getSpeed().x; + velocity.y = mobile->getSpeed().z; + if (velocity.x * velocity.x + velocity.y * velocity.y == 0.0f) + { + velocity.x = self->getTransformation().m[8]; + velocity.y = self->getTransformation().m[10]; + } + Vec2 obstacleVelocity; + obstacleVelocity.x = obstacleMobile->getSpeed().x; + obstacleVelocity.y = obstacleMobile->getSpeed().z; + const float obstacleSpeed = std::sqrt(obstacleVelocity.x * obstacleVelocity.x + + obstacleVelocity.y * obstacleVelocity.y); + Vec2 unusedDirection = obstacleVelocity; + if (obstacleSpeed > 0.0001f) + { + const float inverse = 1.0f / obstacleSpeed; + unusedDirection.x *= inverse; + unusedDirection.y *= inverse; + } + (void)unusedDirection; + Vec2 direction = velocity; + vehiclecontrol::normalizeVec2(direction); + const float dx = obstacleXZ.x - ownXZ.x; + const float dy = obstacleXZ.y - ownXZ.y; + const float ahead = velocity.x * dx + velocity.y * dy; + const float across = direction.y * dx - direction.x * dy; + const float side = obstacleSpeed > 5.0f ? (ahead > 0.0f ? 1.0f : -1.0f) + : (across < 0.0f ? 1.0f : -1.0f); + const float ownRadius = self->getPhysical()->getRadius(); + const float obstacleRadius = obstacle->getPhysical()->getRadius(); + const Mat4& transformation = self->getTransformation(); + const Vec3 offset = {side * transformation.m[0], side * transformation.m[1], side * transformation.m[2]}; + const float radius = ownRadius + obstacleRadius; + Vec3 target = {radius * offset.x + obstaclePosition.x, + radius * offset.y + obstaclePosition.y, + radius * offset.z + obstaclePosition.z}; + BotNavigation* navigation = bot->getBotNavigation(); + Vec3 hit = {0.0f, 0.0f, 0.0f}; + if (navigation->m_infantryPolygon == -1) + return 0; + unsigned int polygon; + const int equipmentType = self->getUnit()->getEquipmentType(); + if (IAIPathfinding::instance->trace(navigation, true, target, hit, polygon, + equipmentType, -1, 0.0f, 0, 0)) + target = hit; + else + { + const Mat4& fallback = self->getTransformation(); + target = Vec3{0.1f + fallback.m[12], fallback.m[13] + 0.0f, fallback.m[14] + 0.0f}; + } + bot->getSquadMember()->clearRequestAction(); + BAPConOr* stop = checkPointer(new BAPConOr()); + stop->addCondition(checkPointer(new BAPConTime(static_cast(time * 1.5f), false, false, false))); + stop->addCondition(checkPointer(new BAPConPosition(target, 1.0f))); + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + BAPAMoveToDirect* move = checkPointer(new BAPAMoveToDirect(bot, target, speed, arriveSpeed, stop, driveControls, m_id)); + BAPAHonkHorn* horn = 0; + if (self->getObjectTypeFlags() & 0x04000000u) + { + const int obstacleSide = obstacle->getSide(); + const int ownSide = self->getSide(); + if (obstacleSide == ownSide && obstacle->getUnit()->isOccupied()) + horn = checkPointer(new BAPAHonkHorn(obstacleHandle, m_id)); + } + BAPCombinerSerial* serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + if (horn) + serial->addStatement(horn); + serial->addStatement(move); + serial->m_owner = this; + return serial; +} + +// ELF 0x229D60 +void BBPAvoidCollision2d::init(Bot* bot, Vec3& point, unsigned int obstacle, Vec3& relativeSpeed, float time) +{ + m_initiated[bot->getBotId()] = true; + vec3ToVec2XZ(point, m_pointXZ[bot->getBotId()]); + m_obstacle[bot->getBotId()] = obstacle; + m_relativeSpeed[bot->getBotId()] = relativeSpeed; + m_value[bot->getBotId()] = time; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.h new file mode 100644 index 000000000..6de3e2456 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.h @@ -0,0 +1,36 @@ +// Vehicle collision-avoidance plan generator. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION2D_H + +#include "../../../../Math/Vec3.h" +#include "BBPAvoidCollision.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB720 (7 words), operator new 0x20, package G-vehicles. +class BBPAvoidCollision2d : public BBPAvoidCollision +{ +public: + explicit BBPAvoidCollision2d(int); // 0x229AD0 + virtual ~BBPAvoidCollision2d(); // 0x229CC0 + + virtual BotScript* createPlan(Bot*); // 0x229E20, slot +0x08; from the base declaration + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float); // 0x229D60, slot +0x18; from the base declaration + + // Same layout as BBPAvoidCollisionInfantery (operator new 0x20 in both create arms). + /* +0x18 */ unsigned char m_unwritten18[4]; // not written by the constructor [UNRESOLVED] + /* +0x1C */ Vec2* m_pointXZ; // per bot, zeroed [INFERRED] name, as in the infantry pattern +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp new file mode 100644 index 000000000..7e41344e1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp @@ -0,0 +1,183 @@ +// Collision-avoidance pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp +// in the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was read from the Intel-syntax listing (fsubrp operand order) and checked +// against the Ghidra pseudocode, which misnames the altitude calls (+0x34) as getMaxSpeed. + +// static init: ELF 0x22C390 (__tcf_0 0x22C3F0, _GLOBAL__I 0x22C420): 's Init object only. +#include + +#include "BBPAvoidCollision3d.h" + +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x22B220: BBPAvoidCollision(), the vtable store, the argument at +0x08, then +// `new Vec3[getMaxNBots()]` (IAISettings slot 0; every component stored from the 0.0f constant) +// through the inlined checkPointer into +0x1C. +BBPAvoidCollision3d::BBPAvoidCollision3d(int id) + : BBPAvoidCollision() +{ + m_id = id; + m_collisionPoint = + checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); +} + +// ELF 0x22B410 (D2 0x22B3C0, D0 0x22B460): delete[] +0x1C when set, then ~BBPAvoidCollision. +BBPAvoidCollision3d::~BBPAvoidCollision3d() +{ + if (m_collisionPoint) + delete[] m_collisionPoint; +} + +// ELF 0x22B4B0. Stores the arguments per bot, in this order. +void BBPAvoidCollision3d::init(Bot* bot, Vec3& collisionPoint, unsigned int obstacle, Vec3& relativeSpeed, + float value) +{ + m_initiated[bot->getBotId()] = true; + m_collisionPoint[bot->getBotId()] = collisionPoint; + m_obstacle[bot->getBotId()] = obstacle; + m_relativeSpeed[bot->getBotId()] = relativeSpeed; + m_value[bot->getBotId()] = value; +} + +// ELF 0x22B570. Always rebuilds: a single BAPAMoveTo3d to a point 45 degrees left or right of the +// own XZ speed (whichever side the obstacle is not on, judged by the own speed's normal), at the +// own altitude plus twice the stored value when above the obstacle and minus it otherwise, until +// 1.1 times the value has passed or the point is within 5 m. The speed is the own maximum, reduced +// to 30 % unless the obstacle lies behind both 45-degree directions. Neither information is +// null-checked, nor the obstacle's mobile plug-in, as compiled. +// The first test compares |dot(own speed normal, obstacle heading)| - pi/2 with 20 degrees; a dot +// product of unit vectors can never pass it, so the left turn without the obstacle test is dead +// code in practice, kept as compiled. The statement list is constructed and destroyed unused. +// [PLATFORM] precision: the x87 build keeps the rotated components, the dot products and the +// normalization factor in extended precision; the float expressions below round them. +BotScript* BBPAvoidCollision3d::createPlan(Bot* bot) +{ + std::list statements; + std::list conditions; + bool behindBoth = false; + + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getSquadMember()->clearRequestAction(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + Information* const obstacle = informationManager->getInformation(m_obstacle[bot->getBotId()]); + + Vec2 selfXZ; + vec3ToVec2XZ(self->getPosition(), selfXZ); + Vec2 obstacleXZ; + vec3ToVec2XZ(obstacle->getPosition(), obstacleXZ); + Vec2 speed; + vec3ToVec2XZ(mobile->getSpeed(), speed); + Vec2 obstacleSpeed; + vec3ToVec2XZ(obstacle->getMobile()->getSpeed(), obstacleSpeed); + Vec2 obstacleHeading = obstacleSpeed; + bapinline::normalize(obstacleHeading); // inlined Vec2 normalization + + Vec2 left; + left.x = speed.x * 0.7071f - speed.y * 0.7071f; + left.y = speed.x * 0.7071f + speed.y * 0.7071f; + Vec2 right; + right.x = speed.x * 0.7071f + speed.y * 0.7071f; + right.y = speed.y * 0.7071f - 0.7071f * speed.x; + + Vec2 normal; + getNormal(speed, normal); + Vec2 destinationXZ = selfXZ; + if (std::fabs(normal.x * obstacleHeading.x + normal.y * obstacleHeading.y) - 1.5708f > 0.349066f) + { + destinationXZ.x += left.x; + destinationXZ.y += left.y; + } + else + { + Vec2 toObstacle; + toObstacle.x = obstacleXZ.x - selfXZ.x; + toObstacle.y = obstacleXZ.y - selfXZ.y; + if (toObstacle.x * left.x + toObstacle.y * left.y <= 0.0f + && toObstacle.x * right.x + toObstacle.y * right.y <= 0.0f) + behindBoth = true; + if (normal.x * toObstacle.x + normal.y * toObstacle.y > 0.0f) + { + destinationXZ.x += left.x; + destinationXZ.y += left.y; + } + else + { + destinationXZ.x += right.x; + destinationXZ.y += right.y; + } + } + + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + float maxSpeed = mobile->getMaxSpeed(); + Vec3 destination; + vec2ToVec3XZ(destinationXZ, destination); + const float altitude = self->getAltitude(); + if (altitude > obstacle->getAltitude()) + destination.y = m_value[bot->getBotId()] + m_value[bot->getBotId()] + altitude; + else + destination.y = altitude - (m_value[bot->getBotId()] + m_value[bot->getBotId()]); + + // The product is formed in extended precision and stored as the double argument; a float + // times float product is exact in double. + BAPConTime* const timeout = checkPointer(new BAPConTime( + static_cast(1.1f) * m_value[bot->getBotId()], false, false, false)); + BAPConPosition* const reached = checkPointer(new BAPConPosition(destination, 5.0f)); + conditions.push_back(timeout); + conditions.push_back(reached); + BAPConOr* const stop = checkPointer(new BAPConOr(conditions)); + if (!behindBoth) + maxSpeed *= 0.3f; + BAPAMoveTo3d* const move = + checkPointer(new BAPAMoveTo3d(bot, destination, maxSpeed, maxSpeed, stop, controls, 30.0f, m_id)); + move->setParent(this); // +0x04 (BotScript::m_owner) + return move; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.h new file mode 100644 index 000000000..bae60e535 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.h @@ -0,0 +1,39 @@ +// Collision-avoidance pattern of aircraft (3d navigation): steers 45 degrees off the own course, +// away from the obstacle, and climbs or dives by twice the time to collision. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION3D_H + +#include "../../../../Math/Vec3.h" +#include "BBPAvoidCollision.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB7A0 (7 words), operator new 0x20, package H-deferred. +class BBPAvoidCollision3d : public BBPAvoidCollision +{ +public: + explicit BBPAvoidCollision3d(int); // 0x22B220 + virtual ~BBPAvoidCollision3d(); // 0x22B410 + + virtual BotScript* createPlan(Bot*); // 0x22B570, slot +0x08; from the base declaration + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float); // 0x22B4B0, slot +0x18; from the base declaration + + // Same layout as BBPAvoidCollision2d, with a Vec3 per bot at +0x1C. + /* +0x18 */ unsigned char m_unwritten18[4]; // not written by the constructor [UNRESOLVED] + /* +0x1C */ Vec3* m_collisionPoint; // per bot, zeroed: init's first Vec3 [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISION3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp new file mode 100644 index 000000000..1ac213a12 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp @@ -0,0 +1,264 @@ +// Infantry avoid-collision pattern (AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp +// in the image): init keeps the collision point (XZ), the obstacle, the relative speed and the time +// or strength per bot; createPlan sprints the bot to a free point away from the obstacle, a tear-gas +// cloud or a grenade. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries +// its ELF address. +// +// static init: ELF 0x22E420 (__tcf_0 0x22E480, _GLOBAL__I 0x22E4B0): the guard object only. + +#include "BBPAvoidCollisionInfantery.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIRandom.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Game/GameLogic/Player.h" +#include "../../../../Game/Objects/IPlayer.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x22C440 (C2) / 0x22C5E0 (C1): BBPAvoidCollision(), +0x08 = the argument, +0x1C = +// checkPointer(new Vec2[getMaxNBots]) with every Vec2 zeroed (rodata 0x49CB34) before the check. +BBPAvoidCollisionInfantery::BBPAvoidCollisionInfantery(int id) + : BBPAvoidCollision() +{ + m_id = id; + m_pointXZ = checkPointer(new Vec2[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); +} + +// ELF 0x22C780 (D2) / 0x22C7D0 (D1) / 0x22C820 (D0): delete[] +0x1C when set, then +// ~BBPAvoidCollision. +BBPAvoidCollisionInfantery::~BBPAvoidCollisionInfantery() +{ + if (m_pointXZ) + delete[] m_pointXZ; +} + +// ELF 0x22C930 (listing; Ghidra loses the stack after the sret calls). Builds +// serial { turn lock on, +// parallel { override sensing agent, +// sprint (BAPAMoveToDirect) to the flee point until BAPConOr(time, within 2 m), +// merge soldier inputs }, +// turn lock off } +// The danger is the obstacle's position (XZ) or, without obstacle information, the tear-gas +// position of the bot's engine Player plus (1, 1, 1) with a 5 s flee time, else the grenade warning +// (none: 0). Without an obstacle handle, or with a zero collision point, the flee point is a trace +// 15 m (with an obstacle handle 10 m) straight away from the danger, then to a random side, then the +// other side (the last result is used whatever the trace answers); otherwise one trace sideways of the +// obstacle's velocity (its facing when it stands still), on the side away from it. The time is the +// flee time without an obstacle handle (rounded to float), else init's value. As compiled: the +// current plan is always dropped, the bot's equipment information is not null-checked, the obstacle's +// mobile plug-in is not null-checked, and a pattern that is not initiated returns 0 untouched. +BotScript* BBPAvoidCollisionInfantery::createPlan(Bot* bot) +{ + Vec2 ownXZ; + ownXZ.x = ownXZ.y = 0.0f; + Vec2 dangerXZ; + dangerXZ.x = dangerXZ.y = 0.0f; + Vec2 destinationXZ; + destinationXZ.x = destinationXZ.y = 0.0f; + + world::IPlayer* const player = bot->getPlayer()->getPlayer(); // 0x22C97C, before the test + if (!m_initiated[bot->getBotId()]) + return 0; // 0x22E412 + + bot->getSquadMember()->clearRequestAction(); + if (bot->getPlan()) + { + // 0x22E3E1 + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); // 0x22E3C6 + bot->getScriptContext()->clear(); + + const bool noObstacle = m_obstacle[bot->getBotId()] == 0xFFFFFFFFu; + Information* const obstacle = informationManager->getInformation(m_obstacle[bot->getBotId()]); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = info->getMobile(); // 0x22CAA0: unchecked + const Vec3& position = info->getPosition(); + vec3ToVec2XZ(position, ownXZ); + + double fleeTime = 0.0; + Vec3 destination; // -0x1A8: the danger position first, then the trace's flee point + if (!obstacle) + { + // 0x22E2A3 + destination.x = destination.y = destination.z = 0.0f; + if (player->getIsGassed()) + { + fleeTime = 5.0; + Vec3 one; + one.x = one.y = one.z = 1.0f; + const Vec3 gas = static_cast(player)->getTearGasPosition(); // raw +0x2E8 in the image + destination = bapinline::add(gas, one); + } + else if (!bot->getBotNavigation()->getGrenadeWarning(destination, fleeTime)) + { + return 0; // 0x22E3AA + } + vec3ToVec2XZ(destination, dangerXZ); + } + else + { + vec3ToVec2XZ(obstacle->getPosition(), dangerXZ); // 0x22CAE6 + } + + // 0x22CB0F + const float distance = noObstacle ? 15.0f : 10.0f; + info->getMobile()->getVehicleNumber(); // result discarded + const unsigned long long driveControls = info->getControlInfo()->getDriveControls(); + destination.x = destination.y = destination.z = 0.0f; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + const float maxSpeed = mobile->getMaxSpeed(); + const float side = AIRandom::m_instance->next() * 2.3283064e-10f > 0.5f ? 1.0f : -1.0f; + const int equipmentType = info->getUnit()->getEquipmentType(); + + bool atZeroPoint = false; + if (!noObstacle) + { + // 0x22E200: the collision point compared with zero. + Vec2 zero; + zero.x = zero.y = 0.0f; + const Vec2& point = m_pointXZ[bot->getBotId()]; + if (std::fabs(point.x - zero.x) + std::fabs(point.y - zero.y) <= 1.1920929e-07f) + atZeroPoint = true; + } + + Vec3 target; + target.x = target.y = target.z = 0.0f; + unsigned int polygon; + if (atZeroPoint || noObstacle) + { + // 0x22CC76: straight away from the danger, else to one side, else the other. + Vec2 toDanger; + toDanger.x = dangerXZ.x - ownXZ.x; + toDanger.y = dangerXZ.y - ownXZ.y; + bapinline::normalize(toDanger); + Vec2 sideways; + sideways.x = distance * toDanger.y; + sideways.y = distance * -toDanger.x; + Vec2 offset; + offset.x = distance * -toDanger.x; + offset.y = -toDanger.y * distance; + + target = position; + addVec2ToVec3XZ(offset, target); + if (!pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0)) + { + // 0x22DC20 + offset.x = side * sideways.x; + offset.y = side * sideways.y; + target = position; + addVec2ToVec3XZ(offset, target); + if (!pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0)) + { + // 0x22DCEC + offset.x = sideways.x * -side; + offset.y = -side * sideways.y; + target = position; + addVec2ToVec3XZ(offset, target); + pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0); + } + } + } + else + { + // 0x22DE00: sideways of the obstacle's motion, on the side away from the obstacle. + Vec3 velocity = obstacle->getMobile()->getSpeed(); + const Vec3& zero = Vec3::getZero(); + if (std::fabs(velocity.x - zero.x) <= 1.1920929e-07f && std::fabs(velocity.y - zero.y) <= 1.1920929e-07f + && std::fabs(velocity.z - zero.z) <= 1.1920929e-07f) + velocity = obstacle->getFaceing(); // 0x22E1B4 + const Vec3& obstaclePosition = obstacle->getPosition(); + const Vec3 own = position; + Vec3 away; + away.x = own.x - obstaclePosition.x; + away.y = 0.0f; + away.z = own.z - obstaclePosition.z; + Vec3 offset; + offset.x = velocity.z; + offset.y = 0.0f; + offset.z = -velocity.x; + bapinline::normalize(offset); + offset.x = distance * offset.x; + offset.y = distance * offset.y; + offset.z = distance * offset.z; + if (bapinline::dot(offset, away) > 0.0f) + target = bapinline::add(position, offset); + else + target = bapinline::sub(position, offset); // 0x22E107 + pathfinding->trace(bot->getBotNavigation(), false, target, destination, polygon, equipmentType, -1, 0.0f, 0, 0); + } + + // 0x22CE58 + BAPConTime* time; + if (noObstacle) + time = checkPointer(new BAPConTime(static_cast(fleeTime), false, false, false)); + else + time = checkPointer(new BAPConTime(m_value[bot->getBotId()], false, false, false)); // 0x22DAD0 + vec3ToVec2XZ(destination, destinationXZ); + BAPConPosition* const reached = checkPointer(new BAPConPosition(destinationXZ, 2.0f)); + BAPConOr* const done = checkPointer(new BAPConOr()); + done->addCondition(time); + done->addCondition(reached); + BAPAMoveToDirect* const move = + checkPointer(new BAPAMoveToDirect(bot, destination, maxSpeed, maxSpeed, done, driveControls, m_id)); + move->setIsSprinting(bot, true, destination, 0xFFFFFFFFu); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + serial->addStatement(checkPointer(new BAPICTurnLock(true))); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, true, -1, false)); + parallel->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + parallel->addStatement(move); + parallel->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_id))); + serial->addStatement(parallel); + serial->addStatement(checkPointer(new BAPICTurnLock(false))); + serial->setParent(this); // +0x04 (BotScript::m_owner) + return serial; +} + +// ELF 0x22C870 (64 insns; reached from BBAvoid::calculateUrgency through slot +0x18): +// m_initiated[id] = true, vec3ToVec2XZ(point, +0x1C[id]), +0x0C[id] = handle, +0x10[id] = speed +// (three-word copy), +0x14[id] = value. +void BBPAvoidCollisionInfantery::init(Bot* bot, Vec3& point, unsigned int obstacle, Vec3& relativeSpeed, float value) +{ + m_initiated[bot->getBotId()] = true; + vec3ToVec2XZ(point, m_pointXZ[bot->getBotId()]); + m_obstacle[bot->getBotId()] = obstacle; + m_relativeSpeed[bot->getBotId()] = relativeSpeed; + m_value[bot->getBotId()] = value; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h new file mode 100644 index 000000000..d113d3d94 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h @@ -0,0 +1,41 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISIONINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISIONINFANTERY_H + +#include "../../../../Math/Vec3.h" +#include "BBPAvoidCollision.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB820 (7 words), operator new 0x20, package F-infantry. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPAvoidCollisionInfantery : public BBPAvoidCollision +{ +public: + explicit BBPAvoidCollisionInfantery(int); // 0x22C5E0 + virtual ~BBPAvoidCollisionInfantery(); // 0x22C7D0 + + virtual BotScript* createPlan(Bot*); // 0x22C930, slot +0x08; from the base declaration + virtual void init(Bot*, Vec3&, unsigned int, Vec3&, float); // 0x22C870, slot +0x18; from the base declaration + +private: + /* +0x18 */ unsigned char m_unwritten18[4]; // not written by the constructor or init [UNRESOLVED] + /* +0x1C */ Vec2* m_pointXZ; // per bot, zeroed: init's first Vec3 projected to XZ [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPAVOIDCOLLISIONINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp new file mode 100644 index 000000000..d6fdd3798 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp @@ -0,0 +1,225 @@ +// Bridge-repair pattern: per-bot plan parameters that BBBridgeRepair::calculateUrgency stores through +// init. Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x232140 (__tcf_0 0x2321A0, _GLOBAL__I 0x2321D0): 's Init object only. +#include + +#include "BBPBridgeRepair.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x22E4D0 (C2) / 0x22EC30 (C1): BBPPattern(), the argument to +0x08, six getMaxNBots-sized +// arrays (each checkPointer'd; the Vec3 ones run the zeroing Vec3 constructor loop, rodata +// 0x49CB34 0.0f, reproduced here by value-initialisation), then for each bot (getMaxNBots re-read +// per pass) segment and weapon index -1 and the near-request flag false. +BBPBridgeRepair::BBPBridgeRepair(int value) + : BBPPattern() +{ + m_unknown8 = value; + m_segment = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_weaponIndex = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_direction = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_nearRequest = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_standPosition = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_segmentEnd = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); ++i) + { + m_segment[i] = 0xFFFFFFFFu; + m_weaponIndex[i] = -1; + m_nearRequest[i] = false; + } +} + +// ELF 0x22F390 (D2) / 0x22F450 (D1) / 0x22F510 (D0): delete[] +0x0C..+0x20 in order when set, then +// the base. +BBPBridgeRepair::~BBPBridgeRepair() +{ + if (m_segment) + delete[] m_segment; + if (m_weaponIndex) + delete[] m_weaponIndex; + if (m_direction) + delete[] m_direction; + if (m_nearRequest) + delete[] m_nearRequest; + if (m_standPosition) + delete[] m_standPosition; + if (m_segmentEnd) + delete[] m_segmentEnd; +} + +// ELF 0x22F6E0 +BotScript* BBPBridgeRepair::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getPlayer()->getSpawnKit(); + bot->getCommunicationAgent(); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_unknown8 + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_segment[bot->getBotId()]) + return bot->getPlan(); + + const unsigned int segment = m_segment[bot->getBotId()]; + bot->getSquadMember()->clearRequestAction(); + bot->getSensingAgent()->clearPlanTargetInformation(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_segment[bot->getBotId()]); + if (!self || !self->getUnit() || !target) + return 0; + bot->setBridgeRepairTarget(segment); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controls = self->getControlInfo(); + const int weaponIndex = m_weaponIndex[bot->getBotId()]; + if (weaponIndex == -1) { + self->getAIObject()->update(); + return 0; + } + + const int side = bot->getSide(); + const unsigned int soldierHandle = bot->getPlayer()->getSoldier()->getInformation(side); + Information* const soldier = informationManager->getInformation(soldierHandle); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(soldier->getArmament()->getWeapon(weaponIndex)); + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + sequence->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_unknown8))); + BAPStatement* last; + if (!(self->getObjectTypeFlags() & 0x200000)) { + BAPCombinerSerial* const leave = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + leave->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, + 0x400ULL, m_unknown8, 0.0, false))); + leave->addStatement(checkPointer(new BAPICChangeVehicle(soldierHandle))); + last = leave; + } else { + if (m_nearRequest[bot->getBotId()] && !bot->getSquadMember()->getSquad()->haveConfirmedRepairRequest()) { + bot->getSquadMember()->getSquad()->confirmRepairRequested(); + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(3), 3, 2.0f, 0); + } + const Vec3 standPosition = m_standPosition[bot->getBotId()]; + const Vec3 segmentEnd = m_segmentEnd[bot->getBotId()]; + const unsigned long long drive = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + sequence->addStatement(checkPointer(new BAPAMoveToFinding(bot, standPosition, speed, arriveSpeed, + 0, drive, m_unknown8, 0.0f, 0.0f))); + + // shipped defect: input masks shift a signed 32-bit one, then sign-extend to 64 bits. + const unsigned int activateBit = 1u << (weapon->getWeaponActivate() & 31); + const unsigned long long activateMask = static_cast(static_cast(static_cast(activateBit))); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(static_cast(weapon->getWeaponActivate()), + start, stop, activateMask, m_unknown8, 0.0, false))); + const unsigned long long directControls = self->getControlInfo()->getDriveControls(); + const Vec2 endXZ = {segmentEnd.x, segmentEnd.z}; + BAPConPosition* const atEnd = checkPointer(new BAPConPosition(endXZ, 1.0f)); + const float directArriveSpeed = mobile->getMaxSpeed(); + const float directSpeed = mobile->getMaxSpeed(); + sequence->addStatement(checkPointer(new BAPAMoveToDirect(bot, segmentEnd, directSpeed, directArriveSpeed, + atEnd, directControls, m_unknown8))); + sequence->addStatement(checkPointer(new BAPAResetControls(true, false, false, m_unknown8))); + BAPCombinerParallel* const repair = checkPointer(new BAPCombinerParallel(m_unknown8, -1, false)); + repair->addStatement(checkPointer(new BAPASoldierPose(static_cast(2), + checkPointer(new BAPConTrue()), m_unknown8, true))); + repair->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + const unsigned long long lookControls = self->getControlInfo()->getLookControls(); + repair->addStatement(checkPointer(new BAPALookAtObject(bot, segment, 0.0f, checkPointer(new BAPConFalse()), + lookControls, m_unknown8, 0, 0.0f))); + const unsigned int fireBit = 1u << (weapon->getWeaponFire() & 31); + const unsigned long long fireMask = static_cast(static_cast(static_cast(fireBit))); + BAPConFalse* const abort = checkPointer(new BAPConFalse()); + BAPConFalse* const fireStop = checkPointer(new BAPConFalse()); + BAPConTrue* const fireStart = checkPointer(new BAPConTrue()); + repair->addStatement(checkPointer(new BAPATriggerContinously(static_cast(weapon->getWeaponFire()), + fireStart, fireStop, abort, fireMask, m_unknown8, 0.0))); + last = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), repair, true, m_unknown8)); + } + sequence->addStatement(last); + root->addStatement(sequence); + const unsigned int requestHandle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(2, requestHandle); + BAPIWFire* const wrapper = checkPointer(new BAPIWFire(bot, m_segment[bot->getBotId()], true, false, + weaponIndex, -1, root, m_unknown8)); + wrapper->m_owner = this; + static_cast(bot)->resetAllControls(true, true, true); + return wrapper; +} + +// ELF 0x22F5E0: marks the bot initiated (BBPPattern +0x04) and stores the parameters; getBotId is +// called once per store. +void BBPBridgeRepair::init(unsigned int segment, int weaponIndex, Vec3 direction, Bot* bot, bool nearRequest, + Vec3 standPosition, Vec3 segmentEnd) +{ + m_initiated[bot->getBotId()] = true; + m_segment[bot->getBotId()] = segment; + m_weaponIndex[bot->getBotId()] = weaponIndex; + m_direction[bot->getBotId()] = direction; + m_nearRequest[bot->getBotId()] = nearRequest; + m_standPosition[bot->getBotId()] = standPosition; + m_segmentEnd[bot->getBotId()] = segmentEnd; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.h new file mode 100644 index 000000000..ce3a75de7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.h @@ -0,0 +1,45 @@ +// Bridge-repair plan parameters and generation, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPBRIDGEREPAIR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPBRIDGEREPAIR_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB8A0 (6 words), operator new 0x24, package F-infantry. +class BBPBridgeRepair : public BBPPattern +{ +public: + explicit BBPBridgeRepair(int); // 0x22EC30 + virtual ~BBPBridgeRepair(); // 0x22F450 + + virtual BotScript* createPlan(Bot*); // 0x22F6E0, slot +0x08; from the base declaration + + // 0x22F5E0: void (stores only, %eax is left as the last getBotId result). + void init(unsigned int, int, Vec3, Bot*, bool, Vec3, Vec3); + +private: + // Constructor 0x22E4D0/0x22EC30, destructor 0x22F390/0x22F450/0x22F510; per-bot arrays are + // new [getMaxNBots] (IAISettings slot 0); init 0x22F5E0 writes them by Bot::getBotId. + /* +0x08 */ int m_unknown8; // pattern id carried by the generated plan + /* +0x0C */ unsigned int* m_segment; // -1; bridge segment Information handle [INFERRED] name + /* +0x10 */ int* m_weaponIndex; // -1; first weapon of type 1 [INFERRED] name + /* +0x14 */ Vec3* m_direction; // zeroed (Vec3 array constructor loop) + /* +0x18 */ bool* m_nearRequest; // false; segment within 50 m of the squad repair request + /* +0x1C */ Vec3* m_standPosition; // zeroed + /* +0x20 */ Vec3* m_segmentEnd; // zeroed +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPBRIDGEREPAIR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp new file mode 100644 index 000000000..315982aba --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp @@ -0,0 +1,171 @@ +// C4 pattern: places or detonates the bot's C4 (AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp in the +// image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF +// address. +// +// static init: ELF 0x235010 (__tcf_0 0x235070, _GLOBAL__I 0x2350A0): the guard object only. + +#include "BBPC4.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAIdle.h" +#include "../AIBotActionPlan/BAPAPlaceC4.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponDetonatorIsActive.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// One weapon key as the image builds it inline every time: a trigger of the key that starts at +// once (BAPConTrue) and never stops by condition (BAPConFalse), with the key's control bit +// (1 << key, sign-extended from int) and no repeat time. The key is read twice, for the controls +// and for the input map (right-to-left argument order: the controls' read comes first). +BAPATrigger* newKeyTrigger(const WeaponInfo* weapon, int (WeaponInfo::*key)() const, int patternId, bool flag) +{ + return checkPointer(new BAPATrigger(static_cast((weapon->*key)()), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 1 << (weapon->*key)(), patternId, 0.0, flag)); +} + +} // namespace + +// ELF 0x2321F0 (C2) / 0x232370 (C1): BBPPattern(), +0x08 = id, +0x0C = checkPointer(new[getMaxNBots]). +BBPC4::BBPC4(int id) + : BBPPattern() +{ + m_id = id; + m_perBot = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x2324F0 (D2) / 0x232540 (D1) / 0x232590 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPC4::~BBPC4() +{ + if (m_perBot) + delete[] m_perBot; +} + +// ELF 0x232620 (listing). Builds, under a BAPIWFire(bot, -1, true, false, 4, -1, ..) wrapper, +// serial { reset controls, trigger(activate key of the C4 slot 4 weapon), +// if (detonator [not] active) trigger(alt-fire key), idle 0.7 s, trigger(fire key), +// [trigger(activate key of the slot 2 weapon)], place C4 (type 0, target) } +// m_placed (init's bool) selects the variant: placed: the alt-fire key when the detonator is NOT +// active and BAPAPlaceC4(.., false); not placed: when it IS active and BAPAPlaceC4(.., true). +// The script context is cleared first, also when the current plan of this pattern is kept, and the +// equipment handle is read once without use; as compiled. Returns 0 without equipment, unit, mobile +// or a slot 4 weapon. The bot's controls are reset after the plan is built. +BotScript* BBPC4::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + // 0x234F98 + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + bot->getCurrentEquipment(); // 0x232692, result unused + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_id) + return bot->getPlan(); // 0x234F73 + if (bot->getPlan()) + dropPlan(bot); // 0x234F48 + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment || !equipment->getUnit() || !equipment->getMobile()) + return 0; + IPIArmament* const armament = equipment->getArmament(); + WeaponInfo* const c4 = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(4)); // 0x23274B + if (!c4) + return 0; + + BAPATrigger* const activate = newKeyTrigger(c4, &WeaponInfo::getWeaponActivate, m_id, false); // 0x232880 + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + serial->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + serial->addStatement(checkPointer(activate)); // checkPointer'd a second time (0x232945) + + // 0x23296B: the plan variable of the C4 weapon (inline BAPVariable, then list insert at begin). + BAPVariable* const weaponVariable = checkPointer(new BAPVariable(context, c4)); + context->addVariable(weaponVariable); + + BAPFlowCIf* detonate; + BAPAPlaceC4* place; + if (m_placed) + { + // 0x232A02 + detonate = checkPointer(new BAPFlowCIf( + checkPointer(new BAPConNot(checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)))), + newKeyTrigger(c4, &WeaponInfo::getWeaponAltFire, m_id, true), 0, m_id, true, false)); + place = checkPointer(new BAPAPlaceC4(0, m_target, false)); + } + else + { + // 0x2340D0 + detonate = checkPointer(new BAPFlowCIf(checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)), + newKeyTrigger(c4, &WeaponInfo::getWeaponAltFire, m_id, true), 0, m_id, true, + false)); + place = checkPointer(new BAPAPlaceC4(0, m_target, true)); + } + // 0x232C55 + serial->addStatement(detonate); + serial->addStatement(checkPointer(new BAPAIdle(checkPointer(new BAPConTime(0.7f, false, false, false)), 0ULL, m_id))); + serial->addStatement(newKeyTrigger(c4, &WeaponInfo::getWeaponFire, m_id, true)); + serial->addStatement(place); + + WeaponInfo* const other = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(2)); // 0x232E9E + if (other) + serial->addStatement(newKeyTrigger(other, &WeaponInfo::getWeaponActivate, m_id, false)); + + // 0x232FE2 + BAPIWFire* const root = checkPointer(new BAPIWFire(bot, 0xFFFFFFFFu, true, false, 4, -1, serial, m_id)); + root->setParent(this); // +0x04 (BotScript::m_owner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x2325E0: m_initiated[bot->getBotId()] = true (BBPPattern +0x04), then +0x10/+0x14. +void BBPC4::init(Bot* bot, bool placed, AIStrategicObject* target) +{ + m_initiated[bot->getBotId()] = true; + m_placed = placed; + m_target = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h new file mode 100644 index 000000000..2e5c3fa1c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPC4_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPC4_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class AIStrategicObject; +class Bot; +class BotScript; + +// ELF: vtable 0x4BB920 (6 words), operator new 0x18, package F-infantry. +class BBPC4 : public BBPPattern +{ +public: + explicit BBPC4(int); // 0x232370 + virtual ~BBPC4(); // 0x232540 + + virtual BotScript* createPlan(Bot*); // 0x232620, slot +0x08; from the base declaration + + void init(Bot*, bool, AIStrategicObject*); // 0x2325E0; void [INFERRED]: %eax is left holding the bool argument, no caller reads it + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name (the pattern id) + /* +0x0C */ unsigned int* m_perBot; // new[getMaxNBots], checkPointer'd, never filled here [UNRESOLVED] use + /* +0x10 */ bool m_placed; // init's bool: BBC4 passes "own C4 is placed and the area is taken" [INFERRED] + /* +0x14 */ AIStrategicObject* m_target; // init's object +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPC4_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp new file mode 100644 index 000000000..6f2538b28 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp @@ -0,0 +1,74 @@ +// Medic-request radio pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x235730 (__tcf_0 0x235790, _GLOBAL__I 0x2357C0): 's Init object only. +#include + +#include "BBPCallForMedic.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2352E0 (C2), 0x235320 (C1). +BBPCallForMedic::BBPCallForMedic(int patternId) + : m_patternId(patternId) +{ +} + +// ELF 0x235360 (D2), 0x2353A0 (D1), 0x2353E0 (D0). +BBPCallForMedic::~BBPCallForMedic() +{ +} + +// ELF 0x235450 +BotScript* BBPCallForMedic::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + bot->getCurrentEquipment(); + if (!bot->hasPlan()) { + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + } else if (static_cast(bot->getPlan())->getPatternId() == m_patternId) { + return bot->getPlan(); + } + // shipped defect: a valid plan of another pattern is not deleted here. + bot->getSquadMember()->clearRequestAction(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + BAPASendRadioMessage* const plan = checkPointer(new BAPASendRadioMessage(static_cast(3), + static_cast(0), 5, 0.0f, m_patternId, -1)); + plan->m_owner = this; + return plan; +} + +// ELF 0x235420 +void BBPCallForMedic::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.h new file mode 100644 index 000000000..f28b4c590 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.h @@ -0,0 +1,35 @@ +// Medic-request radio pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCALLFORMEDIC_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCALLFORMEDIC_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BB980 (6 words), operator new 0xC, package H-deferred. +class BBPCallForMedic : public BBPPattern +{ +public: + explicit BBPCallForMedic(int); // 0x235320 + virtual ~BBPCallForMedic(); // 0x2353A0 + + virtual BotScript* createPlan(Bot*); // 0x235450, slot +0x08; from the base declaration + + void init(Bot*); // 0x235420; [INFERRED] ELF void + +private: + /* +0x08 */ int m_patternId; // [INFERRED] name: id passed to the generated radio statement +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCALLFORMEDIC_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp new file mode 100644 index 000000000..58c8466c6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp @@ -0,0 +1,539 @@ +// Change pattern: per-bot target vehicle/seat, entry position and get-in flags. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x23DC90 (__tcf_0 0x23DCF0, _GLOBAL__I 0x23DD20): 's Init object only. +#include + +#include "BBPChange.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Math/Mat4.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPAUpdateVehicle.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectBehind.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectEnemyOccupied.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWChange.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../Main/IBotManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2357E0 (C2) / 0x235CB0 (C1). After the BBPPattern base, four getMaxNBots-sized arrays, each +// checkPointer'd (the inlined "AI::Allocation failed" Debug blocks): +0x10 Vec3 (the new[] loop stores +// 0.0f, rodata 0x49CB34, into all three floats before the null test), +0x14 and +0x18 bool (left +// uninitialised), then +0x08 = the argument and +0x0C unsigned int (uninitialised). +BBPChange::BBPChange(int value) +{ + m_entryPositions = checkPointer( + new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_sameVehicle = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_getInConfirm = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_patternId = value; + m_targets = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x236180 (D2) / 0x236210 (D1) / 0x2362A0 (D0): delete[] +0x0C, +0x14, +0x10, +0x18 (each when +// set), then the BBPPattern base. +BBPChange::~BBPChange() +{ + if (m_targets) + delete[] m_targets; + if (m_sameVehicle) + delete[] m_sameVehicle; + if (m_entryPositions) + delete[] m_entryPositions; + if (m_getInConfirm) + delete[] m_getInConfirm; +} + +namespace { + +// The plan-reset idiom of createPlan (debugger slot +0x164 -> clear vfn +0xC; plan slot +0x60, deleted +// through vfn +8, then setPlan(0) slot +0x64; script context slot +0x168 -> BAPContext::clear). The +// image inlines it three times with two different orders; the callers keep their order. +void clearDebugger(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); +} + +void deletePlan(Bot* bot) +{ + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// Radius of an information's physical plug-in (+0x3C, IPIPhysical::getRadius vfn +0x2C); a seat that is +// not the primary object uses its primary's (getPrimaryObject(bot side), no null test in the image). +float radiusOf(Information* info, Bot* bot) +{ + if (info->isPrimary()) + return info->getPhysical()->getRadius(); + return informationManager->getInformation(info->getPrimaryObject(bot->getSide()))->getPhysical()->getRadius(); +} + +} // namespace + +// ELF 0x236A20. Stack-slot map and branch order in docs/macos-ai-w1-f-urgency.md. +BotScript* BBPChange::createPlan(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); // esi + CommunicationAgent* const communication = bot->getCommunicationAgent(); // -0x180 + if (!m_initiated[bot->getBotId()]) { + // 0x23DC07: debugger, context, plan. + clearDebugger(bot); + bot->getScriptContext()->clear(); + deletePlan(bot); + return 0; + } + + // 0x236A8A..0x236AC5, -0x181 / -0x182: keep the running plan when it is this pattern's + // (BAPStatement +0x10) and wraps the same target (BAPIWChange +0x18). + bool otherPattern = false; + if (!bot->getPlan() || static_cast(bot->getPlan())->getPatternId() != m_patternId) + otherPattern = true; + bool otherTarget = false; + if (otherPattern || static_cast(bot->getPlan())->getTarget() != m_targets[botId]) + otherTarget = true; + if (!otherTarget) { + if (m_getInConfirm[botId] && communication->generalConfirmReceivedMessage(static_cast(1))) + communication->enqueueRadioMessage(static_cast(6), static_cast(6), 3, + 1.0f, -1); + return bot->getPlan(); + } + + static_cast(bot)->resetAllControls(true, true, true); + // -0x188 current equipment, -0x18C its IPIMobile, -0x190 its IPIPhysical, -0x198/-0x194 its drive + // controls. The image reads +0x38/+0x3C/+0x30 before the null test at 0x236CEE. + Information* const current = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = current->getMobile(); + const unsigned long long driveControls = current->getControlInfo()->getDriveControls(); + // -0x19C target (the vehicle/seat), -0x1A0 its IPIUnit. + Information* const target = informationManager->getInformation(m_targets[bot->getBotId()]); + if (!target) { + // 0x23DB20: debugger, plan, context. + clearDebugger(bot); + deletePlan(bot); + bot->getScriptContext()->clear(); + return 0; + } + IPIUnit* const targetUnit = target->getUnit(); + // -0x1A8 = target radius (-0x1A4) + current radius (-0x1AC), float adds (0x236C98). + const float targetRadius = radiusOf(target, bot); + const float currentRadius = radiusOf(current, bot); + float radiusSum = targetRadius + currentRadius; + + // 0x236CAF: debugger, plan, context. + clearDebugger(bot); + deletePlan(bot); + bot->getScriptContext()->clear(); + if (!current) + return 0; + bot->getSquadMember()->clearRequestAction(); + + BAPStatement* plan; // the node the tail wraps + if (!(current->getObjectTypeFlags() & 0x200000)) { + // 0x236D12 `testb $0x20, 0x6(%esi)`: the bot sits in a vehicle or stationary weapon. + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); // -0x1B0 + // Getting out to the bot's own soldier: confirm a pending type-0 message with 6 on channel 7. + if (m_targets[bot->getBotId()] == bot->getPlayer()->getSoldier()->getInformation(bot->getSide()) + && communication->generalConfirmReceivedMessage(static_cast(0))) + sequence->addStatement(checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(7), 3, 1.0f, m_patternId, -1))); + + if (m_sameVehicle[bot->getBotId()]) { + // 0x23A260: another seat of the same vehicle: press its select key, then hand over the target. + BAPCombinerSerial* const seatChange = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + const int patternId = m_patternId; + const unsigned long long controls = 1ULL << targetUnit->getSelectKey(); // 64-bit shift (0x23A2CA) + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + seatChange->addStatement(checkPointer(new BAPATrigger(targetUnit->getSelectKey(), start, stop, controls, + patternId, 0.0, false))); + seatChange->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + sequence->addStatement(seatChange); + plan = sequence; + } else if (!current->getMobile()) { + // 0x236DEB: a stationary weapon: press enter/exit (input 10, controls 0x400). + BAPCombinerSerial* const leave = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + const int patternId = m_patternId; + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + leave->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, 0x400ULL, + patternId, 0.0, false))); + leave->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + sequence->addStatement(leave); + plan = sequence; + } else { + // 0x237822: drive (or fly) to the target first. -0x1A8 becomes radiusSum * 1.2 + 50. + radiusSum = radiusSum * 1.2f + 50.0f; + Vec2 targetXZ; + targetXZ.x = target->getPosition().x; + targetXZ.y = target->getPosition().z; + BAPConPosition* arrived = checkPointer(new BAPConPosition(targetXZ, radiusSum)); // -0x26C + + bool toEntryPosition = false; // -0x276 / -0x275 + if (targetUnit->useNoPathfindingToGetToObject() || !target->hasMobile()) + toEntryPosition = true; + if (toEntryPosition && !target->isPrimary()) + toEntryPosition = + !informationManager->getInformation(target->getPrimaryObject(bot->getSide()))->hasMobile(); + + BAPAction* move; + if (toEntryPosition) { + if (!(current->getObjectTypeFlags() & 0x10)) { + // 0x239CF0 + BAPConAnd* const arrivedBehind = checkPointer(new BAPConAnd()); + arrivedBehind->addCondition(arrived); + arrivedBehind->addCondition( + checkPointer(new BAPConObjectBehind(m_targets[bot->getBotId()], -0.95f, false))); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToFinding(bot, m_entryPositions[bot->getBotId()], speed, arriveSpeed, + arrivedBehind, driveControls, patternId, 0.0f, 0.0f)); + } else { + // 0x239B40: flag 0x10 (air): 3d move to the target's position. + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveTo3d(bot, target->getPosition(), speed, arriveSpeed, arrived, + driveControls, 25.0f, patternId)); + } + } else if (!(current->getObjectTypeFlags() & 0x10)) { + bool aroundAircraft = false; + Vec3 position; + const unsigned int targetFlags = target->getObjectTypeFlags(); + if ((targetFlags & 0x10) && !(targetFlags & 0x20)) { + // 0x239064: the target is an aircraft (0x10 without 0x20): a navigable point behind + // or beside it. + position = target->getPosition(); + const int equipmentType = current->getUnit()->getEquipmentType(); + const int vehicleNumber = current->getMobile()->getVehicleNumber(); + aroundAircraft = getPosAroundAircraft(target, vehicleNumber, equipmentType, position); + } + if (aroundAircraft) { + // 0x2390EF: radius = the current equipment's own radius (-0x1AC); the first + // BAPConPosition is not freed. + Vec2 positionXZ; + positionXZ.x = position.x; + positionXZ.y = position.z; + arrived = checkPointer(new BAPConPosition(positionXZ, currentRadius)); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.5f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToFinding(bot, position, speed, arriveSpeed, arrived, driveControls, + patternId, 0.0f, 0.0f)); + } else { + // 0x23791C / 0x2393C0 + BAPConAnd* const repath = checkPointer(new BAPConAnd()); + repath->addCondition( + checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 20.0f, true, false, false))); + repath->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 10.0f))); + const int patternId = m_patternId; + const float arriveSpeed = 0.5f * mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToObjectFinding(bot, m_targets[bot->getBotId()], 0.5f, speed, + arriveSpeed, arrived, driveControls, patternId, + repath, 0.0f, -1)); + } + } else { + // 0x239950: flying: 3d move to the object. + const int patternId = m_patternId; + const float arriveSpeed = 0.5f * mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveTo3dObject(m_targets[bot->getBotId()], 0.5f, speed, arriveSpeed, 25.0f, + arrived, driveControls, patternId)); + } + sequence->addStatement(move); + + // 0x237B2A: then press exit/enter (input 10, controls 0x400) unless an enemy took the target. + BAPAUpdateVehicle* const update = checkPointer(new BAPAUpdateVehicle(m_patternId)); + BAPConObjectEnemyOccupied* const enemy = + checkPointer(new BAPConObjectEnemyOccupied(m_targets[bot->getBotId()])); + const int patternId = m_patternId; + BAPConTrue* const start = checkPointer(new BAPConTrue()); + BAPATrigger* const enter = checkPointer(new BAPATrigger(static_cast(10), start, enemy, + 0x400ULL, patternId, 0.0, false)); + // 0x237C66: getting out to the soldier from the primary seat of a ground vehicle whose health + // (IPIPhysical vfn +0x14) is below IBotManager::getVehicleBailValue: also press input 0x2F + // (controls bit 47). + if ((target->getObjectTypeFlags() & 0x200000) && current->isPrimary() + && !(current->getObjectTypeFlags() & 0x10) && !(current->getObjectTypeFlags() & 0x20)) { + if (current->getPhysical()->getHealth() < IBotManager::instance->getVehicleBailValue()) { + const int bailPatternId = m_patternId; + BAPConFalse* const bailStop = checkPointer(new BAPConFalse()); + BAPConTrue* const bailStart = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(static_cast(0x2F), bailStart, + bailStop, 0x800000000000ULL, bailPatternId, 0.0, + false))); + } + } + sequence->addStatement(checkPointer(new BAPICTurnLock(true))); + sequence->addStatement(enter); + sequence->addStatement(update); + sequence->addStatement(checkPointer(new BAPICTurnLock(false))); + + BAPCombinerParallel* const withChange = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + withChange->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + withChange->addStatement(sequence); + plan = withChange; + } + } else { + // 0x23AF40: on foot, walk to the target and get in. + BAPCombinerParallel* const approach = // -0x3A8 + checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + + // -0x3AE / -0x3AD: walk straight to the stored entry position when the target's unit wants no + // pathfinding or the target cannot move; a seat counts as movable when its primary is. + bool toEntryPosition = false; + if (targetUnit->useNoPathfindingToGetToObject() || !target->hasMobile()) + toEntryPosition = true; + if (toEntryPosition && !target->isPrimary()) + toEntryPosition = !informationManager->getInformation(target->getPrimaryObject(bot->getSide()))->hasMobile(); + + BAPAction* move; + if (toEntryPosition) { + // 0x23D384 + BAPConObjectOccupied* const occupied = checkPointer(new BAPConObjectOccupied(m_targets[bot->getBotId()])); + BAPConObjectEnemyOccupied* const enemy = + checkPointer(new BAPConObjectEnemyOccupied(m_targets[bot->getBotId()])); + BAPConOr* const taken = checkPointer(new BAPConOr()); + taken->addCondition(occupied); + taken->addCondition(enemy); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToFinding(bot, m_entryPositions[bot->getBotId()], speed, arriveSpeed, taken, + driveControls, patternId, 0.5f, 0.0f)); + } else { + // 0x23AFEB + BAPConObjectOccupied* const occupied = checkPointer(new BAPConObjectOccupied(m_targets[bot->getBotId()])); + BAPConObjectEnemyOccupied* const enemy = + checkPointer(new BAPConObjectEnemyOccupied(m_targets[bot->getBotId()])); + BAPConOr* const taken = checkPointer(new BAPConOr()); // -0x3C4 + taken->addCondition(occupied); + taken->addCondition(enemy); + BAPConAnd* const repath = checkPointer(new BAPConAnd()); // -0x3CC + repath->addCondition(checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 10.0f, true, false, false))); + repath->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 5.0f))); + const int patternId = m_patternId; + const float arriveSpeed = mobile->getMaxSpeed() * 0.5f; + const float speed = mobile->getMaxSpeed(); + move = checkPointer(new BAPAMoveToObjectFinding(bot, m_targets[bot->getBotId()], 0.0f, speed, arriveSpeed, + taken, driveControls, patternId, repath, 0.0f, -1)); + } + approach->addStatement(move); + + // 0x23B2E3: press the enter key (input 10, controls 0x400) once within reach (radius sum + 1), + // and, for objects entered without pathfinding, from behind (dot <= -0.8). + BAPConObjectDistance* const reach = // -0x41C + checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], radiusSum + 1.0f, false, false, false)); + BAPCondition* enterCondition = reach; + if (targetUnit->useNoPathfindingToGetToObject()) { + BAPConAnd* const both = checkPointer(new BAPConAnd()); // -0x424 + both->addCondition(reach); + both->addCondition(checkPointer(new BAPConObjectBehind(m_targets[bot->getBotId()], -0.8f, false))); + enterCondition = both; + } + BAPATrigger* const enter = checkPointer(new BAPATrigger( // -0x434 + static_cast(10), enterCondition, 0, 0x400ULL, m_patternId, 0.0, false)); + BAPAUpdateVehicle* const update = checkPointer(new BAPAUpdateVehicle(m_patternId)); // -0x43C + approach->addStatement(enter); + + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); // -0x444 + // -0x449 / -0x44A: messages of type 1 / 0 waiting (std::list not empty). + const bool type1Waiting = !communication->getReceivedMessages(static_cast(1)).empty(); + const bool type0Waiting = !communication->getReceivedMessages(static_cast(0)).empty(); + // -0x450 the target's primary, -0x454 its IAIObject (read before the null test), -0x458 its bot. + Information* const primary = informationManager->getInformation(target->getPrimaryObject(bot->getSide())); + // shipped defect: the primary is dereferenced before its null test, and the distance + // calculation below runs only for a null primary. + IAIObject* const primaryObject = primary->getAIObject(); + Bot* const primaryBot = IBotManager::instance->getBot(primaryObject); + float primaryDistanceSqr = 0.0f; + if (!primary) { + const Mat4& primaryTransform = primary->getTransformation(); + const Mat4& currentTransform = current->getTransformation(); + const Vec3 delta = {primaryTransform.m[12] - currentTransform.m[12], + primaryTransform.m[13] - currentTransform.m[13], + primaryTransform.m[14] - currentTransform.m[14]}; + primaryDistanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + } + // 0x23B558: ask the driver for a ride when the bot walks into a manned vehicle's seat. + if (!m_sameVehicle[bot->getBotId()] && (current->getObjectTypeFlags() & 0x200000) + && primaryObject->getPlayerId() >= 0 && primary && primary->hasMobile() && primaryDistanceSqr < 400.0f + && !type1Waiting && !type0Waiting) { + BAPConObjectOccupied* const driverIn = checkPointer(new BAPConObjectOccupied(primary->getHandle())); // -0x464 + BAPASendRadioMessage* const ask = checkPointer(new BAPASendRadioMessage( // -0x46C + static_cast(2), static_cast(6), 3, 0.0f, m_patternId, + primaryObject->getPlayerId())); + BAPFlowCIf* const askIfManned = checkPointer(new BAPFlowCIf(driverIn, ask, 0, m_patternId, false, false)); + sequence->addStatement(askIfManned); + // 0x23C453: CommunicationAgent +0x5C = the driver's player id (IAIObject +0x148) when the + // driver is a bot, else 0xFF. + if (primaryBot) + communication->setInt92(primaryObject->getPlayerId()); + else + communication->setInt92(0xFF); + } + + // 0x23B57D: loop the approach until the target is occupied, then re-read the equipment. + BAPFlowCWhile* const untilInside = checkPointer(new BAPFlowCWhile( // -0x47C + checkPointer(new BAPConNot(checkPointer(new BAPConObjectOccupied(m_targets[bot->getBotId()])))), approach, + false, m_patternId)); + sequence->addStatement(untilInside); + sequence->addStatement(update); + + BAPCombinerParallel* const withChange = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); // -0x498 + withChange->addStatement(checkPointer(new BAPICChangeVehicle(m_targets[bot->getBotId()]))); + withChange->addStatement(sequence); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); // -0x4A8 + if (m_getInConfirm[bot->getBotId()] + && communication->generalConfirmReceivedMessage(static_cast(1))) + root->addStatement(checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(6), 2, 1.0f, m_patternId, -1))); + root->addStatement(withChange); + plan = root; + } + + // Shared tail (inlined after every branch, 0x23B7B3 here): in a vehicle, run the plan beside + // BAPAUseFlareOnMissileLock (controls bit 47); wrap it in BAPIWChange (books the target), owner = this + // (0x2370E0). + BAPStatement* wrapped = plan; + if (!(current->getObjectTypeFlags() & 0x200000)) { + BAPCombinerParallel* const flares = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + flares->addStatement(checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId))); + flares->addStatement(plan); + wrapped = flares; + } + const int playerId = bot->getPlayerId(); + BAPIWChange* const wrapper = + checkPointer(new BAPIWChange(m_targets[bot->getBotId()], wrapped, m_patternId, playerId)); + wrapper->m_owner = this; + return wrapper; +} + +// ELF 0x236340: five getBotId (Bot slot +0xE8) calls, one per store: initiated (+0x04) = true, +// +0x14 = the first bool, +0x0C = handle, +0x10 = position (three floats), +0x18 = the second bool. +void BBPChange::init(unsigned int handle, const Vec3& position, bool sameVehicle, bool getInConfirm, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_targets[bot->getBotId()] = handle; + m_entryPositions[bot->getBotId()] = position; + m_getInConfirm[bot->getBotId()] = getInConfirm; +} + +// ELF 0x2363F0: as above without the position. +void BBPChange::init(unsigned int handle, bool sameVehicle, bool getInConfirm, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_targets[bot->getBotId()] = handle; + m_getInConfirm[bot->getBotId()] = getInConfirm; +} + +// ELF 0x236470: +0x18[getBotId] = confirm. +void BBPChange::setGetInConfirm(bool confirm, Bot* bot) +{ + m_getInConfirm[bot->getBotId()] = confirm; +} + +// ELF 0x2364A0: IAIPathfinding::findClosestValidPolygon (vfn +0x94) on map `map` from `from` towards +// `to` with 10 as the search argument and `type` last; the found point (zero-initialised) goes to `out` +// in XZ whatever the answer. The Vec3 arguments arrive by invisible reference (GCC 3.3 class by value). +bool BBPChange::findValidNavPosToAir(int map, int type, Vec3 from, Vec3 to, Vec2& out) +{ + Vec3 found; + found.x = 0.0f; + found.y = 0.0f; + found.z = 0.0f; + unsigned int island; + unsigned int polygon; + const bool valid = static_cast(IAIPathfinding::instance) + ->findClosestValidPolygon(polygon, island, found, map, from, to, 10, type); + vec3ToVec2XZ(found, out); + return valid; +} + +// ELF 0x236540: three candidate segments around the aircraft, r = its IPIPhysical radius (vfn +0x2C), +// p = transformation row 3, f = row 2, s = row 0: behind (p - 2r f -> p - 3r f), right (p + r s -> +// p + 3r s), left (p - r s -> p - 3r s). The first valid one is written to `position` in XZ (y kept). +bool BBPChange::getPosAroundAircraft(Information* aircraft, int map, int type, Vec3& position) +{ + const Mat4& m = aircraft->getTransformation(); + const float r = aircraft->getPhysical()->getRadius(); + const Vec3 p = {m.m[12], m.m[13], m.m[14]}; + Vec2 found; + found.x = 0.0f; + found.y = 0.0f; + + Vec3 f = {m.m[8], m.m[9], m.m[10]}; + Vec3 to = {p.x - f.x * 3.0f * r, p.y - f.y * 3.0f * r, p.z - f.z * 3.0f * r}; + Vec3 from = {p.x - f.x * 2.0f * r, p.y - f.y * 2.0f * r, p.z - f.z * 2.0f * r}; + if (!findValidNavPosToAir(map, type, from, to, found)) { + const Vec3 s = {m.m[0], m.m[1], m.m[2]}; + to = {s.x * 3.0f * r + p.x, s.y * 3.0f * r + p.y, s.z * 3.0f * r + p.z}; + from = {p.x + s.x * r, p.y + s.y * r, p.z + s.z * r}; + if (!findValidNavPosToAir(map, type, from, to, found)) { + const Vec3 s2 = {m.m[0], m.m[1], m.m[2]}; + to = {p.x - s2.x * 3.0f * r, p.y - s2.y * 3.0f * r, p.z - s2.z * 3.0f * r}; + from = {p.x - s2.x * r, p.y - s2.y * r, p.z - s2.z * r}; + if (!findValidNavPosToAir(map, type, from, to, found)) + return false; + } + } + vec2ToVec3XZ(found, position); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h new file mode 100644 index 000000000..a4f557fa0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h @@ -0,0 +1,49 @@ +// Change pattern: per-bot target vehicle/seat, entry position and get-in flags that BBChange's urgency +// fills (init / setGetInConfirm) and createPlan consumes. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. Virtual functions are in ELF vtable slot order (vtable check). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGE_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class Information; + +// ELF: vtable 0x4BBA00 (6 words), operator new 0x1C, package F-infantry. +class BBPChange : public BBPPattern +{ +public: + explicit BBPChange(int); // 0x235CB0 + virtual ~BBPChange(); // 0x236210 + + virtual BotScript* createPlan(Bot*); // 0x236A20, slot +0x08; from the base declaration + + void init(unsigned int, const Vec3&, bool, bool, Bot*); // 0x236340; ELF void (no result register) + void init(unsigned int, bool, bool, Bot*); // 0x2363F0; ELF void + void setGetInConfirm(bool, Bot*); // 0x236470; ELF void + bool findValidNavPosToAir(int, int, Vec3, Vec3, Vec2&); // 0x2364A0; [INFERRED] ELF bool, callers {'bool': 2} + bool getPosAroundAircraft(Information*, int, int, Vec3&); // 0x236540; [INFERRED] ELF int, callers {'bool': 1} + +private: + // Every array is new[]'d with IAISettings::getMaxNBots (slot 0) entries and indexed by Bot::getBotId. + /* +0x08 */ int m_patternId; // the constructor argument: the pattern id the plan nodes carry + /* +0x0C */ unsigned int* m_targets; // init: the vehicle/seat handle + /* +0x10 */ Vec3* m_entryPositions; // value-initialised (0,0,0); init(handle, pos, ...) only + /* +0x14 */ bool* m_sameVehicle; // [INFERRED] name: init's first bool, BBChange passes "same primary object" + /* +0x18 */ bool* m_getInConfirm; // init's second bool and setGetInConfirm (named after the setter) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp new file mode 100644 index 000000000..0560c349e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp @@ -0,0 +1,133 @@ +// Seat-change pattern for landing craft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp in +// the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was checked against the listing for the trigger arguments. + +// static init: ELF 0x23F620 (__tcf_0 0x23F680, _GLOBAL__I 0x23F6B0): 's Init object only. +#include + +#include "BBPChangeLandingCraft.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWChange.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x23DFD0: BBPPattern(), the vtable store (GOT -0x280 + 8), `new bool[getMaxNBots()]` into +// +0x10, the argument at +0x08, then `new unsigned int[getMaxNBots()]` into +0x0C (both not +// initialised, each through the inlined checkPointer; operator new 0x14). The image's order. +BBPChangeLandingCraft::BBPChangeLandingCraft(int id) +{ + m_sameVehicle = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_patternId = id; + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x23E260 (D2) / 0x23E2C0 (D1) / 0x23E320 (D0): delete[] +0x0C, then +0x10 (each when set), then +// ~BBPPattern. +BBPChangeLandingCraft::~BBPChangeLandingCraft() +{ + if (m_target) + delete[] m_target; + if (m_sameVehicle) + delete[] m_sameVehicle; +} + +// ELF 0x23E400. Keeps a BAPIWChange of this pattern for the same target; otherwise drops the plan +// and builds `IWChange(target, serial(trigger, change vehicle))`: the trigger presses the target +// seat's select key when init named a seat of the same vehicle, else enter/exit (input 10, controls +// 0x400). The target's information is not null-checked before its unit is read; without own +// equipment information nothing is built. +BotScript* BBPChangeLandingCraft::createPlan(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bool otherPattern = false; + if (!bot->getPlan() || static_cast(bot->getPlan())->getPatternId() != m_patternId) + otherPattern = true; + bool otherTarget = false; + if (otherPattern || static_cast(bot->getPlan())->getTarget() != m_target[botId]) + otherTarget = true; + if (!otherTarget) + return bot->getPlan(); + + bot->getSquadMember()->clearRequestAction(); + Information* const current = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + IPIUnit* const targetUnit = target->getUnit(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + if (!current) + return 0; + + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + if (m_sameVehicle[bot->getBotId()]) + { + const int patternId = m_patternId; + const unsigned long long controls = 1ULL << targetUnit->getSelectKey(); // 64-bit shift (0x23E618) + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(targetUnit->getSelectKey(), start, stop, controls, + patternId, 0.0, false))); + } + else + { + const int patternId = m_patternId; + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + sequence->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, + 0x400ULL, patternId, 0.0, false))); + } + sequence->addStatement(checkPointer(new BAPICChangeVehicle(m_target[bot->getBotId()]))); + const int playerId = bot->getPlayerId(); + BAPIWChange* const wrapper = + checkPointer(new BAPIWChange(m_target[bot->getBotId()], sequence, m_patternId, playerId)); + wrapper->setParent(this); // +0x04 (BotScript::m_owner) + return wrapper; +} + +// ELF 0x23E390: three getBotId calls, one per store. +void BBPChangeLandingCraft::init(unsigned int target, bool sameVehicle, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_target[bot->getBotId()] = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.h new file mode 100644 index 000000000..528163645 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.h @@ -0,0 +1,38 @@ +// Seat-change pattern for landing craft: moves the bot to another seat or out of the vehicle. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGELANDINGCRAFT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGELANDINGCRAFT_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBA80 (6 words), operator new 0x14, package G-vehicles. +class BBPChangeLandingCraft : public BBPPattern +{ +public: + explicit BBPChangeLandingCraft(int); // 0x23DFD0 + virtual ~BBPChangeLandingCraft(); // 0x23E2C0 + + virtual BotScript* createPlan(Bot*); // 0x23E400, slot +0x08; from the base declaration + + void init(unsigned int target, bool sameVehicle, Bot*); // 0x23E390; ELF void (no return value materialized) + + /* +0x08 */ int m_patternId; // the constructor argument + /* +0x0C */ unsigned int* m_target; // per bot: init's handle [INFERRED] name + /* +0x10 */ bool* m_sameVehicle; // per bot: init's bool [INFERRED] name (as BBPChange's) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGELANDINGCRAFT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp new file mode 100644 index 000000000..4a7c877dc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp @@ -0,0 +1,125 @@ +// Teleport and same-vehicle seat-change plans, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x240ED0 (__tcf_0 0x240F30, _GLOBAL__I 0x240F60): 's Init object only. +#include + +#include "BBPChangeTeleport.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWait.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWChange.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIStrategic/SAI.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x23F960: BBPPattern(), the vtable store (GOT -0xFC0 + 8), `new bool[getMaxNBots()]` into +// +0x10, the argument at +0x08, then `new unsigned int[getMaxNBots()]` into +0x0C (both not +// initialised, each through the inlined checkPointer; operator new 0x14). The image's order. +BBPChangeTeleport::BBPChangeTeleport(int id) +{ + m_sameVehicle = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_patternId = id; + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x23FBF0 (D2) / 0x23FC50 (D1) / 0x23FCB0 (D0): delete[] +0x0C, then +0x10 (each when set), then +// ~BBPPattern. +BBPChangeTeleport::~BBPChangeTeleport() +{ + if (m_target) + delete[] m_target; + if (m_sameVehicle) + delete[] m_sameVehicle; +} + +// ELF 0x23FD90 +BotScript* BBPChangeTeleport::createPlan(Bot* bot) +{ + const unsigned int botId = bot->getBotId(); + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + const bool otherPattern = !bot->getPlan() + || static_cast(bot->getPlan())->getPatternId() != m_patternId; + const bool otherTarget = otherPattern + || static_cast(bot->getPlan())->getTarget() != m_target[botId]; + if (!otherTarget) + return bot->getPlan(); + + bot->getSquadMember()->clearRequestAction(); + Information* const current = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + IPIUnit* const targetUnit = target->getUnit(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + if (!current) + return 0; + + bot->setChangeTarget(m_target[bot->getBotId()]); + BAPCombinerParallel* plan; + if (m_sameVehicle[bot->getBotId()]) { + plan = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + plan->addStatement(checkPointer(new BAPICChangeVehicle(m_target[bot->getBotId()]))); + const unsigned long long controls = 1ULL << targetUnit->getSelectKey(); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + plan->addStatement(checkPointer(new BAPATrigger(targetUnit->getSelectKey(), start, stop, controls, + m_patternId, 0.0, false))); + } else { + const unsigned int teleporter = bot->getBotId(); + IAIMain::m_instance->getSAI(bot->getSide())->registerTeleporter(teleporter); + plan = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + plan->addStatement(checkPointer(new BAPICChangeVehicle(m_target[bot->getBotId()]))); + plan->addStatement(checkPointer(new BAPFlowCWait(checkPointer(new BAPConTime(2.0, false, false, false)), + m_patternId))); + } + const int playerId = bot->getPlayerId(); + BAPIWChange* const wrapper = checkPointer(new BAPIWChange(m_target[bot->getBotId()], plan, m_patternId, playerId)); + wrapper->m_owner = this; + return wrapper; +} + +// ELF 0x23FD20 +void BBPChangeTeleport::init(unsigned int target, bool sameVehicle, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_sameVehicle[bot->getBotId()] = sameVehicle; + m_target[bot->getBotId()] = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.h new file mode 100644 index 000000000..f033a2864 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.h @@ -0,0 +1,36 @@ +// Teleport and same-vehicle seat-change pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGETELEPORT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGETELEPORT_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBB00 (6 words), operator new 0x14, package G-vehicles. +class BBPChangeTeleport : public BBPPattern +{ +public: + explicit BBPChangeTeleport(int); // 0x23F960 + virtual ~BBPChangeTeleport(); // 0x23FC50 + + virtual BotScript* createPlan(Bot*); // 0x23FD90, slot +0x08; from the base declaration + + void init(unsigned int, bool, Bot*); // 0x23FD20; [INFERRED] ELF void + + /* +0x08 */ int m_patternId; // the constructor argument + /* +0x0C */ unsigned int* m_target; // per bot: init's handle [INFERRED] name + /* +0x10 */ bool* m_sameVehicle; // per bot: init's bool [INFERRED] name (as BBPChange's) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPCHANGETELEPORT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp new file mode 100644 index 000000000..049f51edd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp @@ -0,0 +1,205 @@ +// Defuse-mines pattern: per-bot plan parameters that BBDefuseMines::calculateUrgency stores through +// init. Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see +// docs/macos-ai-behaviour-plan.md. + +// static init: ELF 0x244060 (__tcf_0 0x2440C0, _GLOBAL__I 0x2440F0): 's Init object only. +#include + +#include "BBPDefuseMines.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtPoint.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICChangeVehicle.h" +#include "../AIBotActionPlan/BAPIWDefuseMines.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x240F80 (C2) / 0x2414A0 (C1): BBPPattern(), the argument to +0x08, four getMaxNBots-sized +// arrays (each checkPointer'd; the Vec3 ones run the zeroing Vec3 constructor loop, rodata +// 0x49CB34 0.0f, reproduced here by value-initialisation), then for each bot (getMaxNBots re-read +// per pass) mine and weapon index -1. +BBPDefuseMines::BBPDefuseMines(int value) + : BBPPattern() +{ + m_unknown8 = value; + m_mine = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_weaponIndex = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_minePosition = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + m_targetPosition = checkPointer(new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); ++i) + { + m_mine[i] = 0xFFFFFFFFu; + m_weaponIndex[i] = -1; + } +} + +// ELF 0x2419C0 (D2) / 0x241A50 (D1) / 0x241AE0 (D0): delete[] +0x0C..+0x18 in order when set, then +// the base. +BBPDefuseMines::~BBPDefuseMines() +{ + if (m_mine) + delete[] m_mine; + if (m_weaponIndex) + delete[] m_weaponIndex; + if (m_minePosition) + delete[] m_minePosition; + if (m_targetPosition) + delete[] m_targetPosition; +} + +// ELF 0x241C00 +BotScript* BBPDefuseMines::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + bot->getPlayer()->getSpawnKit(); + bot->getCommunicationAgent(); + if (bot->hasPlan() + && static_cast(bot->getPlan())->getPatternId() == m_unknown8 + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 1) + { + const unsigned int previousMine = static_cast(bot->getPlan())->m_mine; + if (previousMine == m_mine[bot->getBotId()]) + return bot->getPlan(); + } + const unsigned int mine = m_mine[bot->getBotId()]; + bot->getSquadMember()->clearRequestAction(); + bot->getSensingAgent()->clearPlanTargetInformation(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + bot->getScriptContext()->clear(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!self || !self->getUnit() || mine == 0) + return 0; + IPIMobile* mobile = self->getMobile(); + IPIControlInfo* controls = self->getControlInfo(); + const int weaponIndex = m_weaponIndex[bot->getBotId()]; + if (weaponIndex == -1) + { + self->getAIObject()->update(); + return 0; + } + const int side = bot->getSide(); + const unsigned int soldierHandle = bot->getPlayer()->getSoldier()->getInformation(side); + Information* soldier = informationManager->getInformation(soldierHandle); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(soldier->getArmament()->getWeapon(weaponIndex)); + BAPCombinerSerial* root = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + BAPCombinerSerial* sequence = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); + sequence->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_unknown8))); + if (!(self->getObjectTypeFlags() & 0x200000)) + { + BAPCombinerParallel* leave = checkPointer(new BAPCombinerParallel(m_unknown8, -1, false)); + leave->addStatement(checkPointer(new BAPICChangeVehicle(soldierHandle))); + BAPConFalse* stop = checkPointer(new BAPConFalse()); + BAPConTrue* start = checkPointer(new BAPConTrue()); + leave->addStatement(checkPointer(new BAPATrigger(static_cast(10), start, stop, + 0x400ULL, m_unknown8, 0.0, false))); + sequence->addStatement(leave); + } + else + { + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + const Vec3& destination = m_targetPosition[bot->getBotId()]; + sequence->addStatement(checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + 0, driveControls, m_unknown8, 0.0f, 0.0f))); + // shipped defect: a signed 32-bit input mask is sign-extended to 64 bits. + const unsigned int activateBit = 1u << (weapon->getWeaponActivate() & 31); + const unsigned long long activateMask = static_cast(static_cast(static_cast(activateBit))); + BAPConFalse* activateStop = checkPointer(new BAPConFalse()); + BAPConTrue* activateStart = checkPointer(new BAPConTrue()); + const io::PlayerInputMap activate = static_cast(weapon->getWeaponActivate()); + sequence->addStatement(checkPointer(new BAPATrigger(activate, activateStart, activateStop, + activateMask, m_unknown8, 0.0, false))); + BAPCombinerParallel* defuse = checkPointer(new BAPCombinerParallel(m_unknown8, -1, false)); + defuse->addStatement(checkPointer(new BAPASoldierPose(SPCrouching, checkPointer(new BAPConTrue()), + m_unknown8, true))); + defuse->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + const unsigned long long lookControls = self->getControlInfo()->getLookControls(); + BAPConFalse* lookCondition = checkPointer(new BAPConFalse()); + const Vec3& minePosition = m_minePosition[bot->getBotId()]; + defuse->addStatement(checkPointer(new BAPALookAtPoint(minePosition, bot, 0.0f, lookCondition, + lookControls, m_unknown8))); + const unsigned int fireBit = 1u << (weapon->getWeaponFire() & 31); + const unsigned long long fireMask = static_cast(static_cast(static_cast(fireBit))); + BAPConFalse* abort = checkPointer(new BAPConFalse()); + BAPConFalse* fireStop = checkPointer(new BAPConFalse()); + BAPConTrue* fireStart = checkPointer(new BAPConTrue()); + const io::PlayerInputMap fire = static_cast(weapon->getWeaponFire()); + defuse->addStatement(checkPointer(new BAPATriggerContinously(fire, fireStart, fireStop, abort, + fireMask, m_unknown8, 0.0))); + sequence->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), defuse, true, m_unknown8))); + } + root->addStatement(sequence); + const unsigned int target = m_mine[bot->getBotId()]; + BAPIWDefuseMines* wrapper = checkPointer(new BAPIWDefuseMines(bot, target, root, m_unknown8)); + wrapper->m_owner = this; + static_cast(bot)->resetAllControls(true, true, true); + return wrapper; +} + +// ELF 0x241B80: one getBotId; marks the bot initiated (BBPPattern +0x04) and stores the parameters. +void BBPDefuseMines::init(unsigned int mine, int weaponIndex, Bot* bot, Vec3 minePosition, Vec3 targetPosition) +{ + const unsigned int botId = bot->getBotId(); + m_initiated[botId] = true; + m_mine[botId] = mine; + m_weaponIndex[botId] = weaponIndex; + m_minePosition[botId] = minePosition; + m_targetPosition[botId] = targetPosition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.h new file mode 100644 index 000000000..9f5ad7411 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.h @@ -0,0 +1,43 @@ +// Per-bot mine, tool and movement parameters for defusing plans. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPDEFUSEMINES_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPDEFUSEMINES_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBB80 (6 words), operator new 0x1C, package F-infantry. +class BBPDefuseMines : public BBPPattern +{ +public: + explicit BBPDefuseMines(int); // 0x2414A0 + virtual ~BBPDefuseMines(); // 0x241A50 + + virtual BotScript* createPlan(Bot*); // 0x241C00, slot +0x08; from the base declaration + + // 0x241B80: void (stores only). + void init(unsigned int, int, Bot*, Vec3, Vec3); + +private: + // Constructor 0x240F80/0x2414A0, destructor 0x2419C0/0x241A50/0x241AE0; per-bot arrays are + // new [getMaxNBots] (IAISettings slot 0); init 0x241B80 writes them by Bot::getBotId. + /* +0x08 */ int m_unknown8; // creating pattern id + /* +0x0C */ unsigned int* m_mine; // -1; mine id [INFERRED] name + /* +0x10 */ int* m_weaponIndex; // -1; first weapon of type 1 [INFERRED] name + /* +0x14 */ Vec3* m_minePosition; // zeroed (Vec3 array constructor loop) + /* +0x18 */ Vec3* m_targetPosition; // zeroed +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPDEFUSEMINES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp new file mode 100644 index 000000000..08eceaeb4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp @@ -0,0 +1,68 @@ +// Fire pattern base (AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x244F10 (__tcf_0 0x244F70, _GLOBAL__I 0x244FA0): 's Init object only. +#include + +#include "BBPFire.h" + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x244910. m_patternId, m_flag20 and m_urgencyGenerator are left to the concrete constructor +// and BBFire's constructor (setUrgencyGenerator). +BBPFire::BBPFire() +{ + m_targets = checkPointer(new unsigned int[settings()->getMaxNBots()]); + m_targetChanged = checkPointer(new bool[settings()->getMaxNBots()]); + m_weapons = checkPointer(new int[settings()->getMaxNBots()]); + m_positionArgs = checkPointer(new unsigned int[settings()->getMaxNBots()]); + // [CHOSEN, not recovered] value-initialisation stands in for the image's zeroing Vec3 + // constructor loop (0x244A4B: three zero stores per element); Math::Vec3 is a POD here. + m_targetPositions = checkPointer(new Vec3[settings()->getMaxNBots()]()); +} + +// ELF 0x2441C0 +BBPFire::~BBPFire() +{ + if (m_targets) + delete[] m_targets; + if (m_targetChanged) + delete[] m_targetChanged; + if (m_weapons) + delete[] m_weapons; + if (m_positionArgs) + delete[] m_positionArgs; + if (m_targetPositions) + delete[] m_targetPositions; +} + +// ELF 0x244FC0 +int BBPFire::getImplementationType() +{ + return 0; +} + +// ELF 0x244F00 +void BBPFire::setUrgencyGenerator(BotBehaviour* behaviour) +{ + m_urgencyGenerator = behaviour; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.h new file mode 100644 index 000000000..8444e6aa9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.h @@ -0,0 +1,55 @@ +// Fire pattern base: the per-bot target state every fire pattern shares, set by BBFire's +// initializeGenerator through the two init overloads. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotBehaviour; + +// ELF: vtable 0x4BBBC0 (9 words), package D-behaviours. Abstract; the concrete patterns +// (BBPFireInfantery 0x34 bytes) start their own members at +0x28. +class BBPFire : public BBPPattern +{ +public: + BBPFire(); // 0x244910 + virtual ~BBPFire(); // 0x2441C0 + + // BBPFireInfantery::init (0x25C480) stores into the arrays below; see the member comments. + virtual void init(Bot*, unsigned int target, int weapon, bool, bool) = 0; // slot +0x18 + virtual void init(Bot*, unsigned int target, const Vec3& position, int weapon) = 0; // slot +0x1C + virtual int getImplementationType(); // 0x244FC0, slot +0x20: 0 + + void setUrgencyGenerator(BotBehaviour* behaviour); // 0x244F00 + +protected: + // Per bot slot (IAISettings::getMaxNBots), allocated by the constructor and not initialised there. + // Names as agreed with package E (coord/ai-requests.md). + /* +0x08 */ int m_patternId; // written by the concrete constructors (their int argument); + // compared with BAPStatement +0x10 of the current plan + /* +0x0C */ unsigned int* m_targets; // the firing target handle + /* +0x10 */ bool* m_targetChanged; // init: the handle differs from the previous one + /* +0x14 */ int* m_weapons; // init's int argument (the chosen weapon) + /* +0x18 */ unsigned int* m_positionArgs; // init(Vec3) overload: its handle argument + /* +0x1C */ Vec3* m_targetPositions; // init(Vec3) overload: the position; constructed zero + /* +0x20 */ bool m_flag20; // [UNRESOLVED] not written by BBPFire; E's createPlan reads it + /* +0x21 */ bool m_flag21; // [UNRESOLVED] init(Bot*, unsigned, int, bool, bool)'s second bool + // (BBPFire3d::init 0x2513C0); not read by BBPFire3d + /* +0x24 */ BotBehaviour* m_urgencyGenerator;// the owning BBFire (setUrgencyGenerator) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp new file mode 100644 index 000000000..867d4eb31 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp @@ -0,0 +1,464 @@ +// Ground-vehicle firing plans, including the shipped pointer test and inverted heat branch. + +// static init: ELF 0x24B620 (__tcf_0 0x24B680, _GLOBAL__I 0x24B6B0): 's Init object only. +#include + +#include "BBPFire2d.h" + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSenses.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAtObject.h" +#include "../AIBotActionPlan/BAPAChangeWeapon.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPANotifyBot.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCConPrecision.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConOpLessThan.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPConWeaponMagAmmo.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPWrapperWeapon.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Core/Debug.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "WeaponChoice.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] Local factoring of the image's inline variable, cleanup, +// distance, input-mask and repeated reload-trigger operations; these helper names have no symbols. + +// Inline construction and context-list insertion in ELF 0x245B58 and subsequent allocations. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +float distanceBetween(const Vec3& a, const Vec3& b) +{ + const float x = a.x - b.x; + const float y = a.y - b.y; + const float z = a.z - b.z; + return std::sqrt(x * x + y * y + z * z); +} + +// ELF 0x246B53 / 0x24769E: 32-bit shl, then sign extension to the 64-bit mask. +unsigned long long inputMask(int input) +{ + const int mask = static_cast(1u << (static_cast(input) & 31u)); + return static_cast(static_cast(mask)); +} + +// The identical reload triggers at ELF 0x245F18 and 0x248FC8. +BAPATrigger* reloadTrigger(int patternId) +{ + return checkPointer(new BAPATrigger(static_cast(32), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, patternId, 0.0, false)); +} + +} // namespace + +// ELF 0x245140: BBPFire(), the vtable store (GOT -0x178 + 8), the argument at +0x08, then +// `new bool[getMaxNBots()]` (IAISettings slot 0, not initialised) through the inlined checkPointer +// into +0x28 (operator new 0x2C). +BBPFire2d::BBPFire2d(int patternId) + : BBPFire() +{ + m_patternId = patternId; + m_perBotFlag = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x2452B0 (D2) / 0x245300 (D1) / 0x245350 (D0): delete[] +0x28 when set, then ~BBPFire. +BBPFire2d::~BBPFire2d() +{ + if (m_perBotFlag) + delete[] m_perBotFlag; +} + +// ELF 0x245650 +BotScript* BBPFire2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + return 0; + } + static_cast(bot)->resetAllControls(true, false, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const targetInfo = informationManager->getInformation(m_targets[bot->getBotId()]); + if (!targetInfo) + return 0; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + IPIPhysical* const physical = targetInfo->getPhysical(); + IPIArmament* const armament = self->getArmament(); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controls = self->getControlInfo(); + const unsigned long long driveControls = controls->getDriveControls(); + const unsigned long long aimControls = controls->getAimControls(); + const bool separateControls = (driveControls & aimControls) == 0; + SensedObject* const sensed = bot->getSensedObjectFromHandle(m_targets[bot->getBotId()]); + LocalBoundingBox* const bounds = const_cast(physical->getLocalBoundingBox()); + const int strength = physical->getStrengthType(); + const Vec3& selfPosition = self->getPosition(); + const Vec3& targetPosition = targetInfo->getPosition(); + const float distance = distanceBetween(selfPosition, targetPosition); + const unsigned int botId = bot->getBotId(); + const std::vector& weapons = armament->getWeapons(); + const int weapon = choseWeapon(weapons, m_weapons[botId], distance, strength, false, false, false, false); + if (weapon == -1) + { + self->getAIObject()->update(); + return 0; + } + WeaponInfo* const weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + armament->setActiveWeapon(weapon, bot->getSide()); + // Three inline size getters are evaluated even though their values are discarded. + (void)bounds->getSize().x; + (void)bounds->getSize().y; + (void)bounds->getSize().z; + const Vec3& currentSelfPosition = self->getPosition(); + const Vec3& currentTargetPosition = targetInfo->getPosition(); + const float targetDistance = distanceBetween(currentSelfPosition, currentTargetPosition); + const float maxRange = weaponInfo->getMaxRange(); + int lineOfFire; + if (targetDistance > static_cast(maxRange) * 0.95) + lineOfFire = mobile ? 0 : 3; + else if (sensed && !(sensed->m_flags & SensedObject::SENSE_INDIRECT)) + lineOfFire = 1; + else + { + Vec3 aimPoint = {0.0f, 0.0f, 0.0f}; + if (sensed) + { + const Mat4& m = targetInfo->getTransformation(); + const Vec3& p = sensed->m_seenPosition; + aimPoint.x = m.m[0] * p.x + m.m[4] * p.y + m.m[8] * p.z + m.m[12]; + aimPoint.y = m.m[1] * p.x + m.m[5] * p.y + m.m[9] * p.z + m.m[13]; + aimPoint.z = m.m[2] * p.x + m.m[6] * p.y + m.m[10] * p.z + m.m[14]; + } + else + aimPoint = targetInfo->getPosition(); + std::vector excluded; + excluded.push_back(self->getAIObject()); + excluded.push_back(targetInfo->getAIObject()); + lineOfFire = environment->hasIndirectLineOfFire(weaponInfo->getWeapon(), weaponInfo->getPosition(), aimPoint, excluded) + ? 2 : (mobile ? 0 : 3); + } + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0) + { + BAPIWFire* const existing = static_cast(bot->getPlan()); + if (existing->getTarget() == m_targets[bot->getBotId()] && existing->getInt28() == lineOfFire) + return bot->getPlan(); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + bot->getSquadMember()->clearRequestAction(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + BAPVariable* const weaponVariable = newVariable(context, weaponInfo); + BAPVariable* const targetVariable = newVariable(context, m_targets[bot->getBotId()]); + BAPStatement* statement = 0; + if (lineOfFire == 3) + { + SensedObject* blocked = bot->getSensedObjectFromHandle(m_targets[bot->getBotId()]); + if (!blocked) + { + const unsigned int primary = targetInfo->getPrimaryObject(targetInfo->getSide()); + Information* const primaryInfo = informationManager->getInformation(primary); + if (primaryInfo) + { + const Vec3 zero = {0.0f, 0.0f, 0.0f}; + bot->getSensingAgent()->getSenses()->event_seenObject(primary, zero, static_cast(-1), + primaryInfo, false, false); + blocked = bot->getSensedObjectFromHandle(primary); + } + } + // shipped defect: no guard if the primary information/sensed record is absent. + blocked->m_flags |= 0x20; + blocked->m_fireRating = -100; + blocked->m_lastSense = 0x20; + return 0; + } + if (lineOfFire == 0) + { + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + BAPCombinerParallel* const approach = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + const int equipment = self->getUnit()->getEquipmentType(); + BAPStatement* movement; + if (pathfinding->isValidPosition(mobile->getVehicleNumber(), equipment, targetInfo->getPosition(), true)) + { + BAPConAnd* const close = checkPointer(new BAPConAnd()); + close->addCondition(checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 50.0f, true, true, false))); + close->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 10.0f))); + const unsigned long long drive = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + const float approachDistance = targetDistance * 0.75f; + const float rangeLimit = weaponInfo->getMaxRange() * 0.95f; + movement = checkPointer(new BAPAMoveToObjectFinding(bot, m_targets[bot->getBotId()], + rangeLimit > approachDistance ? approachDistance : rangeLimit, speed, arriveSpeed, 0, + drive, m_patternId, close, 0.0f, -1)); + } + else + { + Vec3 goal = {0.0f, 0.0f, 0.0f}; + unsigned int polygon, island; + const Vec3& from = self->getPosition(); + const Vec3& to = targetInfo->getPosition(); + pathfinding->findClosestValidPolygon(polygon, island, goal, mobile->getVehicleNumber(), to, from, 10, equipment); + const float maximum = weaponInfo->getMaxRange(); + const float minimum = weaponInfo->getMinRange(); + const float band = (maximum - minimum) * 0.1f; + const float stoppingDistance = weaponInfo->getMinRange() + band; + const unsigned long long drive = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + movement = checkPointer(new BAPAMoveToFinding(bot, goal, speed, arriveSpeed, 0, + drive, m_patternId, stoppingDistance, 0.0f)); + } + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject(bot, m_targets[bot->getBotId()], 0.034906585f, + checkPointer(new BAPConFalse()), controls->getLookControls(), m_patternId, 0, 0.0f)); + approach->addStatement(movement); + approach->addStatement(look); + statement = approach; + } + else if (lineOfFire == 1 || lineOfFire == 2) + { + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + if (weaponInfo->getWeaponActivate() != 64) + sequence->addStatement(checkPointer(new BAPAChangeWeapon(bot, weapon, m_patternId))); + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const reload = reloadTrigger(m_patternId); + sequence->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, false, false))); + BAPVariable* const unused = newVariable(context, 0); + (void)unused; + BAPConNot* alive; + { + std::list lost; + lost.push_back(checkPointer(new BAPConObjectHealth(m_targets[bot->getBotId()], 0.0f))); + lost.push_back(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false))); + BAPConOr* const any = checkPointer(new BAPConOr(lost)); + std::list wrapped; + wrapped.push_back(any); + alive = checkPointer(new BAPConNot(wrapped)); + } + BAPCombinerSerial* const repeat = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + if (!weaponInfo->hasAutoReload()) + { + BAPConWeaponMagAmmo* const noAmmo = checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const trigger = reloadTrigger(m_patternId); + repeat->addStatement(checkPointer(new BAPFlowCWhile(noAmmo, trigger, m_patternId))); + } + // shipped defect: this cooling branch is selected when hasHeat() is false. + if (!weaponInfo->hasHeat()) + { + BAPConWeaponHeat* const hot = checkPointer(new BAPConWeaponHeat(weaponVariable, 0.8f)); + BAPConWeaponHeat* const cooled = checkPointer(new BAPConWeaponHeat(weaponVariable, 0.7f)); + BAPCombinerSerial* const cool = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, false, true, m_patternId)); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject(bot, m_targets[bot->getBotId()], 0.1f, + cooled, controls->getLookControls(), m_patternId, 0, 0.0f)); + cool->addStatement(look); + cool->addStatement(reset); + repeat->addStatement(checkPointer(new BAPFlowCIf(hot, cool, 0, m_patternId, false, false))); + } + BAPVariable* const ammo = newVariable(context, 0); + repeat->addStatement(checkPointer(new BAPWrapperWeapon(static_cast(0), ammo, weaponVariable, false))); + BAPCombinerParallel* const firing = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + const Vec3 zero = {0.0f, 0.0f, 0.0f}; + // shipped defect: tests the allocated array pointer, not this bot's flag. + BAPAAimAtObject* const aim = checkPointer(new BAPAAimAtObject(bot, m_targets[bot->getBotId()], zero, + checkPointer(new BAPConFalse()), controls->getAimControls(), m_patternId, m_perBotFlag != 0, 0, 0)); + firing->addStatement(aim); + BAPVariable* const heat = newVariable(context, 0.0f); + firing->addStatement(checkPointer(new BAPWrapperWeapon(static_cast(1), heat, weaponVariable, true))); + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const Vec3& selfPositionNow = self->getPosition(); + const Vec3& targetPositionNow = targetInfo->getPosition(); + const float rangeDistance = distanceBetween(selfPositionNow, targetPositionNow); + const float minimum = weaponInfo->getMinRange(); + const float maximum = weaponInfo->getMaxRange(); + const float rangeMinimum = weaponInfo->getMinRange(); + const float fraction = (rangeDistance - minimum) / (maximum - rangeMinimum); + const float precisionScale = (1.0f - fraction) * 0.1f + fraction * 5.0f; + float precisionFactor; + float minimumPrecision; + if (targetInfo->getObjectTypeFlags() & 0x10) + { + precisionFactor = 0.8f; + minimumPrecision = 0.5f; + } + else if (m_perBotFlag) + { + precisionFactor = 2.5f; + minimumPrecision = 10.0f; + } + else + { + precisionFactor = 1.5f; + minimumPrecision = 5.0f; + } + const float xSize = box->getSize().x; + const float ySize = box->getSize().y; + const float zSize = box->getSize().z; + const float yz = zSize > ySize ? zSize : ySize; + const float size = yz > xSize ? yz : xSize; + const float scaled = size * precisionFactor; + const float precision = scaled > minimumPrecision ? scaled : minimumPrecision; + BAPCConPrecision* const accurate = checkPointer(new BAPCConPrecision(m_targets[bot->getBotId()], aim, + precision * precisionScale, !weaponInfo->getBurst(), false, false)); + BAPConOr* stopFiring; + { + std::list stop; + stop.push_back(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, ammo, true))); + stop.push_back(checkPointer(new BAPConOpLessThan(newVariable(context, 0.5f), heat))); + stopFiring = checkPointer(new BAPConOr(stop)); + } + BAPStatement* fire; + if (weaponInfo->getBurst()) + { + const unsigned long long mask = inputMask(weaponInfo->getWeaponFire()); + fire = checkPointer(new BAPATriggerContinously(static_cast(weaponInfo->getWeaponFire()), accurate, 0, + stopFiring, mask, m_patternId, 0.0)); + } + else + { + const unsigned long long mask = inputMask(weaponInfo->getWeaponFire()); + BAPConFalse* const end = checkPointer(new BAPConFalse()); + BAPATrigger* const trigger = checkPointer(new BAPATrigger(static_cast(weaponInfo->getWeaponFire()), accurate, + end, mask, m_patternId, 0.0, false)); + std::list conditions; + conditions.push_back(stopFiring); + BAPConNot* const keepFiring = checkPointer(new BAPConNot(conditions)); + fire = checkPointer(new BAPFlowCWhile(keepFiring, trigger, m_patternId)); + } + firing->addStatement(fire); + repeat->addStatement(firing); + repeat->addStatement(checkPointer(new BAPANotifyBot(static_cast(0), + newVariable(context, 1), targetVariable))); + sequence->addStatement(checkPointer(new BAPFlowCWhile(alive, repeat, m_patternId))); + BAPCombiner* root; + if (separateControls) + root = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + else + root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + root->addStatement(checkPointer(new BAPAResetControls(true, false, false, m_patternId))); + root->addStatement(sequence); + statement = root; + } + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, m_targets[bot->getBotId()], m_flag20, false, + weapon, -1, statement, m_patternId)); + plan->setInt28(lineOfFire); + plan->setParent(this); + const unsigned int firingBotId = bot->getBotId(); + const unsigned int* const targets = m_targets; + const int side = bot->getSide(); + const int player = bot->getPlayerId(); + SquadManager::m_instance->shotsFired(player, side, targets[firingBotId]); + return plan; +} + +// ELF 0x2453A0 +void BBPFire2d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + init(bot, target, weapon, flag20, flag21, false); +} + +// ELF 0x2454A0 +void BBPFire2d::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp", 0x8D, "") + << "LaserGuided missiles unsuported by artillry."; + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x24B6D0 +int BBPFire2d::getImplementationType() +{ + return 2; +} + +// ELF 0x245400 +void BBPFire2d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21, bool perBotFlag) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_perBotFlag[bot->getBotId()] = perBotFlag; + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; + m_positionArgs[bot->getBotId()] = static_cast(-1); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.h new file mode 100644 index 000000000..6052017b7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.h @@ -0,0 +1,38 @@ +// Builds approach and firing plans for ground-vehicle weapons. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2D_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBC80 (9 words), operator new 0x2C, package G-vehicles. +class BBPFire2d : public BBPFire +{ +public: + explicit BBPFire2d(int); // 0x245140 + virtual ~BBPFire2d(); // 0x245300 + + virtual BotScript* createPlan(Bot*); // 0x245650, slot +0x08; from the base declaration + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x2453A0, slot +0x18; from the base declaration + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x2454A0, slot +0x1C; from the base declaration + virtual int getImplementationType(); // 0x24B6D0, slot +0x20; from the base declaration + + void init(Bot*, unsigned int, int, bool, bool, bool); // 0x245400; [INFERRED] ELF void + + /* +0x28 */ bool* m_perBotFlag; // per bot: the last bool of init 0x245400 [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp new file mode 100644 index 000000000..b98e236c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp @@ -0,0 +1,464 @@ +// Fire pattern of artillery drivers and other ground vehicles that aim with their own turret +// (AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp in the image, the init(Vec3) __FILE__). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// createPlan was rebuilt from the listing block by block: Ghidra drops the bool arguments of the +// condition and flow constructors, passes the findClosestValidPolygon out-values by value and +// shows the while loop's swapped arguments as constants; GCC evaluates the constructor arguments +// right to left, which fixes the source order of the nested allocations below. +// [PLATFORM] precision: the x87 build keeps the distance sums, the circle radius and the +// approach-distance products in extended precision before rounding; the float expressions below +// round each step. + +#include "BBPFire2dDriver.h" + +#include +#include +#include + +#include "../../../../Core/Debug.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATurnTowardsObject.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConObjectValidAiming.h" +#include "../AIBotActionPlan/BAPConObjectValidPitchAiming.h" +#include "../AIBotActionPlan/BAPConObjectValidYawAiming.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIBotActionPlan/BAPWrapperAiming.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/TraceUtils.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "WeaponChoice.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x251060, __tcf_0 0x2510C0, _GLOBAL__I 0x2510F0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +IAIObjectEnvironment* objectEnvironment() +{ + return static_cast(CommonSingletonServer::m_iaiObjectEnvironment); +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// |to - from| from the extended-precision sum, as the image computes both target distances. +float distanceBetween(const Vec3& from, const Vec3& to) +{ + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// The approach move both the direct and the aiming branch build when there is no line of fire or +// the target is out of reach (0x24CC23..0x24CEE3 and 0x250310..0x2505CA, 0x24EB30.., 0x250A10..). +// A valid target position gets an object-finding move that ends near (50 m) or when the target +// moved 10 m; otherwise the closest valid polygon towards the target is approached up to a tenth +// of the weapon's range band. The findClosestValidPolygon answer is discarded as compiled. +BAPStatement* newApproach(Bot* bot, unsigned int target, unsigned int currentTarget, Information* self, + Information* targetInfo, IPIMobile* mobile, IPIControlInfo* controlInfo, + WeaponInfo* weaponInfo, int equipmentType, float targetDistance, int patternId) +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + if (pathfinding->isValidPosition(mobile->getVehicleNumber(), equipmentType, targetInfo->getPosition(), true)) + { + BAPConAnd* const close = checkPointer(new BAPConAnd()); + close->addCondition(checkPointer(new BAPConObjectDistance(currentTarget, 50.0f, true, true, false))); + close->addCondition(checkPointer(new BAPConObjectMoved(currentTarget, 10.0f))); + // min(range * 0.95, distance * 0.75); unordered keeps the range term (`fcmovnbe`). + const float rangeLimit = weaponInfo->getMaxRange() * 0.95f; + const float approach = targetDistance * 0.75f; + return checkPointer(new BAPAMoveToObjectFinding(bot, target, rangeLimit > approach ? approach : rangeLimit, + mobile->getMaxSpeed(), mobile->getMaxSpeed(), + checkPointer(new BAPConFalse()), + controlInfo->getDriveControls(), patternId, close, 0.0f, -1)); + } + + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec3 unused; // zeroed beside the goal and never read + unused.x = unused.y = unused.z = 0.0f; + (void)unused; + unsigned int island; + unsigned int polygon; + pathfinding->findClosestValidPolygon(polygon, island, goal, mobile->getVehicleNumber(), targetInfo->getPosition(), + self->getPosition(), 10, equipmentType); + return checkPointer(new BAPAMoveToFinding( + bot, goal, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, controlInfo->getDriveControls(), patternId, + weaponInfo->getMinRange() + (weaponInfo->getMaxRange() - weaponInfo->getMinRange()) * 0.1f, 0.0f)); +} + +} // namespace + +// ELF 0x24BBF0 (C1; C2 0x24BA80): BBPFire(), the vtable store, the argument at +0x08, then one +// flag per bot slot (IAISettings::getMaxNBots), not initialised. +BBPFire2dDriver::BBPFire2dDriver(int patternId) + : BBPFire() +{ + m_patternId = patternId; + m_flags28 = checkPointer(new bool[settings()->getMaxNBots()]); +} + +// ELF 0x24BDB0 (D1; D2 0x24BD60, D0 0x24BE00): the flag array, then BBPFire's destructor. +BBPFire2dDriver::~BBPFire2dDriver() +{ + if (m_flags28) + delete[] m_flags28; +} + +// ELF 0x24C100. An uninitiated pattern clears the debugger and drops the plan (the context is left) +// and builds nothing. Otherwise the controls are reset (true, false, true), a weapon is chosen +// for the distance and the target's strength type (none: the own object's update, no plan), and +// the line of fire is classified: 1 when the target is sensed directly, else 2 or 0 from the +// indirect line-of-fire test against the sensed part (or the target's position). A fire plan of +// this pattern built for the same target, classification and closeness is kept. Otherwise the +// plan is rebuilt as IWFire over +// 0: an approach move (newApproach); +// too close (inside the minimum range + 0.5 m): a move to the best point found by tracing a +// circle of 2 * minimum range + 5 m around the target, 15 degree steps alternating to both +// sides of the bearing away from the target, ended once outside the minimum range + 1 m; +// else: parallel(aiming wrapper, if(within minimum range + 0.5 m: nothing, +// else if(out of 0.9 * range or no valid aim: approach move, else fire loop))), +// the fire loop being while(alive and occupied and not within the minimum range + 0.5 m: reset +// controls), behind a yaw check that turns towards the target first for a turnable vehicle. +// Shipped quirks kept: the target information, its physical, the armament and the equipment are +// not null-checked; the target's local bounding box is fetched and dropped; two plan variables +// (weapon, target) are created and never used; the while loop gets (m_patternId != 0, 0) for +// (testOnFinish, patternId); the turn takes the raw drive-turn input as its control mask. +BotScript* BBPFire2dDriver::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + return 0; + } + + static_cast(bot)->resetAllControls(true, false, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); + IAIObjectEnvironment* const environment = objectEnvironment(); + Vec2 targetPosition2d; // converted and never read + targetPosition2d.x = targetPosition2d.y = 0.0f; + Vec2 selfPosition2d; + selfPosition2d.x = selfPosition2d.y = 0.0f; + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + vec3ToVec2XZ(targetInfo->getPosition(), targetPosition2d); + vec3ToVec2XZ(self->getPosition(), selfPosition2d); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + int armamentIterator; + IPIArmament* const armament = + informationManager->getInformation(self->getFirstSecondaryObject(armamentIterator, bot->getSide()))->getArmament(); + const int strengthType = targetPhysical->getStrengthType(); + const float distance = distanceBetween(self->getPosition(), targetInfo->getPosition()); + const int weapon = choseWeapon(armament->getWeapons(), m_weapons[bot->getBotId()], distance, strengthType, false, + false, false, false); + if (weapon == -1) + { + self->getAIObject()->update(); + return 0; + } + + WeaponInfo* const weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + const float targetDistance = distanceBetween(self->getPosition(), targetInfo->getPosition()); + const bool tooClose = weaponInfo->getMinRange() + 0.5f > targetDistance; + SensedObject* const sensed = bot->getSensedObjectFromHandle(m_targets[bot->getBotId()]); + targetPhysical->getLocalBoundingBox(); // [UNRESOLVED] result unused in the image (0x24C57D) + + int lineOfFire; + if (sensed && !(sensed->m_flags & 8)) + lineOfFire = 1; + else + { + Vec3 aimPoint; + aimPoint.x = aimPoint.y = aimPoint.z = 0.0f; + if (sensed) + { + // The sensed part's offset in the target's frame, in world space (0x250DC0). + const Mat4& transform = targetInfo->getTransformation(); + const Vec3& part = sensed->m_seenPosition; + aimPoint.x = transform.m[0] * part.x + transform.m[4] * part.y + transform.m[8] * part.z + transform.m[12]; + aimPoint.y = transform.m[1] * part.x + transform.m[5] * part.y + transform.m[9] * part.z + transform.m[13]; + aimPoint.z = part.x * transform.m[2] + part.y * transform.m[6] + part.z * transform.m[10] + transform.m[14]; + } + else + aimPoint = targetInfo->getPosition(); + std::vector excluded; + excluded.push_back(self->getAIObject()); + excluded.push_back(targetInfo->getAIObject()); + lineOfFire = environment->hasIndirectLineOfFire(weaponInfo->getWeapon(), weaponInfo->getPosition(), aimPoint, + excluded) + ? 2 + : 0; + } + + if (bot->hasPlan() && static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && static_cast(bot->getPlan())->getInt28() == lineOfFire + && static_cast(bot->getPlan())->getFlagB() == tooClose) + return bot->getPlan(); + + bot->getSquadMember()->clearRequestAction(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + const int equipmentType = self->getUnit()->getEquipmentType(); + + BAPStatement* statement; + if (lineOfFire == 0) + { + statement = newApproach(bot, target, m_targets[bot->getBotId()], self, targetInfo, mobile, controlInfo, + weaponInfo, equipmentType, targetDistance, m_patternId); + } + else if (tooClose) + { + float angle = 0.0f; + float bestDistanceSqr = 0.0f; + Vec2 best = selfPosition2d; + const float minRange = weaponInfo->getMinRange(); + const float radius = minRange + minRange + 5.0f; + const float limitSqr = (radius - 1.0f) * (radius - 1.0f); + const Vec3& targetPosition = targetInfo->getPosition(); + const Vec3& selfPosition = self->getPosition(); + Vec3 away = bapinline::vec3(selfPosition.x - targetPosition.x, selfPosition.y - targetPosition.y, + selfPosition.z - targetPosition.z); + if (bapinline::lengthSqr(away) > 0.1f) + bapinline::normalize(away); + else + away = bapinline::vec3(1.0f, 0.0f, 0.0f); + while (bestDistanceSqr <= limitSqr && angle <= 1.5707964f) + { + Vec3 point = bapinline::vec3(0.0f, 0.0f, 0.0f); + const bool reached = TraceUtils::tracePointOnCircle(away, targetInfo->getPosition(), self->getPosition(), + mobile->getVehicleNumber(), angle, radius, point); + angle = -angle; + if (angle >= 0.0f) + angle += 0.2617994f; // 15 degrees (0x3E860A92) + if (reached) + { + const Vec3& centre = targetInfo->getPosition(); + const float dx = centre.x - point.x; + const float dy = centre.y - point.y; + const float dz = centre.z - point.z; + const float distanceSqr = dx * dx + dy * dy + dz * dz; + if (distanceSqr > bestDistanceSqr) + { + bestDistanceSqr = distanceSqr; + vec3ToVec2XZ(point, best); + } + } + } + + Vec3 goal = bapinline::vec3(0.0f, 0.0f, 0.0f); + BAPConObjectDistance* const inside = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange() + 1.0f, true, false, false)); + BAPConNot* const outside = checkPointer(new BAPConNot()); + outside->addCondition(inside); + vec2ToVec3XZ(best, goal); + statement = checkPointer(new BAPAMoveToFinding(bot, goal, mobile->getMaxSpeed(), mobile->getMaxSpeed(), outside, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + } + else + { + const bool turnable = mobile->isTurnable(); + int secondaryIterator; + const unsigned int secondary = self->getFirstSecondaryObject(secondaryIterator, self->getSide()); + newVariable(context, weaponInfo); // never read + newVariable(context, target); // never read + BAPVariable* const aimValid = newVariable(context, false); + BAPVariable* const aimDirection = newVariable(context, bapinline::vec3(0.0f, 1.0f, 0.0f)); + BAPVariable* const aimPosition = newVariable(context, bapinline::vec3(0.0f, 1.0f, 0.0f)); + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + parallel->addStatement( + checkPointer(new BAPWrapperAiming(aimDirection, aimValid, aimPosition, secondary, target, false))); + + // Reposition when out of 0.9 * range or without a valid aim. + BAPConOr* const reposition = checkPointer(new BAPConOr()); + { + BAPConObjectDistance* const inRange = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMaxRange() * 0.9f, true, false, false)); + BAPConNot* const outOfRange = checkPointer(new BAPConNot()); + outOfRange->addCondition(inRange); + reposition->addCondition(outOfRange); + } + if (turnable) + { + BAPConObjectValidPitchAiming* const pitch = + checkPointer(new BAPConObjectValidPitchAiming(target, secondary, aimValid, aimDirection)); + BAPConNot* const noPitch = checkPointer(new BAPConNot()); + noPitch->addCondition(pitch); + reposition->addCondition(noPitch); + } + else + { + BAPConObjectValidAiming* const aim = + checkPointer(new BAPConObjectValidAiming(target, secondary, aimValid, aimDirection, false)); + BAPConNot* const noAim = checkPointer(new BAPConNot()); + noAim->addCondition(aim); + reposition->addCondition(noAim); + } + + BAPStatement* const approach = newApproach(bot, target, m_targets[bot->getBotId()], self, targetInfo, mobile, + controlInfo, weaponInfo, equipmentType, targetDistance, m_patternId); + + BAPConAnd* keepFiring; + { + std::list lost; + lost.push_back(checkPointer(new BAPConObjectHealth(target, 0.0f))); + BAPConObjectOccupied* const occupied = checkPointer(new BAPConObjectOccupied(secondary)); + BAPConNot* const empty = checkPointer(new BAPConNot()); + empty->addCondition(occupied); + lost.push_back(empty); + BAPConOr* const lostTarget = checkPointer(new BAPConOr(lost)); + std::list wrapped; + wrapped.push_back(lostTarget); + BAPConNot* const alive = checkPointer(new BAPConNot(wrapped)); + BAPConObjectDistance* const inside = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange() + 0.5f, true, false, false)); + BAPConNot* const outside = checkPointer(new BAPConNot()); + outside->addCondition(inside); + keepFiring = checkPointer(new BAPConAnd()); + keepFiring->addCondition(outside); + keepFiring->addCondition(alive); + } + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(true, true, true, m_patternId)); + // The image passes (m_patternId != 0, 0) for (testOnFinish, patternId) (0x24D2CF): kept. + BAPFlowCWhile* const fireLoop = checkPointer(new BAPFlowCWhile(keepFiring, reset, m_patternId != 0, 0)); + BAPStatement* fire = fireLoop; + if (turnable) + { + BAPConObjectValidYawAiming* const yaw = + checkPointer(new BAPConObjectValidYawAiming(target, secondary, aimValid, aimDirection)); + // The drive-turn input itself, zero-extended, is the control mask (0x24D958). + BAPATurnTowardsObject* const turn = checkPointer(new BAPATurnTowardsObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), // 5 degrees (0x3DB2B8C2) + static_cast(static_cast(controlInfo->getDriveTurnControl())), + m_patternId)); + fire = checkPointer(new BAPFlowCIf(yaw, fireLoop, turn, m_patternId, true, false)); + } + BAPFlowCIf* const engage = checkPointer(new BAPFlowCIf(reposition, approach, fire, m_patternId, true, false)); + BAPConObjectDistance* const inside = + checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange() + 0.5f, true, false, false)); + parallel->addStatement(checkPointer(new BAPFlowCIf(inside, 0, engage, m_patternId, true, false))); + statement = parallel; + } + + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, m_targets[bot->getBotId()], m_flag20, tooClose, weapon, -1, + statement, m_patternId)); + plan->setInt28(lineOfFire); + plan->setParent(this); // +0x04 (BotScript::m_owner) + SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); + return plan; +} + +// ELF 0x24BE50: the six-argument form with the last flag false. +void BBPFire2dDriver::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + init(bot, target, weapon, flag20, flag21, false); +} + +// ELF 0x24BF50. The Debug error is the image's (it aborts in this tree); the arguments are then +// stored like BBPFire3d's overload. +void BBPFire2dDriver::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp", 0x93, "") + << "LaserGuided missiles unsuported by artillry drivers."; + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x251110 (weak) +int BBPFire2dDriver::getImplementationType() +{ + return 3; +} + +// ELF 0x24BEB0 +void BBPFire2dDriver::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21, bool flag28) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_flags28[bot->getBotId()] = flag28; + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; + m_positionArgs[bot->getBotId()] = static_cast(-1); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.h new file mode 100644 index 000000000..828a4ac81 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.h @@ -0,0 +1,42 @@ +// Fire pattern of artillery drivers and other ground vehicles aiming with their own turret. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2DDRIVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2DDRIVER_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBD60 (9 words), operator new 0x2C, package H-deferred. +class BBPFire2dDriver : public BBPFire +{ +public: + explicit BBPFire2dDriver(int); // 0x24BBF0 + virtual ~BBPFire2dDriver(); // 0x24BDB0 + + virtual BotScript* createPlan(Bot*); // 0x24C100, slot +0x08; from the base declaration + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x24BE50, slot +0x18; from the base declaration + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x24BF50, slot +0x1C; from the base declaration + virtual int getImplementationType(); // 0x251110, slot +0x20; from the base declaration + + void init(Bot*, unsigned int, int, bool, bool, bool); // 0x24BEB0; [INFERRED] ELF void + + // One flag per bot slot, allocated (not initialised) by the constructor; init's sixth + // argument. [UNRESOLVED] meaning: createPlan does not read it. + /* +0x28 */ bool* m_flags28; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE2DDRIVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp new file mode 100644 index 000000000..ca7c28ec7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp @@ -0,0 +1,532 @@ +// Fire pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Ghidra pseudocode was checked against the listing for constructor overloads, constant arguments +// and statement order (it drops the bool arguments of the combiner constructors and misreads the +// last turn lock of mode 1). +// [PLATFORM] precision: the x87 build keeps the radius sum and the bounding-box sum in extended +// precision before doubling or dividing; the float expressions below round them first. + +// static init: ELF 0x25B970 (__tcf_0 0x25B9D0, _GLOBAL__I 0x25BA00): 's Init object only. +#include + +#include "BBPFire3d.h" + +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPAAimAtPoint3d.h" +#include "../AIBotActionPlan/BAPAChangeWeapon.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCConBombPrecision3d.h" +#include "../AIBotActionPlan/BAPCConPrecision3d.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConInsideBattleZone.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectInFront.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConPointDistance.h" +#include "../AIBotActionPlan/BAPConPointInFront.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponHasLockOnTarget.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPConWeaponMagAmmo.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// `1 << input` sign-extended to the 64-bit control mask (`movl %eax,%edx; sarl $0x1f,%edx`). +unsigned long long inputMask(int input) +{ + return static_cast(static_cast(1 << input)); +} + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// "The target is still worth attacking": And{ Exists(target), [Occupied(target)], Not(Health(target, 0)), +// [WeaponHeat(weapon) < heat] }, the loop condition of createPlanInternal's three arms. +BAPConAnd* newTargetAlive(BAPContext* context, unsigned int target, IPIUnit* targetUnit, WeaponInfo* weapon, + float heat) +{ + BAPConAnd* const alive = checkPointer(new BAPConAnd()); + alive->addCondition(checkPointer(new BAPConObjectExists(target))); + if (targetUnit && targetUnit->isOccupied()) + alive->addCondition(new BAPConObjectOccupied(target)); // no checkPointer in the image + alive->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConObjectHealth(target, 0.0f))))); + if (weapon->hasHeat()) + alive->addCondition(checkPointer(new BAPConWeaponHeat(newVariable(context, weapon), heat))); + return alive; +} + +} // namespace + +// ELF 0x2512C0: BBPFire(), the vtable store, then the argument at +0x08. +BBPFire3d::BBPFire3d(int patternId) + : BBPFire() +{ + m_patternId = patternId; +} + +// ELF 0x251340 (D0 0x251380): the vtable store, then BBPFire's destructor; nothing of its own. +BBPFire3d::~BBPFire3d() +{ +} + +// ELF 0x2514E0. Keeps a fire plan of this pattern built for the same target, flag and weapon; +// otherwise drops the plan and builds `IWFire(serial([change weapon], parallel(reset controls, +// flares on missile lock, attack)))`. The attack comes from createPlanLaserGuided when the target +// is no object but a designated point, otherwise from createPlanInternal with the FireData mode +// chosen from the own vehicle and the target. Without a usable target, or with no weapon chosen, +// no plan is built (with no weapon the own object's update is called first, as compiled). +BotScript* BBPFire3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + static_cast(bot)->resetAllControls(false, true, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() && static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && m_flag20 == static_cast(bot->getPlan())->getFlagA() + && static_cast(bot->getPlan())->getWeapon() == m_weapons[bot->getBotId()]) + return bot->getPlan(); + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + bot->getScriptContext()->clear(); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); + FireData data; + data.m_position.x = data.m_position.y = data.m_position.z = 0.0f; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(self->getArmament()->getWeapon(m_weapons[bot->getBotId()])); + + BAPStatement* attack; + if (!targetInfo) + { + if (m_positionArgs[bot->getBotId()] == static_cast(-1)) + return 0; + attack = createPlanLaserGuided(bot, data); + } + else + { + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIPhysical* const selfPhysical = self->getPhysical(); + if (!targetPhysical || !controlInfo || !selfPhysical) + return 0; + IPIMobile* const targetMobile = targetInfo->getMobile(); + LocalBoundingBox* const box = const_cast(targetPhysical->getLocalBoundingBox()); + if (m_weapons[bot->getBotId()] == -1) + { + self->getAIObject()->update(); + return 0; + } + bot->getSquadMember()->clearRequestAction(); + const float selfRadius = selfPhysical->getRadius(); + const float radius = targetMobile ? targetPhysical->getRadius() + selfRadius : selfRadius + 0.0f; + data.m_approachRadius = radius + radius; + const bool indirect = weapon->getIndirect(); + const bool flag40 = (targetInfo->getObjectTypeFlags() & 0x40) != 0; + if (!self->getMobile()) + { + data.m_mode = 3; + } + else if (!flag40) + { + data.m_mode = 0; + data.m_precision = weapon->getAllowedDeviation(); + } + else if (!indirect) + { + data.m_mode = 1; + data.m_precision = weapon->getAllowedDeviation(); + } + else + { + data.m_mode = 2; + const float size = (box->getSize().x + box->getSize().y + box->getSize().z) / 3.0f; + data.m_precision = size > 10.0f ? size : 10.0f; // 0x251FD4 fcmovbe: NaN gives 10 + } + attack = createPlanInternal(bot, data); + } + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + parallel->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); // no checkPointer + parallel->addStatement(attack); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, true, -1)); + if (m_weapons[bot->getBotId()] != -1 && weapon->getWeaponActivate() != 0x40) + serial->addStatement(checkPointer(new BAPAChangeWeapon(bot, m_weapons[bot->getBotId()], m_patternId))); + serial->addStatement(parallel); + BAPIWFire* const plan = checkPointer( + new BAPIWFire(bot, target, m_flag20, false, m_weapons[bot->getBotId()], -1, serial, m_patternId)); + plan->setParent(this); // +0x04 (BotScript::m_owner) + SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); + return plan; +} + +// ELF 0x2513C0 +void BBPFire3d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_positionArgs[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; +} + +// ELF 0x251440 +void BBPFire3d::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x25BA20 +int BBPFire3d::getImplementationType() +{ + return 4; +} + +// ELF 0x252260 (listing; the switch is `cmpl $1/2/3` at 0x252447). Modes 1 and 2 (the target has +// type flag 0x40) and mode 0 loop while the target is alive and, for a weapon with heat, not too +// hot: inside the battle zone (150) the bot attacks when the target is in range (mode 0: and in the +// line of fire; modes 1/2: and in front) and otherwise approaches it; outside it flies back to the +// map centre at 200 m. Modes 1 and 2 wrap the loop in a serial with a trailing turn unlock and lock +// turning during the attack. Mode 3 (no IPIMobile of its own) is the plain attack. +BAPStatement* BBPFire3d::createPlanInternal(Bot* bot, BBPFire3d::FireData& data) +{ + BAPContext* const context = bot->getScriptContext(); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIArmament* const armament = self->getArmament(); + IPIMobile* const mobile = self->getMobile(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + if (m_weapons[bot->getBotId()] != -1) + armament->setActiveWeapon(m_weapons[bot->getBotId()], bot->getSide()); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); // no null test + IPIUnit* const targetUnit = targetInfo->getUnit(); + const float worldSizeX = static_cast(terrain()->getWorldSizeX()); + const float worldSizeZ = static_cast(terrain()->getWorldSizeZ()); + bool targetIsLodBot = false; + if (Bot* const targetBot = IBotManager::instance->getBot(targetInfo->getAIObject())) + targetIsLodBot = targetBot->getLodLevel() > 0; + + switch (data.m_mode) + { + case 1: + case 2: + { + // 0x255A14 (mode 1) and 0x252490 (mode 2) differ only in the order of the range + // conditions and in the approach (200 / 350) and return (200 / 300) distances. + const bool bomb = data.m_mode == 2; + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPConAnd* const alive = newTargetAlive(context, target, targetUnit, weapon, 0.8f); + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + BAPConObjectInFront* const inFront = checkPointer(new BAPConObjectInFront(target, 10.0f, 0.0f)); + BAPConObjectDistance* const distance = + checkPointer(new BAPConObjectDistance(target, 0.9f, weapon->getMaxRange(), false, false)); + if (bomb) + { + inRange->addCondition(distance); + inRange->addCondition(inFront); + } + else + { + inRange->addCondition(inFront); + inRange->addCondition(distance); + } + BAPCombinerParallel* const attackBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const lock = checkPointer(new BAPICTurnLock(true)); + BAPStatement* const attack = createMobileLessAttackPlan(bot, data); + attackBlock->addStatement(lock); + attackBlock->addStatement(attack); + BAPCombinerParallel* const approachBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const unlock = checkPointer(new BAPICTurnLock(false)); + BAPCombinerSerial* const approach = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + approach->addStatement(checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), bomb ? 350.0f : 200.0f, + checkPointer(new BAPConFalse()), controlInfo->getDriveControls(), m_patternId))); + approachBlock->addStatement(unlock); + approachBlock->addStatement(approach); + BAPFlowCIf* const engage = + checkPointer(new BAPFlowCIf(inRange, attackBlock, approachBlock, m_patternId, true, false)); + const Vec3 centre = { worldSizeX * 0.5f, 200.0f, worldSizeZ * 0.5f }; + BAPAMoveTo3d* const back = checkPointer(new BAPAMoveTo3d( + bot, centre, mobile->getMaxSpeed(), mobile->getMaxSpeed(), checkPointer(new BAPConInsideBattleZone(200.0f)), + controlInfo->getDriveControls(), bomb ? 300.0f : 200.0f, m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, back, m_patternId, true, false)); + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(alive, zone, m_patternId)); + BAPICTurnLock* const release = checkPointer(new BAPICTurnLock(false)); + root->addStatement(loop); + root->addStatement(release); + return root; + } + case 0: + { + // 0x254214 + BAPConAnd* const alive = newTargetAlive(context, target, targetUnit, weapon, 0.5f); + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + inRange->addCondition(checkPointer(new BAPConObjectDistance(target, 0.9f, weapon->getMaxRange(), false, false))); + inRange->addCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot))); + BAPStatement* const attack = createMobileLessAttackPlan(bot, data); + BAPConAnd* const stopApproach = checkPointer(new BAPConAnd()); + BAPConObjectDistance* const distance = + checkPointer(new BAPConObjectDistance(target, 0.8f, weapon->getMaxRange(), false, false)); + BAPConObjectLineOfFire* const lineOfFire = checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot)); + stopApproach->addCondition(distance); + stopApproach->addCondition(lineOfFire); + BAPAMoveTo3dObject* const approach = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed() * 0.5f, 50.0f, stopApproach, + controlInfo->getDriveControls(), m_patternId)); + BAPFlowCIf* const engage = checkPointer(new BAPFlowCIf(inRange, attack, approach, m_patternId, false, false)); + const Vec3 centre = { worldSizeX * 0.5f, 200.0f, worldSizeZ * 0.5f }; + BAPAMoveTo3d* const back = checkPointer(new BAPAMoveTo3d( + bot, centre, mobile->getMaxSpeed(), mobile->getMaxSpeed(), checkPointer(new BAPConInsideBattleZone(200.0f)), + controlInfo->getDriveControls(), 200.0f, m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, back, m_patternId, true, false)); + return checkPointer(new BAPFlowCWhile(alive, zone, m_patternId)); + } + case 3: + return createMobileLessAttackPlan(bot, data); // 0x25246A + default: + return 0; + } +} + +// ELF 0x2577D0. The attack itself: serial(arm the weapon, [reload when the magazine is empty], +// parallel(aim, trigger)). Arming is a reset of the controls, plus pressing the weapon's activation +// input unless it is 0x40. The aim is at the target object, or at FireData::m_position when there +// is no target. The trigger fires while the aim precision holds (modes 0, 1 and 3 also need the +// weapon's range; mode 3 a missile lock for guidance type 1; mode 2 uses the bomb precision); +// burst weapons hold the trigger continuously. +BAPStatement* BBPFire3d::createMobileLessAttackPlan(Bot* bot, BBPFire3d::FireData& data) +{ + BAPContext* const context = bot->getScriptContext(); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = self->getArmament(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + const unsigned int target = m_targets[bot->getBotId()]; + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + + BAPStatement* arm; + if (weapon->getWeaponActivate() == 0x40) + { + arm = checkPointer(new BAPAResetControls(false, true, true, m_patternId)); + } + else + { + BAPCombinerParallel* const block = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, true, m_patternId)); + BAPATrigger* const activate = checkPointer(new BAPATrigger( + static_cast(weapon->getWeaponActivate()), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponActivate()), m_patternId, 0.0, false)); + block->addStatement(reset); + block->addStatement(activate); + arm = block; + } + root->addStatement(arm); + + if (!weapon->hasAutoReload()) + { + BAPVariable* const ammo = newVariable(context, 0); + BAPVariable* const weaponVariable = newVariable(context, weapon); + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo(weaponVariable, ammo, false)); + // Input 0x20 with the mask constant 0x100000000 (bit 32). + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + root->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, false, false))); + } + + BAPCombinerParallel* const fire = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPAAimAt3d* aim; + if (target == static_cast(-1)) + { + Vec3 offset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtPoint3d(data.m_position, offset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, 50.0f, 350.0f)); + } + else + { + const Vec3 offset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtObject3d(bot, target, offset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, + data.m_mode != 1 ? 40.0f : 50.0f, 350.0f)); + } + + BAPConAnd* const ready = checkPointer(new BAPConAnd()); + BAPCondition* precision = 0; + if (data.m_mode == 1) + { + ready->addCondition(checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false))); + precision = checkPointer(new BAPCConPrecision3d(target, aim, data.m_precision, !weapon->getBurst())); + } + else if (data.m_mode == 2) + { + precision = checkPointer(new BAPCConBombPrecision3d(aim, data.m_precision, true)); + } + else if (data.m_mode == 0 || data.m_mode == 3) + { + ready->addCondition(checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false))); + if (weapon->getWeaponGuidanceType() == 1) + precision = checkPointer(new BAPConWeaponHasLockOnTarget(newVariable(context, weapon), target)); + else + precision = checkPointer(new BAPCConPrecision3d(target, aim, data.m_precision, !weapon->getBurst())); + } + ready->addCondition(precision); // a null condition for any other mode, as compiled + + BAPStatement* trigger; + if (!weapon->getBurst()) + trigger = checkPointer(new BAPATrigger(static_cast(weapon->getWeaponFire()), ready, + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponFire()), + m_patternId, 0.0, true)); + else + trigger = checkPointer(new BAPATriggerContinously(static_cast(weapon->getWeaponFire()), + ready, 0, checkPointer(new BAPConFalse()), + inputMask(weapon->getWeaponFire()), m_patternId, 0.0)); + fire->addStatement(aim); + fire->addStatement(trigger); + root->addStatement(fire); + return root; +} + +// ELF 0x25A260. Attack on a designated point (init's Vec3 overload): mode 2 with radius 20 and +// precision 40 at the stored position; the weapon is told its target (the handle argument). +// Inside the battle zone (150) the bot attacks when the point is in range and in front, otherwise +// flies to it at 50 m; outside it returns to the map centre at 300 m. +BAPStatement* BBPFire3d::createPlanLaserGuided(Bot* bot, BBPFire3d::FireData& data) +{ + data.m_mode = 2; + data.m_approachRadius = 20.0f; + data.m_precision = 40.0f; + data.m_position = m_targetPositions[bot->getBotId()]; + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + IPIArmament* const armament = self->getArmament(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + weapon->setTarget(m_positionArgs[bot->getBotId()]); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + BAPConPointInFront* const inFront = checkPointer(new BAPConPointInFront(data.m_position, 10.0f, 0.0f)); + BAPConPointDistance* const distance = + checkPointer(new BAPConPointDistance(data.m_position, 0.9f, weapon->getMaxRange(), false)); + inRange->addCondition(distance); + inRange->addCondition(inFront); + BAPCombinerParallel* const attackBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const lock = checkPointer(new BAPICTurnLock(true)); + BAPStatement* const attack = createMobileLessAttackPlan(bot, data); + attackBlock->addStatement(lock); + attackBlock->addStatement(attack); + BAPCombinerParallel* const approachBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPICTurnLock* const unlock = checkPointer(new BAPICTurnLock(false)); + BAPCombinerSerial* const approach = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + approach->addStatement(checkPointer(new BAPAMoveTo3d(bot, data.m_position, mobile->getMaxSpeed(), + mobile->getMaxSpeed(), checkPointer(new BAPConFalse()), + controlInfo->getDriveControls(), 50.0f, m_patternId))); + approachBlock->addStatement(unlock); + approachBlock->addStatement(approach); + BAPFlowCIf* const engage = + checkPointer(new BAPFlowCIf(inRange, attackBlock, approachBlock, m_patternId, true, false)); + const float worldSizeX = static_cast(terrain()->getWorldSizeX()); + const float worldSizeZ = static_cast(terrain()->getWorldSizeZ()); + const Vec3 centre = { worldSizeX * 0.5f, 200.0f, worldSizeZ * 0.5f }; + BAPAMoveTo3d* const back = checkPointer(new BAPAMoveTo3d( + bot, centre, mobile->getMaxSpeed(), mobile->getMaxSpeed(), checkPointer(new BAPConInsideBattleZone(200.0f)), + controlInfo->getDriveControls(), 300.0f, m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, back, m_patternId, true, false)); + BAPICTurnLock* const release = checkPointer(new BAPICTurnLock(false)); + root->addStatement(zone); + root->addStatement(release); + return root; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.h new file mode 100644 index 000000000..110ee939e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.h @@ -0,0 +1,58 @@ +// Fire pattern of aircraft (3d navigation): attack runs against a target object or a laser-designated +// point, built by createPlan from the target and the chosen weapon. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE3D_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +class BAPStatement; + +// ELF: vtable 0x4BBE00 (9 words), operator new 0x28 (nothing beyond BBPFire), package G-vehicles. +class BBPFire3d : public BBPFire +{ +public: + // The attack parameters createPlan hands to the plan builders; a stack object of createPlan + // (no constructor in the image). Names are [INFERRED] from createPlan (0x2514E0). + struct FireData + { + /* +0x00 */ int m_unused00; // [UNRESOLVED] neither written nor read by BBPFire3d + // 0: target without object type flag 0x40; 1: flag 0x40, direct weapon; 2: flag 0x40, + // indirect weapon, or a laser-designated point; 3: the own vehicle has no IPIMobile. + /* +0x04 */ int m_mode; + /* +0x08 */ float m_approachRadius; // twice the own (plus the moving target's) physical radius + /* +0x0C */ float m_precision; // weapon deviation, or the target's mean box size (at least 10) + /* +0x10 */ Vec3 m_position; // zero, or the laser-designated point + }; + + explicit BBPFire3d(int); // 0x2512C0 + virtual ~BBPFire3d(); // 0x251340 + + virtual BotScript* createPlan(Bot*); // 0x2514E0, slot +0x08 + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x2513C0, slot +0x18 + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x251440, slot +0x1C + virtual int getImplementationType(); // 0x25BA20, slot +0x20: 4 + + // The three builders return the statement createPlan puts into its parallel block + // (`movl %eax,-0x18c(%ebp)` after each call, 0x2517CC). + BAPStatement* createPlanInternal(Bot*, BBPFire3d::FireData&); // 0x252260 + BAPStatement* createMobileLessAttackPlan(Bot*, BBPFire3d::FireData&); // 0x2577D0 + BAPStatement* createPlanLaserGuided(Bot*, BBPFire3d::FireData&); // 0x25A260 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIRE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp new file mode 100644 index 000000000..0d7e22b2a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp @@ -0,0 +1,2161 @@ +// Infantry fire pattern: chooses how a soldier bot engages its target (direct weapon, indirect +// weapon from here or from a firing position) and builds the matching action plan. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, with symbols); every body carries its ELF +// address. x87 code was read with the AT&T fsub(r)p/fdiv(r)p operand swap in mind. Package E +// (docs/macos-ai-behaviour-plan.md; state and next steps in docs/macos-ai-w1-e-fire.md). + +// static init: ELF 0x27BA40 (__tcf_0 0x27BAA0, _GLOBAL__I 0x27BAD0): 's Init object only. +#include + +#include "BBPFireInfantery.h" + +#include +#include +#include + +#include "../../../../Core/Debug.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAt.h" +#include "../AIBotActionPlan/BAPAAimAtPoint.h" +#include "../AIBotActionPlan/BAPALook.h" +#include "../AIBotActionPlan/BAPALookAtPoint.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCConLookDeviation.h" +#include "../AIBotActionPlan/BAPCConPrecision.h" +#include "../AIBotActionPlan/BAPConAllowFire.h" +#include "../AIBotActionPlan/BAPConDistanceToProj.h" +#include "../AIBotActionPlan/BAPConOkToThrowGrenade.h" +#include "../AIBotActionPlan/BAPConSplashDamage.h" +#include "../AIBotActionPlan/BAPConWeaponHasLockOnTarget.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPConWeaponIsZoomed.h" +#include "../AIBotActionPlan/BAPAAimAtObject.h" +#include "../AIBotActionPlan/BAPAChangeWeapon.h" +#include "../AIBotActionPlan/BAPAEvaluateCondition.h" +#include "../AIBotActionPlan/BAPAForgetTarget.h" +#include "../AIBotActionPlan/BAPAIdle.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConIsSprinting.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConObjectValidAiming.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPointDistance.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConSharedCondition.h" +#include "../AIBotActionPlan/BAPConStrategicObjectStatus.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponDetonatorIsActive.h" +#include "../AIBotActionPlan/BAPConWeaponMagAmmo.h" +#include "../AIBotActionPlan/BAPConWeaponReadyToFire.h" +#include "../AIBotActionPlan/BAPFlowCEnd.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPICTurnLock.h" +#include "../AIBotActionPlan/BAPWrapperAiming.h" +#include "../AIBotActionPlan/BAPWrapperLookAt.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotBehaviour/BBFire.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../AIUtils/TraceUtils.h" +#include "../Main/AIRandom.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +int maxBots() +{ + return static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); +} + +// [INFERRED] helper shape: the image inlines AIRandom's tempering and computes +// `r * 2.3283064e-10 * scale + offset` at every site (createPlan 0x25E382, 0x25DF17, ...). +float randomFloat(float scale, float offset) +{ + return AIRandom::m_instance->nextFloat() * scale + offset; +} + +IAIObjectEnvironment* objectEnvironment() +{ + return static_cast(CommonSingletonServer::m_iaiObjectEnvironment); +} + +// ELF 0x25C5F0. Finds a firing position for an indirect weapon: 10 m short of the target, then +// moved along the line towards (too far) or away from (too close) the target so that the +// weapon's minimum range plus 3 m fits, snapped to the navmesh. Returns false (no position) when +// the 10-m point is already inside [minRange, maxRange]; outBase is written in every case. +bool getIndirectWeaponCloseToFiringPositions(Vec3& outPosition, Vec3& outBase, Information* self, + IPIMobile* mobile, int equipmentType, WeaponInfo* weapon, + Information* target, const Vec3& targetPosition) +{ + const Vec3& selfPosition = self->getPosition(); + Vec3 aim = targetPosition; + Vec3 dir = { aim.x - selfPosition.x, aim.y - selfPosition.y, aim.z - selfPosition.z }; + float distance = std::sqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); + if (distance > 0.0001f) + { + const float inv = 1.0f / distance; + dir.x *= inv; + dir.y *= inv; + dir.z *= inv; + } + distance -= 10.0f; + const Vec3 step = { dir.x * 10.0f, dir.y * 10.0f, dir.z * 10.0f }; + aim.x -= step.x; + aim.y -= step.y; + aim.z -= step.z; + outBase = aim; + + unsigned int polygon; + unsigned int cluster; + Vec3 position; + if (!(weapon->getMinRange() > distance)) // 0x25C705 jbe: NaN takes this arm + { + if (!(distance > weapon->getMaxRange())) // 0x25C7F0 jbe: NaN returns false + return false; + + // Too far: walk towards the target. + const Vec3& from = self->getPosition(); + const float move = (distance + 3.0f) - weapon->getMinRange(); + position.x = dir.x * move + from.x; + position.y = dir.y * move + from.y; + position.z = move * dir.z + from.z; + } + else + { + // Too close: back away from the target. + const Vec3& from = self->getPosition(); + const float move = (weapon->getMinRange() + 3.0f) - distance; + const Vec3 offset = { dir.x * move, dir.y * move, move * dir.z }; + position.x = from.x - offset.x; + position.y = from.y - offset.y; + position.z = from.z - offset.z; + } + const Vec3& reference = target->getPosition(); + const int vehicleNumber = mobile->getVehicleNumber(); + IAIPathfinding::instance->findClosestValidPolygon(polygon, cluster, outPosition, vehicleNumber, position, + reference, 10, equipmentType); + return true; +} + +// ELF 0x25C8E0: `xorl %eax,%eax; ret` - aiming failures are never detected in this build. +bool detectAimingFailure(BotMain*) +{ + return false; +} + +// The image's "drop the plan" sequence (createPlan 0x25C8F0 head and 0x25D769). +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + BotScript* const plan = bot->getPlan(); + delete plan; + bot->setPlan(0); + } +} + +// Phase 3 (firing) is over when the target is dead or the magazine is empty (m_shots == -1), or +// when the burst is fired; a finished decision goes to the front of the history +// (createPlan 0x25E93D..0x25E906, three copies in the image). +bool burstFinished(BBPFireInfantery::Data& data, const BBPFireInfantery::FiringState* state, + IPIPhysical* targetPhysical, WeaponInfo* weapon, IAIPlayer* player) +{ + if (state->m_shots == -1) + { + if (targetPhysical->getHealth() <= 0.0f || weapon->getAmmo() == 0) + { + data.m_history.push_front(data.m_decision); + return true; + } + return false; + } + if (state->m_shots <= player->getNumShotsFired(weapon->getWeapon()) - data.m_shotsAtPhaseStart + || weapon->getAmmo() == 0) + { + data.m_history.push_front(data.m_decision); + return true; + } + return false; +} + +} // namespace + +// ELF 0x25BAA0 +BBPFireInfantery::FiringState::FiringState() + : m_target(static_cast(-1)) + , m_weapon(-1) + , m_shots(-1) + , m_bool0C(false) + , m_bool14(false) + , m_backOff(false) + , m_independentAim(false) + , m_hasFiringPosition(false) + , m_bool24(false) + , m_bool25(false) + , m_bool26(false) + , m_arrivalRadius(0.0f) +{ + m_position.x = m_position.y = m_position.z = 0.0f; + m_firingPosition.x = m_firingPosition.y = m_firingPosition.z = 0.0f; +} + +// ELF 0x25BC60 +BBPFireInfantery::Data::Data() + : m_decision(FireDecisionNone) + , m_history() + , m_phase(0) + , m_lockStartTime(0.0) + , m_lockDuration(10.0) + , m_int4C(-1) + , m_int50(-1) +{ + m_vec24.x = m_vec24.y = m_vec24.z = 0.0f; + m_phaseTargetPosition.x = m_phaseTargetPosition.y = m_phaseTargetPosition.z = 0.0f; + m_firePosition.x = m_firePosition.y = m_firePosition.z = 0.0f; +} + +// ELF 0x25BFE0 +BBPFireInfantery::BBPFireInfantery(int patternId) + : BBPFire() +{ + m_patternId = patternId; + m_firingStates = checkPointer(new FiringState[maxBots()]); + m_data = checkPointer(new Data[maxBots()]); +} + +// ELF 0x25C350 +BBPFireInfantery::~BBPFireInfantery() +{ + delete[] m_firingStates; + delete[] m_data; +} + +// ELF 0x27BC00 +int BBPFireInfantery::getImplementationType() +{ + return 5; +} + +// ELF 0x25C480. Both bools are unused. +void BBPFireInfantery::init(Bot* bot, unsigned int target, int weapon, bool, bool) +{ + const unsigned int id = bot->getBotId(); + m_targetChanged[id] = target != m_targets[id]; + m_targets[id] = target; + m_weapons[id] = weapon; + if (!m_initiated[id]) + { + Data& data = m_data[id]; + data.m_decision = Data::FireDecisionNone; + data.m_phase = 0; + data.m_lockStartTime = 0.0; + data.m_lockDuration = 10.0; + m_firingStates[id].m_target = static_cast(-1); + } + m_initiated[id] = true; +} + +// ELF 0x25C530 +void BBPFireInfantery::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + const unsigned int id = bot->getBotId(); + m_initiated[id] = true; + m_targets[id] = static_cast(-1); + m_weapons[id] = weapon; + m_positionArgs[id] = positionArg; + m_targetPositions[id] = position; + Data& data = m_data[id]; + data.m_decision = Data::FireDecisionNone; + data.m_phase = 0; + data.m_lockStartTime = 0.0; + data.m_lockDuration = 10.0; + m_firingStates[id].m_target = static_cast(-1); +} + +// ELF 0x25C8F0 (2,906 instructions; Ghidra pseudocode cross-checked against the listing at the +// jump tables 0x4A00C4 / 0x4A00DC, the isFireAllowed sites 0x25D7FC / 0x25D60E and the range +// checks 0x25D830..0x25DA1E). Keeps the current plan while it is this pattern's fire plan for the +// same target, weapon and static-attack mode; otherwise re-evaluates the per-bot decision (Data), +// fills the bot's FiringState and asks createPlanInternal for the plan. Returns 0 and drops the +// current plan while a new decision is pending. +BotScript* BBPFireInfantery::createPlan(Bot* bot) +{ + const unsigned int id = bot->getBotId(); + FiringState* const state = &m_firingStates[id]; + Data& data = m_data[id]; + + if (!m_initiated[id]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + BBFire* const urgencyGenerator = static_cast(m_urgencyGenerator); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = self->getArmament(); + IPIPhysical* const selfPhysical = self->getPhysical(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IAIPlayer* const player = bot->getPlayer(); + if (!armament || !selfPhysical || !controlInfo || !player) + { + m_initiated[id] = false; + return bot->getPlan(); + } + + const int equipmentType = self->getUnit()->getEquipmentType(); + const Vec3& selfPosition = self->getPosition(); + IPIMobile* const selfMobile = self->getMobile(); + bool independentAim = false; + if (selfMobile) + { + independentAim = (controlInfo->getDriveControls() & controlInfo->getAimControls()) == 0; + selfMobile->getSector(); // [UNRESOLVED] result unused in the image (0x25CA96) + } + + bool freshPlan = false; + if (!bot->hasPlan() || static_cast(bot->getPlan())->getGeneratorId() != m_patternId + || static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill() < 0.3f) + freshPlan = true; + m_freshPlan = freshPlan; + + // Keep the current plan while nothing it was built from has changed (0x25F541..0x25F5D8). + int previousWeapon = -1; + if (bot->hasPlan()) + { + if (static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && m_flag20 == static_cast(bot->getPlan())->getFlagA()) + { + previousWeapon = static_cast(bot->getPlan())->getWeapon(); + if (previousWeapon == m_weapons[bot->getBotId()] + && static_cast(bot->getPlan())->getUseStaticAttack() + == static_cast(bot)->getUseStaticAttack()) + return bot->getPlan(); + } + } + + unsigned int target = m_targets[id]; + Information* targetInfo = informationManager->getInformation(target); + IPIUnit* const targetUnit = targetInfo ? targetInfo->getUnit() : 0; + Information* vehicleInfo = 0; + SensedObject* sensed = 0; + if (targetUnit && targetUnit->getAlwaysTargetSoldier()) + { + // Aim at the soldier in the vehicle instead, when this bot senses him. + Information* const occupant = + informationManager->getInformation(targetUnit->getOccupiedObject(bot->getSide())); + if (occupant) + { + sensed = bot->getSensedObjectFromHandle(targetUnit->getOccupiedObject(bot->getSide())); + if (sensed) + { + target = targetUnit->getOccupiedObject(bot->getSide()); + vehicleInfo = targetInfo; + targetInfo = occupant; + } + } + } + IPIPhysical* const targetPhysical = targetInfo ? targetInfo->getPhysical() : 0; + if (!sensed) + sensed = bot->getSensedObjectFromHandle(target); + if (!targetInfo || !targetPhysical || !sensed) + { + m_initiated[id] = false; + return bot->getPlan(); + } + + bool targetIsLodBot = false; + if (Bot* const targetBot = IBotManager::instance->getBot(targetInfo->getAIObject())) + targetIsLodBot = targetBot->getLodLevel() > 0; + + const Vec3 targetPosition = targetInfo->getPosition(); + if (IPIMobile* const targetMobile = targetInfo->getMobile()) + targetMobile->getSector(); // [UNRESOLVED] result unused in the image (0x25CC3D) + + if (!(sensed->m_flags & 0x20)) + { + sensed->m_fireRating = 0; + sensed->m_unresolved44 = 0; + sensed->m_flags |= 0x20; + sensed->m_lastSense = 0x20; + } + + std::vector excluded; + excluded.push_back(self->getAIObject()); + excluded.push_back(targetInfo->getAIObject()); + if (vehicleInfo) + excluded.push_back(vehicleInfo->getAIObject()); + + const Vec3 toTarget = { targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z }; + const float targetDistance = + std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y + toTarget.z * toTarget.z); + Vec3 direction = { targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z }; + const float directionLength = + std::sqrt(direction.z * direction.z + direction.x * direction.x + direction.y * direction.y); + if (directionLength > 0.0001f) + { + const float inv = 1.0f / directionLength; + direction.x *= inv; + direction.y *= inv; + direction.z *= inv; + } + + const int weapon = m_weapons[id]; + WeaponInfo* directWeapon = 0; + WeaponInfo* indirectWeapon = 0; + WeaponInfo* previousWeaponInfo = 0; + if (weapon != -1) + { + // The image looks the same weapon up twice (0x25CEF6 / 0x25CF28). + directWeapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + indirectWeapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + } + if (previousWeapon != -1) + previousWeaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(previousWeapon)); + + if (weapon == -1) + { + sensed->m_fireRating = -100; + return bot->getPlan(); + } + + // The sensed part's offset in the target's frame, in world space. + const Mat4& targetTransform = targetInfo->getTransformation(); + const Vec3& part = sensed->m_seenPosition; + const Vec3 aimPoint = { + targetTransform.m[8] * part.z + targetTransform.m[0] * part.x + targetTransform.m[4] * part.y + + targetTransform.m[12], + targetTransform.m[1] * part.x + targetTransform.m[5] * part.y + targetTransform.m[9] * part.z + + targetTransform.m[13], + part.x * targetTransform.m[2] + part.y * targetTransform.m[6] + part.z * targetTransform.m[10] + + targetTransform.m[14] + }; + // The camera position (translation row) is copied to the stack and never read (0x25D029). + const float* const camera = static_cast(bot->getPlayer()->getCameraTransformation()); + const Vec3 cameraPosition = { camera[12], camera[13], camera[14] }; + (void)cameraPosition; + + const double now = gameTime(); + if (state->m_target != target || now - data.m_lastUpdateTime > 5.0) + { + data.m_decision = Data::FireDecisionNone; + data.m_history.clear(); + data.m_int4C = -1; + data.m_int50 = -1; + data.m_lockStartTime = 0.0; + data.m_lockDuration = 0.0; + } + + float firingPositionDistance = 0.0f; // XZ distance to the state's position + if (state->m_hasFiringPosition) + { + const float dx = state->m_position.x - selfPosition.x; + const float dz = state->m_position.z - selfPosition.z; + firingPositionDistance = std::sqrt(dz * dz + dx * dx); + } + + // 1. Is the current decision finished or invalid? (jump table 0x4A00C4: 0, 1, 2, 4, 5; 3 and + // anything above 5 report and keep the decision) + bool redecide = false; + bool reset = false; // the image's `decision = phase = 0` tail at 0x25E924 + switch (data.m_decision) + { + case Data::FireDecisionNone: + redecide = true; + reset = true; + break; + + case Data::FireDecision1: + case Data::FireDecision2: + { + WeaponInfo* const current = data.m_decision == Data::FireDecision1 ? directWeapon : indirectWeapon; + if (!current) + { + redecide = false; + reset = true; + break; + } + const int phase = data.m_phase; + if (phase == 0) + { + redecide = false; + } + else if (data.m_decision == Data::FireDecision1 && phase == 2 && self->getMobile()) + { + if (!previousWeaponInfo) + redecide = true; + else if (state->m_bool14) + redecide = previousWeaponInfo->getMinRange() + 1.0f < targetDistance; + else + { + redecide = true; + reset = true; + } + } + else if (phase == 1 && self->getMobile()) + { + if (!previousWeaponInfo) + redecide = true; + else if (state->m_bool14) + redecide = previousWeaponInfo->getMinRange() < targetDistance + && targetDistance < previousWeaponInfo->getMaxRange(); + else if (state->m_hasFiringPosition) + { + const float dx = targetPosition.x - data.m_phaseTargetPosition.x; + const float dy = targetPosition.y - data.m_phaseTargetPosition.y; + const float dz = targetPosition.z - data.m_phaseTargetPosition.z; + if (std::sqrt(dz * dz + dx * dx + dy * dy) > 10.0f) + { + redecide = true; + reset = true; + } + else + { + redecide = firingPositionDistance < state->m_arrivalRadius + || (previousWeaponInfo->getMinRange() < targetDistance + && targetDistance < previousWeaponInfo->getMaxRange()); + } + } + } + else if (phase == 3) + { + if (!previousWeaponInfo || !current) + { + redecide = true; + reset = true; + break; + } + const bool aimingFailed = detectAimingFailure(static_cast(bot)); + bool inRange = false; + if ((self->getMobile() || previousWeaponInfo->getMinRange() < targetDistance) + && targetDistance < previousWeaponInfo->getMaxRange()) + inRange = true; + if (aimingFailed) + { + urgencyGenerator->getBBPFeedback(target)->m_time = gameTime(); + redecide = true; + reset = true; + break; + } + redecide = true; + if (inRange) + redecide = burstFinished(data, state, targetPhysical, previousWeaponInfo, player); + reset = redecide; + } + break; + } + + case Data::FireDecision4: + { + if (!indirectWeapon) + { + redecide = false; + reset = true; + break; + } + const int phase = data.m_phase; + if (phase == 0) + redecide = false; + else if (phase == 1 && self->getMobile()) + redecide = firingPositionDistance < state->m_arrivalRadius; + else if (phase == 3) + { + redecide = true; + if (previousWeaponInfo) + { + if (detectAimingFailure(static_cast(bot))) + urgencyGenerator->getBBPFeedback(target)->m_time = gameTime(); + else + redecide = burstFinished(data, state, targetPhysical, previousWeaponInfo, player); + } + reset = redecide; + } + break; + } + + case Data::FireDecision5: + if (data.m_phase == 0 && !self->getMobile()) + redecide = false; + else if (data.m_phase == 1) + { + redecide = firingPositionDistance < state->m_arrivalRadius; + if (redecide) + data.m_history.push_front(data.m_decision); + reset = redecide; + } + break; + + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp", 0x417, "") + << "I don't belive we should be here!"; + break; + } + if (reset) + { + data.m_decision = Data::FireDecisionNone; + data.m_phase = 0; + } + + // 2. Draw the next decision. This always runs; it replaces the current decision only when a + // candidate wins its draw or none is set. + while (static_cast(data.m_history.size()) > 8.0f) + data.m_history.erase(--data.m_history.end()); + int counts[8]; + for (int i = 0; i < 8; ++i) + counts[i] = 0; + for (std::list::iterator it = data.m_history.begin(); it != data.m_history.end(); ++it) + ++counts[*it]; + + const int candidates[7] = { 1, 2, 3, 4, 7, 6, 5 }; + const float weight = self->getMobile() ? 1.0f : 0.0f; + const float weights[7] = { 1.0f, 1.0f, 1.0f, weight, weight, weight, weight }; // stored, never read + (void)weights; + + const bool locked = gameTime() - data.m_lockStartTime < data.m_lockDuration; + const int decision = data.m_decision; + const bool moving = (decision == 5 || decision == 7 || decision == 6) && self->getMobile(); + const int indirectCount = counts[2] + counts[3] + counts[4]; + bool lastWasIndirect = false; + if (indirectCount > 0 + && (data.m_history.front() == 2 || data.m_history.front() == 3 || data.m_history.front() == 4)) + lastWasIndirect = true; + const bool fewIndirect = indirectCount < 2 && !lastWasIndirect; + + bool chosen = false; + int choice = 0; + for (int i = 0; i < 7 && !chosen; ++i) + { + const int candidate = candidates[i]; + if (candidate == 0) + break; + if (candidate == 2) + { + if (!indirectWeapon || locked || (!moving && decision != 0) || (!fewIndirect && directWeapon)) + continue; + bool clear = false; + if (targetIsLodBot) + clear = true; + else if (objectEnvironment()->hasIndirectLineOfFire(indirectWeapon->getWeapon(), + indirectWeapon->getPosition(), aimPoint, excluded)) + clear = true; + const float chance = clear ? 0.5f : 0.05f; + if (!choice) + choice = candidate; + if (randomFloat(1.0f, 0.0f) < chance) + { + choice = candidate; + chosen = true; + } + } + else if (candidate == 1) + { + if (!directWeapon || decision == 1) + continue; + float chance = 1.0f; + if (counts[1] > 0 && static_cast(counts[1]) * 0.1f > 1e-05f) + chance = 1.0f / (static_cast(counts[1]) * 0.1f); + if (moving) + chance /= 5.0f; + if (static_cast(decision - 2) < 3 && data.m_phase == 3) + chance = 0.0f; + if (!choice) + choice = candidate; + if (randomFloat(1.0f, 0.0f) < chance) + { + choice = candidate; + chosen = true; + } + } + else if (candidate == 4) + { + if (!indirectWeapon || locked || !(moving || decision == 0) || !(fewIndirect || !directWeapon)) + continue; + const Vec3 shortPoint = { targetPosition.x - direction.x * 5.0f, targetPosition.y - direction.y * 5.0f, + targetPosition.z - direction.z * 5.0f }; + if (!targetIsLodBot + && !objectEnvironment()->hasIndirectLineOfFire(indirectWeapon->getWeapon(), + indirectWeapon->getPosition(), shortPoint, excluded)) + continue; + if (!choice) + choice = candidate; + if (randomFloat(1.0f, 0.0f) < 0.5f) + { + choice = candidate; + chosen = true; + } + } + } + if (chosen || data.m_decision == Data::FireDecisionNone) + { + data.m_decision = static_cast(choice); + data.m_phase = 0; + redecide = true; + } + data.m_lastUpdateTime = gameTime(); + + // 3. Fill the next firing state from the current one (jump table 0x4A00DC: 0, 1, 2, 4, 5). + FiringState next = *state; + next.m_target = target; + next.m_position = selfPosition; + switch (data.m_decision) + { + case Data::FireDecisionNone: + next.m_hasFiringPosition = false; + next.m_bool25 = false; + next.m_weapon = -1; + break; + + case Data::FireDecision1: + { + int phase = data.m_phase; + bool startBurst = false; + if (phase == 0) + { + redecide = true; + if (self->getMobile()) + { + next.m_bool26 = false; + next.m_shots = 0; + next.m_bool25 = true; + next.m_bool14 = true; + next.m_backOff = false; + next.m_independentAim = independentAim; + next.m_hasFiringPosition = false; + next.m_bool24 = true; + data.m_phase = 1; + data.m_phaseTargetPosition = targetPosition; + next.m_weapon = weapon; + phase = 1; + } + else + startBurst = true; + } + if (phase == 1 || startBurst) + { + if (redecide) + { + // 0x25DAD9: start a burst of 2..4 shots, or 1..min(magazine, 10) for burst weapons. + next.m_weapon = weapon; + if (!directWeapon->getBurst()) + { + const float draw = randomFloat(1.0f, 0.0f); + next.m_shots = static_cast(3.0f * draw + 2.0f); + } + else + { + const float magazine = static_cast(directWeapon->getMaxAmmoInMag()); + float limit = 10.0f; + if (1.0f <= magazine && magazine < 10.0f) + limit = magazine; + const float range = limit - 1.0f; + const float draw = randomFloat(1.0f, 0.0f); + next.m_shots = static_cast(draw * range + 1.0f); + } + next.m_bool26 = false; + next.m_bool25 = true; + next.m_bool14 = self->getMobile() != 0; + next.m_backOff = false; + next.m_independentAim = independentAim; + next.m_hasFiringPosition = false; + data.m_phase = 3; + data.m_phaseTargetPosition = targetPosition; + data.m_shotsAtPhaseStart = player->getNumShotsFired(directWeapon->getWeapon()); + data.m_phaseStartTime = gameTime(); + redecide = false; + } + phase = 3; + } + bool backOffCheck = phase == 2; + if (phase == 3) + { + // 0x25D7F4 (the image tests isFireAllowed here and again at 0x25D60E). + next.m_int10 = bot->isFireAllowed() ? next.m_int10 : 1; + if (!redecide) + next.m_backOff = false; + else + data.m_phase = 0; + backOffCheck = true; + } + if (backOffCheck) + { + // 0x25D830: inside the weapon's minimum range - back off. + const float minRange = directWeapon->getMinRange(); + bool handled = false; + if (selfMobile) + { + const float dx = targetPosition.x - selfPosition.x; + const float dy = targetPosition.y - selfPosition.y; + const float dz = targetPosition.z - selfPosition.z; + if (dx * dx + dy * dy + dz * dz < (minRange + 1.0f) * (minRange + 1.0f)) // 0x25D89D..0x25D8C2 + { + const float minRange2 = directWeapon->getMinRange(); + bool keepPosition = false; + if (data.m_phase == 2) + { + const float fx = targetPosition.x - state->m_firingPosition.x; + const float fy = targetPosition.y - state->m_firingPosition.y; + const float fz = targetPosition.z - state->m_firingPosition.z; + // A squared distance against an unsquared bound, as in the image (0x25D9C2). + keepPosition = fx * fx + fy * fy + fz * fz > (minRange2 + minRange2 + 5.0f) * 0.75f; + } + if (keepPosition) + { + data.m_firePosition = state->m_position; + next.m_position = state->m_position; + } + else + { + next.m_position.x = 1.0f; + next.m_position.y = 0.0f; + next.m_position.z = 1.0f; + data.m_firePosition = next.m_position; + next.m_backOff = true; + data.m_phase = 2; + } + redecide = false; + handled = true; + } + } + if (!handled && data.m_phase == 2) + { + data.m_phase = 0; + next.m_backOff = false; + redecide = true; + } + } + break; + } + + case Data::FireDecision2: + case Data::FireDecision4: + { + const bool fromPosition = data.m_decision == Data::FireDecision4; + int phase = data.m_phase; + bool start = false; + if (phase == 0) + { + redecide = true; + if (self->getMobile()) + { + next.m_bool26 = false; + next.m_shots = 0; + next.m_bool25 = false; + next.m_weapon = weapon; + if (fromPosition) + { + next.m_bool14 = false; + next.m_independentAim = false; + const bool found = getIndirectWeaponCloseToFiringPositions( + next.m_position, next.m_firingPosition, self, selfMobile, equipmentType, indirectWeapon, + targetInfo, targetPosition); + next.m_hasFiringPosition = found; + next.m_bool24 = false; + redecide = !found; + } + else + { + next.m_independentAim = independentAim; + next.m_bool24 = true; + } + data.m_phase = 1; + data.m_phaseTargetPosition = targetPosition; + phase = 1; + } + else + start = true; + } + if ((phase == 1 && redecide) || start) + { + // 0x25DDF6 / 0x25E063: start firing, then lock indirect fire for 5..10 s. + next.m_bool26 = fromPosition; + next.m_bool25 = false; + next.m_shots = 1; + if (fromPosition) + { + next.m_bool14 = false; + next.m_independentAim = false; + } + else + { + next.m_bool14 = self->getMobile() != 0; + next.m_independentAim = independentAim; + next.m_hasFiringPosition = false; + } + data.m_phase = 3; + data.m_phaseTargetPosition = targetPosition; + next.m_weapon = weapon; + data.m_shotsAtPhaseStart = player->getNumShotsFired(indirectWeapon->getWeapon()); + data.m_lockStartTime = gameTime(); + data.m_lockDuration = static_cast(randomFloat(5.0f, 5.0f)); + data.m_phaseStartTime = gameTime(); + redecide = false; + } + else if (phase == 3 && redecide) + data.m_phase = 0; + break; + } + + case Data::FireDecision5: + if (data.m_phase == 0) + { + redecide = true; + if (self->getMobile()) + { + Vec2 unused = { 0.0f, 0.0f }; // computed and never read in the image (0x25E1F0) + vec3ToVec2XZ(targetInfo->getPosition(), unused); + next.m_bool26 = false; + next.m_shots = 0; + next.m_independentAim = independentAim; + next.m_bool14 = true; + next.m_hasFiringPosition = false; + next.m_bool25 = true; + next.m_bool24 = false; + data.m_phase = 1; + data.m_phaseTargetPosition = targetPosition; + redecide = false; + next.m_weapon = weapon; + } + else + data.m_phase = 0; + } + else if (data.m_phase == 1 && redecide) + data.m_phase = 0; + break; + + default: + break; + } + + // 0x25D606 + next.m_int10 = bot->isFireAllowed() ? next.m_int10 : 1; + if (!redecide) + { + bot->getSquadMember()->clearRequestAction(); + next.m_arrivalRadius = selfPhysical->getRadius() + 2.0f; + m_firingStates[id] = next; + return createPlanInternal(bot, targetIsLodBot); + } + dropPlan(bot); + return 0; +} + +namespace { + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// Component-wise comparison with Vec3::getZero() at FLT_EPSILON, as inlined (0x276E3A, 0x267A0B). +bool isZero(const Vec3& v) +{ + const Vec3& zero = Vec3::getZero(); + return std::fabs(v.x - zero.x) <= 1.1920929e-07f && std::fabs(v.y - zero.y) <= 1.1920929e-07f + && std::fabs(v.z - zero.z) <= 1.1920929e-07f; +} + +// The inlined normalisation (0x2653F0..): a unit vector is kept, a near-zero one becomes zero. +void normalize(Vec3& v) +{ + const float lengthSq = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSq - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSq) < 1.1920929e-07f) + { + v.x = v.y = v.z = 0.0f; + return; + } + const float inv = 1.0f / std::sqrt(lengthSq); + v.x *= inv; + v.y *= inv; + v.z *= inv; +} + +// `1 << input` sign-extended to the 64-bit control mask (`movl %eax,%edx; sarl $0x1f,%edx`). +unsigned long long inputMask(int input) +{ + return static_cast(static_cast(1 << input)); +} + +// Every branch starts its parallel block with the sensing-agent override; bots whose own +// object has type flag 0x200000 only override while not sprinting. +BAPStatement* newOverrideSensingAgent(bool selfFlag200000, int patternId) +{ + if (selfFlag200000) + return checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(checkPointer(new BAPConIsSprinting()))), + checkPointer(new BAPAOverrideSensingAgent()), 0, patternId, true, false)); + return checkPointer(new BAPAOverrideSensingAgent()); +} + +// "Fire while the target lives": And{ Not(ObjectHealth(target, 0)) }. +BAPCondition* newTargetAlive(unsigned int target) +{ + BAPConAnd* const alive = checkPointer(new BAPConAnd()); + alive->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConObjectHealth(target, 0.0f))))); + return alive; +} + +float atLeast(float value, float minimum) +{ + return value <= minimum ? minimum : value; +} + +} // namespace + +// ELF 0x2650F0 (18,046 instructions). Builds the fire plan for the FiringState createPlan filled: +// a serial root { change weapon, parallel(reset controls, sensing override, the branch's block) } +// wrapped in a BAPIWFire. Branches (FiringState flags): +// m_bool14 && m_independentAim move and fire (infantry; 0x265B1A) recovered +// m_bool14 && !independent && weapon type 4 place and detonate (0x26B5xx) recovered +// m_bool14 && !independent, other weapons move then fire (0x271F4A) recovered +// !m_bool14 && m_hasFiringPosition go to the firing position, fire recovered +// otherwise / no mobile fire from here (0x2709A0) recovered +BotScript* BBPFireInfantery::createPlanInternal(Bot* bot, bool targetIsLodBot) +{ + const unsigned int id = bot->getBotId(); + FiringState* const state = &m_firingStates[id]; + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + static_cast(bot)->setHadPrecisionTimeStamp(gameTime()); + dropPlan(bot); + + const unsigned int self = bot->getCurrentEquipment(); + Information* const selfInfo = informationManager->getInformation(self); + IPIArmament* const armament = selfInfo->getArmament(); + IPIPhysical* const selfPhysical = selfInfo->getPhysical(); + IPIControlInfo* const controlInfo = selfInfo->getControlInfo(); + if (!armament || !selfPhysical || !controlInfo) + return 0; + IPIMobile* const selfMobile = selfInfo->getMobile(); + if (selfMobile) + selfMobile->isTurnable(); // result unused in the image (0x265258) + controlInfo->getDriveControls(); // results unused in the image (0x265266 / 0x265272) + controlInfo->getAimControls(); + const Vec3& selfPosition = selfInfo->getPosition(); + + const unsigned int target = state->m_target; + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + if (!targetPhysical) + return 0; + + WeaponInfo* weaponInfo = 0; + if (m_weapons[bot->getBotId()] != -1) + { + weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(m_weapons[bot->getBotId()])); + armament->setActiveWeapon(m_weapons[bot->getBotId()], bot->getSide()); + } + + // The target, or its primary object, can move. + bool targetMobile = targetInfo->getMobile() != 0; + if (!targetMobile && !targetInfo->isPrimary()) + targetMobile = informationManager->getInformation(targetInfo->getPrimaryObject(bot->getSide()))->getMobile() != 0; + + // A reachable spot 30 m from the target on the bot's side (0x265300..0x2653D1). + bool pathFound = true; + Vec3 movePosition = { 0.0f, 0.0f, 0.0f }; + if (selfMobile && !targetMobile) + { + const Vec3& from = targetInfo->getPosition(); + const Vec3& own = selfInfo->getPosition(); + Vec3 direction = { own.x - from.x, own.y - from.y, own.z - from.z }; + normalize(direction); + const Vec3 point = { direction.x * 30.0f + from.x, direction.y * 30.0f + from.y, direction.z * 30.0f + from.z }; + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + unsigned int polygon; + unsigned int cluster; + pathFound = IAIPathfinding::instance->findClosestValidPolygon(polygon, cluster, movePosition, + selfMobile->getVehicleNumber(), from, point, + 10, equipmentType); + } + + const int guidance = weaponInfo->getWeaponGuidanceType(); + if (guidance != 0 && (selfInfo->getObjectTypeFlags() & 0x200000)) + return createGuidedPlanInternalInfantry(bot, targetIsLodBot, movePosition); // 0x2779B1 + + // The plan variables (0x26543B..0x265819), shared by the wrappers and the fire plans. + BAPVariable* const weaponVariable = newVariable(context, weaponInfo); + BAPVariable* const targetVariable = newVariable(context, target); + BAPVariable* const aimValidVariable = newVariable(context, false); + const Vec3 up = { 0.0f, 1.0f, 0.0f }; + const Vec3 zero = { 0.0f, 0.0f, 0.0f }; + BAPVariable* const aimVariable = newVariable(context, up); + BAPVariable* const aimOffsetVariable = newVariable(context, zero); + BAPVariable* const lookVariable = newVariable(context, zero); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, 0)); + if (m_weapons[bot->getBotId()] != -1 && weaponInfo->getWeaponActivate() != 0x40) + root->addStatement(checkPointer(new BAPAChangeWeapon(bot, m_weapons[bot->getBotId()], m_patternId))); + BAPCombinerParallel* const block = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + root->addStatement(block); + block->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + + const bool placedExplosive = weaponInfo->getWeaponType() == 4; + const int antiAircraft = armament->isAntiAircraft(); + const bool targetFlag10 = (targetInfo->getObjectTypeFlags() & 0x10) != 0; + const bool noMove = targetFlag10 && antiAircraft == 1; // -0x246 + bool fireFromHere = (targetFlag10 && antiAircraft == 2) || !pathFound; // -0x247 + if (weaponInfo->getMaxRange() < 10.0f) + fireFromHere = false; + + // The squad's strategic-area position, when the squad has a mission (0x277055). + SquadMember* const squadMember = bot->getSquadMember(); + bool squadPositionValid = false; + Vec3 squadPosition = { 0.0f, 0.0f, 0.0f }; + if (squadMember && squadMember->getSquad() && squadMember->getSquad()->squadHasMission() + && squadMember->getSquad()->getValidSaPos(squadMember, squadPosition)) + squadPositionValid = true; + + const bool selfFlag = (selfInfo->getObjectTypeFlags() & 0x200000) != 0; // -0x249 + const bool targetFlag = (targetInfo->getObjectTypeFlags() & 0x200000) != 0; // -0x24A + const bool targetIsBot = IBotManager::instance->getBotFromPlayerId(targetInfo->getPlayerId()) != 0; + + BAPStatement* branch = 0; // added to the parallel block at 0x2671C0 + bool stationary = false; // 0x2709A0 + if (!fireFromHere && m_targetChanged[id]) + { + if (!selfMobile) + stationary = true; + else if (squadPositionValid && !isZero(squadPosition)) + { + // 0x276E2B: fire from here when the squad position lies behind the bot, away from a + // target beyond 30 m (50 m unless either side has type flag 0x200000). + const Vec3 toSquad = { squadPosition.x - selfPosition.x, squadPosition.y - selfPosition.y, + squadPosition.z - selfPosition.z }; + const Vec3& targetPosition = targetInfo->getPosition(); + const Vec3 toTarget = { targetPosition.x - selfPosition.x, targetPosition.y - selfPosition.y, + targetPosition.z - selfPosition.z }; + const float range = (selfFlag || targetFlag) ? 30.0f : 50.0f; + if (range * range < toTarget.z * toTarget.z + toTarget.y * toTarget.y + toTarget.x * toTarget.x + && toTarget.z * toSquad.z + toTarget.x * toSquad.x + toTarget.y * toSquad.y < 0.0f) + fireFromHere = true; + } + } + + // 0x265AF0 + if (!stationary && !selfMobile) + stationary = true; + if (!stationary && state->m_bool14 && state->m_independentAim) + { + // ---- Move and fire (0x265B1A..0x2671BB) ---- + if (!fireFromHere) + { + if (IPIMobile* const targetMover = targetInfo->getMobile()) + { + const IPIMobile::ValidPos& valid = targetMover->getLastValidPosition(selfMobile->getVehicleNumber()); + if (valid.quadTree == static_cast(-1) || valid.polygon == static_cast(-1)) + fireFromHere = true; + } + if (!fireFromHere && targetIsBot && targetFlag) + fireFromHere = true; + } + const bool splash = weaponInfo->getExplosionRadius() != 0.0f && guidance == 0; + const bool staticAttack = static_cast(bot)->getUseStaticAttack() && splash && targetFlag; + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + + BAPConSharedCondition* const lineOfFire = + staticAttack ? checkPointer(new BAPConSharedCondition(checkPointer(new BAPConTrue()))) + : checkPointer(new BAPConSharedCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot)))); + + // A control point close to the bot: fire at any range while it is not ours (0x265D8A). + BAPConSharedCondition* controlPointCondition = 0; + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(selfPosition, bot->getSide(), false); + Vec3 controlPoint = { 0.0f, 0.0f, 0.0f }; + if (object && !noMove && !fireFromHere + && static_cast(object)->m_controlPointId != static_cast(-1)) + { + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = selfMobile->getVehicleNumber(); + static_cast(object)->getControlpointPos(object, bot->getSide(), vehicleNumber, + equipmentType, selfPosition, controlPoint); + const float radius = object->m_size[bot->getSide()]; + Vec3 objectPosition = { 0.0f, 0.0f, 0.0f }; + vec2ToVec3XZ(object->getPosition(bot->getSide()), objectPosition); + objectPosition.y = controlPoint.y; + const Vec3 offset = { objectPosition.x - controlPoint.x, objectPosition.y - controlPoint.y, + objectPosition.z - controlPoint.z }; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius * radius) + { + // 0x26A7A5 also computes controlPoint - selfPosition into a slot it never reads. + BAPConAnd* const near = checkPointer(new BAPConAnd()); + near->addCondition(checkPointer(new BAPConStrategicObjectStatus(object, bot->getSide(), false))); + near->addCondition(checkPointer(new BAPConPointDistance(controlPoint, 40.0f, true))); + controlPointCondition = checkPointer(new BAPConSharedCondition(near)); + } + } + + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); + fireCondition->addCondition(lineOfFire->getNewSharedCondition()); + if (!controlPointCondition) + fireCondition->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange(), weaponInfo->getMaxRange(), true, false))); + else + { + BAPConOr* const inRange = checkPointer(new BAPConOr()); + inRange->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange(), weaponInfo->getMaxRange(), true, false))); + inRange->addCondition(controlPointCondition->getNewSharedCondition()); + fireCondition->addCondition(inRange); + } + BAPConSharedCondition* const validAiming = checkPointer(new BAPConSharedCondition(checkPointer( + new BAPConObjectValidAiming(target, self, aimValidVariable, aimVariable, staticAttack)))); + + BAPStatement* fireOrAim; + if (guidance == 0) + { + BAPStatement* const firePlan = createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, + aimVariable, aimOffsetVariable, lookVariable, weaponInfo, + selfInfo, controlInfo, targetInfo, targetPhysical, WGSNone); + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + BAPAAimAtObject* const aim = checkPointer(new BAPAAimAtObject( + bot, target, noOffset, checkPointer(new BAPConFalse()), controlInfo->getAimControls(), m_patternId, + false, aimValidVariable, aimVariable)); + fireOrAim = checkPointer(new BAPFlowCIf(fireCondition, firePlan, aim, m_patternId, true, false)); + } + else + { + BAPStatement* const firePlan = createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, + weaponInfo, selfInfo, controlInfo, targetInfo, + targetPhysical, static_cast(guidance)); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.0f, checkPointer(new BAPConFalse()), controlInfo->getLookControls(), m_patternId, + lookVariable, 0.0f)); + fireOrAim = checkPointer(new BAPFlowCIf(fireCondition, firePlan, look, m_patternId, true, false)); + } + + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(lineOfFire, m_patternId))); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(validAiming, m_patternId))); + if (guidance == 0) + engage->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + else + engage->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); + + // Movement while engaging (0x2664xx..0x266Fxx). + BAPStatement* movement = 0; + if (selfMobile && !noMove && !fireFromHere) + { + // No line of fire: walk to within 1.1 x minimum range (>= 15 m), forget the target, end. + BAPStatement* away; + if (targetMobile) + away = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f), 3)); + else + away = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f))); + BAPCombinerSerial* const lost = checkPointer(new BAPCombinerSerial(m_patternId, 300)); + lost->addStatement(away); + lost->addStatement(checkPointer(new BAPAForgetTarget(state->m_target))); + lost->addStatement(checkPointer(new BAPFlowCEnd(m_patternId, static_cast(0), 0))); + + // Aim valid: close in while beyond half the maximum range or inside 1.05 x minimum (>= 18 m). + BAPConOr* const approachCondition = checkPointer(new BAPConOr()); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, weaponInfo->getMaxRange() * 0.5f, true, false, true))); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, atLeast(weaponInfo->getMinRange() * 1.05f, 18.0f), true, false, false))); + BAPStatement* approachMove; + if (targetMobile) + approachMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, weaponInfo->getMaxRange() * 0.35f, selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, 0, + atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f), 4)); + else + approachMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, weaponInfo->getMaxRange() * 0.35f, + atLeast(weaponInfo->getMinRange() * 1.05f, 15.0f))); + BAPFlowCIf* const approach = checkPointer(new BAPFlowCIf(approachCondition, approachMove, 0, m_patternId, false, false)); + + // Aim not valid: reposition, near (beyond max(minimum, 15) + 5 m) or far. + BAPConObjectDistance* const beyond = checkPointer(new BAPConObjectDistance( + target, atLeast(weaponInfo->getMinRange(), 15.0f) + 5.0f, true, false, true)); + BAPStatement* nearMove; + BAPStatement* farMove; + if (targetMobile) + { + nearMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, atLeast(weaponInfo->getMinRange() * 1.1f, 10.0f), selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 5)); + BAPConAnd* const moved = checkPointer(new BAPConAnd()); + moved->addCondition(checkPointer(new BAPConObjectDistance(m_targets[bot->getBotId()], 50.0f, true, true, false))); + moved->addCondition(checkPointer(new BAPConObjectMoved(m_targets[bot->getBotId()], 5.0f))); + farMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, weaponInfo->getMaxRange() * 0.7f, selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, moved, + atLeast(weaponInfo->getMinRange() * 2.2f, 30.0f), 6)); + } + else + { + nearMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, atLeast(weaponInfo->getMinRange() * 1.1f, 10.0f), 0.0f)); + farMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, weaponInfo->getMaxRange() * 0.7f, + atLeast(weaponInfo->getMinRange() * 2.2f, 30.0f))); + } + BAPFlowCIf* const reposition = checkPointer(new BAPFlowCIf(beyond, nearMove, farMove, m_patternId, false, false)); + BAPFlowCIf* const aimed = checkPointer(new BAPFlowCIf( + checkPointer(new BAPConNot(validAiming->getNewSharedCondition())), reposition, approach, m_patternId, + false, false)); + movement = checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(lineOfFire->getNewSharedCondition())), + lost, aimed, m_patternId, true, false)); + } + if (!controlPointCondition) + { + if (movement) + engage->addStatement(movement); + else if (fireFromHere && squadPositionValid && !isZero(squadPosition)) + { + static_cast(bot)->setIsGoingForFlag(true); // 0x267A42 + engage->addStatement(checkPointer(new BAPAMoveToFinding( + bot, squadPosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f))); + } + } + else + { + BAPAMoveToFinding* const toControlPoint = checkPointer(new BAPAMoveToFinding( + bot, controlPoint, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + engage->addStatement(checkPointer(new BAPFlowCIf(controlPointCondition, toControlPoint, movement, + m_patternId, false, false))); + } + engage->addStatement(fireOrAim); + + branch = checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId)); + if (!selfFlag) + block->addStatement(checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId))); + } + else if (!stationary && state->m_bool14 && placedExplosive) + { + // ---- Place and detonate (weapon type 4; 0x26B5xx..) ---- + block->addStatement(checkPointer(new BAPFlowCIf( + checkPointer(new BAPConNot(checkPointer(new BAPConIsSprinting()))), + checkPointer(new BAPAOverrideSensingAgent()), 0, m_patternId, true, false))); + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); + branch = checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId)); + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + engage->addStatement(checkPointer(new BAPAAimAtObject(bot, target, noOffset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, false, 0, 0))); + BAPCombinerSerial* const steps = checkPointer(new BAPCombinerSerial(m_patternId, 1)); + const float contact = targetPhysical->getSmallestRadius() + selfPhysical->getSmallestRadius(); + + // 1. Walk up to the target. + BAPStatement* walkUp; + if (targetMobile) + { + steps->addStatement(checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, contact, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 1))); + BAPAMoveToObjectFinding* const follow = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 3)); + walkUp = checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConNot(checkPointer(new BAPConTime(0.20000000298023224, false, false, false)))), + follow, false, m_patternId)); + } + else + walkUp = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + steps->addStatement(walkUp); + + // 2. Place: alternate fire while the detonator is active, then fire, then lock turning. + const int altFire = weaponInfo->getWeaponAltFire(); + steps->addStatement(checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)), + checkPointer(new BAPATrigger(static_cast(altFire), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(altFire), m_patternId, 0.0, true)), + false, m_patternId))); + const int fire = weaponInfo->getWeaponFire(); + steps->addStatement(checkPointer(new BAPATrigger(static_cast(fire), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(fire), m_patternId, 0.0, true))); + steps->addStatement(checkPointer(new BAPICTurnLock(true))); + + // 3. Keep close until the weapon is ready again, then back off 30 m. + BAPStatement* stay; + if (targetMobile) + stay = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, 0.0f, 2)); + else + stay = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + steps->addStatement(checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConNot(checkPointer(new BAPConWeaponReadyToFire(weaponVariable)))), stay, false, m_patternId))); + BAPStatement* backOff; + if (targetMobile) + backOff = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 30.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, contact + 9.0f, 2)); + else + backOff = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 30.0f, contact + 9.0f)); + steps->addStatement(backOff); + + // 4. Crouch (pose 2) and detonate: alternate fire until the detonator is active, wait 0.7 s, fire. + BAPCombinerParallel* const detonate = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + detonate->addStatement(checkPointer(new BAPASoldierPose(SPCrouching, checkPointer(new BAPConTrue()), m_patternId, true))); + BAPFlowCWhile* const arm = checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConNot(checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)))), + checkPointer(new BAPATrigger(static_cast(altFire), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(altFire), m_patternId, 0.0, false)), + false, m_patternId)); + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + sequence->addStatement(arm); + sequence->addStatement(checkPointer(new BAPAIdle( + checkPointer(new BAPConTime(0.699999988079071, false, false, false)), 0, m_patternId))); + sequence->addStatement(checkPointer(new BAPATrigger( + static_cast(fire), checkPointer(new BAPConWeaponDetonatorIsActive(weaponVariable)), + checkPointer(new BAPConFalse()), inputMask(fire), m_patternId, 0.0, false))); + detonate->addStatement(sequence); + steps->addStatement(detonate); + steps->addStatement(checkPointer(new BAPICTurnLock(false))); + engage->addStatement(steps); + engage->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_patternId))); + } + else if (!stationary && state->m_bool14) + { + // ---- Move then fire, drive and aim controls overlapping (0x271F4A..0x272B1F, with the + // out-of-line blocks 0x273020.., 0x273C3A..0x27422C, 0x2754D0, 0x2759CA, 0x275C5A, 0x275DC0, + // 0x2762A1, 0x2763B1, 0x276504, 0x276D76..0x276E26) ---- + const bool splash = weaponInfo->getExplosionRadius() != 0.0f && guidance == 0; // -0x5D5 + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); + bool targetAbove = false; // -0x5D6 + if (bot->getSpawnKit() != 1 && !weaponInfo->getIsThrown()) + { + if (30.0f < targetInfo->getPosition().y - selfInfo->getPosition().y) + targetAbove = true; + } + bool grenadeChecks = false; // -0x5D7 (no splash-at-target term, unlike createFirePlan) + if (static_cast(bot)->getUseStaticAttack() && splash && targetFlag + && ((sensed->m_flags & 8) || targetAbove)) + grenadeChecks = true; + + // Ranges: a target more than 5 m above adds 1.25 x the height to the maximum (not for + // thrown weapons, only beyond 10 m); thrown weapons in static attack keep 5 m minimum. + const float dy = targetInfo->getPosition().y - selfInfo->getPosition().y; // -0x5DC + float heightBonus = 0.0f; // -0x5E0 + if (dy > 5.0f && weaponInfo->getMaxRange() > 10.0f && !weaponInfo->getIsThrown()) + heightBonus = dy * 1.25f; + const float maxRange = weaponInfo->getMaxRange() + heightBonus; // -0x5E4 + float minRange = weaponInfo->getMinRange(); // -0x5E8 + if (dy > 3.0f && grenadeChecks && weaponInfo->getIsThrown()) + minRange = 5.0f; // 0x276D8C cmovne + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + + // The fire condition: the shared "can hit" And (valid aiming when the bot will fire, + // line of fire unless grenade checks), then the range (or a control point nearby). + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); // -0x604 + BAPConAnd* const canHit = checkPointer(new BAPConAnd()); + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0 && guidance == 0) + canHit->addCondition(checkPointer(new BAPConObjectValidAiming(target, self, aimValidVariable, aimVariable, + grenadeChecks))); // 0x276504 + if (!grenadeChecks) + canHit->addCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot))); // 0x2763B1 + BAPConSharedCondition* const canHitShared = checkPointer(new BAPConSharedCondition(canHit)); // -0x61C + fireCondition->addCondition(canHitShared->getNewSharedCondition()); + + BAPConSharedCondition* controlPointCondition = 0; // -0x620 + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(selfPosition, bot->getSide(), false); + Vec3 controlPoint = { 0.0f, 0.0f, 0.0f }; + if ((!selfFlag || weaponInfo->getMaxRange() > 5.0f) && object && !fireFromHere + && static_cast(object)->m_controlPointId != static_cast(-1)) + { + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = selfMobile->getVehicleNumber(); + static_cast(object)->getControlpointPos(object, bot->getSide(), vehicleNumber, + equipmentType, selfPosition, controlPoint); + const float radius = object->m_size[bot->getSide()]; + Vec3 objectPosition = { 0.0f, 0.0f, 0.0f }; + vec2ToVec3XZ(object->getPosition(bot->getSide()), objectPosition); + objectPosition.y = controlPoint.y; + const Vec3 offset = { objectPosition.x - controlPoint.x, objectPosition.y - controlPoint.y, + objectPosition.z - controlPoint.z }; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius * radius) + { + // 0x275DC0 also computes controlPoint - selfPosition into a slot it never reads. + BAPConAnd* const near = checkPointer(new BAPConAnd()); + near->addCondition(checkPointer(new BAPConStrategicObjectStatus(object, bot->getSide(), false))); + near->addCondition(checkPointer(new BAPConPointDistance(controlPoint, 40.0f, true))); + controlPointCondition = checkPointer(new BAPConSharedCondition(near)); + } + } + if (!grenadeChecks) + { + if (!controlPointCondition) + fireCondition->addCondition(checkPointer(new BAPConObjectDistance( + target, minRange * 0.9f, maxRange * 1.1f, true, false))); // 0x275C5A + else + { + BAPConOr* const inRange = checkPointer(new BAPConOr()); + inRange->addCondition(checkPointer(new BAPConObjectDistance( + target, minRange * 0.9f, maxRange * 1.1f, true, false))); + inRange->addCondition(controlPointCondition->getNewSharedCondition()); + fireCondition->addCondition(inRange); + } + } + + // Fire (createFirePlan with the weapon's guidance) or keep aiming (0x272573..0x2726B6). + BAPStatement* firePlan = 0; // -0x654 + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0) + firePlan = createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, aimVariable, + aimOffsetVariable, lookVariable, weaponInfo, selfInfo, controlInfo, targetInfo, + targetPhysical, static_cast(guidance)); // 0x275A5C + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + BAPAAimAtObject* const aim = checkPointer(new BAPAAimAtObject( + bot, target, noOffset, checkPointer(new BAPConFalse()), controlInfo->getAimControls(), m_patternId, false, + aimValidVariable, aimVariable)); + BAPFlowCIf* const fireOrAim = checkPointer(new BAPFlowCIf(fireCondition, firePlan, aim, m_patternId, true, false)); + + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); // -0x674 + if (guidance == 0) + engage->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + else + engage->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); // 0x2754D0 + + // Movement (0x273C3A..0x27422C): no line of fire or fire not allowed -> walk up to + // 1.1 x minimum range, forget the target, end; otherwise keep the distance at + // min + (max - min) x optimal range (randomised 0.8..1.2 beyond 10 m). + BAPStatement* movement = 0; // -0x680 + if (selfMobile && !fireFromHere) + { + BAPConOr* const noFire = checkPointer(new BAPConOr()); // -0x684 + if (!grenadeChecks) + noFire->addCondition(checkPointer(new BAPConNot(canHitShared->getNewSharedCondition()))); + else + noFire->addCondition(checkPointer(new BAPConFalse())); // 0x2751C0 + noFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConAllowFire())))); + + BAPStatement* away; + if (targetMobile) // -0x695, recomputed as before + away = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, minRange * 1.1f, 7)); + else + away = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.5f, minRange * 1.1f)); // 0x274CD7 + BAPCombinerSerial* const lost = checkPointer(new BAPCombinerSerial(m_patternId, 300)); // -0x6B4 + lost->addStatement(away); + lost->addStatement(checkPointer(new BAPAForgetTarget(state->m_target))); + lost->addStatement(checkPointer(new BAPFlowCEnd(m_patternId, static_cast(0), 0))); + + float optimal = weaponInfo->getOptimalRangePercentage() * 0.01f; // -0x6C4 + if (weaponInfo->getMaxRange() > 10.0f) + optimal = (randomFloat(0.4f, 0.0f) + 0.8f) * optimal; + float desired = (maxRange - minRange) * optimal + minRange; // -0x6CC + if (grenadeChecks && !weaponInfo->getIsThrown()) + { + const float height = targetInfo->getPosition().y - selfInfo->getPosition().y; + if (height > 0.0f) + desired += height * 0.25f; // 0x2748D6 + } + BAPStatement* keep; // -0x6D0 + if (targetMobile) + keep = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, desired, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, minRange * 1.1f, 8)); + else + keep = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, desired, minRange * 1.1f)); // 0x2746D1 + BAPConObjectDistance* const inBand = checkPointer(new BAPConObjectDistance( + target, minRange, desired * 1.1f, true, false)); + BAPFlowCIf* const approach = checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(inBand)), keep, 0, + m_patternId, false, false)); + movement = checkPointer(new BAPFlowCIf(noFire, lost, approach, m_patternId, true, true)); + } + + // Reload once the magazine is empty (0x2727A5; no auto-reload check here). + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo( + weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + engage->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, true, false))); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(canHitShared, m_patternId))); + + if (controlPointCondition && !fireFromHere) + { + BAPAMoveToFinding* const toControlPoint = checkPointer(new BAPAMoveToFinding( + bot, controlPoint, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); // 0x27329B + engage->addStatement(checkPointer(new BAPFlowCIf(controlPointCondition, toControlPoint, movement, + m_patternId, false, false))); + } + else if (movement) + engage->addStatement(movement); + else if (fireFromHere && squadPositionValid && !isZero(squadPosition)) + { + static_cast(bot)->setIsGoingForFlag(true); // 0x2730D8 + engage->addStatement(checkPointer(new BAPAMoveToFinding( + bot, squadPosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f))); + } + engage->addStatement(fireOrAim); + if (selfFlag) + engage->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_patternId))); // 0x272EE2 + + branch = checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId)); // 0x272B18 + } + else if (!stationary && state->m_hasFiringPosition) + { + // ---- Go to the firing position, then fire (0x26FBxx..0x26FF9x) ---- + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + const Vec2 firingPosition = { state->m_position.x, state->m_position.z }; + BAPConPosition* const arrived = checkPointer(new BAPConPosition(firingPosition, state->m_arrivalRadius * 0.5f)); + block->addStatement(checkPointer(new BAPAMoveToFinding( + bot, state->m_position, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, arrived, + selfInfo->getControlInfo()->getDriveControls(), m_patternId, 0.0f, 0.0f))); + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0) + { + BAPCombinerParallel* const fireBlock = checkPointer(new BAPCombinerParallel(m_patternId, 6, false)); + if (guidance == 0) + fireBlock->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + else + fireBlock->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); + if (guidance == 0) + fireBlock->addStatement(createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, aimVariable, + aimOffsetVariable, lookVariable, weaponInfo, selfInfo, controlInfo, + targetInfo, targetPhysical, WGSNone)); + else + fireBlock->addStatement(createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, + weaponInfo, selfInfo, controlInfo, targetInfo, targetPhysical, + static_cast(guidance))); + branch = fireBlock; + } + } + else + stationary = true; + + if (stationary) + { + // ---- Fire from here (0x2709A0..0x270D26) ---- + if (m_weapons[bot->getBotId()] == -1 || state->m_shots == 0) + return 0; // the variables and the statements built so far are not released (as in the image) + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); + BAPCombinerParallel* const fireBlock = checkPointer(new BAPCombinerParallel(m_patternId, 7, false)); + if (!weaponInfo->hasAutoReload() && weaponInfo->getNumberOfMags() != 1) + { + // Reload (input 0x20) once the magazine is empty. + BAPConWeaponMagAmmo* const empty = checkPointer(new BAPConWeaponMagAmmo( + weaponVariable, newVariable(context, 0), false)); + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + fireBlock->addStatement(checkPointer(new BAPFlowCIf(empty, reload, 0, m_patternId, true, false))); + } + BAPStatement* firePlan; + if (guidance == 0) + { + fireBlock->addStatement(checkPointer(new BAPWrapperAiming(aimVariable, aimValidVariable, aimOffsetVariable, + self, target, true))); + firePlan = createFirePlan(bot, state, weaponVariable, targetVariable, aimValidVariable, aimVariable, + aimOffsetVariable, lookVariable, weaponInfo, selfInfo, controlInfo, targetInfo, + targetPhysical, WGSNone); + } + else + { + fireBlock->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, + aimVariable, aimValidVariable))); + firePlan = createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, weaponInfo, selfInfo, + controlInfo, targetInfo, targetPhysical, + static_cast(guidance)); + } + fireBlock->addStatement(checkPointer(new BAPFlowCIf( + checkPointer(new BAPConObjectValidAiming(target, self, aimValidVariable, aimVariable, false)), firePlan, 0, + m_patternId, true, false))); + branch = fireBlock; + } + + // 0x2671C0 / 0x2671C3 + if (branch) + block->addStatement(branch); + int weapon = -1; + if (weaponInfo) + weapon = m_weapons[bot->getBotId()]; + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, target, m_flag20, state->m_backOff, weapon, -1, root, m_patternId)); + plan->setParent(this); + SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); + return plan; +} + +// ELF 0x25F740 (5,526 instructions; returns the BAPIWFire). The plan for a guided weapon of a bot +// whose object has type flag 0x200000 (createPlanInternal 0x2779B1): look at the target, fire the +// guided plan while the line of fire and the range (or a control point nearby) hold, keep within +// 0.5 x max .. min range, reload when empty and no own projectile is within 1000 m. +BotScript* BBPFireInfantery::createGuidedPlanInternalInfantry(Bot* bot, bool targetIsLodBot, const Vec3& movePosition) +{ + const unsigned int id = bot->getBotId(); + FiringState* const state = &m_firingStates[id]; + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + BAPContext* const context = bot->getScriptContext(); + context->clear(); + static_cast(bot)->setHadPrecisionTimeStamp(gameTime()); + dropPlan(bot); + + Information* const selfInfo = informationManager->getInformation(bot->getCurrentEquipment()); + IPIArmament* const armament = selfInfo->getArmament(); + IPIControlInfo* const controlInfo = selfInfo->getControlInfo(); + if (!armament || !selfInfo->getPhysical() || !controlInfo) + return 0; + IPIMobile* const selfMobile = selfInfo->getMobile(); + if (selfMobile) + selfMobile->isTurnable(); // result unused in the image + controlInfo->getDriveControls(); // results unused in the image + controlInfo->getAimControls(); + const Vec3& selfPosition = selfInfo->getPosition(); + + const unsigned int target = state->m_target; + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + if (!targetPhysical) + return 0; + + // No -1 check on the weapon index here (createPlanInternal made it). + const int weapon = m_weapons[bot->getBotId()]; + WeaponInfo* const weaponInfo = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weapon)); + armament->setActiveWeapon(weapon, bot->getSide()); + + BAPVariable* const weaponVariable = newVariable(context, weaponInfo); + BAPVariable* const targetVariable = newVariable(context, target); + BAPVariable* const aimValidVariable = newVariable(context, false); + const Vec3 up = { 0.0f, 1.0f, 0.0f }; + const Vec3 zero = { 0.0f, 0.0f, 0.0f }; + BAPVariable* const aimVariable = newVariable(context, up); + BAPVariable* const lookVariable = newVariable(context, zero); + + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, 0)); + if (weaponInfo->getWeaponActivate() != 0x40) + root->addStatement(checkPointer(new BAPAChangeWeapon(bot, weapon, m_patternId))); + BAPCombinerParallel* const block = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + root->addStatement(block); + const bool selfFlag = (selfInfo->getObjectTypeFlags() & 0x200000) != 0; + block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); // before the reset here + block->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + if (!selfFlag) + block->addStatement(checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId))); + const int guidance = weaponInfo->getWeaponGuidanceType(); + + // A control point close to the bot (no fire-from-here / no-move checks in this function). + BAPConSharedCondition* controlPointCondition = 0; // -0x220 + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(selfPosition, bot->getSide(), false); + Vec3 controlPoint = { 0.0f, 0.0f, 0.0f }; + if (object && static_cast(object)->m_controlPointId != static_cast(-1)) + { + // The image reads the vehicle number of a null mobile here as well (non-virtual field read). + const int equipmentType = selfInfo->getUnit()->getEquipmentType(); + const int vehicleNumber = selfMobile->getVehicleNumber(); + static_cast(object)->getControlpointPos(object, bot->getSide(), vehicleNumber, + equipmentType, selfPosition, controlPoint); + const float radius = object->m_size[bot->getSide()]; + Vec3 objectPosition = { 0.0f, 0.0f, 0.0f }; + vec2ToVec3XZ(object->getPosition(bot->getSide()), objectPosition); + objectPosition.y = controlPoint.y; + const Vec3 offset = { objectPosition.x - controlPoint.x, objectPosition.y - controlPoint.y, + objectPosition.z - controlPoint.z }; + if (offset.x * offset.x + offset.y * offset.y + offset.z * offset.z < radius * radius) + { + // The image also computes controlPoint - selfPosition into a slot it never reads. + BAPConAnd* const near = checkPointer(new BAPConAnd()); + near->addCondition(checkPointer(new BAPConStrategicObjectStatus(object, bot->getSide(), false))); // 0x263FCF + near->addCondition(checkPointer(new BAPConPointDistance(controlPoint, 40.0f, true))); + controlPointCondition = checkPointer(new BAPConSharedCondition(near)); + } + } + + BAPConSharedCondition* const lineOfFire = + checkPointer(new BAPConSharedCondition(checkPointer(new BAPConObjectLineOfFire(target, targetIsLodBot)))); + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); + fireCondition->addCondition(lineOfFire->getNewSharedCondition()); + if (!controlPointCondition) + fireCondition->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange() * 0.9f, weaponInfo->getMaxRange() * 1.1f, true, false))); + else + { + BAPConOr* const inRange = checkPointer(new BAPConOr()); + inRange->addCondition(checkPointer(new BAPConObjectDistance( + target, weaponInfo->getMinRange() * 0.9f, weaponInfo->getMaxRange() * 1.1f, true, false))); + inRange->addCondition(controlPointCondition->getNewSharedCondition()); + fireCondition->addCondition(inRange); + } + + BAPStatement* firePlan = 0; // -0x268 + if (m_weapons[bot->getBotId()] != -1 && state->m_shots != 0) + firePlan = createFirePlanGuided(bot, state, weaponVariable, targetVariable, lookVariable, weaponInfo, selfInfo, + controlInfo, targetInfo, targetPhysical, + static_cast(guidance)); // 0x2638FA + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.0f, checkPointer(new BAPConFalse()), controlInfo->getLookControls(), m_patternId, + lookVariable, 0.0f)); + BAPFlowCIf* const fireOrLook = checkPointer(new BAPFlowCIf(fireCondition, firePlan, look, m_patternId, true, false)); + + BAPCombinerParallel* const engage = checkPointer(new BAPCombinerParallel(m_patternId, 4, false)); + engage->addStatement(checkPointer(new BAPAEvaluateCondition(lineOfFire, m_patternId))); + engage->addStatement(checkPointer(new BAPWrapperLookAt(target, lookVariable, true, guidance == 3, aimVariable, + aimValidVariable))); + + // Movement (0x260456..0x260B3F): no line of fire or fire not allowed -> walk to 1.1 x minimum + // range, forget the target, end; else close in to 0.85 x max while beyond 0.5 x max or inside min. + BAPStatement* movement = 0; // -0x294 + if (selfMobile) + { + BAPConOr* const noFire = checkPointer(new BAPConOr()); + noFire->addCondition(checkPointer(new BAPConNot(lineOfFire->getNewSharedCondition()))); + noFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConAllowFire())))); + bool targetMobile = targetInfo->getMobile() != 0; + if (!targetMobile && !targetInfo->isPrimary()) + targetMobile = informationManager->getInformation(targetInfo->getPrimaryObject(bot->getSide()))->getMobile() != 0; + BAPStatement* away; + if (targetMobile) + away = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, 0.0f, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.5f, 0, + controlInfo->getDriveControls(), m_patternId, 0, weaponInfo->getMinRange() * 1.1f, 1)); + else + away = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.5f, weaponInfo->getMinRange() * 1.1f)); + BAPCombinerSerial* const lost = checkPointer(new BAPCombinerSerial(m_patternId, 300)); + lost->addStatement(away); + lost->addStatement(checkPointer(new BAPAForgetTarget(state->m_target))); + lost->addStatement(checkPointer(new BAPFlowCEnd(m_patternId, static_cast(0), 0))); + + BAPConOr* const approachCondition = checkPointer(new BAPConOr()); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, weaponInfo->getMaxRange() * 0.5f, true, false, true))); + approachCondition->addCondition(checkPointer(new BAPConObjectDistance(target, weaponInfo->getMinRange(), true, false, false))); + BAPStatement* approachMove; + if (targetMobile) + approachMove = checkPointer(new BAPAMoveToObjectFinding( + bot, state->m_target, weaponInfo->getMaxRange() * 0.85f, selfMobile->getMaxSpeed(), + selfMobile->getMaxSpeed() * 0.5f, 0, controlInfo->getDriveControls(), m_patternId, + checkPointer(new BAPConFalse()), atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f), 2)); + else + approachMove = checkPointer(new BAPAMoveToFinding( + bot, movePosition, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, weaponInfo->getMaxRange() * 0.85f, + atLeast(weaponInfo->getMinRange() * 1.1f, 15.0f))); + BAPFlowCIf* const approach = checkPointer(new BAPFlowCIf(approachCondition, approachMove, 0, m_patternId, false, false)); + movement = checkPointer(new BAPFlowCIf(noFire, lost, approach, m_patternId, true, false)); // 0x260B3F + } + + // Reload: empty magazine and no own projectile within 1000 m (0x260B52..0x260DE4). + BAPConAnd* const reloadCondition = checkPointer(new BAPConAnd()); + reloadCondition->addCondition(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false))); + reloadCondition->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConDistanceToProj(armament, 1000.0f))))); + BAPATrigger* const reload = checkPointer(new BAPATrigger( + static_cast(0x20), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 0x100000000ULL, m_patternId, 0.0, false)); + engage->addStatement(checkPointer(new BAPFlowCIf(reloadCondition, reload, 0, m_patternId, true, false))); + if (controlPointCondition) + { + BAPAMoveToFinding* const toControlPoint = checkPointer(new BAPAMoveToFinding( + bot, controlPoint, selfMobile->getMaxSpeed(), selfMobile->getMaxSpeed() * 0.75f, 0, + controlInfo->getDriveControls(), m_patternId, 0.0f, 0.0f)); + movement = checkPointer(new BAPFlowCIf(controlPointCondition, toControlPoint, movement, m_patternId, false, false)); + } + engage->addStatement(movement); // null is ignored + engage->addStatement(fireOrLook); + if (selfFlag) + engage->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_patternId))); + block->addStatement(checkPointer(new BAPFlowCWhile(newTargetAlive(target), engage, false, m_patternId))); + + int planWeapon = -1; + if (weaponInfo) + planWeapon = m_weapons[bot->getBotId()]; + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, target, m_flag20, state->m_backOff, planWeapon, -1, root, m_patternId)); + plan->setParent(this); + return plan; // no SquadManager::shotsFired here (unlike createPlanInternal) +} + +// ELF 0x277CF0 (1,941 instructions). The firing part of a plan: aim at the target (or at the +// firing position's point for indirect fire, FiringState::m_bool26), pull the trigger while the +// precision condition (and, for splash weapons in static attack, the grenade checks) hold, and +// zoom first when the weapon has a zoom input. +BAPStatement* BBPFireInfantery::createFirePlan(Bot* bot, BBPFireInfantery::FiringState* state, + BAPVariable* weaponVariable, BAPVariable*, + BAPVariable* aimValidVariable, BAPVariable* aimVariable, + BAPVariable* aimOffsetVariable, BAPVariable*, + WeaponInfo* weaponInfo, Information* selfInfo, IPIControlInfo* controlInfo, + Information* targetInfo, IPIPhysical*, WeaponGuidingSystem guidance) +{ + BAPContext* const context = bot->getScriptContext(); + const unsigned int target = state->m_target; + + // A sniper (spawn kit 1) with a zoomed long-range weapon (-0x179). + bool sniping = false; + if (weaponInfo->getWeaponZoom() != 0x40 && bot->getSpawnKit() == 1 && weaponInfo->getMaxRange() > 100.0f) + sniping = true; + bool splash = false; // -0x17A + if (weaponInfo->getExplosionRadius() != 0.0f && guidance == 0) + splash = true; + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); + const bool selfFlag = (selfInfo->getObjectTypeFlags() & 0x200000) != 0; + const bool targetFlag = (targetInfo->getObjectTypeFlags() & 0x200000) != 0; + bool splashAtTarget = false; // -0x198 + if (!selfFlag && targetFlag && guidance == 0 && weaponInfo->getExplosionRadius() != 0.0f) + splashAtTarget = true; + bool targetAbove = false; + if (bot->getSpawnKit() != 1 && !weaponInfo->getIsThrown()) + { + const Vec3& targetPosition = targetInfo->getPosition(); + const Vec3& selfPosition = selfInfo->getPosition(); + if (30.0f < targetPosition.y - selfPosition.y) + targetAbove = true; + } + bool grenadeChecks = false; // -0x1AA + if (static_cast(bot)->getUseStaticAttack() && splash && targetFlag + && ((sensed->m_flags & 8) || splashAtTarget || targetAbove)) + grenadeChecks = true; + + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(m_patternId, false, 0xE, false)); + BAPAAimAt* aim; + if (!state->m_bool26) + { + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtObject(bot, target, noOffset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, false, aimValidVariable, + aimVariable)); + } + else + { + BAPVariable* const point = newVariable(context, state->m_firingPosition); + const Vec3 noOffset = { 0.0f, 0.0f, 0.0f }; + aim = checkPointer(new BAPAAimAtPoint(bot, point, noOffset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, aimValidVariable, aimVariable)); + } + plan->addStatement(aim); + + float deviation = weaponInfo->getAllowedDeviation(); + if (splash && targetFlag && !selfFlag) + deviation = 1.0f; // 0x2780B1 cmove + BAPCondition* precision; + if (!aimValidVariable) + precision = checkPointer(new BAPCConPrecision(target, aim, deviation, !weaponInfo->getBurst(), sniping, + weaponInfo->getMaxRange() < 5.0f)); + else + precision = checkPointer(new BAPCConPrecision(target, aimValidVariable, aimVariable, aimOffsetVariable, deviation, + !weaponInfo->getBurst(), sniping, weaponInfo->getMaxRange() < 5.0f)); + BAPConAnd* const fireCondition = checkPointer(new BAPConAnd()); + if (weaponInfo->usesHeat()) + fireCondition->addCondition(checkPointer(new BAPConSharedCondition( + checkPointer(new BAPConWeaponHeat(weaponVariable, 0.8f, 0.5f))))); // 0x278F50 + if (grenadeChecks && splashAtTarget) + { + // 0x278E03: the precision condition, then the splash-damage check (3.5 m). + fireCondition->addCondition(precision); + fireCondition->addCondition(checkPointer(new BAPConSplashDamage(target, aimOffsetVariable, aimVariable, 3.5f))); + } + else + { + if (grenadeChecks) + fireCondition->addCondition(checkPointer(new BAPConOkToThrowGrenade(target, aimOffsetVariable, aimVariable))); + fireCondition->addCondition(precision); + } + + // A fresh plan waits (1.5 + U[0,1)) x (1 - skill) s before the first shot (0x278C50). + float delay = 0.0f; + if (m_freshPlan && weaponInfo->getMaxRange() > 10.0f) + { + const float wait = randomFloat(1.0f, 0.0f) + 1.5f; + delay = (1.0f - static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill()) * wait; + } + BAPStatement* trigger; + const int fire = weaponInfo->getWeaponFire(); + if (!weaponInfo->getBurst()) + trigger = checkPointer(new BAPATrigger(static_cast(fire), fireCondition, 0, inputMask(fire), + m_patternId, delay, true)); + else + trigger = checkPointer(new BAPATriggerContinously(static_cast(fire), fireCondition, 0, 0, + inputMask(fire), m_patternId, delay)); + if (weaponInfo->getWeaponZoom() != 0x40) + { + const int zoom = weaponInfo->getWeaponZoom(); + BAPATrigger* const zoomIn = checkPointer(new BAPATrigger( + static_cast(zoom), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + inputMask(zoom), m_patternId, 0.0, false)); + plan->addStatement(checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(checkPointer(new BAPConWeaponIsZoomed()))), + zoomIn, 0, m_patternId, true, false))); + } + plan->addStatement(trigger); + return plan; +} + +// ELF 0x279B40 (1,735 instructions). The firing part for guided weapons: look at the target (or +// at the init(Vec3) position when the target is unknown) and fire once nothing in the Or holds: +// an empty magazine, no lock (heat-seeking and laser-guided), or a look deviation above 5 deg +// (laser-guided; the function-static `degrees`, 5.0 in .data 0x4BBE64) or 3 deg (otherwise). +BAPStatement* BBPFireInfantery::createFirePlanGuided(Bot* bot, const BBPFireInfantery::FiringState* state, + BAPVariable* weaponVariable, BAPVariable*, + BAPVariable* lookVariable, WeaponInfo* weaponInfo, + Information*, IPIControlInfo* controlInfo, Information* targetInfo, + IPIPhysical*, WeaponGuidingSystem guidance) +{ + static float degrees = 5.0f; + BAPContext* const context = bot->getScriptContext(); + const unsigned int target = state->m_target; + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(m_patternId, false, 0xE, false)); + BAPALook* look; + if (targetInfo) + look = checkPointer(new BAPALookAtObject(bot, target, 0.0f, checkPointer(new BAPConFalse()), + controlInfo->getLookControls(), m_patternId, lookVariable, 0.0f)); + else + look = checkPointer(new BAPALookAtPoint(m_targetPositions[bot->getBotId()], bot, 0.00872664619f, + checkPointer(new BAPConFalse()), controlInfo->getLookControls(), + m_patternId)); // 0x27B345 + plan->addStatement(look); + + BAPConOr* const holdFire = checkPointer(new BAPConOr()); + holdFire->addCondition(checkPointer(new BAPConWeaponMagAmmo(weaponVariable, newVariable(context, 0), false))); + if (static_cast(guidance) - 1u < 2u) + holdFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConWeaponHasLockOnTarget(weaponVariable, target))))); + if (guidance == WGSLaserGuided) + holdFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPCConLookDeviation(look, degrees * 0.017453292f, false))))); + else + holdFire->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPCConLookDeviation(look, 0.052359879f, false))))); + + const int fire = weaponInfo->getWeaponFire(); + BAPATrigger* const trigger = checkPointer(new BAPATrigger(static_cast(fire), checkPointer(new BAPConTrue()), + holdFire, inputMask(fire), m_patternId, 0.0, true)); + if (weaponInfo->getWeaponZoom() != 0x40) + { + const int zoom = weaponInfo->getWeaponZoom(); + BAPATrigger* const zoomIn = checkPointer(new BAPATrigger( + static_cast(zoom), checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + inputMask(zoom), m_patternId, 0.0, false)); + plan->addStatement(checkPointer(new BAPFlowCIf(checkPointer(new BAPConNot(checkPointer(new BAPConWeaponIsZoomed()))), + zoomIn, 0, m_patternId, true, false))); + } + plan->addStatement(trigger); + return plan; +} + +// ELF 0x27B6F0. Tries alternating angles on a circle and keeps the furthest valid trace endpoint. +void BBPFireInfantery::calculateAwayPosition(const Vec3& from, const Vec3& centre, int map, Vec3& out, float radius) +{ + const float requiredDistanceSqr = (radius - 1.0f) * (radius - 1.0f); + Vec3 best = from; + Vec3 candidate = {0.0f, 0.0f, 0.0f}; + Vec3 direction = {from.x - centre.x, 0.0f, from.z - centre.z}; + const float directionLengthSqr = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (directionLengthSqr > 0.1f) { + if (std::fabs(directionLengthSqr - 1.0f) >= 1.1920929e-7f) { + if (std::fabs(directionLengthSqr) >= 1.1920929e-7f) { + const float inverseLength = 1.0f / std::sqrt(directionLengthSqr); + direction.x *= inverseLength; + direction.y *= inverseLength; + direction.z *= inverseLength; + } else { + direction = {0.0f, 0.0f, 0.0f}; + } + } + } else { + direction = {1.0f, 0.0f, 0.0f}; + } + + float bestDistanceSqr = 0.0f; + float angle = 0.0f; + while (bestDistanceSqr <= requiredDistanceSqr && angle <= 1.570796371f) { + const bool valid = TraceUtils::tracePointOnCircle(direction, centre, from, map, angle, radius, candidate); + angle = -angle; + if (angle >= 0.0f) + angle += 0.261799395f; + if (valid) { + const Vec3 delta = {centre.x - candidate.x, centre.y - candidate.y, centre.z - candidate.z}; + const float distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + if (distanceSqr > bestDistanceSqr) { + best = candidate; + bestDistanceSqr = distanceSqr; + } + } + } + out = best; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.h new file mode 100644 index 000000000..7421c0bc1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.h @@ -0,0 +1,120 @@ +// Infantry fire-plan generation, recovered from libaidll.so (Linux 1.5, ia-32). +// Virtual order is checked by tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIREINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIREINFANTERY_H + +#include + +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/WeaponTemplate.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; +class BotScript; +class IPIControlInfo; +class IPIPhysical; +class Information; +class WeaponInfo; + +// ELF: vtable 0x4BBE80 (9 words), operator new 0x34, package E-fire-pattern. +// Layout (x86 ELF): BBPFire up to +0x28, then the per-bot arrays below and one bool (ctor 0x25BFE0). +class BBPFireInfantery : public BBPFire +{ +public: + // Per-bot fire-decision record, 0x5C bytes in the image (new[] with a count cookie, ctor 0x25BC60). + // Names are [INFERRED] from BBPFireInfantery::createPlan (0x25C8F0); offsets are the ELF's. + class Data + { + public: + // The decision createPlan picks among its seven candidates; the image stores and compares + // the values 0..7 (`m_decision`, the history list's element). [INFERRED] numeric names: + // createPlan's candidate order is 1, 2, 3, 4, 7, 6, 5 and it handles 1, 2, 4 and 5. + enum FireDecision + { + FireDecisionNone = 0, + FireDecision1 = 1, // the direct weapon (checks its min/max range) + FireDecision2 = 2, // the indirect weapon from here (hasIndirectLineOfFire to the aim point) + FireDecision3 = 3, + FireDecision4 = 4, // the indirect weapon from a firing position (getIndirectWeaponCloseToFiringPositions) + FireDecision5 = 5, + FireDecision6 = 6, + FireDecision7 = 7 + }; + + Data(); // 0x25BC60 + + /* +0x00 */ double m_lastUpdateTime; // createPlan: game time of the last decision pass (not set by the ctor) + /* +0x08 */ FireDecision m_decision; // ctor 0 + /* +0x0C */ std::list m_history; // newest first, trimmed to 8 entries + /* +0x10 */ int m_phase; // ctor 0; 0 start, 1 approach, 2 back off, 3 firing + /* +0x14 */ double m_lockStartTime; // ctor 0.0 + /* +0x1C */ double m_lockDuration; // ctor 10.0; indirect fire: 5..10 s random + /* +0x24 */ Vec3 m_vec24; // ctor 0; [UNRESOLVED] not used by createPlan + /* +0x30 */ Vec3 m_phaseTargetPosition; // ctor 0; the target's position when the phase began + /* +0x3C */ Vec3 m_firePosition; // ctor 0 + /* +0x48 */ int m_shotsAtPhaseStart; // IAIPlayer::getNumShotsFired when phase 3 began (not set by the ctor) + /* +0x4C */ int m_int4C; // ctor -1; [UNRESOLVED] createPlan only resets it + /* +0x50 */ int m_int50; // ctor -1; [UNRESOLVED] createPlan only resets it + /* +0x54 */ double m_phaseStartTime; // game time when phase 3 began (not set by the ctor) + }; + + // The firing parameters createPlan hands to createPlanInternal, 0x38 bytes (ctor 0x25BAA0). + // Names are [INFERRED] from createPlan; offsets are the ELF's. + class FiringState + { + public: + FiringState(); // 0x25BAA0 + + /* +0x00 */ unsigned int m_target; // ctor -1 + /* +0x04 */ int m_weapon; // ctor -1; the BBPFire weapon index + /* +0x08 */ int m_shots; // ctor -1; -1 = until the target dies or the magazine is empty + /* +0x0C */ bool m_bool0C; // ctor false; carried over unchanged by createPlan + /* +0x10 */ int m_int10; // not set by the ctor; createPlan forces 1 while fire is not allowed + /* +0x14 */ bool m_bool14; // ctor false + /* +0x15 */ bool m_backOff; // ctor false; set with Data::m_phase 2 + /* +0x16 */ bool m_independentAim; // ctor false; drive and aim controls do not overlap + /* +0x17 */ bool m_hasFiringPosition; // ctor false + /* +0x18 */ Vec3 m_position; // ctor 0 + /* +0x24 */ bool m_bool24; // ctor false + /* +0x25 */ bool m_bool25; // ctor false + /* +0x26 */ bool m_bool26; // ctor false + /* +0x28 */ Vec3 m_firingPosition; // ctor 0 + /* +0x34 */ float m_arrivalRadius; // ctor 0; createPlan: own physical radius + 2 + }; + + explicit BBPFireInfantery(int); // 0x25BFE0 + virtual ~BBPFireInfantery(); // 0x25C350 + + virtual BotScript* createPlan(Bot*); // 0x25C8F0, slot +0x08; from the base declaration + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x25C480, slot +0x18; from the base declaration + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x25C530, slot +0x1C; from the base declaration + virtual int getImplementationType(); // 0x27BC00, slot +0x20; from the base declaration + + // createPlanInternal returns its result as the plan (0x2779B1, then `jmp 0x2672D0`, the common return with %eax). + BotScript* createGuidedPlanInternalInfantry(Bot*, bool, const Vec3&); // 0x25F740 + // createPlan returns its result as the plan (`movl %eax,%esi` after the call at 0x25D734). + BotScript* createPlanInternal(Bot*, bool); // 0x2650F0 + // Both fire-plan builders return the statement createPlanInternal adds to a combiner or an If. + BAPStatement* createFirePlan(Bot*, BBPFireInfantery::FiringState*, BAPVariable*, BAPVariable*, BAPVariable*, BAPVariable*, BAPVariable*, BAPVariable*, WeaponInfo*, Information*, IPIControlInfo*, Information*, IPIPhysical*, WeaponGuidingSystem); // 0x277CF0 + BAPStatement* createFirePlanGuided(Bot*, const BBPFireInfantery::FiringState*, BAPVariable*, BAPVariable*, BAPVariable*, WeaponInfo*, Information*, IPIControlInfo*, Information*, IPIPhysical*, WeaponGuidingSystem); // 0x279B40 + void calculateAwayPosition(const Vec3&, const Vec3&, int, Vec3&, float); // 0x27B6F0 + +protected: + /* +0x28 */ FiringState* m_firingStates; // new FiringState[maxBots] + /* +0x2C */ Data* m_data; // new Data[maxBots] + /* +0x30 */ bool m_freshPlan; // createPlan: no plan of this pattern yet, or bot skill < 0.3 [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPFIREINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoint.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoint.h new file mode 100644 index 000000000..de96cc198 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoint.h @@ -0,0 +1,33 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINT_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// ELF: vtable 0x4BBF40 (7 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPGotoWaypoint : public BBPPattern +{ +public: + virtual ~BBPGotoWaypoint() {} // weak in the image (inline) + + virtual void init(Bot*) = 0; // no body, slot +0x18; [INFERRED] from BBPGotoWaypoint3d: ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp new file mode 100644 index 000000000..5489e147e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp @@ -0,0 +1,320 @@ +// Waypoint pattern of ground vehicles (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp in the +// image; class BBPGotoWaypoint2d). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); +// every body carries its ELF address. +// +// static init: ELF 0x27F440 (__tcf_0 0x27F4A0, _GLOBAL__I 0x27F4D0): the guard object only. + +#include "BBPGotoWaypoints2d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBot/WPCloseTo.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPASetSensingAgentFocus.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPIWMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Waypoint list ids (WaypointList::getId, slot +0x10): WPCloseTo 0, WPMoveTo 1, WPPatrol 2. +const int kWaypointCloseTo = 0; +const int kWaypointMoveTo = 1; +const int kWaypointPatrol = 2; + +// BAPInfoWrapper::getInfoType of a BAPIWMoveTo. +const int kInfoTypeMoveTo = 2; + +void clearScript(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); +} + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// The larger of the waypoint radius and the approach range; unordered gives the range +// (fcmovbe 0x27C84C). +float approachDistance(float wayPointRadius, float range) +{ + return wayPointRadius > range ? wayPointRadius : range; +} + +// The serial body every arm starts with: the sensing focus (0.5) towards the goal. Every arm of +// createPlan builds it inline in this order (serial, focus, add). +BAPCombinerSerial* beginRoute(Information* equipment, const Vec3& goal, int patternId) +{ + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(patternId, -1)); + Vec3 look; + look.x = look.y = look.z = 0.0f; + const Vec3& position = equipment->getPosition(); + look.x = goal.x - position.x; + look.y = goal.y - position.y; + look.z = goal.z - position.z; + BAPASetSensingAgentFocus* const focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, look, patternId, false)); + serial->addStatement(focus); + return serial; +} + +// The common tail of every arm: parallel(use flares on missile lock, serial) inside a BAPIWMoveTo at +// the goal. The flare action is not checkPointer'd (no null test in any arm). +BotScript* finishRoute(Bot* bot, BAPCombinerSerial* serial, const Vec3& goal, int patternId, void* owner) +{ + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(patternId, true, -1, false)); + parallel->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, patternId)); + parallel->addStatement(serial); + BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, parallel, patternId)); + root->setParent(owner); // +0x04 (BotScript::m_owner) + return root; +} + +} // namespace + +// ELF 0x27BC50: BBPPattern(), the vtable store (GOT -0x2FC + 8), then the argument at +0x08. +BBPGotoWaypoint2d::BBPGotoWaypoint2d(int id) + : m_patternId(id) +{ +} + +// ELF 0x27F4F0 (D0 0x27F530): nothing of its own; the BBPGotoWaypoint vtable store and +// BBPPattern's destructor. +BBPGotoWaypoint2d::~BBPGotoWaypoint2d() +{ +} + +// ELF 0x27BCC0 (listing). Drives the vehicle along its waypoint list: +// BAPIWMoveTo(goal, parallel { BAPAUseFlareOnMissileLock, serial { BAPASetSensingAgentFocus(0.5, +// goal - position), BAPAMoveToFinding or BAPAMoveToObjectFinding } }) +// WPPatrol moves with the full waypoint radius, WPMoveTo with half of it; WPCloseTo approaches the +// object until it moved (BAPConObjectMoved). An existing plan of this pattern is rebuilt only once +// the waypoints changed; a WPPatrol or WPCloseTo plan is then kept while its goal is farther than +// 4 * the squad member's max speed from the new goal (the reverse of the soldier pattern's test), +// and the WPPatrol test reads the x components twice; both as shipped. +BotScript* BBPGotoWaypoint2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + // 0x27F3FE + clearScript(bot); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + const float maxSpeed = bot->getSquadMember()->getMaxSpeed(); // 0x27BD0F + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); // 0x27BD5B, read before the plan test + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + { + // 0x27D7A3: the current plan is ours. Keep it unless the waypoints changed. + if (!bot->getWaypoints()->m_flag4 || bot->getWaypoints()->getWayPointError()) + return bot->getPlan(); + bot->getWaypoints()->m_flag4 = false; + + if (static_cast(bot->getPlan())->getInfoType() == kInfoTypeMoveTo) + { + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = controlInfo->getDriveControls(); + float range = equipment->getPhysical()->getRadius() * 4.0f; + const int id = waypoints->getId(); + if (id == kWaypointMoveTo) + { + // 0x27EB97: always rebuilt. + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + dropPlan(bot); + clearScript(bot); + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius() * 0.5f, + 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + if (id < kWaypointMoveTo) + { + if (id != kWaypointCloseTo) + { + // 0x27D860 + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + // 0x27E12D + Vec3 target; + target.x = target.y = target.z = 0.0f; + Information* const targetInfo = + informationManager->getInformation(static_cast(waypoints)->getTarget()); + if (!targetInfo) + { + dropPlan(bot); + return 0; + } + target = targetInfo->getPosition(); + const Vec3& current = static_cast(bot->getPlan())->getPosition(); + Vec3 delta; + delta.x = delta.y = delta.z = 0.0f; + delta.x = target.x - current.x; + delta.y = target.y - current.y; + delta.z = target.z - current.z; + const float keep = maxSpeed * 4.0f; + if (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z > keep * keep) // 0x27E248 + return bot->getPlan(); + dropPlan(bot); + clearScript(bot); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + BAPCombinerSerial* const serial = beginRoute(equipment, target, m_patternId); + // The end condition is built inside the argument list, after the action's allocation. + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, static_cast(waypoints)->getTarget(), range, maxSpeed, maxSpeed, 0, controls, + m_patternId, + checkPointer(new BAPConObjectMoved(static_cast(waypoints)->getTarget(), range)), + 0.0f, -1)); + serial->addStatement(move); + return finishRoute(bot, serial, target, m_patternId, this); + } + if (id != kWaypointPatrol) + { + // 0x27D860 + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + // 0x27D89B + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + const float dx = static_cast(bot->getPlan())->getPosition().x - goal2d.x; + const float dx2 = static_cast(bot->getPlan())->getPosition().x - goal2d.x; // sic: x again + const float keep = 4.0f * maxSpeed; + if (dx * dx + dx2 * dx2 > keep * keep) // 0x27D960 + return bot->getPlan(); + dropPlan(bot); + clearScript(bot); + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + // 0x27D778: another wrapper; build a new plan. + dropPlan(bot); + } + else if (bot->getPlan()) + { + dropPlan(bot); + } + + // 0x27BD94 + clearScript(bot); + if (bot->getWaypoints()->getWayPointError()) + return 0; + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = controlInfo->getDriveControls(); + float range = equipment->getPhysical()->getRadius() * 4.0f; + bot->getWaypoints()->m_flag4 = false; // 0x27BE2A + bot->getSquadMember()->clearRequestAction(); + + const int id = waypoints->getId(); + if (id == kWaypointMoveTo) + { + // 0x27CF80: the goal point is asked for twice, as compiled. + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + vec3ToVec2XZ(goal, goal2d); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius() * 0.5f, 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + if (id < kWaypointMoveTo) + { + if (id != kWaypointCloseTo) + return 0; + // 0x27C62D + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Information* const targetInfo = + informationManager->getInformation(static_cast(waypoints)->getTarget()); + if (!targetInfo) + return 0; + goal = targetInfo->getPosition(); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + // The end condition is built inside the argument list, after the action's allocation. + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, static_cast(waypoints)->getTarget(), + approachDistance(waypoints->getWayPointRadius(), range), maxSpeed, maxSpeed, 0, controls, m_patternId, + checkPointer(new BAPConObjectMoved(static_cast(waypoints)->getTarget(), range)), 0.0f, -1)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); + } + if (id != kWaypointPatrol) + return 0; + // 0x27BE72 + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerSerial* const serial = beginRoute(equipment, goal, m_patternId); + vec3ToVec2XZ(goal, goal2d); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + serial->addStatement(move); + return finishRoute(bot, serial, goal, m_patternId, this); +} + +// ELF 0x27BC90: marks the bot's slot of the initiated array (+0x04). +void BBPGotoWaypoint2d::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.h new file mode 100644 index 000000000..029fa11f7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS2D_H + +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBF00 (7 words), operator new 0xC, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPGotoWaypoint2d : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypoint2d(int); // 0x27BC50 + virtual ~BBPGotoWaypoint2d(); // 0x27F4F0 + + virtual BotScript* createPlan(Bot*); // 0x27BCC0, slot +0x08; from the base declaration + virtual void init(Bot*); // 0x27BC90, slot +0x18; from the base declaration + + /* +0x08 */ int m_patternId; // the constructor argument (operator new 0xC) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp new file mode 100644 index 000000000..afe56bf5f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp @@ -0,0 +1,179 @@ +// Waypoint-following pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp in +// the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was checked against the listing for constructor arguments and the +// waypoint fields each arm reads. + +// static init: ELF 0x280C40 (__tcf_0 0x280CA0, _GLOBAL__I 0x280CD0): 's Init object only. +#include + +#include "BBPGotoWaypoints3d.h" + +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WPAltitudeCloseTo.h" +#include "../AIBot/WPAltitudeMoveTo.h" +#include "../AIBot/WPAltitudePatrol.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +// `parallel(reset controls, flares on missile lock)`, the head every arm of createPlan builds. +BAPCombinerParallel* newFlightPlan(Bot* bot, int patternId) +{ + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(patternId, true, -1, false)); + plan->addStatement(checkPointer(new BAPAResetControls(true, true, true, patternId))); + // No checkPointer on this allocation in the image. + plan->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, patternId)); + return plan; +} + +} // namespace + +// ELF 0x27F630 (C2 0x27F5F0): BBPPattern(), the vtable store, then the argument at +0x08. +BBPGotoWaypoint3d::BBPGotoWaypoint3d(int id) + : m_patternId(id) +{ +} + +// ELF 0x280CF0 (weak; D0 0x280D30): the BBPGotoWaypoint vtable store and BBPPattern's destructor. +BBPGotoWaypoint3d::~BBPGotoWaypoint3d() +{ +} + +// ELF 0x27F6A0. Keeps a plan of this pattern unless the waypoints were renewed (their +4 flag, +// cleared here, drops the plan); a plan of another pattern that hasPlan reports is not deleted, +// as compiled. Builds `parallel(reset controls, flares on missile lock, move)` for the flight +// waypoint lists: WPAltitudeCloseTo (5) follows the target object, WPAltitudeMoveTo (6) and +// WPAltitudePatrol (7) fly to the goal point, each with the list's distance argument. The speed is +// the list's +8 value, or the vehicle's maximum when it is negative; the arrival radius is four +// times the own physical radius (plus the target's, or 2 m for an equipment with type flag 0x20 +// on a WPAltitudeMoveTo). Any other list, like an uninitiated pattern, clears the debugger, the +// context and the plan and builds nothing. The equipment information is not null-checked. +BotScript* BBPGotoWaypoint3d::createPlan(Bot* bot) +{ + if (m_initiated[bot->getBotId()]) + { + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan()) + { + if (bot->getWaypoints()->m_flag4) + { + bot->getWaypoints()->m_flag4 = false; + dropPlan(bot); + } + else if (static_cast(bot->getPlan())->getPatternId() == m_patternId) + return bot->getPlan(); + } + else + dropPlan(bot); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + + IPIMobile* const mobile = self->getMobile(); + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + float radius = self->getPhysical()->getRadius() * 4.0f; + const float maxSpeed = mobile->getMaxSpeed(); + const float waypointSpeed = bot->getWaypoints()->m_float8; + const float speed = waypointSpeed < 0.0f ? maxSpeed : waypointSpeed; // NaN keeps the list's value + bot->getSquadMember()->clearRequestAction(); + + switch (waypoints->getId()) + { + case 5: + { + WPAltitudeCloseTo* const closeTo = static_cast(waypoints); + Information* const target = informationManager->getInformation(closeTo->m_target); + if (!target) + return 0; + BAPCombinerParallel* const plan = newFlightPlan(bot, m_patternId); + if (target->getPhysical()) + radius = target->getPhysical()->getRadius() + radius; + plan->addStatement(checkPointer(new BAPAMoveTo3dObject(closeTo->m_target, radius, speed, speed, + closeTo->m_third, checkPointer(new BAPConFalse()), + controls, m_patternId))); + plan->setParent(this); // +0x04 (BotScript::m_owner) + return plan; + } + case 6: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerParallel* const plan = newFlightPlan(bot, m_patternId); + BAPConPosition* const reached = (self->getObjectTypeFlags() & 0x20) + ? checkPointer(new BAPConPosition(goal, 2.0f)) + : checkPointer(new BAPConPosition(goal, radius)); + plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, goal, speed, speed, reached, controls, + static_cast(waypoints)->m_third, + m_patternId))); + plan->setParent(this); + return plan; + } + case 7: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + BAPCombinerParallel* const plan = newFlightPlan(bot, m_patternId); + BAPConPosition* const reached = checkPointer(new BAPConPosition(goal, radius)); + plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, goal, speed, speed, reached, controls, + static_cast(waypoints)->m_third, + m_patternId))); + plan->setParent(this); + return plan; + } + default: + break; + } + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; +} + +// ELF 0x27F670 +void BBPGotoWaypoint3d::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.h new file mode 100644 index 000000000..643c5783a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.h @@ -0,0 +1,35 @@ +// Waypoint-following pattern of aircraft (3d navigation): flies the bot's flight waypoint list. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS3D_H + +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BBFC0 (7 words), operator new 0xC, package G-vehicles. +class BBPGotoWaypoint3d : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypoint3d(int); // 0x27F630 + virtual ~BBPGotoWaypoint3d(); // 0x280CF0 + + virtual BotScript* createPlan(Bot*); // 0x27F6A0, slot +0x08; from the base declaration + virtual void init(Bot*); // 0x27F670, slot +0x18; from the base declaration + + /* +0x08 */ int m_patternId; // the constructor argument (operator new 0xC) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTS3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp new file mode 100644 index 000000000..9a6edd6a8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp @@ -0,0 +1,287 @@ +// Waypoint-following pattern of boats (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp in +// the image). Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its +// ELF address. createPlan was checked against the listing for constructor arguments (bools and +// the 64-bit masks), allocation order and the waypoint fields each arm reads. + +#include "BBPGotoWaypointsBoat.h" + +#include "../../../../IO/Input/Input.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WPBeachLanding.h" +#include "../AIBot/WPCloseTo.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPALookAhead.h" +#include "../AIBotActionPlan/BAPAMoveToDirect.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWMoveTo.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../AIUtils/checkPointer.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x284510, __tcf_0 0x284570, _GLOBAL__I 0x2845A0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] packaging: the image repeats these blocks inline in each arm. + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +void clearScript(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); +} + +// The look-ahead built when the vehicle looks with another control than it steers with: 5 degrees +// per update (0x3DB2B8C2), a never-ending condition, the look controls. +BAPALookAhead* newLookAhead(Bot* bot, Information* self, int patternId) +{ + return checkPointer(new BAPALookAhead(bot, 0.08726646f, checkPointer(new BAPConFalse()), + self->getControlInfo()->getLookControls(), patternId)); +} + +} // namespace + +// ELF 0x280DB0 (C1; C2 0x280D70): BBPPattern(), the vtable store (GOT -0xC5C + 8), then the argument +// at +0x08. +BBPGotoWaypointBoat::BBPGotoWaypointBoat(int id) + : m_patternId(id) +{ +} + +// ELF 0x280E30 (D1; D2 0x280DF0, D0 0x280E70): nothing of its own; the BBPGotoWaypoint vtable store +// and BBPPattern's destructor. +BBPGotoWaypointBoat::~BBPGotoWaypointBoat() +{ +} + +// ELF 0x280EE0. An uninitiated pattern clears the debugger and the context, drops the plan and +// builds nothing. A plan of this pattern is kept unless the waypoints were renewed (their +4 flag, +// cleared here); otherwise the plan is dropped, and a waypoint error builds nothing. The plan is a +// BAPIWMoveTo over the waypoint list's goal: +// 0 WPCloseTo: object-finding move to the target, ended when the target moved by the radius; +// 1 WPMoveTo: finding move to the goal point; +// 2 WPPatrol: serial(parallel(finding move ended at the goal in XZ), reset controls); +// 3/4 beach landing: outside the zone as 1; inside, serial(while(true, parallel(direct move, +// pitch held continuously))) towards the zone's box centre. +// Every move except 0 gets a parallel look-ahead when the look control differs from the drive turn +// control. The arrival radius is four times the own physical radius (plus the target's in arm 0); +// the speed is the list's +8 value, or the vehicle's maximum when it is negative. The equipment +// information is not null-checked; any other list id returns null without clearing. +BotScript* BBPGotoWaypointBoat::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + clearScript(bot); + dropPlan(bot); + return 0; + } + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + const bool lookSeparately = controlInfo->getLookHorizontalControl() != controlInfo->getDriveTurnControl(); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && !bot->getWaypoints()->m_flag4) + return bot->getPlan(); + + bot->getWaypoints()->m_flag4 = false; + dropPlan(bot); + clearScript(bot); + if (bot->getWaypoints()->getWayPointError()) + return 0; + + IPIMobile* const mobile = self->getMobile(); + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + float radius = self->getPhysical()->getRadius() * 4.0f; + const float maxSpeed = mobile->getMaxSpeed(); + const float waypointSpeed = bot->getWaypoints()->m_float8; + const float speed = waypointSpeed < 0.0f ? maxSpeed : waypointSpeed; // NaN keeps the list's value + bot->getSquadMember()->clearRequestAction(); + + switch (waypoints->getId()) + { + case 0: + { + WPCloseTo* const closeTo = static_cast(waypoints); + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Information* const target = informationManager->getInformation(closeTo->m_target); + if (!target) + return 0; + goal = target->getPosition(); + if (target->getPhysical()) + radius = target->getPhysical()->getRadius() + radius; + BAPConFalse* const never = checkPointer(new BAPConFalse()); + const float listRadius = waypoints->getWayPointRadius(); + const float distance = listRadius > radius ? listRadius : radius; // unordered: radius + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, closeTo->m_target, distance, speed, speed, never, controls, m_patternId, + checkPointer(new BAPConObjectMoved(closeTo->m_target, radius)), 0.0f, -1)); + BAPIWMoveTo* const plan = checkPointer(new BAPIWMoveTo(goal, move, m_patternId)); + plan->setParent(this); + return plan; + } + case 1: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + BAPALookAhead* look = 0; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); // not read in this arm + if (lookSeparately) + look = newLookAhead(bot, self, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, speed, speed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + BAPIWMoveTo* plan; + if (lookSeparately) + { + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + both->addStatement(move); + both->addStatement(look); + plan = checkPointer(new BAPIWMoveTo(goal, both, m_patternId)); + } + else + plan = checkPointer(new BAPIWMoveTo(goal, move, m_patternId)); + plan->setParent(this); + return plan; + } + case 2: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + BAPCombinerSerial* const steps = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + // The list radius is read once for the move's distance and once more for the arrival test. + const float listRadius = waypoints->getWayPointRadius(); + const float arrivalListRadius = waypoints->getWayPointRadius(); + const float arrival = arrivalListRadius > radius ? arrivalListRadius : radius; // unordered: radius + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, speed, speed, checkPointer(new BAPConPosition(goal2d, arrival)), controls, m_patternId, + listRadius, 0.0f)); + both->addStatement(move); + if (lookSeparately) + both->addStatement(newLookAhead(bot, self, m_patternId)); + steps->addStatement(both); + steps->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + BAPIWMoveTo* const plan = checkPointer(new BAPIWMoveTo(goal, steps, m_patternId)); + plan->setParent(this); + return plan; + } + case 3: + case 4: + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + BAPALookAhead* look = 0; + // The goal point is asked twice; the second answer is the one used. + if (!waypoints->getGoalPoint(goal)) + return 0; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); // not read in this arm + WPBeachLanding* const landing = static_cast(waypoints); + if (landing->insideZone()) + { + BAPCombinerSerial* const steps = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + both->addStatement(checkPointer(new BAPAMoveToDirect(bot, goal, speed, speed, + checkPointer(new BAPConFalse()), controls, + m_patternId))); + if (lookSeparately) + both->addStatement(newLookAhead(bot, self, m_patternId)); + // Pitch (input 1, mask bit 1) held for as long as the loop runs. + both->addStatement(checkPointer(new BAPATriggerContinously( + io::PIPitch, checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + checkPointer(new BAPConFalse()), 2ULL, m_patternId, 0.0))); + steps->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), both, false, + m_patternId))); + + Vec3 centre3d; + centre3d.x = centre3d.y = centre3d.z = 0.0f; + Vec2 centre2d; + centre2d.x = centre2d.y = 0.0f; + Vec2 centre; + centre.x = centre.y = 0.0f; + getBoxCentre(landing->m_zone->getMinCorner(), centre, landing->m_zone->getMaxCorner()); + centre2d = centre; + vec2ToVec3XZ(centre2d, centre3d); + BAPIWMoveTo* const plan = checkPointer(new BAPIWMoveTo(centre3d, steps, m_patternId)); + plan->setParent(this); + return plan; + } + + if (lookSeparately) + look = newLookAhead(bot, self, m_patternId); + BAPAMoveToFinding* const move = checkPointer(new BAPAMoveToFinding( + bot, goal, speed, speed, 0, controls, m_patternId, waypoints->getWayPointRadius(), 0.0f)); + BAPIWMoveTo* plan; + if (lookSeparately) + { + BAPCombinerParallel* const both = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + both->addStatement(move); + both->addStatement(look); + plan = checkPointer(new BAPIWMoveTo(goal, both, m_patternId)); + } + else + plan = checkPointer(new BAPIWMoveTo(goal, move, m_patternId)); + plan->setParent(this); + return plan; + } + default: + return 0; + } +} + +// ELF 0x280EB0 +void BBPGotoWaypointBoat::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.h new file mode 100644 index 000000000..745950664 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.h @@ -0,0 +1,36 @@ +// Waypoint-following pattern of boats: follows the bot's waypoint list, including beach landings. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSBOAT_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSBOAT_H + +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC040 (7 words), operator new 0xC, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPGotoWaypointBoat : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypointBoat(int); // 0x280DB0 + virtual ~BBPGotoWaypointBoat(); // 0x280E30 + + virtual BotScript* createPlan(Bot*); // 0x280EE0, slot +0x08; from the base declaration + virtual void init(Bot*); // 0x280EB0, slot +0x18; from the base declaration + + /* +0x08 */ int m_patternId; // the constructor argument (operator new 0xC) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSBOAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp new file mode 100644 index 000000000..d0654bd33 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp @@ -0,0 +1,261 @@ +// Waypoint pattern of infantry (AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp in +// the image; class BBPGotoWaypointSoldier). Recovered from libaidll.so (Linux 1.5.3153, ia-32, +// symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x287410 (__tcf_0 0x287470, _GLOBAL__I 0x2874A0): 's Init object only. +#include + +#include "BBPGotoWaypointsInfantery.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPASetSensingAgentFocus.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPIWMoveTo.h" +#include "../AIBotBehaviour/BBPendingCalls.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Waypoint list ids (WaypointList::getId, slot +0x10): WPCloseTo 0, WPMoveTo 1, WPPatrol 2. +const int kWaypointCloseTo = 0; +const int kWaypointMoveTo = 1; +const int kWaypointPatrol = 2; + +// BAPInfoWrapper::getInfoType of a BAPIWMoveTo. +const int kInfoTypeMoveTo = 2; + +void clearScript(Bot* bot) +{ + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); +} + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +} // namespace + +// ELF 0x284600 +BBPGotoWaypointSoldier::BBPGotoWaypointSoldier(int id) + : m_patternId(id) +{ +} + +// ELF 0x284680 +BBPGotoWaypointSoldier::~BBPGotoWaypointSoldier() +{ +} + +// ELF 0x284730. Moves the soldier along its waypoint list: for a point goal (WPMoveTo, WPPatrol) +// BAPIWMoveTo(goal, serial { BAPASetSensingAgentFocus(0.5, goal - position), BAPAMoveToFinding }) +// and for an object goal (WPCloseTo) the same with BAPAMoveToObjectFinding, which ends when the +// object moved (BAPConObjectMoved). A current plan of this pattern is kept while its goal is +// within 4 * the squad member's max speed of the new goal (the patrol and object cases; a WPMoveTo +// plan is always rebuilt once the list changed). +BotScript* BBPGotoWaypointSoldier::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + clearScript(bot); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + const float maxSpeed = bot->getSquadMember()->getMaxSpeed(); // 0x28477F + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + { + // 0x285CA3: the current plan is ours. Keep it unless the waypoints changed. + if (!bot->getWaypoints()->m_flag4 || bot->getWaypoints()->getWayPointError()) + return bot->getPlan(); + bot->getWaypoints()->m_flag4 = false; + + if (static_cast(bot->getPlan())->getInfoType() == kInfoTypeMoveTo) + { + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = + equipment->getControlInfo()->getDriveControls(); + float range = equipment->getPhysical()->getRadius() * 4.0f; + const int id = waypoints->getId(); + if (id == kWaypointPatrol || id == kWaypointMoveTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + if (id == kWaypointPatrol) + { + // 0x285E21: keep the plan while its goal is close (XZ) to the new one. + const Vec3& current = static_cast(bot->getPlan())->getPosition(); + const float dx = current.x - goal.x; + const float dz = current.z - goal.z; + const float keep = 4.0f * maxSpeed; + if (keep * keep >= dx * dx + dz * dz) + return bot->getPlan(); + } + dropPlan(bot); + clearScript(bot); + return buildMoveTo(bot, equipment, goal, maxSpeed, controls, waypoints->getWayPointRadius()); + } + if (id == kWaypointCloseTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + const unsigned int target = bbpending::closeToTarget(waypoints); + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + { + dropPlan(bot); + return 0; + } + goal = targetInfo->getPosition(); + // 0x2864EB: keep the plan while its goal is close (3d) to the object. + const Vec3& current = static_cast(bot->getPlan())->getPosition(); + Vec3 delta; + delta.x = goal.x - current.x; + delta.y = goal.y - current.y; + delta.z = goal.z - current.z; + const float keep = maxSpeed * 4.0f; + if (keep * keep >= delta.x * delta.x + delta.y * delta.y + delta.z * delta.z) + return bot->getPlan(); + dropPlan(bot); + clearScript(bot); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + return buildMoveToObject(bot, equipment, waypoints, target, goal, range, maxSpeed, controls); + } + // 0x285D70 + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + // 0x285C78: another wrapper; build a new plan. + if (bot->getPlan()) + dropPlan(bot); + } + else if (bot->getPlan()) + { + dropPlan(bot); + } + + // 0x2847F8 + clearScript(bot); + if (bot->getWaypoints()->getWayPointError()) + return 0; + WaypointList* const waypoints = bot->getWaypoints(); + const unsigned long long controls = equipment->getControlInfo()->getDriveControls(); // 0x284848 +0x30, 0x28484E + float range = equipment->getPhysical()->getRadius() * 4.0f; + bot->getSquadMember()->clearRequestAction(); // 0x28488A + + const int id = waypoints->getId(); + if (id == kWaypointPatrol || id == kWaypointMoveTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + Vec2 goal2d; + goal2d.x = goal2d.y = 0.0f; + if (!waypoints->getGoalPoint(goal)) + return 0; + vec3ToVec2XZ(goal, goal2d); + return buildMoveTo(bot, equipment, goal, maxSpeed, controls, waypoints->getWayPointRadius()); + } + if (id == kWaypointCloseTo) + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + const unsigned int target = bbpending::closeToTarget(waypoints); + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + goal = targetInfo->getPosition(); + if (targetInfo->getPhysical()) + range = targetInfo->getPhysical()->getRadius() + range; + return buildMoveToObject(bot, equipment, waypoints, target, goal, range, maxSpeed, controls); + } + return 0; +} + +// The point-goal plan, built identically by the WPMoveTo and WPPatrol arms (0x2848C0, 0x285660, +// 0x285DAB, 0x286D45). +BotScript* BBPGotoWaypointSoldier::buildMoveTo(Bot* bot, Information* equipment, const Vec3& goal, float maxSpeed, + unsigned long long controls, float wayPointRadius) +{ + BAPAMoveToFinding* const move = checkPointer( + new BAPAMoveToFinding(bot, goal, maxSpeed, maxSpeed, 0, controls, m_patternId, wayPointRadius, 0.0f)); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + Vec3 look; + const Vec3& position = equipment->getPosition(); + look.x = goal.x - position.x; + look.y = goal.y - position.y; + look.z = goal.z - position.z; + BAPASetSensingAgentFocus* const focus = + checkPointer(new BAPASetSensingAgentFocus(0.5f, look, m_patternId, false)); + serial->addStatement(focus); + serial->addStatement(move); + BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, serial, m_patternId)); + root->setParent(this); // +0x04 (BotScript::m_owner) + return root; +} + +// The object-goal plan of the WPCloseTo arm (0x284EC0, 0x286470): the approach distance is the +// larger of the waypoint radius and `range` (4 * own radius + the object's radius). +BotScript* BBPGotoWaypointSoldier::buildMoveToObject(Bot* bot, Information* equipment, WaypointList* waypoints, + unsigned int target, const Vec3& goal, float range, + float maxSpeed, unsigned long long controls) +{ + BAPConObjectMoved* const moved = checkPointer(new BAPConObjectMoved(target, range)); + const float wayPointRadius = waypoints->getWayPointRadius(); + const float distance = !(wayPointRadius > range) ? range : wayPointRadius; // fcmovbe 0x284FEA (unordered: range) + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, target, distance, maxSpeed, maxSpeed, 0, controls, m_patternId, moved, 0.0f, -1)); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + Vec3 look; + const Vec3& position = equipment->getPosition(); + look.x = goal.x - position.x; + look.y = goal.y - position.y; + look.z = goal.z - position.z; + BAPASetSensingAgentFocus* const focus = + checkPointer(new BAPASetSensingAgentFocus(0.5f, look, m_patternId, false)); + serial->addStatement(focus); + serial->addStatement(move); + BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, serial, m_patternId)); + root->setParent(this); // +0x04 (BotScript::m_owner) + return root; +} + +// ELF 0x284700 +void BBPGotoWaypointSoldier::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h new file mode 100644 index 000000000..9d0b5cfe5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h @@ -0,0 +1,46 @@ +// Waypoint-following pattern of infantry (class BBPGotoWaypointSoldier in BBPGotoWaypointsInfantery.cpp; +// aibehaviours.ai names it BBPGotoWaypointInfantery). +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSINFANTERY_H + +#include "../../../../Math/Vec3.h" +#include "BBPGotoWaypoint.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class Information; +class WaypointList; + +// ELF: vtable 0x4BC0C0 (7 words), operator new 0xC, package D-behaviours. +class BBPGotoWaypointSoldier : public BBPGotoWaypoint +{ +public: + explicit BBPGotoWaypointSoldier(int id); // 0x284600 + virtual ~BBPGotoWaypointSoldier(); // 0x284680 + + virtual BotScript* createPlan(Bot*); // 0x284730, slot +0x08 + virtual void init(Bot*); // 0x284700, slot +0x18 + +private: + // [CHOSEN, not recovered] helpers for the plan the image builds inline in four arms. + BotScript* buildMoveTo(Bot*, Information* equipment, const Vec3& goal, float maxSpeed, + unsigned long long controls, float wayPointRadius); + BotScript* buildMoveToObject(Bot*, Information* equipment, WaypointList*, unsigned int target, const Vec3& goal, + float range, float maxSpeed, unsigned long long controls); + + /* +0x08 */ int m_patternId; // the constructor argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPGOTOWAYPOINTSINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp new file mode 100644 index 000000000..95264a0c5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp @@ -0,0 +1,427 @@ +// Fire pattern of helicopters (AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// The builders were written from the listing block by block; Ghidra drops the bool constructor +// arguments and shows createPlanInternal's mode 0/1 arm once for both modes. +// [PLATFORM] precision: the x87 build keeps the radius sum, the bounding-box sums, the fire-rate +// scale and the 60 / shots quotient in extended precision before rounding or converting them; the +// float expressions below round them first. + +// static init: ELF 0x28C0E0 (__tcf_0 0x28C140, _GLOBAL__I 0x28C170): 's Init object only. +#include + +#include "BBPHeliFire3d.h" + +#include + +#include "../../../../Core/Debug.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPAMoveAwayFrom3dObject.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCConBombPrecision3d.h" +#include "../AIBotActionPlan/BAPCConPrecision3d.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConInsideBattleZone.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectInFront.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectOccupied.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponHeat.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "WeaponChoice.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by `std::list::insert(context->begin(), &variable)`. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// `1 << input` sign-extended to the 64-bit control mask (`movl %eax,%edx; sarl $0x1f,%edx`). +unsigned long long inputMask(int input) +{ + return static_cast(static_cast(1 << input)); +} + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +// [CHOSEN, not recovered] spelling of the image's inlined row copy (three loads at 4 * row floats). +Vec3 row(const Mat4& transformation, int index) +{ + const Vec3 result = { transformation.m[index * 4], transformation.m[index * 4 + 1], + transformation.m[index * 4 + 2] }; + return result; +} + +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +} // namespace + +// ELF 0x287500: BBPFire(), the vtable store (GOT -0x1308 + 8), then the argument at +0x08 +// (operator new 0x28: nothing beyond BBPFire). +BBPHeliFire3d::BBPHeliFire3d(int patternId) + : BBPFire() +{ + m_patternId = patternId; +} + +// ELF 0x287580 (D0 0x2875C0): the vtable store, then BBPFire's destructor; nothing of its own. +BBPHeliFire3d::~BBPHeliFire3d() +{ +} + +// ELF 0x287830. Keeps a fire plan of this pattern built for the same target and flag; otherwise +// drops the plan, chooses the strongest weapon with ammunition against the target's strength type +// regardless of range (7: every weapon class), and builds `IWFire(createPlanInternal)`. The mode +// comes from the own vehicle and the target, the precision from the target's bounding box (mode 0: +// 0.8 of the largest extent, at least 0.5; mode 1: the extent sum, at least 5; mode 2: the mean +// extent, at least 10). Without a usable target no plan is built; with no weapon the own object's +// update is called first, as compiled. +BotScript* BBPHeliFire3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + static_cast(bot)->resetAllControls(false, true, true); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() && static_cast(bot->getPlan())->getGeneratorId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_targets[bot->getBotId()] + && m_flag20 == static_cast(bot->getPlan())->getFlagA()) + return bot->getPlan(); + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + dropPlan(bot); + bot->getScriptContext()->clear(); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); + if (!targetInfo) + return 0; + IPIArmament* const armament = self->getArmament(); + IPIPhysical* const selfPhysical = self->getPhysical(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIPhysical* const targetPhysical = targetInfo->getPhysical(); + if (!armament || !targetPhysical || !controlInfo || !selfPhysical) + return 0; + IPIMobile* const targetMobile = targetInfo->getMobile(); + LocalBoundingBox* const box = const_cast(targetPhysical->getLocalBoundingBox()); + FireData data; + data.m_weapon = choseWeaponDistanceIndependent(m_weapons[bot->getBotId()], targetPhysical->getStrengthType(), + armament->getWeapons(), 7); + if (data.m_weapon == -1) + { + self->getAIObject()->update(); + return 0; + } + + const float selfRadius = selfPhysical->getRadius(); + const float radius = targetMobile ? targetPhysical->getRadius() + selfRadius : selfRadius + 0.0f; + data.m_approachRadius = radius + radius; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(data.m_weapon)); + const Vec3 weaponPosition = row(weapon->getAbsoluteTransformation(), 3); // stored, never read + (void)weaponPosition; + data.m_weaponDirection = row(weapon->getAbsoluteTransformation(), 2); + data.m_position = row(self->getTransformation(), 3); + data.m_direction = row(self->getTransformation(), 2); + const bool indirect = weapon->getIndirect(); + const bool flag40 = (targetInfo->getObjectTypeFlags() & 0x40) != 0; + bot->getSquadMember()->clearRequestAction(); + if (!self->getMobile()) + { + data.m_mode = 3; + } + else + { + float limit; + float precision; + if (!flag40) + { + limit = 0.5f; + data.m_mode = 0; + precision = std::max(box->getSize().x, std::max(box->getSize().y, box->getSize().z)) * 0.8f; + } + else if (!indirect) + { + limit = 5.0f; + data.m_mode = 1; + precision = box->getSize().x + box->getSize().y + box->getSize().z; + } + else + { + limit = 10.0f; + data.m_mode = 2; + precision = (box->getSize().x + box->getSize().y + box->getSize().z) / 3.0f; + } + data.m_precision = std::max(limit, precision); + } + + BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, target, m_flag20, false, data.m_weapon, -1, + createPlanInternal(bot, data), m_patternId)); + plan->setParent(this); // +0x04 (BotScript::m_owner) + return plan; +} + +// ELF 0x287600 +void BBPHeliFire3d::init(Bot* bot, unsigned int target, int weapon, bool flag20, bool flag21) +{ + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = target; + m_weapons[bot->getBotId()] = weapon; + m_flag20 = flag20; + m_flag21 = flag21; + m_positionArgs[bot->getBotId()] = static_cast(-1); +} + +// ELF 0x287680. Helicopters have no laser-guided attack: the image reports it (an Error-type +// Debug, which aborts in this tree) and then stores the arguments like BBPFire3d's overload. +void BBPHeliFire3d::init(Bot* bot, unsigned int positionArg, const Vec3& position, int weapon) +{ + Debug(DebugTypeError, "AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp", 0x7D, "") + << "LaserGuided missiles unsuported by helicopters."; + m_initiated[bot->getBotId()] = true; + m_targets[bot->getBotId()] = static_cast(-1); + m_weapons[bot->getBotId()] = weapon; + m_positionArgs[bot->getBotId()] = positionArg; + m_targetPositions[bot->getBotId()] = position; +} + +// ELF 0x28C190 +int BBPHeliFire3d::getImplementationType() +{ + return 4; +} + +// ELF 0x288130 (listing; the switch is at 0x2882B4). Modes 0 and 1 loop while the target is +// alive and, for a weapon with heat, not too hot: inside the battle zone (150) the helicopter +// attacks when the target is in the line of fire, in range (20 m to the weapon's range) and in +// front, and otherwise backs away and re-approaches it twice; outside it closes in on the target at +// 25 m. Controls are reset and flares answer missile locks throughout. Mode 3 (no IPIMobile of its +// own) is the plain attack; mode 2 builds nothing, as compiled. +BAPStatement* BBPHeliFire3d::createPlanInternal(Bot* bot, BBPHeliFire3d::FireData& data) +{ + static float dotLimit = 0.5f; // 0x4BC124 + static float minHeight = 25.0f; // 0x4BC128 + + BAPContext* const context = bot->getScriptContext(); + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + IPIArmament* const armament = self->getArmament(); + IPIMobile* const mobile = self->getMobile(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(data.m_weapon)); + if (data.m_weapon != -1) + armament->setActiveWeapon(data.m_weapon, bot->getSide()); + + const unsigned int target = m_targets[bot->getBotId()]; + Information* const targetInfo = informationManager->getInformation(target); // no null test + IPIUnit* const targetUnit = targetInfo->getUnit(); + const float worldSizeX = static_cast(terrain()->getWorldSizeX()); // not read + const float worldSizeZ = static_cast(terrain()->getWorldSizeZ()); // not read + (void)worldSizeX; + (void)worldSizeZ; + if (Bot* const targetBot = IBotManager::instance->getBot(targetInfo->getAIObject())) + (void)targetBot->getLodLevel(); // called, result not used + + switch (data.m_mode) + { + case 0: + case 1: + { + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPConAnd* const alive = checkPointer(new BAPConAnd()); + alive->addCondition(checkPointer(new BAPConObjectExists(target))); + if (targetUnit && targetUnit->isOccupied()) + alive->addCondition(new BAPConObjectOccupied(target)); // no checkPointer in the image + alive->addCondition(checkPointer(new BAPConNot(checkPointer(new BAPConObjectHealth(target, 0.0f))))); + if (weapon->hasHeat()) + alive->addCondition(checkPointer(new BAPConWeaponHeat(newVariable(context, weapon), 0.8f))); + + BAPConInsideBattleZone* const inside = checkPointer(new BAPConInsideBattleZone(150.0f)); + BAPConAnd* const inRange = checkPointer(new BAPConAnd()); + BAPConObjectLineOfFire* const lineOfFire = checkPointer(new BAPConObjectLineOfFire(target, false)); + BAPConObjectDistance* const distance = + checkPointer(new BAPConObjectDistance(target, 20.0f, weapon->getMaxRange(), false, true)); + inRange->addCondition(lineOfFire); + inRange->addCondition(distance); + inRange->addCondition(checkPointer(new BAPConObjectInFront(target, 0.0f, dotLimit))); + + BAPCombinerParallel* const attackBlock = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + attackBlock->addStatement(createMobileLessAttackPlan(bot, data)); + + BAPCombinerSerial* const evade = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPAMoveAwayFrom3dObject* const away1 = checkPointer(new BAPAMoveAwayFrom3dObject( + target, 150.0f, checkPointer(new BAPConFalse()), controlInfo->getDriveControls(), m_patternId)); + BAPAMoveTo3dObject* const return1 = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), minHeight, + checkPointer(new BAPConObjectDistance(target, 30.0f, true, true, false)), controlInfo->getDriveControls(), + m_patternId)); + BAPAMoveAwayFrom3dObject* const away2 = checkPointer(new BAPAMoveAwayFrom3dObject( + target, 150.0f, checkPointer(new BAPConFalse()), controlInfo->getDriveControls(), m_patternId)); + BAPAMoveTo3dObject* const return2 = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), minHeight, + checkPointer(new BAPConObjectDistance(target, 30.0f, true, true, false)), controlInfo->getDriveControls(), + m_patternId)); + evade->addStatement(away1); + evade->addStatement(return1); + evade->addStatement(away2); + evade->addStatement(return2); + + BAPFlowCIf* const engage = checkPointer(new BAPFlowCIf(inRange, attackBlock, evade, m_patternId, true, false)); + BAPAMoveTo3dObject* const approach = checkPointer(new BAPAMoveTo3dObject( + target, data.m_approachRadius, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 25.0f, + checkPointer(new BAPConObjectDistance(target, 30.0f, true, true, false)), controlInfo->getDriveControls(), + m_patternId)); + BAPFlowCIf* const zone = checkPointer(new BAPFlowCIf(inside, engage, approach, m_patternId, true, false)); + + BAPCombinerParallel* const body = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + body->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + body->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); // no checkPointer + body->addStatement(zone); + root->addStatement(checkPointer(new BAPFlowCWhile(alive, body, m_patternId))); + return root; + } + case 3: + return createMobileLessAttackPlan(bot, data); // 0x2882D0 + default: + return 0; + } +} + +// ELF 0x28A7B0. The attack itself: serial([press the weapon's activation input unless it is 0x40], +// parallel(aim at the target, trigger)). The trigger fires while the precision holds (modes 0, 1 +// and 3 also need the weapon's range; mode 2 uses the bomb precision) and, for a weapon with a fire +// rate, at most at 1.5 times that rate scaled down by the bot skill; burst weapons hold the +// trigger continuously. +BAPStatement* BBPHeliFire3d::createMobileLessAttackPlan(Bot* bot, BBPHeliFire3d::FireData& data) +{ + bot->getScriptContext(); // called, result not used + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* const controlInfo = self->getControlInfo(); + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(self->getArmament()->getWeapon(data.m_weapon)); + int shots = static_cast(weapon->getFireRate() * 1.5f); + const unsigned int target = m_targets[bot->getBotId()]; + BAPCombinerSerial* const root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + const Vec3 offset = { 0.0f, 0.0f, 0.0f }; + + if (weapon->getWeaponActivate() != 0x40) + root->addStatement(checkPointer(new BAPATrigger( + static_cast(weapon->getWeaponActivate()), checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponActivate()), m_patternId, 0.0, false))); + + BAPCombinerParallel* const fire = checkPointer(new BAPCombinerParallel(m_patternId, -1, false)); + BAPAAimAtObject3d* const aim = + checkPointer(new BAPAAimAtObject3d(bot, target, offset, checkPointer(new BAPConFalse()), + controlInfo->getAimControls(), m_patternId, 40.0f, 0.0f)); + BAPConAnd* const ready = checkPointer(new BAPConAnd()); + BAPCondition* precision = 0; + if (data.m_mode == 1) + { + BAPConObjectDistance* const inRange = + checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false)); + precision = checkPointer(new BAPCConPrecision3d(target, aim, weapon->getAllowedDeviation(), false)); + ready->addCondition(inRange); + } + else if (data.m_mode == 2) + { + precision = checkPointer(new BAPCConBombPrecision3d(aim, data.m_precision, true)); + } + else if (data.m_mode == 0 || data.m_mode == 3) + { + BAPConObjectDistance* const inRange = + checkPointer(new BAPConObjectDistance(target, weapon->getMaxRange(), false, false, false)); + precision = checkPointer( + new BAPCConPrecision3d(target, aim, weapon->getAllowedDeviation(), !weapon->getBurst())); + ready->addCondition(inRange); + } + if (shots != 0) + { + const float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + shots = static_cast(shots * (1.0f - (1.0f - skill) * 0.8f)); + ready->addCondition(checkPointer(new BAPConTime(60.0f / shots, false, false, true))); + } + ready->addCondition(precision); // a null condition for any other mode, as compiled + + BAPStatement* trigger; + if (!weapon->getBurst()) + trigger = checkPointer(new BAPATrigger(static_cast(weapon->getWeaponFire()), ready, + checkPointer(new BAPConFalse()), inputMask(weapon->getWeaponFire()), + m_patternId, 0.0, true)); + else + trigger = checkPointer(new BAPATriggerContinously(static_cast(weapon->getWeaponFire()), + ready, 0, checkPointer(new BAPConFalse()), + inputMask(weapon->getWeaponFire()), m_patternId, 0.0)); + fire->addStatement(aim); + fire->addStatement(trigger); + root->addStatement(fire); + return root; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.h new file mode 100644 index 000000000..030ae8d23 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.h @@ -0,0 +1,62 @@ +// Fire pattern of helicopters: hover attacks against a target object, built by createPlan from the +// target and a weapon chosen independently of the distance. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPHELIFIRE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPHELIFIRE3D_H + +#include "../../../../Math/Vec3.h" +#include "BBPFire.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +class BAPStatement; + +// ELF: vtable 0x4BC140 (9 words), operator new 0x28 (nothing beyond BBPFire), package G-vehicles. +class BBPHeliFire3d : public BBPFire +{ +public: + // The attack parameters createPlan hands to the plan builders; a stack object of createPlan + // (0x3C bytes at -0x158, no constructor in the image). Names are [INFERRED] from createPlan (0x287830). + struct FireData + { + /* +0x00 */ int m_weapon; // armament index from choseWeaponDistanceIndependent + // 0: target without object type flag 0x40; 1: flag 0x40, direct weapon; 2: flag 0x40, + // indirect weapon (createPlanInternal builds nothing for it); 3: no IPIMobile of its own. + /* +0x04 */ int m_mode; + /* +0x08 */ float m_approachRadius; // twice the own (plus the moving target's) physical radius + /* +0x0C */ float m_precision; // from the target's bounding box; not set in mode 3 + // Written by createPlan, read by neither builder. + /* +0x10 */ Vec3 m_weaponDirection; // third row of the weapon's absolute transformation + /* +0x1C */ float m_unused1C; // [UNRESOLVED] never accessed + /* +0x20 */ Vec3 m_position; // fourth row of the own transformation + /* +0x2C */ float m_unused2C; // [UNRESOLVED] never accessed + /* +0x30 */ Vec3 m_direction; // third row of the own transformation + }; + + explicit BBPHeliFire3d(int); // 0x287500 + virtual ~BBPHeliFire3d(); // 0x287580 + + virtual BotScript* createPlan(Bot*); // 0x287830, slot +0x08 + virtual void init(Bot*, unsigned int, int, bool, bool); // 0x287600, slot +0x18 + virtual void init(Bot*, unsigned int, const Vec3&, int); // 0x287680, slot +0x1C: refuses (Debug Error) + virtual int getImplementationType(); // 0x28C190, slot +0x20: 4 + + // createPlan hands createPlanInternal's statement to the BAPIWFire constructor; createPlanInternal + // returns createMobileLessAttackPlan's root for mode 3 and puts it into a parallel otherwise. + BAPStatement* createPlanInternal(Bot*, BBPHeliFire3d::FireData&); // 0x288130 + BAPStatement* createMobileLessAttackPlan(Bot*, BBPHeliFire3d::FireData&); // 0x28A7B0 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPHELIFIRE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp new file mode 100644 index 000000000..88cf59b91 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp @@ -0,0 +1,82 @@ +// Idle pattern base (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp in the image). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. Package D. + +// static init: ELF 0x28C620 (__tcf_0 0x28C680, _GLOBAL__I 0x28C6B0): 's Init object only. +#include + +#include "BBPIdle.h" + +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x28C1E0 +BBPIdle::BBPIdle(int id) + : m_patternId(id) +{ +} + +// ELF 0x28C260 +BBPIdle::~BBPIdle() +{ +} + +// ELF 0x28C6D0 +int BBPIdle::getType() +{ + return 0; +} + +// ELF 0x28C2E0. Retail quirk: the primary-object lookup is not null-checked. +bool BBPIdle::freePosition(unsigned int equipment, int side) +{ + Information* info = informationManager->getInformation(equipment); + if (!info) + return false; + if (!info->isPrimary()) + info = informationManager->getInformation(info->getPrimaryObject(side)); + + if (!info->getUnit()) + return false; + if (!info->getUnit()->isOccupied()) + return true; + + int iterator; + for (Information* seat = informationManager->getInformation(info->getFirstSecondaryObject(iterator, side)); seat; + seat = informationManager->getInformation(info->getSecondaryObject(iterator, side))) + { + if (seat->getUnit() && !seat->getUnit()->isOccupied()) + return true; + } + return false; +} + +// ELF 0x28C480. Same walk as freePosition, testing Information::isBooked. +bool BBPIdle::anyBookedPositions(unsigned int equipment, int side) +{ + Information* info = informationManager->getInformation(equipment); + if (!info) + return false; + if (!info->isPrimary()) + info = informationManager->getInformation(info->getPrimaryObject(side)); + + if (info->isBooked()) + return true; + + int iterator; + for (Information* seat = informationManager->getInformation(info->getFirstSecondaryObject(iterator, side)); seat; + seat = informationManager->getInformation(info->getSecondaryObject(iterator, side))) + { + if (seat->isBooked()) + return true; + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h new file mode 100644 index 000000000..33cc9f2a5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.h @@ -0,0 +1,39 @@ +// Idle pattern base: the pattern id and the pickup-seat queries the idle patterns share. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +// ELF: vtable 0x4BC1C0 (7 words), package D-behaviours. +class BBPIdle : public BBPPattern +{ +public: + explicit BBPIdle(int id); // 0x28C1E0 + virtual ~BBPIdle(); // 0x28C260 + + // 0 for the base; BBPIdle2d 1, BBPIdle3d 2, BBPIdleInfantery 3 (BBIdle::calculateUrgency switches on it). + virtual int getType(); // 0x28C6D0, slot +0x18 + + // True when the equipment's primary object, or one of its secondary objects (seats), has an + // unoccupied unit. + bool freePosition(unsigned int equipment, int side); // 0x28C2E0 + // True when the primary object or one of its secondary objects is booked. + bool anyBookedPositions(unsigned int equipment, int side); // 0x28C480 + +protected: + /* +0x08 */ int m_patternId; // the constructor argument (the BBCreateFunction's pattern id) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp new file mode 100644 index 000000000..d1395997a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp @@ -0,0 +1,183 @@ +// Idle pattern of ground vehicles (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x28D950 (__tcf_0 0x28D9B0, _GLOBAL__I 0x28D9E0): 's Init object only. +#include + +#include "BBPIdle2d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Math/Mat4.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x28C880 +BBPIdle2d::BBPIdle2d(int id) + : BBPIdle(id) +{ + m_pickupPlayerId = checkPointer(new int[settings()->getMaxNBots()]); + for (int i = 0; i < settings()->getMaxNBots(); ++i) + m_pickupPlayerId[i] = -1; +} + +// ELF 0x28CA70 +BBPIdle2d::~BBPIdle2d() +{ + if (m_pickupPlayerId) + delete[] m_pickupPlayerId; +} + +// ELF 0x28CB60 (listing). The plan is `parallel(use flares on missile lock, serial(...))` inside a +// BAPIWIdle at the equipment's position; the serial's first statement is `while (true) reset +// controls`. A vehicle waiting for a passenger (a pickup player id >= 0 on equipment whose primary +// object lacks the 0x200000 type flag) first queues a pickup radio message (BAPASendRadioMessage +// 6/6/2, 1.0) when the passenger's vehicle is within 40 m (1600 squared) of the primary object, the +// position is free (not asked for id 255), the equipment is primary and the passenger's request +// (type 2) is confirmed. An existing plan of this pattern is kept; for a waiting vehicle it also +// re-enqueues the radio message (6/6/3, 1.0) after a confirmed request. A plan of another pattern +// that hasPlan reports is not deleted here, as compiled. Builds the plan and clears the +// navigation progress. +BotScript* BBPIdle2d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan()) + { + if (static_cast(bot->getPlan())->getPatternId() == m_patternId) + { + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + if (pickupPlayerId >= 0 && !(equipment->getObjectTypeFlags() & 0x200000) + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(6), 3, 1.0f, -1); + } + return bot->getPlan(); + } + } + else if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + Information* const primary = informationManager->getInformation(equipment->getPrimaryObject(bot->getSide())); + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + const bool anyPosition = pickupPlayerId == 0xFF; + if (pickupPlayerId >= 0 && !(primary->getObjectTypeFlags() & 0x200000)) + { + IAIPlayer* const passenger = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(pickupPlayerId); + IAIObject* const passengerVehicle = passenger ? passenger->getCurrentVehicle() : 0; // +0x54 + if (passengerVehicle) + { + const unsigned int equipmentHandle = bot->getCurrentEquipment(); + Information* const passengerInfo = + informationManager->getInformation(passengerVehicle->getHandle(bot->getSide())); // +0xD0 + if (passengerInfo) + { + const Mat4& own = primary->getTransformation(); // +0x3C + const Mat4& other = passengerInfo->getTransformation(); + const float dx = own.m[12] - other.m[12]; + const float dy = own.m[13] - other.m[13]; + const float dz = own.m[14] - other.m[14]; + const float distanceSqr = dx * dx + dy * dy + dz * dz; + if ((anyPosition || freePosition(equipmentHandle, bot->getSide())) + && 1600.0f > distanceSqr + && equipment->isPrimary() + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + BAPASendRadioMessage* const message = checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(6), 2, 1.0f, + m_patternId, -1)); + serial->addStatement(message); + } + } + } + } + + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile( + checkPointer(new BAPConTrue()), checkPointer(new BAPAResetControls(true, true, true, m_patternId)), + m_patternId)); + serial->addStatement(loop); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + BAPAUseFlareOnMissileLock* const flares = + checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); + parallel->addStatement(flares); + parallel->addStatement(serial); + BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), parallel, m_patternId, bot)); + idle->setParent(this); // +0x04 (BotScript::m_owner) + bot->getBotNavigation()->clearProgress(); + return idle; +} + +// ELF 0x28DA00 +int BBPIdle2d::getType() +{ + return 1; +} + +// ELF 0x28CB10 +void BBPIdle2d::init(Bot* bot, int pickupPlayerId) +{ + m_initiated[bot->getBotId()] = true; + m_pickupPlayerId[bot->getBotId()] = pickupPlayerId; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.h new file mode 100644 index 000000000..60e5cb7c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.h @@ -0,0 +1,38 @@ +// Idle pattern of ground vehicles (2d navigation): waits, optionally for a passenger to pick up. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE2D_H + +#include "BBPIdle.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC240 (7 words), operator new 0x10, package D-behaviours. +class BBPIdle2d : public BBPIdle +{ +public: + explicit BBPIdle2d(int id); // 0x28C880 + virtual ~BBPIdle2d(); // 0x28CA70 + + virtual BotScript* createPlan(Bot*); // 0x28CB60, slot +0x08 + virtual int getType(); // 0x28DA00, slot +0x18: 1 + + void init(Bot*, int pickupPlayerId); // 0x28CB10 + +protected: + /* +0x0C */ int* m_pickupPlayerId; // per bot slot, -1 = none (BBIdle::calculateUrgency passes it) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp new file mode 100644 index 000000000..a986e8af0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp @@ -0,0 +1,237 @@ +// Idle pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x28F420 (__tcf_0 0x28F480, _GLOBAL__I 0x28F4B0): 's Init object only. +#include + +#include "BBPIdle3d.h" + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBot/WaypointList.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPAUseFlareOnMissileLock.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAISettings* settings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + +} // namespace + +// ELF 0x28DCF0 +BBPIdle3d::BBPIdle3d(int id) + : BBPIdle(id) +{ + m_pickupPlayerId = checkPointer(new int[settings()->getMaxNBots()]); + const int bots = settings()->getMaxNBots(); + m_altitude = checkPointer(new float[bots]); + for (int i = 0; i < bots; ++i) + { + m_altitude[i] = 100.0f; + m_pickupPlayerId[i] = -1; + } +} + +// ELF 0x28E020. Retail quirk: m_altitude is not released. +BBPIdle3d::~BBPIdle3d() +{ + if (m_pickupPlayerId) + delete[] m_pickupPlayerId; +} + +// ELF 0x28E120 (listing). The plan is a BAPIWIdle at the equipment's position around +// `serial(reset controls (no aim reset), [pickup radio message], parallel(reset controls, flares on +// missile lock, [move]))`. The bot counts as airborne when the bot reports it, or when the primary +// object has type flag 0x10 and the equipment moves faster than 3 m/s; an airborne bot gets the +// move: 500 m ahead along the flattened heading plus the right axis when the primary object lacks +// type flag 0x20 or has an armament, otherwise to the waypoint goal (or stays) at the aerial +// height map altitude plus 45 m. The pickup message (6/6/2, 1.0) is queued as in BBPIdle2d, but +// only when not airborne. An existing idle plan of this pattern is kept, re-enqueueing the radio +// message (6/6/3, 1.0) for a confirmed request when not airborne. The per-bot altitude that init +// stores (+0x0C) is not read here. The equipment and primary informations are not null-checked, +// as compiled. +// [PLATFORM] precision: the x87 build keeps the heading-plus-right sum and its product with 500 in +// extended precision before adding the position; the float expressions below round each step. +BotScript* BBPIdle3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); + Information* const primary = informationManager->getInformation(equipment->getPrimaryObject(bot->getSide())); + bool airborne = false; + if (bot->isAirBorn() || ((primary->getObjectTypeFlags() & 0x10) && mobile->getSpeedMagnitude() > 3.0f)) + airborne = true; + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getInfoType() == 4) + { + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + if (pickupPlayerId >= 0 && !airborne + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(6), 3, 1.0f, -1); + } + return bot->getPlan(); + } + + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + + const unsigned long long controls = equipment->getControlInfo()->getDriveControls(); + const float maxSpeed = mobile->getMaxSpeed(); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, true, m_patternId)); + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + serial->addStatement(reset); + + const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; + const bool anyPosition = pickupPlayerId == 0xFF; + if (pickupPlayerId >= 0 && !(primary->getObjectTypeFlags() & 0x200000)) + { + IAIPlayer* const passenger = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(pickupPlayerId); + IAIObject* const passengerVehicle = passenger ? passenger->getCurrentVehicle() : 0; // +0x54 + if (passengerVehicle) + { + const unsigned int equipmentHandle = bot->getCurrentEquipment(); + Information* const passengerInfo = + informationManager->getInformation(passengerVehicle->getHandle(bot->getSide())); // +0xD0 + if (passengerInfo) + { + const Mat4& own = primary->getTransformation(); // +0x3C + const Mat4& other = passengerInfo->getTransformation(); + const float dx = own.m[12] - other.m[12]; + const float dy = own.m[13] - other.m[13]; + const float dz = own.m[14] - other.m[14]; + const float distanceSqr = dx * dx + dy * dy + dz * dz; + if ((anyPosition || freePosition(equipmentHandle, bot->getSide())) + && 1600.0f > distanceSqr + && equipment->isPrimary() + && !airborne + && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), + pickupPlayerId)) + { + BAPASendRadioMessage* const message = checkPointer(new BAPASendRadioMessage( + static_cast(6), static_cast(6), 2, 1.0f, + m_patternId, -1)); + serial->addStatement(message); + } + } + } + } + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + // No checkPointer on this allocation in the image. + parallel->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId)); + if (airborne) + { + Vec3 destination = equipment->getPosition(); // +0x30 + if (!(primary->getObjectTypeFlags() & 0x20) || primary->getArmament()) + { + const Mat4& heading = equipment->getTransformation(); // +0x3C + Vec3 direction; + direction.x = heading.m[8]; + direction.y = 0.0f; + direction.z = heading.m[10]; + bapinline::normalize(direction); + const Mat4& axes = equipment->getTransformation(); + direction.x = axes.m[0] + direction.x; + direction.y = axes.m[1] + direction.y; + direction.z = axes.m[2] + direction.z; + direction.y = 0.0f; + destination.x = direction.x * 500.0f + destination.x; + destination.y = direction.y * 500.0f + destination.y; + destination.z = direction.z * 500.0f + destination.z; + } + else + { + Vec3 goal; + goal.x = goal.y = goal.z = 0.0f; + if (bot->getWaypoints()->getGoalPoint(goal)) + destination = goal; + destination.y = AerialHeightMap::m_instance->getAltitude(equipment->getPosition()) + 45.0f; + } + BAPAMoveTo3d* const move = checkPointer(new BAPAMoveTo3d(bot, destination, maxSpeed, maxSpeed, + checkPointer(new BAPConFalse()), controls, 25.0f, + m_patternId)); + parallel->addStatement(move); + } + serial->addStatement(parallel); + + BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), serial, m_patternId, bot)); + idle->setParent(this); // +0x04 (BotScript::m_owner) + bot->getBotNavigation()->clearProgress(); + return idle; +} + +// ELF 0x28F4D0 +int BBPIdle3d::getType() +{ + return 2; +} + +// ELF 0x28E0C0 +void BBPIdle3d::init(float altitude, Bot* bot, int pickupPlayerId) +{ + m_altitude[bot->getBotId()] = altitude; + m_initiated[bot->getBotId()] = true; + m_pickupPlayerId[bot->getBotId()] = pickupPlayerId; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.h new file mode 100644 index 000000000..b6cf9becb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.h @@ -0,0 +1,39 @@ +// Idle pattern of aircraft (3d navigation): circles at an altitude, optionally waiting for a pickup. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE3D_H + +#include "BBPIdle.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC2C0 (7 words), operator new 0x14, package D-behaviours. +class BBPIdle3d : public BBPIdle +{ +public: + explicit BBPIdle3d(int id); // 0x28DCF0 + virtual ~BBPIdle3d(); // 0x28E020 + + virtual BotScript* createPlan(Bot*); // 0x28E120, slot +0x08 + virtual int getType(); // 0x28F4D0, slot +0x18: 2 + + void init(float altitude, Bot*, int pickupPlayerId); // 0x28E0C0 + +protected: + /* +0x0C */ float* m_altitude; // per bot slot, constructed 100.0f + /* +0x10 */ int* m_pickupPlayerId; // per bot slot, -1 = none +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLE3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp new file mode 100644 index 000000000..0f3fab84c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp @@ -0,0 +1,158 @@ +// Idle pattern of infantry (AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. + +// static init: ELF 0x290960 (__tcf_0 0x2909C0, _GLOBAL__I 0x2909F0): 's Init object only. +#include + +#include "BBPIdleInfantery.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponIsZoomed.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x28F520 +BBPIdleInfantery::BBPIdleInfantery(int id) + : BBPIdle(id) +{ +} + +// ELF 0x28F5A0 +BBPIdleInfantery::~BBPIdleInfantery() +{ +} + +// ELF 0x28F650. Stand still with reset controls; near a strategic object, also unzoom a zoomed +// weapon (BAPATrigger on the zoom input while not zoomed) and, for 0x200000-flagged equipment, +// take soldier pose 2. The plan root is a BAPIWIdle around `while (true) parallel`. +BotScript* BBPIdleInfantery::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + return bot->getPlan(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + + bot->getSquadMember()->clearRequestAction(); // SquadMember::clearRequestAction + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_patternId, false, 99, false)); + BAPAResetControls* const resetControls = checkPointer(new BAPAResetControls(true, true, true, m_patternId)); + parallel->addStatement(resetControls); + + const Vec3& position = equipment->getPosition(); + AIStrategicObject* const closest = + AIStrategicObjectManager::getInstance()->getClosestObject(position, bot->getSide(), false); + if (closest) + { + float radius = closest->m_size[bot->getSide()]; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + vec2ToVec3XZ(closest->getPosition(bot->getSide()), centre); + centre.y = position.y; + Vec3 delta; + delta.x = centre.x - position.x; + delta.y = centre.y - position.y; + delta.z = centre.z - position.z; + const float distanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + radius = radius + 2.0f; + if (radius * radius > distanceSqr) + { + IPIArmament* const armament = equipment->getArmament(); + if (armament && armament->getActiveWeapon() != -1) + { + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon && weapon->getWeaponZoom() != 0x40) + { + // Right-to-left argument evaluation in the image: the controls mask and both + // conditions are built before the input is read again. + const int patternId = m_patternId; + const unsigned long long controls = static_cast(1 << weapon->getWeaponZoom()); + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + BAPATrigger* const unzoom = checkPointer(new BAPATrigger( + static_cast(weapon->getWeaponZoom()), start, stop, controls, patternId, + 0.0, false)); + BAPConNot* const notZoomed = checkPointer(new BAPConNot(checkPointer(new BAPConWeaponIsZoomed()))); + BAPFlowCIf* const ifNotZoomed = + checkPointer(new BAPFlowCIf(notZoomed, unzoom, 0, m_patternId, true, false)); + parallel->addStatement(ifNotZoomed); + } + } + if (equipment->getObjectTypeFlags() & 0x200000) + { + BAPASoldierPose* const pose = checkPointer( + new BAPASoldierPose(static_cast(2), checkPointer(new BAPConTrue()), m_patternId, true)); + parallel->addStatement(pose); + } + } + } + + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), parallel, m_patternId)); + BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), loop, m_patternId, bot)); + idle->setParent(this); // +0x04 (BotScript::m_owner) + return idle; +} + +// ELF 0x290A10 +int BBPIdleInfantery::getType() +{ + return 3; +} + +// ELF 0x28F620 +void BBPIdleInfantery::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.h new file mode 100644 index 000000000..414081635 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.h @@ -0,0 +1,35 @@ +// Idle pattern of infantry: what a soldier does while nothing more urgent is chosen. +// Recovered from libaidll.so (Linux 1.5.3153); every body carries its ELF address. Package D. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLEINFANTERY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLEINFANTERY_H + +#include "BBPIdle.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC340 (7 words), operator new 0xC, package D-behaviours. No members of its own. +class BBPIdleInfantery : public BBPIdle +{ +public: + explicit BBPIdleInfantery(int id); // 0x28F520 + virtual ~BBPIdleInfantery(); // 0x28F5A0 + + virtual BotScript* createPlan(Bot*); // 0x28F650, slot +0x08 + virtual int getType(); // 0x290A10, slot +0x18: 3 + + void init(Bot*); // 0x28F620 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPIDLEINFANTERY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp new file mode 100644 index 000000000..1446cfa3e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp @@ -0,0 +1,498 @@ +// Medic/engineer/support assist pattern: heal, repair or resupply a unit. Recovered from +// libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// +// static init: ELF 0x296E20 (__tcf_0 0x296E80, _GLOBAL__I 0x296EB0): the guard object only. + +#include "BBPMedicAssist.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASendRadioMessage.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectHealth.h" +#include "../AIBotActionPlan/BAPConObjectInFront.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPConTotalAmmo.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPConWeaponIsActive.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPVariable.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../Main/IBotManager.h" +#include "WeaponChoice.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x290A20 (C2) / 0x290DE0 (C1): BBPPattern(), +0x08 = argument, then +0x0C/+0x10/+0x14 = +// new[getMaxNBots] (IAISettings slot 0, checkPointer'd) and every slot -1; the loop re-reads +// getMaxNBots on each iteration. +BBPMedicAssist::BBPMedicAssist(int value) + : BBPPattern() +{ + m_id = value; + IAISettings* settings = static_cast(CommonSingletonServer::m_iaiSettings); + m_target = checkPointer(new unsigned int[settings->getMaxNBots()]); + m_weaponIndex = checkPointer(new int[settings->getMaxNBots()]); + m_targetPlayerId = checkPointer(new int[settings->getMaxNBots()]); + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); ++i) + { + m_target[i] = 0xFFFFFFFFu; + m_weaponIndex[i] = -1; + m_targetPlayerId[i] = -1; + } +} + +// ELF 0x2911A0 (D2) / 0x291220 (D1) / 0x2912A0 (D0): delete[] +0x0C, +0x10, +0x14 when set, +// then the base. +BBPMedicAssist::~BBPMedicAssist() +{ + if (m_target) + delete[] m_target; + if (m_weaponIndex) + delete[] m_weaponIndex; + if (m_targetPlayerId) + delete[] m_targetPlayerId; +} + +namespace { + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// One weapon key as the image builds it inline: a trigger of the key that starts at once +// (BAPConTrue) and never stops by condition (BAPConFalse), with the key's control bit +// (1 << key, sign-extended from int) and no repeat time. +BAPATrigger* newKeyTrigger(const WeaponInfo* weapon, int (WeaponInfo::*key)() const, int patternId, bool flag) +{ + return checkPointer(new BAPATrigger(static_cast((weapon->*key)()), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 1 << (weapon->*key)(), patternId, 0.0, flag)); +} + +// The image's inlined plan-variable construction: `checkPointer(new BAPVariable(context, value))` +// followed by the list insert at the context's begin. +template +BAPVariable* newVariable(BAPContext* context, const T& value) +{ + BAPVariable* const variable = checkPointer(new BAPVariable(context, value)); + context->addVariable(variable); + return variable; +} + +// The radio message type a kit confirms for a treatment request: medic 3, engineer 4, support 10; +// 0 for any other kit (no confirmation). +int requestMessageType(int kit) +{ + if (kit == 5) + return 3; + if (kit == 4) + return 4; + if (kit == 3) + return 10; + return 0; +} + +// The inlined Vec3 subtraction followed by the x87 length (fsqrt, sqrtf on NaN). +float distance(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +} // namespace + +// ELF 0x291550 (listing; Ghidra drops the BAPATrigger/BAPASoldierPose bool arguments, merges the +// 64-bit control masks and loses the unused weapon-2 trigger). The medic (kit 5), engineer (kit 4) +// and support (kit 3) treatment plan: heal, repair or resupply the unit m_target[bot]. +// +// The current plan is kept when it is this pattern's BAPIWFire on the same target; the request is +// then confirmed on the radio (enqueue 6/6/3) when the requester accepts. Otherwise the request +// action and the plan target are cleared, the plan dropped and a new one built: +// self (equipment == target): serial { parallel { reset controls, pose (stand/lie/crouch), +// trigger(activate key, true) } } +// other: serial { [radio 6/6/2 when the requester confirms], reset controls, +// while (target exists && health <= 0.99 / 0.75 (ammo <= 0.95 / 0.75 for support; the higher +// value when a human occupies the target)) parallel { reset controls, override sensing, +// move (to the own unit's entry position when the target cannot be reached by pathfinding, +// else to the target), look at target, pose, if (within half the replenish radius plus both +// radii) treat, merge soldier inputs } } +// treat: parallel { trigger(activate key), while (true) { override sensing, look at target, +// if (in front) hold fire while the weapon is active } (vehicles only) }, preceded by 0.5 s +// of closing in with pathfinding when the target is a reachable vehicle. +// Shipped quirks kept: the primary object of a non-primary target is not null-checked; the +// override-sensing action of the treat block, an int plan variable and a trigger of the slot 2 +// weapon's activate key are built and never used (leaked) when not added; the plan context is +// cleared after the plan is dropped; the radio statement is placed before the reset. +BotScript* BBPMedicAssist::createPlan(Bot* bot) +{ + // .bss 0x4CE4D0: no writer in the image, so the look offset is always 0. + static float yOffset; + + if (!m_initiated[bot->getBotId()]) + { + // 0x296DA0 + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + const int kit = bot->getPlayer()->getSpawnKit(); + CommunicationAgent* const communication = bot->getCommunicationAgent(); + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_id + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_target[bot->getBotId()]) + { + // 0x296C68 + const int requester = m_targetPlayerId[bot->getBotId()]; + if (requester >= 0) + { + const int type = requestMessageType(kit); + if (type != 0 && communication->confirmReceivedMessage(static_cast(type), requester)) + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(6), + static_cast(6), 3, 1.0f, -1); + } + return bot->getPlan(); + } + + bot->getBotId(); // 0x2915EC, result unused + bot->getSquadMember()->clearRequestAction(); + bot->getSensingAgent()->clearPlanTargetInformation(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + dropPlan(bot); + bot->getScriptContext()->clear(); + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + if (!equipment || !equipment->getUnit()) + return 0; + IPIMobile* const mobile = equipment->getMobile(); + if (!mobile || !target) + return 0; + IPIArmament* const armament = equipment->getArmament(); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + IPIPhysical* const physical = equipment->getPhysical(); + IPIPhysical* const targetPhysical = target->getPhysical(); + + // 0x291753: the support kit picks among type-2 weapons, the others among type-1 weapons. + int weaponIndex; + if (bot->getPlayer()->getSpawnKit() == 3) + { + const int strengthType = targetPhysical->getStrengthType(); + const float range = distance(equipment->getPosition(), target->getPosition()); + weaponIndex = choseWeapon(armament->getWeapons(), m_weaponIndex[bot->getBotId()], range, strengthType, false, + false, false, true); + } + else + { + const int strengthType = targetPhysical->getStrengthType(); + const float range = distance(equipment->getPosition(), target->getPosition()); + weaponIndex = choseWeapon(armament->getWeapons(), m_weaponIndex[bot->getBotId()], range, strengthType, false, + true, false, false); + } + if (weaponIndex == -1) + { + equipment->getAIObject()->update(); // 0x296A89 + return 0; + } + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weaponIndex)); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + // 0x291942 / 0x291956: IPIPhysical slot +0x34, getSmallestRadius, on both (not getRadius +0x2C). + float radii = physical->getSmallestRadius(); + radii = radii + targetPhysical->getSmallestRadius(); + + bool targetVacant; + if (equipment == target) + { + // 0x295FDF: treating itself. + BAPCombinerParallel* const self = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + self->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + self->addStatement(checkPointer(new BAPASoldierPose(SPStanding, SPLying, 3, SPCrouching, 0.0f, + checkPointer(new BAPConTrue()), + checkPointer(new BAPConFalse()), m_id, true))); + self->addStatement(newKeyTrigger(weapon, &WeaponInfo::getWeaponActivate, m_id, true)); + serial->addStatement(self); + targetVacant = false; + } + else + { + const bool targetIsSoldier = targetPhysical->getStrengthType() == 0; // -0x1C9 + const float reach = weapon->getReplenishRadius() * 0.5f + radii; // -0x1D0 + IPIUnit* const targetUnit = target->getUnit(); + // -0x1D1: approach the own unit's entry position instead of the target. + bool toEntry = true; + if (targetUnit) + { + bool noPathfinding = false; + if (targetUnit->useNoPathfindingToGetToObject() || !target->getMobile()) + noPathfinding = true; + toEntry = noPathfinding; + } + if (toEntry && !target->isPrimary()) + toEntry = !informationManager->getInformation(target->getPrimaryObject(bot->getSide()))->getMobile(); // 0x295F7F + + // 0x291A13 + BAPContext* const context = bot->getScriptContext(); + BAPVariable* const weaponVariable = newVariable(context, weapon); + newVariable(bot->getScriptContext(), 0); // 0x291AE6, never read + + BAPConAnd* const treating = checkPointer(new BAPConAnd()); + treating->addCondition(checkPointer(new BAPConObjectExists(m_target[bot->getBotId()]))); + BAPCondition* needed; + if (kit == 3) + { + // 0x295956 + if (humanPlayerInTarget(target, bot->getSide())) + needed = checkPointer(new BAPConTotalAmmo(m_target[bot->getBotId()], 0.95f)); + else + needed = checkPointer(new BAPConTotalAmmo(m_target[bot->getBotId()], 0.75f)); + } + else if (humanPlayerInTarget(target, bot->getSide())) + { + needed = checkPointer(new BAPConObjectHealth(m_target[bot->getBotId()], 0.99f)); + } + else + { + needed = checkPointer(new BAPConObjectHealth(m_target[bot->getBotId()], 0.75f)); // 0x295820 + } + treating->addCondition(needed); + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + parallel->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + if (toEntry) + { + // 0x2952B1 + const Vec3 entry = equipment->getUnit()->getEntryPositionOfNonMobile(); + parallel->addStatement(checkPointer(new BAPAMoveToFinding(bot, entry, mobile->getMaxSpeed(), mobile->getMaxSpeed(), + 0, controlInfo->getDriveControls(), m_id, 0.5f, + 0.0f))); + } + else + { + parallel->addStatement(checkPointer(new BAPAMoveToObjectFinding( + bot, m_target[bot->getBotId()], radii, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, + controlInfo->getDriveControls(), m_id, 0, 0.0f, -1))); + } + parallel->addStatement(checkPointer(new BAPALookAtObject(bot, m_target[bot->getBotId()], 0.0f, + checkPointer(new BAPConFalse()), + equipment->getControlInfo()->getLookControls(), m_id, 0, + yOffset))); + BAPASoldierPose* pose; + if ((target->getObjectTypeFlags() & 0x200000u) && (kit == 5 || kit == 3)) + pose = checkPointer(new BAPASoldierPose(SPStanding, checkPointer(new BAPConTrue()), m_id, + m_target[bot->getBotId()], true)); // 0x294D90 + else + pose = checkPointer(new BAPASoldierPose(SPStanding, checkPointer(new BAPConTrue()), m_id, true)); + parallel->addStatement(pose); + + BAPConAnd* const inReach = checkPointer(new BAPConAnd()); + inReach->addCondition(checkPointer(new BAPConObjectDistance(m_target[bot->getBotId()], reach, false, false, false))); + BAPCombinerParallel* const treat = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + treat->addStatement(newKeyTrigger(weapon, &WeaponInfo::getWeaponActivate, m_id, false)); + BAPAOverrideSensingAgent* const overrideSensing = checkPointer(new BAPAOverrideSensingAgent()); + BAPCombinerParallel* const aim = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + if (!targetIsSoldier) + { + // 0x293B22 + aim->addStatement(overrideSensing); + aim->addStatement(checkPointer(new BAPALookAtObject(bot, m_target[bot->getBotId()], 0.0f, + checkPointer(new BAPConFalse()), + equipment->getControlInfo()->getLookControls(), m_id, 0, + yOffset))); + BAPATriggerContinously* const fire = checkPointer(new BAPATriggerContinously( + static_cast(weapon->getWeaponFire()), + checkPointer(new BAPConWeaponIsActive(weaponVariable)), checkPointer(new BAPConFalse()), + checkPointer(new BAPConFalse()), 1 << weapon->getWeaponFire(), m_id, 0.0)); + aim->addStatement(checkPointer(new BAPFlowCIf( + checkPointer(new BAPConObjectInFront(m_target[bot->getBotId()], 0.0f, 0.1f)), fire, 0, m_id, true, false))); + } + treat->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), aim, true, m_id))); + + WeaponInfo* const other = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(2)); // 0x2923C1 + if (other) + newKeyTrigger(other, &WeaponInfo::getWeaponActivate, m_id, false); // built, never added + + // 0x292513: confirm the requester's radio request. + const int requester = m_targetPlayerId[bot->getBotId()]; + if (requester >= 0 && requestMessageType(kit) != 0) + { + bool confirmed; + if (kit == 4) + { + // 0x293670 + confirmed = communication->confirmReceivedMessage(static_cast(4), requester); + Bot* const requesterBot = IBotManager::instance->getBotFromPlayerId(requester); + if (requesterBot) + static_cast(requesterBot)->setIsEngineerTarget(true); + } + else + { + confirmed = communication->confirmReceivedMessage(static_cast(requestMessageType(kit)), + requester); + } + if (confirmed) + serial->addStatement(checkPointer(new BAPASendRadioMessage(static_cast(6), + static_cast(6), 2, 1.0f, + m_id, -1))); + } + + // 0x292558 + BAPFlowCIf* approach; + if (targetIsSoldier || toEntry) + { + approach = checkPointer(new BAPFlowCIf(inReach, treat, 0, m_id, true, false)); + } + else + { + // 0x292D47: a vehicle reachable by pathfinding: half a second of closing in first. + BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_id, 1)); + BAPAMoveToObjectFinding* const close = checkPointer(new BAPAMoveToObjectFinding( + bot, m_target[bot->getBotId()], 0.0f, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, + controlInfo->getDriveControls(), m_id, 0, 0.0f, -1)); + BAPConTime* const time = checkPointer(new BAPConTime(0.5, false, false, false)); + sequence->addStatement(checkPointer(new BAPFlowCWhile(checkPointer(new BAPConNot(time)), close, false, m_id))); + sequence->addStatement(treat); + approach = checkPointer(new BAPFlowCIf(inReach, sequence, 0, m_id, true, false)); + } + parallel->addStatement(approach); + parallel->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_id))); + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(treating, parallel, false, m_id)); + serial->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + serial->addStatement(loop); + targetVacant = false; + if (targetUnit) + targetVacant = !targetUnit->isOccupied(); + } + + // 0x292732: the squad request this bot now answers. + if (bot->getPlayer()->getSpawnKit() == 5) + { + const unsigned int handle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(1, handle); + } + else if (bot->getPlayer()->getSpawnKit() == 4) + { + bot->setRepairTarget(m_target[bot->getBotId()]); + const unsigned int handle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(2, handle); + } + else if (bot->getPlayer()->getSpawnKit() == 3) + { + const unsigned int handle = target->getHandle(); + bot->getSquadMember()->setCurrentRequestAction(4, handle); + } + + // 0x29278F + BAPIWFire* const root = checkPointer( + new BAPIWFire(bot, m_target[bot->getBotId()], targetVacant, false, weaponIndex, -1, serial, m_id)); + root->setParent(this); // +0x04 (BotScript::m_owner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x291320: m_initiated (+0x04) [botId] = true, then the three per-bot slots, each indexed by +// a fresh Bot::getBotId (+0xE8). +void BBPMedicAssist::init(unsigned int target, int weaponIndex, int targetPlayerId, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_target[bot->getBotId()] = target; + m_weaponIndex[bot->getBotId()] = weaponIndex; + m_targetPlayerId[bot->getBotId()] = targetPlayerId; +} + +// ELF 0x291390: instruction for instruction BBMedicAssist::isHumanInTarget (0x216980) - the +// primary object of `info` for `side`, then its secondary objects; true at the first unit occupied +// by a known non-AI player (IAIPlayerFactory +0x20 getPlayerFromId, IAIPlayer +0x88 getIsAIPlayer). +bool BBPMedicAssist::humanPlayerInTarget(Information* info, int side) +{ + bool human = false; + if (info) + { + Information* primary = informationManager->getInformation(info->getPrimaryObject(side)); + if (primary) + { + IPIUnit* unit = primary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + return true; + } + int iterator; + for (Information* secondary = + informationManager->getInformation(primary->getFirstSecondaryObject(iterator, side)); + secondary; + secondary = informationManager->getInformation(primary->getSecondaryObject(iterator, side))) + { + unit = secondary->getUnit(); + if (unit && unit->isOccupied()) + { + IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(unit->getOccupyingPlayerId(side)); + if (player && !player->getIsAIPlayer()) + { + human = true; + break; + } + } + } + } + } + return human; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.h new file mode 100644 index 000000000..7b956dc9c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.h @@ -0,0 +1,45 @@ +// Medic/support assist pattern: BBMedicAssist hands it the chosen target, the weapon index to use +// and the target's player per bot (init); createPlan builds the plan from them. Recovered from +// libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see docs/macos-ai-behaviour-plan.md. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPMEDICASSIST_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPMEDICASSIST_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; +class Information; + +// ELF: vtable 0x4BC3C0 (6 words), operator new 0x18, package F-infantry. +class BBPMedicAssist : public BBPPattern +{ +public: + explicit BBPMedicAssist(int); // 0x290DE0 + virtual ~BBPMedicAssist(); // 0x291220 + + virtual BotScript* createPlan(Bot*); // 0x291550, slot +0x08; from the base declaration + + // ELF void: no result register is set (0x291320..0x291389). + void init(unsigned int, int, int, Bot*); // 0x291320 + // ELF bool (movzbl of a 0/1 local); the same body as BBMedicAssist::isHumanInTarget. + bool humanPlayerInTarget(Information*, int); // 0x291390 + +private: + /* +0x08 */ int m_id; // pattern id: createPlan tags every statement with it + // Per bot (new[IAISettings::getMaxNBots], each -1), written by init. + /* +0x0C */ unsigned int* m_target; // information handle of the unit to treat + /* +0x10 */ int* m_weaponIndex; // index into the bot's IPIArmament::getWeapons + /* +0x14 */ int* m_targetPlayerId; // occupying player of the target, -1 if none +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPMEDICASSIST_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp new file mode 100644 index 000000000..e346a5642 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp @@ -0,0 +1,53 @@ +// BBPPattern: recovered by package A-core from libaidll.so (TU BBPPattern.cpp, 0x296ED0..0x297380; the +// three weak members at 0x2298A0). Every body carries its ELF address. + +// static init: ELF 0x2972F0 (__tcf_0 0x297350, _GLOBAL__I 0x297380): 's Init object only. +#include + +#include "BBPPattern.h" + +#include "../AIBot/BotMain.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x296FD0 (C2; C1 0x297160). The flag array has one entry per possible bot. +BBPPattern::BBPPattern() +{ + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_initiated = checkPointer(new bool[count]); + for (int i = 0; i < count; ++i) + m_initiated[i] = false; +} + +// ELF 0x296ED0 (D2; D1 0x296F20, D0 0x296F70). +BBPPattern::~BBPPattern() +{ + delete[] m_initiated; +} + +// ELF 0x2298D0 (weak). +bool BBPPattern::isInitiated(Bot* bot) +{ + return m_initiated[bot->getBotId()]; +} + +// ELF 0x2298A0 (weak). +void BBPPattern::unInit(Bot* bot) +{ + m_initiated[bot->getBotId()] = false; +} + +// ELF 0x229900 (weak). +void BBPPattern::forceInitiated(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.h new file mode 100644 index 000000000..f0558e106 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.h @@ -0,0 +1,41 @@ +// Behaviour-pattern base: the per-bot "initiated" flags every pattern keeps. Recovered by package +// A-core (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order is checked by +// tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPPATTERN_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPPATTERN_H + +#include "PlanGenerator.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// Behaviour-pattern base. Vtable 0x4BC400. +// ELF: vtable 0x4BC400 (6 words), package A-core. +class BBPPattern : public PlanGenerator +{ +public: + BBPPattern(); // 0x297160 + virtual ~BBPPattern(); // 0x296F20 + + // The three are weak in the image (inline in the header, emitted beside BBPAvoidCollision2d); + // defined out of line in BBPPattern.cpp so this header needs no Bot definition. [CHOSEN] + virtual bool isInitiated(Bot*); // 0x2298D0, slot +0x0C; from the base declaration + virtual void unInit(Bot*); // 0x2298A0, slot +0x10; from the base declaration + virtual void forceInitiated(Bot*); // 0x229900, slot +0x14; from the base declaration + +protected: + // BBPPattern() 0x296FD0: checkPointer(new bool[IAISettings::getMaxNBots()]), all false; indexed by + // Bot::getBotId(). Freed by the destructor 0x296ED0. + /* +0x04 */ bool* m_initiated; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPPATTERN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp new file mode 100644 index 000000000..88c64059a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp @@ -0,0 +1,143 @@ +// Random pattern (BBRandom: the grenade-warning reaction). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32). + +// static init: ELF 0x2989B0 (__tcf_0 0x298A10, _GLOBAL__I 0x298A40): 's Init object only. +#include + +#include "BBPRandom.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Core/Random.h" +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// [CHOSEN, not recovered] Local packaging of Random's inlined arithmetic at ELF 0x2979A4..0x297B64. +std::uint32_t randomStage(std::uint32_t seed, int factor) +{ + const std::int32_t low = static_cast((seed & 0xffffu) * factor); + const std::int32_t high = (static_cast(seed) >> 16) * factor + (low >> 16); + const std::uint32_t combined = (static_cast(low) & 0xffffu) + + ((static_cast(high) & 0x7fffu) << 16) + + static_cast(high >> 15); + const std::uint32_t reduced = combined - 0x7fffffffu; + return static_cast(reduced) < 0 ? combined : reduced; +} + +float randomDraw() +{ + Rand.m_seed = randomStage(randomStage(Rand.m_seed, 24112), 26143); + const std::int32_t raw = (static_cast(Rand.m_seed) >> 7) | 1; + return static_cast(raw + 1) * 5.9604644775390625e-8f; +} +} + +// ELF 0x297400 (C2) / 0x297580 (C1): BBPPattern(), +0x08 = id, +0x0C = checkPointer(new[getMaxNBots]). +BBPRandom::BBPRandom(int id) + : BBPPattern() +{ + m_id = id; + m_perBot = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x297700 (D2) / 0x297750 (D1) / 0x2977A0 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPRandom::~BBPRandom() +{ + if (m_perBot) + delete[] m_perBot; +} + +// ELF 0x297840 +BotScript* BBPRandom::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + bot->getSquadMember()->clearRequestAction(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!bot->hasPlan()) + { + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + } + else if (static_cast(bot->getPlan())->getPatternId() == m_id) + return bot->getPlan(); + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getSquadMember()->clearRequestAction(); + // shipped defect: an active plan with a different pattern id is not deleted here. + bot->getScriptContext()->clear(); + BAPCombinerParallel* parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const float first = randomDraw(); + const float second = randomDraw(); + const float third = randomDraw(); + m_initTime = now; + const SoldierPose pose = first > second ? SPCrouching : SPLying; + parallel->addStatement(checkPointer(new BAPASoldierPose(pose, checkPointer(new BAPConTrue()), m_id, false))); + Information* weaponOwner = informationManager->getInformation(bot->getCurrentEquipment()); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(weaponOwner->getArmament()->getWeapon(1)); + if (weapon && third > 0.7f) + { + const unsigned int mask = 1u << (static_cast(weapon->getWeaponFire()) & 31u); + const unsigned long long controls = static_cast(static_cast(static_cast(mask))); + BAPConFalse* stop = checkPointer(new BAPConFalse()); + BAPConTrue* start = checkPointer(new BAPConTrue()); + const io::PlayerInputMap input = static_cast(weapon->getWeaponFire()); + parallel->addStatement(checkPointer(new BAPATrigger(input, start, stop, controls, m_id, 0.0, true))); + } + BAPFlowCWhile* loop = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), parallel, true, m_id)); + BAPIWIdle* wrapper = checkPointer(new BAPIWIdle(self->getPosition(), loop, m_id, bot)); + wrapper->m_owner = this; + return wrapper; +} + +// ELF 0x2977F0: m_initiated[bot->getBotId()] = true; +0x14 = IBFTimer slot +0x08 (getGameTime). +void BBPRandom::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_initTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.h new file mode 100644 index 000000000..29b231608 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.h @@ -0,0 +1,38 @@ +// Random grenade-warning reaction, recovered from libaidll.so. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRANDOM_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRANDOM_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC4A0 (6 words), operator new 0x1C, package F-infantry. +class BBPRandom : public BBPPattern +{ +public: + explicit BBPRandom(int); // 0x297580 + virtual ~BBPRandom(); // 0x297750 + + virtual BotScript* createPlan(Bot*); // 0x297840, slot +0x08; from the base declaration + + void init(Bot*); // 0x2977F0; void (fstpl is the last instruction before the epilogue) + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name + /* +0x0C */ unsigned int* m_perBot; // new[getMaxNBots], checkPointer'd [UNRESOLVED] use + /* +0x10 */ unsigned char m_unwritten10[4]; // not written by the constructor or init + /* +0x14 */ double m_initTime; // init: IBFTimer::getGameTime [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRANDOM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp new file mode 100644 index 000000000..88a41b541 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp @@ -0,0 +1,215 @@ +// Revive pattern: init keeps the man-down soldier and the revive weapon per bot; createPlan builds +// the revive script. Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body +// carries its ELF address. +// +// static init: ELF 0x29B200 (__tcf_0 0x29B260, _GLOBAL__I 0x29B290): the guard object only. + +#include "BBPRevive.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPAMoveToObjectFinding.h" +#include "../AIBotActionPlan/BAPAOverrideSensingAgent.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPARevive.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConObjectDistance.h" +#include "../AIBotActionPlan/BAPConObjectExists.h" +#include "../AIBotActionPlan/BAPConObjectManDown.h" +#include "../AIBotActionPlan/BAPConObjectMoved.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "WeaponChoice.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x298A60 (C2) / 0x298CF0 (C1): BBPPattern(), +0x08 = the argument, +0x0C and +0x10 = +// checkPointer(new[getMaxNBots]) of 4 bytes each (not initialised). +BBPRevive::BBPRevive(int id) + : BBPPattern() +{ + m_id = id; + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); + m_weapon = checkPointer(new int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x298F80 (D2) / 0x298FE0 (D1) / 0x299040 (D0): delete[] +0x0C, +0x10 when set, then ~BBPPattern. +BBPRevive::~BBPRevive() +{ + if (m_target) + delete[] m_target; + if (m_weapon) + delete[] m_weapon; +} + +namespace { + +void dropPlan(Bot* bot) +{ + delete bot->getPlan(); + bot->setPlan(0); +} + +// The inlined Vec3 subtraction followed by the x87 length (fsqrt, sqrtf on NaN). +float distance(const Vec3& a, const Vec3& b) +{ + const float dx = b.x - a.x; + const float dy = b.y - a.y; + const float dz = b.z - a.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +} // namespace + +// ELF 0x299110 (listing; Ghidra cross-check). Revives the man-down soldier m_target[bot] with the +// shock paddles: +// serial { reset controls (true, false, true) when the weapon's activate key is 64, else +// trigger(activate key), +// while (target exists && man down) parallel { reset controls, override sensing, +// look at target, if (within 1.6 m) revive else move to the target with pathfinding +// (re-planned when within 10 m and the target moved 0.2 m), merge soldier inputs } } +// under BAPIWFire(bot, target, true, false, weapon, -1, ..). The current plan is kept when it is +// this pattern's BAPIWFire on the same target. The medic kit answers the squad request (action 1 +// with the target handle). Returns 0 without equipment, unit, mobile, target or a type-3 weapon +// (then the equipment's object is updated). +BotScript* BBPRevive::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + // 0x29B182 + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + dropPlan(bot); + return 0; + } + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_id + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_target[bot->getBotId()]) + return bot->getPlan(); // 0x29B11C + + bot->getSquadMember()->clearRequestAction(); + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + if (bot->getPlan()) + dropPlan(bot); + bot->getScriptContext()->clear(); + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const target = informationManager->getInformation(m_target[bot->getBotId()]); + if (!equipment || !equipment->getUnit()) + return 0; + IPIMobile* const mobile = equipment->getMobile(); + if (!mobile || !target) + return 0; + IPIArmament* const armament = equipment->getArmament(); + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + + const int strengthType = target->getPhysical()->getStrengthType(); + const float range = distance(equipment->getPosition(), target->getPosition()); + const int weaponIndex = choseWeapon(armament->getWeapons(), m_weapon[bot->getBotId()], range, strengthType, false, + false, true, false); + if (weaponIndex == -1) + { + equipment->getAIObject()->update(); // 0x29B08D + return 0; + } + bot->setReviveTarget(m_target[bot->getBotId()]); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(weaponIndex)); + + BAPCombinerSerial* const serial = checkPointer(new BAPCombinerSerial(m_id, -1)); + BAPStatement* select; + if (weapon->getWeaponActivate() == 64) + select = checkPointer(new BAPAResetControls(true, false, true, m_id)); // 0x29AE90 + else + select = checkPointer(new BAPATrigger(static_cast(weapon->getWeaponActivate()), + checkPointer(new BAPConTrue()), checkPointer(new BAPConFalse()), + 1 << weapon->getWeaponActivate(), m_id, 0.0, false)); + serial->addStatement(select); + + // 0x2995B9: the revive distance, stored as a float local and scaled at run time. + const float reviveDistance = 0.4f; + BAPConObjectDistance* const close = checkPointer( + new BAPConObjectDistance(m_target[bot->getBotId()], reviveDistance * 4.0f, false, true, false)); + BAPConAnd* const replan = checkPointer(new BAPConAnd()); + replan->addCondition(checkPointer(new BAPConObjectDistance(m_target[bot->getBotId()], 10.0f, true, true, false))); + replan->addCondition(checkPointer(new BAPConObjectMoved(m_target[bot->getBotId()], reviveDistance * 0.5f))); + BAPAMoveToObjectFinding* const move = checkPointer(new BAPAMoveToObjectFinding( + bot, m_target[bot->getBotId()], 0.0f, mobile->getMaxSpeed(), mobile->getMaxSpeed(), 0, + controlInfo->getDriveControls(), m_id, replan, 0.0f, -1)); + BAPFlowCIf* const revive = checkPointer(new BAPFlowCIf(close, checkPointer(new BAPARevive(m_id)), move, m_id, true, false)); + + BAPConAnd* const down = checkPointer(new BAPConAnd()); + BAPConObjectExists* const exists = checkPointer(new BAPConObjectExists(m_target[bot->getBotId()])); + BAPConObjectManDown* const manDown = checkPointer(new BAPConObjectManDown(m_target[bot->getBotId()])); + down->addCondition(exists); + down->addCondition(manDown); + + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + parallel->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_id))); + parallel->addStatement(checkPointer(new BAPAOverrideSensingAgent())); + parallel->addStatement(checkPointer(new BAPALookAtObject(bot, m_target[bot->getBotId()], 0.0f, + checkPointer(new BAPConFalse()), + equipment->getControlInfo()->getLookControls(), m_id, 0, + 0.0f))); + parallel->addStatement(revive); + parallel->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_id))); + serial->addStatement(checkPointer(new BAPFlowCWhile(down, parallel, false, m_id))); + + if (bot->getPlayer()->getSpawnKit() == 5) + { + // 0x299E4D + const unsigned int handle = m_target[bot->getBotId()]; + bot->getSquadMember()->setCurrentRequestAction(1, handle); + } + + BAPIWFire* const root = checkPointer( + new BAPIWFire(bot, m_target[bot->getBotId()], true, false, weaponIndex, -1, serial, m_id)); + root->setParent(this); // +0x04 (BotScript::m_owner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x2990B0: m_initiated[id] = true; +0x0C[id] = target; +0x10[id] = weapon. +void BBPRevive::init(unsigned int target, int weapon, Bot* bot) +{ + m_initiated[bot->getBotId()] = true; + m_target[bot->getBotId()] = target; + m_weapon[bot->getBotId()] = weapon; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.h new file mode 100644 index 000000000..5e7229208 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPREVIVE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPREVIVE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC520 (6 words), operator new 0x14, package F-infantry. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPRevive : public BBPPattern +{ +public: + explicit BBPRevive(int); // 0x298CF0 + virtual ~BBPRevive(); // 0x298FE0 + + virtual BotScript* createPlan(Bot*); // 0x299110, slot +0x08; from the base declaration + + void init(unsigned int, int, Bot*); // 0x2990B0; void (no result register is set) + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name + /* +0x0C */ unsigned int* m_target; // per bot: init's handle (BBRevive's chosen man-down soldier) + /* +0x10 */ int* m_weapon; // per bot: init's weapon index (BBRevive's m_bestWeapon entry) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPREVIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp new file mode 100644 index 000000000..036d26d9c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp @@ -0,0 +1,39 @@ +// Shared roaming pattern state, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x29B4A0 (__tcf_0 0x29B500, _GLOBAL__I 0x29B530): 's Init object only. +#include + +#include "BBPRoam.h" + +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29B3A0 (C2), 0x29B420 (C1). +BBPRoam::BBPRoam() +{ + m_positions = new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()](); +} + +// ELF 0x29B2B0 (D2), 0x29B300 (D1), 0x29B350 (D0). +BBPRoam::~BBPRoam() +{ + if (m_positions) + delete[] m_positions; +} + +// ELF 0x29B550 +int BBPRoam::getRoamType() +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h new file mode 100644 index 000000000..f057bd5f8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.h @@ -0,0 +1,34 @@ +// Shared roaming pattern state, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM_H + +#include "BBPPattern.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace ai { + + +// ELF: vtable 0x4BC560 (7 words), package H-deferred. +class BBPRoam : public BBPPattern +{ +public: + BBPRoam(); // 0x29B420 + virtual ~BBPRoam(); // 0x29B300 + + virtual int getRoamType(); // 0x29B550, slot +0x18; [INFERRED] ELF int + +protected: + // [INFERRED] member names from the constructors and concrete init methods. + /* +0x08 */ int m_patternId; // set by concrete pattern constructors + /* +0x0C */ Vec3* m_positions; // per-bot positions, initially zero +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp new file mode 100644 index 000000000..f2d226380 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp @@ -0,0 +1,80 @@ +// Ground roaming pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x29B9A0 (__tcf_0 0x29BA00, _GLOBAL__I 0x29BA30): 's Init object only. +#include + +#include "BBPRoam2d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29B560 (C2), 0x29B5A0 (C1). +BBPRoam2d::BBPRoam2d(int patternId) +{ + m_patternId = patternId; +} + +// ELF 0x29B5E0 (D2), 0x29B620 (D1), 0x29B660 (D0). +BBPRoam2d::~BBPRoam2d() +{ +} + +// ELF 0x29B700 +BotScript* BBPRoam2d::createPlan(Bot* bot) +{ + const bool initiated = m_initiated[bot->getBotId()]; + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (!initiated) + return 0; + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + bot->getSquadMember()->clearRequestAction(); + IPIMobile* const mobile = self->getMobile(); + const unsigned long long controls = self->getControlInfo()->getDriveControls(); + const float radius = self->getPhysical()->getRadius() * 4.0f; + const float speed = mobile->getMaxSpeed(); + BAPConPosition* const arrived = new BAPConPosition(m_positions[bot->getBotId()], radius); + BAPAMoveToFinding* const plan = new BAPAMoveToFinding(bot, m_positions[bot->getBotId()], speed, speed, + arrived, controls, m_patternId, 0.0f, 0.0f); + plan->m_owner = this; + return plan; +} + +// ELF 0x29BA50 +int BBPRoam2d::getRoamType() +{ + return 1; +} + +// ELF 0x29B6A0 +void BBPRoam2d::init(Bot* bot, const Vec3& position) +{ + m_initiated[bot->getBotId()] = true; + m_positions[bot->getBotId()] = position; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.h new file mode 100644 index 000000000..99b8f20fc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.h @@ -0,0 +1,34 @@ +// Ground roaming pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM2D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM2D_H + +#include "../../../../Math/Vec3.h" +#include "BBPRoam.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC5E0 (7 words), package H-deferred. +class BBPRoam2d : public BBPRoam +{ +public: + explicit BBPRoam2d(int); // 0x29B5A0 + virtual ~BBPRoam2d(); // 0x29B620 + + virtual BotScript* createPlan(Bot*); // 0x29B700, slot +0x08; from the base declaration + virtual int getRoamType(); // 0x29BA50, slot +0x18; from the base declaration + + void init(Bot*, const Vec3&); // 0x29B6A0; [INFERRED] ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM2D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp new file mode 100644 index 000000000..2efdae9a8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp @@ -0,0 +1,110 @@ +// Airborne roaming recovered from libaidll.so. + +// static init: ELF 0x29C090 (__tcf_0 0x29C0F0, _GLOBAL__I 0x29C120): 's Init object only. +#include + +#include "BBPRoam3d.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIBotActionPlan/BAPConObjectVisible.h" +#include "../AIBotActionPlan/BAPIWRoam.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29BAC0 (C1; C2 0x29BA60) +BBPRoam3d::BBPRoam3d(int patternId) +{ + m_patternId = patternId; + m_objects = new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]; +} + +// ELF 0x29BB70 (D1; D2 0x29BB20, D0 0x29BBC0) +BBPRoam3d::~BBPRoam3d() +{ + if (m_objects) + delete[] m_objects; +} + +// ELF 0x29BC60 +BotScript* BBPRoam3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (bot->hasPlan() + && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 5) + { + const unsigned int previousObject = static_cast(bot->getPlan())->m_object; + if (previousObject == m_objects[bot->getBotId()]) + return bot->getPlan(); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + // shipped defect: a replaced plan is not deleted or cleared here. + bot->getScriptContext()->clear(); + Information* target = informationManager->getInformation(m_objects[bot->getBotId()]); + if (!target) + return 0; + bot->getSquadMember()->clearRequestAction(); + IPIMobile* mobile = self->getMobile(); + const float ownRadius = self->getPhysical()->getRadius(); + float radius = 0.0f; + // shipped defect: the Boolean mobile flag is added to our radius only for this zero test. + if (ownRadius + static_cast(target->getMobile() != 0) != 0.0f) + radius = target->getPhysical()->getRadius(); + radius += radius; + BAPConObjectVisible* visible = new BAPConObjectVisible(m_objects[bot->getBotId()]); + const unsigned long long driveControls = self->getControlInfo()->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed() * 0.5f; + const float speed = mobile->getMaxSpeed(); + const unsigned int object = m_objects[bot->getBotId()]; + BAPAMoveTo3dObject* move = new BAPAMoveTo3dObject(object, radius, speed, arriveSpeed, 50.0f, + visible, driveControls, m_patternId); + BAPIWRoam* wrapper = new BAPIWRoam(m_objects[bot->getBotId()], move, m_patternId); + wrapper->m_owner = this; + return wrapper; +} + +// ELF 0x29C140 +int BBPRoam3d::getRoamType() +{ + return 2; +} + +// ELF 0x29BC10 +void BBPRoam3d::init(unsigned int object, Bot* bot) +{ + m_objects[bot->getBotId()] = object; + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.h new file mode 100644 index 000000000..6b4ed3146 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.h @@ -0,0 +1,36 @@ +// Airborne roaming toward a per-bot information handle. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM3D_H + +#include "BBPRoam.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC660 (7 words), package H-deferred. +class BBPRoam3d : public BBPRoam +{ +public: + explicit BBPRoam3d(int); // 0x29BAC0 + virtual ~BBPRoam3d(); // 0x29BB70 + + virtual BotScript* createPlan(Bot*); // 0x29BC60, slot +0x08; from the base declaration + virtual int getRoamType(); // 0x29C140, slot +0x18; from the base declaration + + void init(unsigned int, Bot*); // 0x29BC10; [INFERRED] ELF void + +private: + /* +0x10 */ unsigned int* m_objects; // [INFERRED] name; uninitialized per-bot handles +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPROAM3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp new file mode 100644 index 000000000..01d157335 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp @@ -0,0 +1,107 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); objdump listings with Ghidra cross-checks, ELF +// addresses on every body. Static init: ELF 0x29CAE0 (the guard object only). + +#include "BBPRunOverSoldier.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPARunOverObject.h" +#include "../AIBotActionPlan/BAPIWFire.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +// static init: ELF 0x29CAE0 (__tcf_0 0x29CB40, _GLOBAL__I 0x29CB70): 's Init object only. + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29C2D0: BBPPattern(), the vtable store (GOT -0x7CC + 8), the argument at +0x08, then +// `new unsigned int[getMaxNBots()]` (not initialised) through the inlined checkPointer into +0x0C +// (operator new 0x10). +BBPRunOverSoldier::BBPRunOverSoldier(int id) + : m_patternId(id) +{ + m_target = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x29C450 (D2) / 0x29C4A0 (D1) / 0x29C4F0 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPRunOverSoldier::~BBPRunOverSoldier() +{ + if (m_target) + delete[] m_target; +} + +namespace { + +// The image's "drop the plan" sequence (0x29C9F6): the plan's deleting destructor, then +// Bot +0x64 setPlan(0). +void dropPlan(Bot* bot) +{ + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } +} + +} // namespace + +// ELF 0x29C580 (listing; Ghidra cross-check). Without init for this bot: clear the debugger and +// the script context, drop the plan, no plan. Otherwise the current plan is kept while it is this +// pattern's fire wrapper (getId 15, info type 0) on the same target; else it is dropped and, when +// the bot's equipment has a unit and a mobile part, the plan is BAPIWFire(bot, target, true, +// false, 4, -1, BAPARunOverObject(target, drive controls, id), id) owned by this pattern, with +// every control reset. The equipment's control part is not null-tested (as shipped). +BotScript* BBPRunOverSoldier::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + dropPlan(bot); + return 0; + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getCurrentEquipment(); // 0x29C60D, result unused + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId + && static_cast(bot->getPlan())->getId() == BAPSTInfoWrapper + && static_cast(bot->getPlan())->getInfoType() == 0 + && static_cast(bot->getPlan())->getTarget() == m_target[bot->getBotId()]) + return bot->getPlan(); + dropPlan(bot); + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment || !equipment->getUnit() || !equipment->getMobile()) + return 0; + IPIControlInfo* const controlInfo = equipment->getControlInfo(); + BAPARunOverObject* const runOver = checkPointer( + new BAPARunOverObject(m_target[bot->getBotId()], controlInfo->getDriveControls(), m_patternId)); + BAPIWFire* const root = checkPointer( + new BAPIWFire(bot, m_target[bot->getBotId()], true, false, 4, -1, runOver, m_patternId)); + root->setParent(this); // +0x04 (BotScript::m_owner) + static_cast(bot)->resetAllControls(true, true, true); + return root; +} + +// ELF 0x29C540: marks the bot initiated and stores its target. +void BBPRunOverSoldier::init(Bot* bot, unsigned int target) +{ + const unsigned int id = bot->getBotId(); + m_initiated[id] = true; + m_target[id] = target; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.h new file mode 100644 index 000000000..84757b248 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.h @@ -0,0 +1,37 @@ +// Recovered from libaidll.so 1.5.3153 (ia-32); ELF addresses on every declaration. +// Vehicle pattern: run over a soldier with a car (BAPARunOverObject under a fire wrapper). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRUNOVERSOLDIER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRUNOVERSOLDIER_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC6E0 (6 words), operator new 0x10, package G-vehicles. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BBPRunOverSoldier : public BBPPattern +{ +public: + explicit BBPRunOverSoldier(int); // 0x29C2D0 + virtual ~BBPRunOverSoldier(); // 0x29C4A0 + + virtual BotScript* createPlan(Bot*); // 0x29C580, slot +0x08; from the base declaration + + void init(Bot*, unsigned int target); // 0x29C540; ELF void (no eax write) + + /* +0x08 */ int m_patternId; // the constructor argument + /* +0x0C */ unsigned int* m_target; // per bot: init's handle (init also sets m_initiated) [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPRUNOVERSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp new file mode 100644 index 000000000..e773b9ad2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp @@ -0,0 +1,82 @@ +// Suicide input pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +// static init: ELF 0x29D240 (__tcf_0 0x29D2A0, _GLOBAL__I 0x29D2D0): 's Init object only. +#include + +#include "BBPSuicide.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29CB90 (C2), 0x29CBD0 (C1). +BBPSuicide::BBPSuicide(int patternId) + : BBPPattern(), m_patternId(patternId) +{ +} + +// ELF 0x29CC10 (D2), 0x29CC50 (D1), 0x29CC90 (D0). +BBPSuicide::~BBPSuicide() +{ +} + +// ELF 0x29CD00 +BotScript* BBPSuicide::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getSquadMember()->clearRequestAction(); + bot->getCurrentEquipment(); + if (!bot->hasPlan()) { + if (bot->getPlan()) { + delete bot->getPlan(); + bot->setPlan(0); + } + } else if (static_cast(bot->getPlan())->getPatternId() == m_patternId) { + return bot->getPlan(); + } + // shipped defect: a valid plan of another pattern is not deleted here. + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getSquadMember()->clearRequestAction(); + bot->getScriptContext()->clear(); + + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + // shipped defect: the signed input-31 mask is widened with every upper bit set. + BAPATrigger* const plan = checkPointer(new BAPATrigger(static_cast(31), start, stop, + 0xFFFFFFFF80000000ULL, m_patternId, 0.0, false)); + plan->m_owner = this; + return plan; +} + +// ELF 0x29CCD0 +void BBPSuicide::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.h new file mode 100644 index 000000000..e1f58c2fa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.h @@ -0,0 +1,36 @@ +// Suicide input pattern, recovered from libaidll.so (Linux 1.5, ia-32). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPSUICIDE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPSUICIDE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC760 (6 words), operator new 0xC, package H-deferred. +class BBPSuicide : public BBPPattern +{ +public: + explicit BBPSuicide(int); // 0x29CBD0 + virtual ~BBPSuicide(); // 0x29CC50 + + virtual BotScript* createPlan(Bot*); // 0x29CD00, slot +0x08; from the base declaration + + void init(Bot*); // 0x29CCD0; [INFERRED] ELF void + +private: + // [INFERRED] member name from the constructor and generated trigger. + /* +0x08 */ int m_patternId; // constructor argument carried by the trigger +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPSUICIDE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp new file mode 100644 index 000000000..87d5605b1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp @@ -0,0 +1,252 @@ +// Cover-plan construction recovered from libaidll.so. + +// static init: ELF 0x29FC30 (__tcf_0 0x29FC90, _GLOBAL__I 0x29FCC0): 's Init object only. +#include + +#include "BBPTakeCover.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConEndOfPath.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPIWTakeCover.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29D910 (C1; C2 0x29D2F0) +BBPTakeCover::BBPTakeCover(int patternId) +{ + const unsigned int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_patternId = patternId; + m_coverObjects = checkPointer(new unsigned int[count]); + m_coverPositions = checkPointer(new Vec3[count]()); + m_threatPositions = checkPointer(new Vec3[count]()); + m_threatObjects = checkPointer(new unsigned int[count]); + m_useObjects = checkPointer(new bool[count]); +} + +// ELF 0x29DFD0 (D1; D2 0x29DF30, D0 0x29E070) +BBPTakeCover::~BBPTakeCover() +{ + if (m_coverObjects) + delete[] m_coverObjects; + if (m_coverPositions) + delete[] m_coverPositions; + if (m_threatPositions) + delete[] m_threatPositions; + // shipped defect: m_threatObjects is leaked, and m_useObjects is deleted twice. + if (m_useObjects) + delete[] m_useObjects; + if (m_useObjects) + delete[] m_useObjects; +} + +// ELF 0x29E330 +BotScript* BBPTakeCover::createPlan(Bot* bot) +{ + if (!isInitiated(bot)) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + + const unsigned int coverObject = m_coverObjects[bot->getBotId()]; + const bool useObject = m_useObjects[bot->getBotId()]; + const Vec3 coverPosition = m_coverPositions[bot->getBotId()]; + Vec3 threatPosition = {}; + if (bot->hasPlan()) + { + BAPStatement* previous = static_cast(bot->getPlan()); + if (previous->getPatternId() == m_patternId && previous->getId() == BAPSTInfoWrapper) + { + BAPIWTakeCover* wrapper = static_cast(previous); + if (wrapper->getInfoType() == 7) + { + if (useObject) + { + if (wrapper->m_useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + Information* oldTarget = informationManager->getInformation(wrapper->m_object); + if (target && oldTarget && target->getAIObject() == oldTarget->getAIObject()) + { + const Vec3& position = oldTarget->getPosition(); + const Vec3 difference = {wrapper->m_position.x - position.x, + wrapper->m_position.y - position.y, + wrapper->m_position.z - position.z}; + if (difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z < 1.0f) + return wrapper; + } + } + } + else if (!wrapper->m_useObject) + { + const Vec3& position = m_threatPositions[bot->getBotId()]; + const Vec3 difference = {wrapper->m_position.x - position.x, + wrapper->m_position.y - position.y, + wrapper->m_position.z - position.z}; + if (difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z < 9.0f) + return wrapper; + } + } + } + } + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!self) + return 0; + IPIControlInfo* controls = self->getControlInfo(); + if (!controls) + return 0; + IPIMobile* mobile = self->getMobile(); + if (!mobile) + return 0; + Information* cover = informationManager->getInformation(coverObject); + if (!cover || !cover->getPhysical()) + return 0; + if (useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (!target) + return 0; + threatPosition = target->getPosition(); + } + else + threatPosition = m_threatPositions[bot->getBotId()]; + + bot->getSquadMember()->clearRequestAction(); + const Vec2 goal = {}; + Vec3 sensePosition = {}; + Vec3 senseNormal = {}; + Vec3 hint = {}; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->pickRandomSensePosition(sensePosition, senseNormal, hint, cover->getAIObject()); + Vec3 tracePosition = {}; + unsigned int polygon; + const int equipmentType = self->getUnit()->getEquipmentType(); + const int vehicleNumber = mobile->getVehicleNumber(); + IAIPathfinding::instance->trace(vehicleNumber, sensePosition, coverPosition, tracePosition, polygon, + equipmentType, -1, 0.0f, 0, 0); + const float maximumSpeed = mobile->getMaxSpeed(); + const float radius = maximumSpeed < 4.0f ? 4.0f : maximumSpeed * 0.5f; + BAPCombinerSerial* root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPAResetControls* reset = checkPointer(new BAPAResetControls(true, false, false, m_patternId)); + BAPCombinerParallel* parallel = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + BAPConAnd* endCondition = checkPointer(new BAPConAnd()); + BAPConEndOfPath* endOfPath = checkPointer(new BAPConEndOfPath()); + BAPConPosition* atPosition = checkPointer(new BAPConPosition(goal, radius)); + endCondition->addCondition(endOfPath); + endCondition->addCondition(atPosition); + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + // shipped defect: the trace output is discarded; the separate XZ goal remains (0, 0). + const Vec3 destination = {goal.x, 0.0f, goal.y}; + BAPAMoveToFinding* move = checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + endCondition, driveControls, m_patternId, 0.0f, 0.0f)); + BAPStatement* look; + if (useObject) + { + const unsigned long long lookControls = controls->getLookControls(); + BAPConFalse* condition = checkPointer(new BAPConFalse()); + const unsigned int target = m_threatObjects[bot->getBotId()]; + look = checkPointer(new BAPALookAtObject(bot, target, 0.314f, condition, lookControls, m_patternId, 0, 0.0f)); + } + else + { + const unsigned long long lookControls = controls->getLookControls(); + BAPConFalse* condition = checkPointer(new BAPConFalse()); + const Vec3& position = self->getPosition(); + const Vec3 direction = {threatPosition.x - position.x, threatPosition.y - position.y, + threatPosition.z - position.z}; + look = checkPointer(new BAPALookInDir(direction, 0.314f, condition, lookControls, m_patternId)); + } + parallel->addStatement(move); + parallel->addStatement(look); + root->addStatement(reset); + root->addStatement(parallel); + BAPIWTakeCover* wrapper; + if (useObject) + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + wrapper = checkPointer(new BAPIWTakeCover(target, root, m_patternId)); + } + else + wrapper = checkPointer(new BAPIWTakeCover(threatPosition, root, m_patternId)); + wrapper->m_owner = this; + return wrapper; +} + +// ELF 0x29E120 +void BBPTakeCover::init(Bot* bot, const Vec3& threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatPositions[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = false; + m_initiated[bot->getBotId()] = true; +} + +// ELF 0x29E1E0 +void BBPTakeCover::init(Bot* bot, unsigned int threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatObjects[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = true; + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (target) + { + Vec3& destination = m_threatPositions[bot->getBotId()]; + destination = target->getPosition(); + m_initiated[bot->getBotId()] = true; + } + else + m_initiated[bot->getBotId()] = false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.h new file mode 100644 index 000000000..e1f3332d4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.h @@ -0,0 +1,43 @@ +// Per-bot cover positions and fixed-point/object threat targets. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC7E0 (6 words), operator new 0x20, package H-deferred. +class BBPTakeCover : public BBPPattern +{ +public: + explicit BBPTakeCover(int); // 0x29D910 + virtual ~BBPTakeCover(); // 0x29DFD0 + + virtual BotScript* createPlan(Bot*); // 0x29E330, slot +0x08; from the base declaration + + void init(Bot*, const Vec3&, const Vec3&, unsigned int); // 0x29E120; [INFERRED] ELF void + void init(Bot*, unsigned int, const Vec3&, unsigned int); // 0x29E1E0; [INFERRED] ELF void + +private: + // [INFERRED] names; constructor and init stores establish the ia-32 layout. + /* +0x08 */ int m_patternId; + /* +0x0C */ unsigned int* m_coverObjects; + /* +0x10 */ Vec3* m_coverPositions; + /* +0x14 */ Vec3* m_threatPositions; + /* +0x18 */ unsigned int* m_threatObjects; + /* +0x1C */ bool* m_useObjects; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp new file mode 100644 index 000000000..934ddeb71 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp @@ -0,0 +1,116 @@ +// Take-cover pattern of aircraft (AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp in the image). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// createPlan was checked against the listing for constructor arguments (Ghidra merges the trigger's +// 64-bit mask and drops the bool arguments). + +// static init: ELF 0x2A0A40 (__tcf_0 0x2A0AA0, _GLOBAL__I 0x2A0AD0): 's Init object only. +#include + +#include "BBPTakeCover3d.h" + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTime.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x29FD20: BBPPattern(), the vtable store, then the argument at +0x08. +BBPTakeCover3d::BBPTakeCover3d(int patternId) + : BBPPattern() +{ + m_patternId = patternId; +} + +// ELF 0x29FDA0 (D0 0x29FDE0): the vtable store, then BBPPattern's destructor; nothing of its own. +BBPTakeCover3d::~BBPTakeCover3d() +{ +} + +// ELF 0x29FE20 +void BBPTakeCover3d::init(Bot* bot) +{ + m_initiated[bot->getBotId()] = true; +} + +// ELF 0x29FE50. Keeps a plan of this pattern; otherwise drops the plan and builds +// `parallel(reset controls, trigger input 47 for 2 s, move to 500 m along the own heading)`. +// The own equipment's information is not null-checked before its mobile and control-info +// plug-ins are read, as compiled. +// [PLATFORM] precision: the x87 build adds the extended product heading * 500 to the position; +// the float expression below rounds the product first. +BotScript* BBPTakeCover3d::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId) + return bot->getPlan(); + + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + + Information* const self = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = self->getMobile(); + IPIControlInfo* const controlInfo = self->getControlInfo(); + + BAPCombinerParallel* const plan = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); + plan->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); + plan->addStatement(checkPointer(new BAPATrigger(static_cast(0x2F), + checkPointer(new BAPConTime(2.0f, false, true, true)), + checkPointer(new BAPConFalse()), 0x800000000000ULL, + m_patternId, 0.0f, false))); + + const Vec3& position = self->getPosition(); // +0x30 + const Mat4& transformation = self->getTransformation(); // +0x3C + Vec3 offset; + offset.x = transformation.m[8] * 500.0f; + offset.y = transformation.m[9] * 500.0f; + offset.z = 500.0f * transformation.m[10]; + Vec3 destination; + destination.x = offset.x + position.x; + destination.y = offset.y + position.y; + destination.z = offset.z + position.z; + plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, destination, mobile->getMaxSpeed(), mobile->getMaxSpeed(), + checkPointer(new BAPConFalse()), + controlInfo->getDriveControls(), 30.0f, m_patternId))); + plan->setParent(this); // +0x04 (BotScript::m_owner) + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.h new file mode 100644 index 000000000..e957d49d7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.h @@ -0,0 +1,38 @@ +// Take-cover pattern of aircraft (3d navigation): flies 500 m straight ahead while pressing input 47. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// Virtual functions are in ELF vtable slot order (tools/macos/ai_behaviour_vtables.py checks them). + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER3D_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER3D_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC860 (6 words), package H-deferred. BotBehaviourManager's create function +// (0x3D7F80) allocates 0x18 bytes; no body of this class touches +0x0C..+0x17. [UNRESOLVED] +class BBPTakeCover3d : public BBPPattern +{ +public: + explicit BBPTakeCover3d(int); // 0x29FD20 + virtual ~BBPTakeCover3d(); // 0x29FDA0 + + virtual BotScript* createPlan(Bot*); // 0x29FE50, slot +0x08; from the base declaration + + void init(Bot*); // 0x29FE20; ELF void (no return value materialized) + +protected: + /* +0x08 */ int m_patternId; // the constructor argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVER3D_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp new file mode 100644 index 000000000..2e1a46378 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp @@ -0,0 +1,392 @@ +// Infantry cover-plan construction recovered from libaidll.so. + +// static init: ELF 0x2A68C0 (__tcf_0 0x2A6920, _GLOBAL__I 0x2A6950): 's Init object only. +#include + +#include "BBPTakeCoverInfantry.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPActionInline.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIBotActionPlan/BAPASetSensingAgentFocus.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPConAnd.h" +#include "../AIBotActionPlan/BAPConEndOfPath.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConLineOfFire.h" +#include "../AIBotActionPlan/BAPConObjectLineOfFire.h" +#include "../AIBotActionPlan/BAPConOr.h" +#include "../AIBotActionPlan/BAPConPosition.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPIWTakeCover.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPICover.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../../Math/Mat4.h" +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] Packaging of the inline transforms in ELF 0x2A1B50. +Vec3 transformPoint(const Mat4& m, const Vec3& point) +{ + const Vec3 result = {point.x * m.m[0] + point.y * m.m[4] + point.z * m.m[8] + m.m[12], + point.x * m.m[1] + point.y * m.m[5] + point.z * m.m[9] + m.m[13], + point.x * m.m[2] + point.y * m.m[6] + point.z * m.m[10] + m.m[14]}; + return result; +} + +Vec3 transformDirection(const Mat4& m, const Vec3& direction) +{ + const Vec3 result = {direction.x * m.m[0] + direction.y * m.m[4] + direction.z * m.m[8], + direction.x * m.m[1] + direction.y * m.m[5] + direction.z * m.m[9], + direction.x * m.m[2] + direction.y * m.m[6] + direction.z * m.m[10]}; + return result; +} + +} // namespace + +// ELF 0x2A1110 (C1; C2 0x2A0AF0) +BBPTakeCoverInfantry::BBPTakeCoverInfantry(int patternId) +{ + const unsigned int count = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + m_patternId = patternId; + m_coverObjects = checkPointer(new unsigned int[count]); + m_coverPositions = checkPointer(new Vec3[count]()); + m_threatPositions = checkPointer(new Vec3[count]()); + m_threatObjects = checkPointer(new unsigned int[count]); + m_useObjects = checkPointer(new bool[count]); +} + +// ELF 0x2A17E0 (D1; D2 0x2A1730, D0 0x2A1890) +BBPTakeCoverInfantry::~BBPTakeCoverInfantry() +{ + if (m_coverObjects) + delete[] m_coverObjects; + if (m_coverPositions) + delete[] m_coverPositions; + if (m_threatPositions) + delete[] m_threatPositions; + if (m_threatObjects) + delete[] m_threatObjects; + if (m_useObjects) + delete[] m_useObjects; +} + +// ELF 0x2A1B50 +BotScript* BBPTakeCoverInfantry::createPlan(Bot* bot) +{ + if (!isInitiated(bot)) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + return 0; + } + IAIPathfinding* pathfinding = IAIPathfinding::instance; + const unsigned int coverObject = m_coverObjects[bot->getBotId()]; + const bool useObject = m_useObjects[bot->getBotId()]; + const Vec3 coverPosition = m_coverPositions[bot->getBotId()]; + Vec3 threatPosition = {}; + if (bot->hasPlan()) + { + BAPStatement* previous = static_cast(bot->getPlan()); + if (previous->getPatternId() == m_patternId && previous->getId() == BAPSTInfoWrapper) + { + BAPIWTakeCover* wrapper = static_cast(previous); + if (wrapper->getInfoType() == 7) + { + if (useObject) + { + if (wrapper->m_useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + Information* oldTarget = informationManager->getInformation(wrapper->m_object); + if (target && oldTarget && target->getAIObject() == oldTarget->getAIObject()) + { + const Vec3 difference = bapinline::sub(wrapper->m_position, oldTarget->getPosition()); + if (bapinline::lengthSqr(difference) < 1.0f) + return wrapper; + } + } + } + else if (!wrapper->m_useObject) + { + const Vec3 difference = bapinline::sub(wrapper->m_position, m_threatPositions[bot->getBotId()]); + if (bapinline::lengthSqr(difference) < 9.0f) + return wrapper; + } + } + } + } + if (bot->getPlan()) + { + BotScript* previous = bot->getPlan(); + if (previous) + delete previous; + bot->setPlan(0); + } + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + bot->getSquadMember()->clearRequestAction(); + Information* self = informationManager->getInformation(bot->getCurrentEquipment()); + if (!self) + return 0; + IPIControlInfo* controls = self->getControlInfo(); + if (!controls) + return 0; + IPIMobile* mobile = self->getMobile(); + if (!mobile) + return 0; + Information* cover = informationManager->getInformation(coverObject); + IPICover* coverInfo = 0; + if (cover) + { + if (!cover->getPhysical()) + return 0; + coverInfo = cover->getCover(); + if (!coverInfo) + return 0; + } + if (useObject) + { + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (!target) + return 0; + threatPosition = target->getPosition(); + } + else + threatPosition = m_threatPositions[bot->getBotId()]; + + BAPCombinerSerial* root; + if (!cover) + { + Vec3 direction = bapinline::sub(threatPosition, self->getPosition()); + const Vec3 destination = coverPosition; + root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPASetSensingAgentFocus* focus; + if (!m_useObjects[bot->getBotId()]) + { + bapinline::normalize(direction); + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, direction, m_patternId, false)); + } + else + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, target, m_patternId, false)); + } + const unsigned long long driveControls = controls->getDriveControls(); + BAPConPosition* atPosition = checkPointer(new BAPConPosition(destination, 4.0f)); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed() + 1.0f; + BAPAMoveToFinding* move = checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + atPosition, driveControls, m_patternId, 0.0f, 0.0f)); + BAPAResetControls* reset = checkPointer(new BAPAResetControls(true, false, false, m_patternId)); + BAPASoldierPose* lie = checkPointer(new BAPASoldierPose(SPLying, checkPointer(new BAPConTrue()), m_patternId, false)); + root->addStatement(move); + root->addStatement(reset); + root->addStatement(lie); + root->addStatement(focus); + } + else + { + Vec2 goal = {}; + const int equipmentType = self->getUnit()->getEquipmentType(); + if (coverInfo->getPortalCount() == 0) + { + Vec3 sensePosition = {}; + Vec3 senseNormal = {}; + Vec3 hint = {}; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->pickRandomSensePosition(sensePosition, senseNormal, hint, cover->getAIObject()); + Vec3 tracePosition = {}; + unsigned int polygon; + const int vehicleNumber = mobile->getVehicleNumber(); + pathfinding->trace(vehicleNumber, coverPosition, sensePosition, tracePosition, polygon, + equipmentType, -1, 0.0f, 0, 0); + vec3ToVec2XZ(tracePosition, goal); + } + else + { + const Mat4& world = cover->getTransformation(); + Mat4 inverse; + inverse.setInverse(world); + const Vec3 localThreat = transformPoint(inverse, threatPosition); + unsigned int selected = 0; + float bestDot = -FLT_MAX; + unsigned int portal; + for (portal = 0; portal < coverInfo->getPortalCount(); ++portal) + { + Vec3 direction = bapinline::sub(localThreat, coverInfo->getPortalCenter(portal)); + bapinline::normalize(direction); + const float dot = bapinline::dot(direction, coverInfo->getPortalNormal(portal)); + if (dot > bestDot) + { + selected = portal; + bestDot = dot; + } + } + const Vec3& centre = coverInfo->getPortalCenter(selected); + const Vec3& normal = coverInfo->getPortalNormal(selected); + const Vec3 worldCentre = transformPoint(world, centre); + const Vec3 worldNormal = transformDirection(world, normal); + const Vec3 offset = {worldNormal.x * -2.0f, worldNormal.y * -2.0f, worldNormal.z * -2.0f}; + Vec3 closest = {}; + unsigned int polygon; + unsigned int island; + const int vehicleNumber = mobile->getVehicleNumber(); + if (pathfinding->findClosestValidPolygon(polygon, island, closest, vehicleNumber, + worldCentre, offset, 10, equipmentType)) + { + const Vec3 tangent = {worldNormal.z, 0.0f, -worldNormal.x}; + const float side = bapinline::dot(tangent, threatPosition) - bapinline::dot(tangent, worldCentre); + const Vec3 step = {tangent.x * 2.0f, tangent.y * 2.0f, tangent.z * 2.0f}; + // shipped defect: the extent query uses the exhausted loop index, not `selected`. + const float extent = side > 0.0f ? coverInfo->getPortalXZExtentR(portal) + : coverInfo->getPortalXZExtentL(portal); + const Vec3 from = {step.x * extent + worldCentre.x, step.y * extent + worldCentre.y, + step.z * extent + worldCentre.z}; + Vec3 tracePosition = {}; + unsigned int tracePolygon; + const int traceVehicle = mobile->getVehicleNumber(); + pathfinding->trace(traceVehicle, from, closest, tracePosition, tracePolygon, + equipmentType, -1, 0.0f, 0, 0); + vec3ToVec2XZ(tracePosition, goal); + } + } + const float maximumSpeed = mobile->getMaxSpeed(); + const float radius = maximumSpeed < 4.0f ? 4.0f : maximumSpeed * 0.5f; + (void)std::sqrt(bapinline::lengthSqr(bapinline::sub(threatPosition, self->getPosition()))); + root = checkPointer(new BAPCombinerSerial(m_patternId, -1)); + BAPASetSensingAgentFocus* focus; + if (!m_useObjects[bot->getBotId()]) + { + Vec3 direction = bapinline::sub(threatPosition, self->getPosition()); + bapinline::normalize(direction); + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, direction, m_patternId, false)); + } + else + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + focus = checkPointer(new BAPASetSensingAgentFocus(0.5f, target, m_patternId, false)); + } + root->addStatement(focus); + BAPAResetControls* reset = checkPointer(new BAPAResetControls(true, false, true, m_patternId)); + BAPCombinerParallel* moving = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + BAPConFalse* poseBreak = checkPointer(new BAPConFalse()); + BAPConTrue* poseRun = checkPointer(new BAPConTrue()); + BAPASoldierPose* pose = checkPointer(new BAPASoldierPose(SPStanding, SPLying, 5, SPCrouching, + 0.0f, poseRun, poseBreak, m_patternId, false)); + BAPConOr* endCondition = checkPointer(new BAPConOr()); + BAPConFalse* never = new BAPConFalse(); + BAPConAnd* arrived = checkPointer(new BAPConAnd()); + BAPConEndOfPath* endOfPath = checkPointer(new BAPConEndOfPath()); + BAPConPosition* atPosition = checkPointer(new BAPConPosition(goal, radius)); + arrived->addCondition(endOfPath); + arrived->addCondition(atPosition); + endCondition->addCondition(never); + endCondition->addCondition(arrived); + const unsigned long long driveControls = controls->getDriveControls(); + const float arriveSpeed = mobile->getMaxSpeed(); + const float speed = mobile->getMaxSpeed(); + const Vec3 destination = {goal.x, 0.0f, goal.y}; + BAPAMoveToFinding* move = checkPointer(new BAPAMoveToFinding(bot, destination, speed, arriveSpeed, + endCondition, driveControls, m_patternId, 0.0f, 0.0f)); + moving->addStatement(pose); + moving->addStatement(move); + BAPCombinerParallel* posing = checkPointer(new BAPCombinerParallel(m_patternId, false, -1, false)); + unsigned int target = 0; + BAPCondition* standingLine; + if (useObject) + { + target = m_threatObjects[bot->getBotId()]; + standingLine = checkPointer(new BAPConObjectLineOfFire(target, false, SPStanding)); + } + else + standingLine = checkPointer(new BAPConLineOfFire(threatPosition, false, SPStanding)); + BAPASoldierPose* stand = checkPointer(new BAPASoldierPose(SPStanding, checkPointer(new BAPConTrue()), m_patternId, false)); + BAPCondition* crouchingLine; + if (useObject) + crouchingLine = checkPointer(new BAPConObjectLineOfFire(target, false, SPCrouching)); + else + crouchingLine = checkPointer(new BAPConLineOfFire(threatPosition, false, SPCrouching)); + BAPASoldierPose* crouch = checkPointer(new BAPASoldierPose(SPCrouching, checkPointer(new BAPConTrue()), m_patternId, false)); + BAPASoldierPose* lie = checkPointer(new BAPASoldierPose(SPLying, checkPointer(new BAPConTrue()), m_patternId, false)); + BAPFlowCIf* lowerPose = checkPointer(new BAPFlowCIf(crouchingLine, lie, crouch, m_patternId, false, false)); + BAPFlowCIf* selectPose = checkPointer(new BAPFlowCIf(standingLine, lowerPose, stand, m_patternId, false, false)); + posing->addStatement(selectPose); + root->addStatement(reset); + root->addStatement(moving); + root->addStatement(posing); + } + BAPIWTakeCover* wrapper; + if (useObject) + { + const unsigned int target = m_threatObjects[bot->getBotId()]; + wrapper = checkPointer(new BAPIWTakeCover(target, root, m_patternId)); + } + else + wrapper = checkPointer(new BAPIWTakeCover(threatPosition, root, m_patternId)); + wrapper->m_owner = this; + return wrapper; +} + +// ELF 0x2A1940 +void BBPTakeCoverInfantry::init(Bot* bot, const Vec3& threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatPositions[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = false; + m_initiated[bot->getBotId()] = true; +} + +// ELF 0x2A1A00 +void BBPTakeCoverInfantry::init(Bot* bot, unsigned int threat, const Vec3& position, unsigned int cover) +{ + m_coverObjects[bot->getBotId()] = cover; + m_coverPositions[bot->getBotId()] = position; + m_threatObjects[bot->getBotId()] = threat; + m_useObjects[bot->getBotId()] = true; + Information* target = informationManager->getInformation(m_threatObjects[bot->getBotId()]); + if (target) + { + Vec3& destination = m_threatPositions[bot->getBotId()]; + destination = target->getPosition(); + m_initiated[bot->getBotId()] = true; + } + else + m_initiated[bot->getBotId()] = false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.h new file mode 100644 index 000000000..e4db79302 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.h @@ -0,0 +1,43 @@ +// Infantry cover planning with optional cover-object portals and stance selection. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVERINFANTRY_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVERINFANTRY_H + +#include "../../../../Math/Vec3.h" +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC8E0 (6 words), operator new 0x20, package H-deferred. +class BBPTakeCoverInfantry : public BBPPattern +{ +public: + explicit BBPTakeCoverInfantry(int); // 0x2A1110 + virtual ~BBPTakeCoverInfantry(); // 0x2A17E0 + + virtual BotScript* createPlan(Bot*); // 0x2A1B50, slot +0x08; from the base declaration + + void init(Bot*, const Vec3&, const Vec3&, unsigned int); // 0x2A1940; [INFERRED] ELF void + void init(Bot*, unsigned int, const Vec3&, unsigned int); // 0x2A1A00; [INFERRED] ELF void + +private: + // [INFERRED] names; constructor and init stores establish the ia-32 layout. + /* +0x08 */ int m_patternId; + /* +0x0C */ unsigned int* m_coverObjects; + /* +0x10 */ Vec3* m_coverPositions; + /* +0x14 */ Vec3* m_threatPositions; + /* +0x18 */ unsigned int* m_threatObjects; + /* +0x1C */ bool* m_useObjects; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTAKECOVERINFANTRY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp new file mode 100644 index 000000000..df0f6750f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp @@ -0,0 +1,127 @@ +// Triggerable pattern (man-down bots and world triggerables). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32). + +// static init: ELF 0x2A7F80 (__tcf_0 0x2A7FE0, _GLOBAL__I 0x2A8010): 's Init object only. +#include + +#include "BBPTriggerable.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/SquadMember.h" +#include "../AIBotActionPlan/BAPAMoveToFinding.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConNot.h" +#include "../AIBotActionPlan/BAPConTriggerableActive.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPIWIdle.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIPlanInterpreter/BotScriptDebugger.h" +#include "../AIPlanInterpreter/VehicleControlInline.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../../Game/Objects/Game/Triggerable.h" +#include "../../../../Game/Objects/TemplateLeaves.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A6970 (C2) / 0x2A6AF0 (C1): BBPPattern(), +0x08 = id, +0x0C = checkPointer(new[getMaxNBots]); +0x14 = 0 (0x2A69D3, stored before +0x0C). +BBPTriggerable::BBPTriggerable(int id) + : BBPPattern() +{ + m_id = id; + m_triggerable = 0; + m_perBot = checkPointer(new unsigned int[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); +} + +// ELF 0x2A6C70 (D2) / 0x2A6CC0 (D1) / 0x2A6D10 (D0): delete[] +0x0C when set, then ~BBPPattern. +BBPTriggerable::~BBPTriggerable() +{ + if (m_perBot) + delete[] m_perBot; +} + +// ELF 0x2A6DA0: retain this pattern's existing plan, otherwise approach the triggerable and +// repeatedly trigger it while it is inactive. The inactive-pattern path destroys the old plan. +BotScript* BBPTriggerable::createPlan(Bot* bot) +{ + if (!m_initiated[bot->getBotId()]) + { + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getScriptContext()->clear(); + if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + return 0; + } + + bot->getSquadMember()->clearRequestAction(); + bot->getCurrentEquipment(); + if (bot->hasPlan()) + { + if (static_cast(bot->getPlan())->getPatternId() == m_id) + return bot->getPlan(); + } + else if (bot->getPlan()) + { + delete bot->getPlan(); + bot->setPlan(0); + } + + if (bot->getDebugger()) + static_cast(bot->getDebugger())->clear(); + bot->getSquadMember()->clearRequestAction(); + bot->getScriptContext()->clear(); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(m_id, -1, false)); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const unsigned long long controls = equipment->getControlInfo()->getDriveControls(); + // Shipped defect: this condition is constructed and leaked; the movement receives null. + new BAPConFalse(); + const float radius = 0.6f * m_triggerable->m_template->m_radius; + const Mat4& transform = m_triggerable->getAbsoluteTransformation(); + Vec3 direction = { transform.m[8], transform.m[9], transform.m[10] }; + vehiclecontrol::normalizeVec3(direction); + const Vec3& position = m_triggerable->getAbsolutePosition(); + const Vec3 goal = { direction.x * 2.0f + position.x, direction.y * 2.0f + position.y, + direction.z * 2.0f + position.z }; + parallel->addStatement(checkPointer(new BAPAMoveToFinding(bot, goal, 5.0f, 5.0f, 0, + controls, m_id, radius, 0.0f))); + + BAPConFalse* const stop = checkPointer(new BAPConFalse()); + BAPConTrue* const start = checkPointer(new BAPConTrue()); + BAPATrigger* const trigger = checkPointer(new BAPATrigger(static_cast(10), + start, stop, 0x400ULL, m_id, 0.0, false)); + BAPConTriggerableActive* const active = checkPointer(new BAPConTriggerableActive(m_triggerable)); + BAPConNot* const inactive = checkPointer(new BAPConNot(active)); + parallel->addStatement(checkPointer(new BAPFlowCIf(inactive, trigger, 0, m_id, true, false))); + BAPConTrue* const repeat = checkPointer(new BAPConTrue()); + BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(repeat, parallel, true, m_id)); + BAPIWIdle* const plan = checkPointer(new BAPIWIdle(equipment->getPosition(), loop, m_id, bot)); + plan->m_owner = this; + return plan; +} + +// ELF 0x2A6D60: bot->invalidatePlan() (+0x5C), m_initiated[bot->getBotId()] = true, +0x14. +void BBPTriggerable::init(Bot* bot, world::Triggerable* triggerable) +{ + bot->invalidatePlan(); + m_initiated[bot->getBotId()] = true; + m_triggerable = triggerable; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.h new file mode 100644 index 000000000..366094209 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.h @@ -0,0 +1,43 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTRIGGERABLE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTRIGGERABLE_H + +#include "BBPPattern.h" + +namespace dice { +namespace hfe { + +namespace world { class Triggerable; } +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BC960 (6 words), operator new 0x18, package F-infantry. +class BBPTriggerable : public BBPPattern +{ +public: + explicit BBPTriggerable(int); // 0x2A6AF0 + virtual ~BBPTriggerable(); // 0x2A6CC0 + + virtual BotScript* createPlan(Bot*); // 0x2A6DA0, slot +0x08; from the base declaration + + void init(Bot*, world::Triggerable*); // 0x2A6D60; void [INFERRED]: no caller in the image reads %eax + +private: + /* +0x08 */ int m_id; // constructor argument [INFERRED] name + /* +0x0C */ unsigned int* m_perBot; // new[getMaxNBots], checkPointer'd [UNRESOLVED] use + /* +0x10 */ unsigned char m_unwritten10[4]; // not written by the constructor or init + /* +0x14 */ world::Triggerable* m_triggerable; // = 0; init's argument +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_BBPTRIGGERABLE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/PlanGenerator.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/PlanGenerator.h new file mode 100644 index 000000000..eee1836c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/PlanGenerator.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_PLANGENERATOR_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_PLANGENERATOR_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// Pattern interface. Vtable 0x4BC420: D1, D0, four pure slots. Inline in the image. +// ELF: vtable 0x4BC420 (6 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class PlanGenerator +{ +public: + virtual ~PlanGenerator() {} // weak in the image (inline) + + virtual BotScript* createPlan(Bot*) = 0; // no body, slot +0x08; from the base declaration + virtual bool isInitiated(Bot*) = 0; // no body, slot +0x0C; from the base declaration + virtual void unInit(Bot*) = 0; // no body, slot +0x10; [INFERRED] from BBPGotoWaypoint: ELF void + virtual void forceInitiated(Bot*) = 0; // no body, slot +0x14; [INFERRED] from BBPGotoWaypoint: ELF void +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_PLANGENERATOR_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp new file mode 100644 index 000000000..33a97bbd8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp @@ -0,0 +1,105 @@ +// Weapon selection helpers shared by the fire patterns. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [INFERRED] file name (see WeaponChoice.h). + +#include "WeaponChoice.h" + +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A8030 +int choseWeapon(const std::vector& weapons, int current, float distance, int strengthType, + bool noIndirect, bool type1, bool type3, bool type2) +{ + int best = -1; + int bestStrength = 0; + bool inRange = false; + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + if ((weapon->getWeaponType() == 3) != type3) + continue; + if ((weapon->getWeaponType() == 1) != type1) + continue; + if ((weapon->getWeaponType() == 2) != type2) + continue; + if (noIndirect && weapon->getIndirect()) + continue; + if (weapon->getAmmo() == 0 && !type2 && !type1 && !type3) + continue; + if (weapon->getStrength(strengthType) <= 0) + continue; + if (weapon->getMaxRange() > distance && weapon->getMinRange() < distance) + { + if (inRange && weapon->getStrength(strengthType) < bestStrength) + continue; + inRange = true; + best = i; + bestStrength = weapon->getStrength(strengthType); + if (best == current) + bestStrength *= 3; + } + else if (!inRange && weapon->getStrength(strengthType) > bestStrength) + { + best = i; + bestStrength = weapon->getStrength(strengthType); + if (best == current) + bestStrength *= 3; + } + } + return best; +} + +// ELF 0x2A8220 +int choseWeaponDistanceIndependent(int current, int strengthType, const std::vector& weapons, + unsigned int allowed) +{ + int best = -1; + int bestStrength = 0; + for (int i = 0; i < static_cast(weapons.size()); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (!weapon) + continue; + if (!(allowed & 4) && weapon->getWeaponType() == 1) + continue; + if (!(allowed & 2) && weapon->getIndirect()) + continue; + if (!(allowed & 1) && !weapon->getIndirect()) + continue; + if (weapon->getAmmo() == 0 || weapon->getStrength(strengthType) <= 0) + continue; + int strength = weapon->getStrength(strengthType); + if (current == i) + strength *= 3; + if (strength > bestStrength) + { + bestStrength = strength; + best = i; + } + } + return best; +} + +// ELF 0x2A8330 +int soldier_choseThrownWeapon(const std::vector& weapons, int, float distance, int strengthType) +{ + for (unsigned int i = 0; i < weapons.size(); ++i) + { + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(weapons[i]); + if (weapon && weapon->getIsThrown() && weapon->getAmmo() != 0 && weapon->getStrength(strengthType) > 0 + && !(weapon->getMinRange() > distance)) + return i; + } + return -1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.h new file mode 100644 index 000000000..e10063f1a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.h @@ -0,0 +1,39 @@ +// Weapon selection helpers shared by the fire patterns. +// Recovered from libaidll.so (Linux 1.5.3153, ia-32, symbols); every body carries its ELF address. +// [INFERRED] file name: the three functions form a translation unit without a static initialiser +// that links between BBPTriggerable.cpp and AIPlanInterpreter/BAPDebugger.cpp; no __FILE__ string +// names it. + +#ifndef AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_WEAPONCHOICE_H +#define AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_WEAPONCHOICE_H + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// Picks the strongest weapon (WeaponInfo::getStrength(strengthType)) among `weapons` (handles) +// whose type matches the three type flags exactly (type 1, 3, 2), with ammunition unless one of +// the type flags is set, and not indirect when `noIndirect`. A weapon whose range brackets +// `distance` beats every weapon out of range; the `current` index counts triple. Returns the +// index into `weapons`, or -1. +int choseWeapon(const std::vector& weapons, int current, float distance, int strengthType, + bool noIndirect, bool type1, bool type3, bool type2); // 0x2A8030 + +// Picks the strongest weapon with ammunition regardless of range. `allowed` bit 0 admits direct +// weapons, bit 1 indirect weapons, bit 2 weapons of type 1; the `current` index counts triple. +// Returns the index into `weapons`, or -1. +int choseWeaponDistanceIndependent(int current, int strengthType, const std::vector& weapons, + unsigned int allowed); // 0x2A8220 + +// The first thrown weapon with ammunition and strength whose minimum range is at most +// `distance`; the int argument is not read. Returns the index into `weapons`, or -1. +int soldier_choseThrownWeapon(const std::vector& weapons, int, float distance, + int strengthType); // 0x2A8330 + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOTBEHAVIOURPATTERN_WEAPONCHOICE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp index 8d1a41c48..d7148ae1f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp @@ -1,6 +1,10 @@ #include "AIInformationGrid.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D74C0, __tcf_0 0x2D7520, _GLOBAL__I 0x2D7550). +#include + #include "Information.h" #include "IPIPhysical.h" #include "InformationManager.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp index 853ff3d33..d345861a6 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp @@ -2,6 +2,10 @@ #include "BFInformationCourier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2E6040, __tcf_0 0x2E60A0, _GLOBAL__I 0x2E60D0). +#include + #include #include #include diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp index a88ad027a..208f978e6 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp @@ -3,9 +3,18 @@ #include "BFInformationEnvironment.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2E7AD0, __tcf_0 0x2E7B30, _GLOBAL__I 0x2E7B60). +#include + #include #include "AIInformationGrid.h" // the grids the constructor builds +#include "Information.h" // removeAllContacts +#include "InformationManager.h" // the information pool +#include "IPIMobile.h" // getCover's search radius +#include "../AIBot/BotMain.h" // Bot +0xD8 / +0xE0 +#include "../AIUtils/VehicleOccupancy.h" // InfoEnemyPredicate #include "../AIUtils/checkPointer.h" // inlined four times by the constructor #include "../../../../Core/ClassManager.h" #include "../../../../Core/SmartItf.h" // the classManager global @@ -97,48 +106,230 @@ BFInformationEnvironment::BFInformationEnvironment() // [FRONTIER] Unimplemented environment queries and modifiers stop by name. // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x2E6C30. Deletes every grid of the second vector, then of the first (null slots skipped, +// the end re-read after each delete); the vectors free themselves. BFInformationEnvironment::~BFInformationEnvironment() { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::~BFInformationEnvironment"); + for (std::vector::iterator i = m_gridsB.begin(); i != m_gridsB.end(); ++i) + { + if (*i != 0) + delete *i; + } + for (std::vector::iterator i = m_gridsA.begin(); i != m_gridsA.end(); ++i) + { + if (*i != 0) + delete *i; + } +} + +namespace { + +// The query predicates of this TU (anonymous in retail: vtables ELF 0x4BE548..0x4BE5A8, bodies +// 0x2E7E80..0x2E8040, all weak). +4 is each one's single field. + +// Units of one side. +class InfoSideUnitPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoSideUnitPredicate(int side) : m_side(side) {} + // ELF 0x2E7F20. The side first, then the unit plug-in. + virtual bool includeInformation(Information* information) const + { + return information->getSide() == m_side && information->getUnit() != 0; + } + int m_side; +}; + +// Units of one side or of side 0. +class InfoSideAndNeutralUnitPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoSideAndNeutralUnitPredicate(int side) : m_side(side) {} + // ELF 0x2E7F70. The unit plug-in first; getSide is called a second time for the 0 test. + virtual bool includeInformation(Information* information) const + { + if (information->getUnit() == 0) + return false; + return information->getSide() == m_side || information->getSide() == 0; + } + int m_side; +}; + +// Any unit. +class InfoUnitPredicate : public IAIInformationGridPredicate +{ +public: + // ELF 0x2E7F00. + virtual bool includeInformation(Information* information) const + { + return information->getUnit() != 0; + } +}; + +// Everything but one record. +class InfoCullSelfPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoCullSelfPredicate(Information* self) : m_self(self) {} + // ELF 0x2E8020. + virtual bool includeInformation(Information* information) const + { + return m_self != information; + } + Information* m_self; +}; + +// Both of two predicates, the first first. +class CompositeInfoPredicate : public IAIInformationGridPredicate +{ +public: + CompositeInfoPredicate(IAIInformationGridPredicate* first, IAIInformationGridPredicate* second) + : m_first(first), m_second(second) + { + } + // ELF 0x2E7FC0. + virtual bool includeInformation(Information* information) const + { + return m_first->includeInformation(information) && m_second->includeInformation(information); + } + IAIInformationGridPredicate* m_first; // +4 + IAIInformationGridPredicate* m_second; // +8 +}; + +// Cover objects of one side or of side 0. Flag 0x40000 accepts any side; 0x10 and 0x80 reject. +// The flag names are [UNRESOLVED]; the bits are the record's object-type flags (+4). +class InfoCoverPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoCoverPredicate(int side) : m_side(side) {} + // ELF 0x2E7E80. + virtual bool includeInformation(Information* information) const + { + if ((information->getObjectTypeFlags() & 0x4000) == 0 || information->getCover() == 0) + return false; + if ((information->getObjectTypeFlags() & 0x40000) != 0) + return true; + const int side = information->getSide(); + const bool sideOk = m_side == side || side == 0; + return sideOk && (information->getObjectTypeFlags() & 0x10) == 0 + && (information->getObjectTypeFlags() & 0x80) == 0; + } + int m_side; +}; + +// Units of another side, when vehicleOccupied says the record counts for that side. +class InfoEnemyPredicate : public IAIInformationGridPredicate +{ +public: + explicit InfoEnemyPredicate(int side) : m_side(side) {} + // ELF 0x2E8040. + virtual bool includeInformation(Information* information) const + { + if (information->getUnit() == 0 || m_side == information->getSide()) + return false; + return vehicleOccupied(information->getHandle(), m_side); + } + int m_side; +}; + +// The bot's own record through Bot +0xD8 (getCurrentEquipment). +Information* informationOf(const Bot* bot) +{ + return informationManager->getInformation(bot->getCurrentEquipment()); } -void BFInformationEnvironment::getFriendlyUnits(std::vector&, const Vec3&, Bot*, float) const +} // anonymous namespace + +// ELF 0x2E6F40. `out` is cleared after the lookup; a bot without a record gets nothing. The +// bot's side is read twice (predicate, then the query's side argument). +void BFInformationEnvironment::getFriendlyUnits(std::vector& out, + const Vec3& position, Bot* bot, float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getFriendlyUnits"); + Information* const self = informationOf(bot); + out.erase(out.begin(), out.end()); + if (self == 0) + return; + InfoSideUnitPredicate keep(bot->getSide()); + getObjectsWithinRadius(out, position, radius, bot->getSide(), true, &keep); } -void BFInformationEnvironment::getFriendlyAndNeutralUnits(std::vector&, const Vec3&, Bot*, float) const +// ELF 0x2E7030. As getFriendlyUnits, side-0 units included. +void BFInformationEnvironment::getFriendlyAndNeutralUnits(std::vector& out, + const Vec3& position, Bot* bot, + float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getFriendlyAndNeutralUnits"); + Information* const self = informationOf(bot); + out.erase(out.begin(), out.end()); + if (self == 0) + return; + InfoSideAndNeutralUnitPredicate keep(bot->getSide()); + getObjectsWithinRadius(out, position, radius, bot->getSide(), true, &keep); } -void BFInformationEnvironment::getCover(const Bot&, std::vector&) const +// ELF 0x2E7120. Both grids (`which` true, then false) within the bot's mobile plug-in's cover +// search radius; `out` is appended to. Retail reads the record's mobile plug-in without testing +// the record for null. +void BFInformationEnvironment::getCover(const Bot& bot, std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getCover"); + Information* const self = informationOf(&bot); + IPIMobile* const mobile = self->getMobile(); + if (mobile == 0) + return; + const float radius = mobile->getCoverSearchRadius(); + InfoCoverPredicate keep(bot.getSide()); + getObjectsWithinRadius(out, radius, bot, true, &keep); + getObjectsWithinRadius(out, radius, bot, false, &keep); } -void BFInformationEnvironment::getHardware(std::vector&, const Vec3&, Bot*) const +// ELF 0x2E7220. Units within 75 m except the bot's own record; 0 (and nothing) without a record. +float BFInformationEnvironment::getHardware(std::vector& out, const Vec3& position, + Bot* bot) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getHardware"); + Information* const self = informationOf(bot); + if (self == 0) + return 0.0f; + return getHardware(out, position, 75.0f, bot->getSide(), self); } -void BFInformationEnvironment::getHardware(std::vector&, const Vec3&, float, int, Information*) const +// ELF 0x2E72C0. Units within `radius` (minus `self` when given), side `side` and side 0 of the +// first grid; answers the radius. +float BFInformationEnvironment::getHardware(std::vector& out, const Vec3& position, + float radius, int side, Information* self) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getHardware (Information*)"); + InfoUnitPredicate units; + InfoCullSelfPredicate notSelf(self); + CompositeInfoPredicate both(&units, ¬Self); + IAIInformationGridPredicate* const keep = + self != 0 ? static_cast(&both) : &units; + getObjectsWithinRadius(out, position, radius, side, true, keep); + return radius; } -void BFInformationEnvironment::getEnemyObjects(std::vector&, Bot*, float) const +// ELF 0x2E7360. A negative radius means 600 m when the bot's record has object flag 0x10 and +// 75 m otherwise (retail does not test the record for null there). +void BFInformationEnvironment::getEnemyObjects(std::vector& out, Bot* bot, + float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getEnemyObjects"); + Information* const self = informationOf(bot); + if (radius < 0.0f) + radius = (self->getObjectTypeFlags() & 0x10) != 0 ? 600.0f : 75.0f; + InfoEnemyPredicate keep(bot->getSide()); + getObjectsWithinRadius(out, radius, *bot, true, &keep); } -void BFInformationEnvironment::getObjectsWithinRadius(std::vector&, float, const Bot&, - bool, IAIInformationGridPredicate*) const +// ELF 0x2E7430. Around the bot's record position, for its side; nothing without a record. +void BFInformationEnvironment::getObjectsWithinRadius(std::vector& out, float radius, + const Bot& bot, bool which, + IAIInformationGridPredicate* keep) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getObjectsWithinRadius (Bot&)"); + Information* const self = informationOf(&bot); + if (self == 0) + return; + const int side = bot.getSide(); + getObjectsWithinRadius(out, self->getPosition(), radius, side, which, keep); } -// flatten XZ, then delegate +// ELF 0x2E74F0: flatten XZ, then delegate // virtually to the Vec2 overload (ELF +0x28 / PE +0x1C). void BFInformationEnvironment::getObjectsWithinRadius(std::vector& out, const Vec3& position, float radius, @@ -152,7 +343,7 @@ void BFInformationEnvironment::getObjectsWithinRadius(std::vector& getObjectsWithinRadius(out, flat, radius, side, which, keep); } -// Query side zero first +// ELF 0x2E7570. Query side zero first // then look up the requested side after that callback. Both calls remain when // side is zero. The grid query is const; output is appended to, never cleared. void BFInformationEnvironment::getObjectsWithinRadius(std::vector& out, @@ -176,10 +367,14 @@ void BFInformationEnvironment::getObjectsWithinRectangle(std::vectorgetInformationWithinRectangle(out, min, max, keep); } -void BFInformationEnvironment::getObjectsWithinFrustum(std::vector&, const Frustum&, - int, bool, IAIInformationGridPredicate*) const +// ELF 0x2E76E0. Side 0 first, then `side` (side 0 twice when asked for it), as the radius and +// rectangle queries. +void BFInformationEnvironment::getObjectsWithinFrustum(std::vector& out, + const Frustum& frustum, int side, bool which, + IAIInformationGridPredicate* keep) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::getObjectsWithinFrustum"); + getInformationGrid(0, which)->getInformationWithinFrustum(out, frustum, keep); + getInformationGrid(side, which)->getInformationWithinFrustum(out, frustum, keep); } void BFInformationEnvironment::getAllInformation(std::vector& out, int side, bool which, @@ -213,24 +408,35 @@ void BFInformationEnvironment::addAndUpdatePosition(int side, bool which, unsign getInformationGrid(side, which)->addAndUpdatePosition(handle); } -void BFInformationEnvironment::updatePosition(int, bool, unsigned int) +// ELF 0x2E78E0: the grid's +5 updatePosition (ELF +0x14). The ELF zero-extends the grid's bool +// into its own result; every caller in both images drops it, so the declared void stays. +void BFInformationEnvironment::updatePosition(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::updatePosition"); + getInformationGrid(side, which)->updatePosition(handle); } -void BFInformationEnvironment::removeInfo(int, bool, unsigned int) +// ELF 0x2E7930: the information's +8 removeAllContacts first, then the grid's +3 removeInfo +// (ELF +0x0C). The handle is resolved through the information pool inline; a stale handle +// yields null and the shipped call dereferences it unguarded. +void BFInformationEnvironment::removeInfo(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::removeInfo"); + informationManager->getInformation(handle)->removeAllContacts(); + getInformationGrid(side, which)->removeInfo(handle); } -void BFInformationEnvironment::safeRemoveInfo(int, bool, unsigned int) +// ELF 0x2E79C0: as removeInfo, but through the grid's +4 safeRemoveInfo (ELF +0x10) with a null +// removal predicate. The grid's bool is not used. +void BFInformationEnvironment::safeRemoveInfo(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::safeRemoveInfo"); + informationManager->getInformation(handle)->removeAllContacts(); + getInformationGrid(side, which)->safeRemoveInfo(handle, nullptr); } -void BFInformationEnvironment::destroyRemoveInfo(int, bool, unsigned int) +// ELF 0x2E7A50: the grid's +4 safeRemoveInfo with a null predicate, without touching the +// information's contacts. +void BFInformationEnvironment::destroyRemoveInfo(int side, bool which, unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFInformationEnvironment::destroyRemoveInfo"); + getInformationGrid(side, which)->safeRemoveInfo(handle, nullptr); } // Selects one of two grid sets by which, then indexes it by side. diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h index 6acb4277e..b6377fd0e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h @@ -31,8 +31,9 @@ class IAIInformationEnvironment virtual void getFriendlyUnits(std::vector&, const Vec3&, Bot*, float) const = 0; virtual void getFriendlyAndNeutralUnits(std::vector&, const Vec3&, Bot*, float) const = 0; virtual void getCover(const Bot&, std::vector&) const = 0; - virtual void getHardware(std::vector&, const Vec3&, Bot*) const = 0; - virtual void getHardware(std::vector&, const Vec3&, float, int, Information*) const = 0; + // Both return the search radius in st0 (ELF 0x2E7220 / 0x2E72C0), not void. + virtual float getHardware(std::vector&, const Vec3&, Bot*) const = 0; + virtual float getHardware(std::vector&, const Vec3&, float, int, Information*) const = 0; virtual void getEnemyObjects(std::vector&, Bot*, float) const = 0; virtual void getObjectsWithinRadius(std::vector&, float, const Bot&, bool, IAIInformationGridPredicate*) const = 0; @@ -79,8 +80,8 @@ class BFInformationEnvironment : public IAIInformationEnvironment, virtual void getFriendlyUnits(std::vector&, const Vec3&, Bot*, float) const; virtual void getFriendlyAndNeutralUnits(std::vector&, const Vec3&, Bot*, float) const; virtual void getCover(const Bot&, std::vector&) const; - virtual void getHardware(std::vector&, const Vec3&, Bot*) const; - virtual void getHardware(std::vector&, const Vec3&, float, int, Information*) const; + virtual float getHardware(std::vector&, const Vec3&, Bot*) const; + virtual float getHardware(std::vector&, const Vec3&, float, int, Information*) const; virtual void getEnemyObjects(std::vector&, Bot*, float) const; virtual void getObjectsWithinRadius(std::vector&, float, const Bot&, bool, IAIInformationGridPredicate*) const; @@ -99,7 +100,7 @@ class BFInformationEnvironment : public IAIInformationEnvironment, virtual void getAllInformation(std::vector&, int, bool, IAIInformationGridPredicate*, IAIInformationGridPredicate*); - // IAIInformationEnvironmentModifiers. All [FRONTIER]. + // IAIInformationEnvironmentModifiers. virtual void addInfo(int, bool, unsigned int); virtual void addAndUpdatePosition(int, bool, unsigned int); virtual void updatePosition(int, bool, unsigned int); diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.cpp new file mode 100644 index 000000000..f33df19a8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.cpp @@ -0,0 +1,4 @@ +// The methods are weak inline bodies in the image; the standalone TU initializes iostream only. +// static init: ELF 0x2D7FE0 (__tcf_0 0x2D8040, _GLOBAL__I 0x2D8070). +#include "DangerObject.h" +#include diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h new file mode 100644 index 000000000..f0754de20 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h @@ -0,0 +1,95 @@ +// Identity and position of a threat used by the cover behaviours. +// Source placement: the image's initializer names AI/AIDLL/AI/AIKnowledge/DangerObject.cpp. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_DANGEROBJECT_H +#define AI_AIDLL_AI_AIKNOWLEDGE_DANGEROBJECT_H + +#include "FireObject.h" +#include "Information.h" +#include "InformationManager.h" + +namespace dice { namespace hfe { namespace ai { + +// The shipped tables contain five virtual slots and no virtual destructor. Objects are borrowed +// threat identities; their FireObject/Information pointees are never owned. +class DangerObject +{ +public: + virtual bool isFireObject() const = 0; + virtual bool isInformation() const = 0; + virtual bool getPosition(Vec3& position) = 0; + // [INFERRED] void* for the untyped identity pointer compared by operator==. + virtual void* getPointer() const = 0; + + // ELF 0x2206C0 + virtual bool operator==(const DangerObject& other) const + { + if (isInformation() && !other.isInformation()) + return false; + if (isFireObject() && !other.isFireObject()) + return false; + if (!getPointer()) + return false; + void* pointer = getPointer(); + return pointer == other.getPointer(); + } +}; + +class FireDanger : public DangerObject +{ +public: + // [INFERRED] Inline construction: the cover bodies store null or their borrowed shot pointer. + FireDanger() : m_fire(0) {} + explicit FireDanger(FireObject* fire) : m_fire(fire) {} + + // ELF 0x220570 + virtual bool isFireObject() const { return true; } + // ELF 0x220580 + virtual bool isInformation() const { return false; } + // ELF 0x220610 + virtual bool getPosition(Vec3& position) + { + if (!m_fire) + return false; + position = m_fire->getOrigin(); + return true; + } + // ELF 0x220590 + virtual void* getPointer() const { return m_fire; } + + /* +0x04 */ FireObject* m_fire; +}; + +class InfoDanger : public DangerObject +{ +public: + // [INFERRED] Inline construction: the cover bodies store -1 or an information handle. + InfoDanger() : m_information(0xFFFFFFFFu) {} + explicit InfoDanger(unsigned int information) : m_information(information) {} + + // ELF 0x2205A0 + virtual bool isFireObject() const { return false; } + // ELF 0x2205B0 + virtual bool isInformation() const { return true; } + // ELF 0x220640 + virtual bool getPosition(Vec3& position) + { + Information* information = informationManager->getInformation(m_information); + if (!information) + return false; + position = information->getPosition(); + return true; + } + // ELF 0x2205C0 + virtual void* getPointer() const + { + if (m_information == 0xFFFFFFFFu) + return 0; + return informationManager->getInformation(m_information); + } + + /* +0x04 */ unsigned int m_information; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.cpp new file mode 100644 index 000000000..ea87beacb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.cpp @@ -0,0 +1,98 @@ +// A reported shot. Evidence: libaidll.so 1.5.3153 (ia-32), see FireObject.h. + +#include "FireObject.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D8710, __tcf_0 0x2D8770, _GLOBAL__I 0x2D87A0). +#include + +#include + +#include "../AIUtils/checkPointer.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2D8090 (C1; C2 0x2D8280 is identical). Field stores first, then the strength count from +// IAISettings +0x34 (getNBattleStrengths), the checked array and the copy loop. +FireObject::FireObject(Vec3 origin, Vec3 target, float* strengths, bool direct, double time, float decay) +{ + m_direct = direct; + m_origin = origin; + m_target = target; + m_time = time; + m_decay = decay; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + const int count = settings->getNBattleStrengths(); + m_strengths = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + m_strengths[i] = strengths[i]; +} + +// ELF 0x2D8470: `if (+4) operator delete[](+4)`. +FireObject::~FireObject() +{ + if (m_strengths) + delete[] m_strengths; +} + +// ELF 0x2D84D0. The shot's XZ direction: getVec2NormalFromVec3XZ(target - origin), then the inline +// Vec2 normalisation (left alone within FLT_EPSILON of unit length, zeroed below FLT_EPSILON^2, +// else scaled by 1 / sqrt). The offset of `position` from the origin, projected to XZ, dotted with +// that normal is the distance from the line. +bool FireObject::isWithinRadius(const Vec3& position, float radius) +{ + Vec3 direction; + direction.x = m_target.x - m_origin.x; + direction.y = m_target.y - m_origin.y; + direction.z = m_target.z - m_origin.z; + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + getVec2NormalFromVec3XZ(direction, normal); + const float lengthSq = normal.x * normal.x + normal.y * normal.y; + if (std::fabs(1.0f - lengthSq) >= 1.1920929e-07f) + { + if (std::fabs(lengthSq) >= 1.4210855e-14f) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + normal.x = normal.x * inverse; + normal.y = inverse * normal.y; + } + else + { + normal.x = 0.0f; + normal.y = 0.0f; + } + } + Vec3 offset; + offset.x = position.x - m_origin.x; + offset.y = position.y - m_origin.y; + offset.z = position.z - m_origin.z; + Vec2 offsetXZ; + offsetXZ.x = 0.0f; + offsetXZ.y = 0.0f; + vec3ToVec2XZ(offset, offsetXZ); + float distance = offsetXZ.x * normal.x + offsetXZ.y * normal.y; + if (distance < 0.0f) + distance = -distance; + return distance <= radius; +} + +// ELF 0x2D86B0: `flds (+4)[type]`; IBFTimer +8 (getGameTime) - +0x20, rounded to float, times +// +0x28, plus 1.0; divide. +float FireObject::getBattleStrength(int type) +{ + const float* const strengths = m_strengths; + const IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const float age = static_cast(timer->getGameTime() - m_time); + return strengths[type] / (age * m_decay + 1.0f); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h new file mode 100644 index 000000000..a22539f2b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/FireObject.h @@ -0,0 +1,50 @@ +// A shot a bot was told about: where it came from, where it went, its per-type battle strengths +// and when it was fired. BotSenses keeps them in its incoming-fire list (+84) and, per shooter, +// in its attacker map (+100); BotMain::event_projectile hands them over. +// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIKnowledge/FireObject.cpp (FILE symbol +// beside 0x2D8710, between DangerObject.cpp and Information.cpp); constructors 0x2D8090 / +// 0x2D8280, destructors 0x2D8470 / 0x2D84A0 (not virtual), isWithinRadius 0x2D84D0, +// getBattleStrength 0x2D86B0. Size 0x2C (ia-32). + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_FIREOBJECT_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIKNOWLEDGE_FIREOBJECT_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class FireObject +{ +public: + // ELF 0x2D8090. Copies IAISettings::getNBattleStrengths() floats from `strengths` into an owned + // array (checkPointer(new float[n])). + FireObject(Vec3 origin, Vec3 target, float* strengths, bool direct, double time, float decay); + ~FireObject(); // ELF 0x2D8470: delete[] the strengths + + // ELF 0x2D84D0: |distance of `position` from the shot's XZ line| <= radius. + bool isWithinRadius(const Vec3& position, float radius); + // ELF 0x2D86B0: strengths[type] / ((float)(now - time) * decay + 1). + float getBattleStrength(int type); + + bool isDirect() const { return m_direct; } // [INFERRED] inline reader (BotSenses reads +0) + double getTime() const { return m_time; } // [INFERRED] inline reader (BotSenses reads +0x20) + // [INFERRED] inline reader: FireDanger::getPosition copies +0x08..+0x10 (ELF 0x220623). + const Vec3& getOrigin() const { return m_origin; } + const Vec3& getTarget() const { return m_target; } // [INFERRED] inline reader (SensingAgent::evaluateFireObjects reads +0x14) + +private: + /* +0x00 */ bool m_direct; // updateFireObjects weights a direct shot x10 + /* +0x04 */ float* m_strengths; // new float[getNBattleStrengths()] + /* +0x08 */ Vec3 m_origin; + /* +0x14 */ Vec3 m_target; + /* +0x20 */ double m_time; + /* +0x28 */ float m_decay; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_FIREOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp index c88b85a17..ca0ca7460 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp @@ -1,6 +1,10 @@ #include "IPIArmament.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EC6C0, __tcf_0 0x2EC720, _GLOBAL__I 0x2EC750). +#include + #include "Information.h" #include "InformationFactory.h" #include "WeaponInfo.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp new file mode 100644 index 000000000..4e3b73c1d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp @@ -0,0 +1,64 @@ +// IPIArmamentDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2EC850..0x2ECD44; the +// inline slots are in IPIArmamentDummy.h. + +#include "IPIArmamentDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2ECC70, __tcf_0 0x2ECCD0, _GLOBAL__I 0x2ECD00). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EC850 / 0x2EC950. The base gets no information. The member is zeroed (the shipped Mat4 +// member construction) and then copied. +IPIArmamentDummy::IPIArmamentDummy(Mat4& transformation) + : IPIArmament(0) +{ + for (int i = 0; i < 16; ++i) + m_transformation.m[i] = 0.0f; + m_transformation = transformation; +} + +// ELF 0x2ECA50 / 0x2ECAB0 / 0x2ECB10: nothing of its own; the base frees the weapon list. +IPIArmamentDummy::~IPIArmamentDummy() +{ +} + +// ELF 0x2ECB80: the transformation's third row; always true. +bool IPIArmamentDummy::getDirection(Bot* /*bot*/, Vec3& direction) +{ + direction.x = m_transformation.m[8]; + direction.y = m_transformation.m[9]; + direction.z = m_transformation.m[10]; + return true; +} + +// ELF 0x2ECBB0. Despite the name it STORES the given matrix into the member (the argument is +// only read); always true. Shipped behaviour. +bool IPIArmamentDummy::getTransformation(Bot* /*bot*/, Mat4& transformation) +{ + m_transformation = transformation; + return true; +} + +// ELF 0x2ECC40: empty. +void IPIArmamentDummy::setTime() +{ +} + +// ELF 0x2ECC50: empty. +void IPIArmamentDummy::setTime(float /*time*/) +{ +} + +// ELF 0x2ECC60: never anti-aircraft. +int IPIArmamentDummy::isAntiAircraft() const +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.h new file mode 100644 index 000000000..ab71c7d84 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.h @@ -0,0 +1,46 @@ +// Placeholder armament plug-in that is not backed by an engine object: it keeps one weapon +// transformation of its own and has no weapons. getWeapon / getWeapons (+7 / +8) stay pure, so +// the class is abstract; nothing in libaidll.so constructs it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2EC850..0x2ECD44, vtable 0x4BEA40 (16 slots); +// FILE symbol IPIArmamentDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTDUMMY_H + +#include "IPIArmament.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Bot; + +class IPIArmamentDummy : public IPIArmament +{ +public: + // No information; the weapon transformation starts as `transformation`. + explicit IPIArmamentDummy(Mat4& transformation); + virtual ~IPIArmamentDummy(); + + virtual void setTime(); // +3 + virtual void setActiveWeapon(int, int) {} // +6 ELF 0x2ECD20 + virtual int isAntiAircraft() const; // +11 + virtual void updateWeapons() {} // +12 ELF 0x2ECD40 + virtual void rearm(WeaponInfo*, float, int) {} // +13 ELF 0x2ECD30 + + // Non-virtual. Both answer true for any bot. + bool getDirection(Bot* bot, Vec3& direction); + bool getTransformation(Bot* bot, Mat4& transformation); + void setTime(float time); + +protected: + // ELF layout; sizeof 0x58. + /* +0x18 */ Mat4 m_transformation; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp new file mode 100644 index 000000000..2e5daaf89 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp @@ -0,0 +1,84 @@ +// IPIArmamentKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2ECD50..0x2ED14E; vtable +// 0x4BEAE0 (17 slots: IPIArmament's 16 plus updateWeaponsInternal()). + +#include "IPIArmamentKnown.h" + +#include "WeaponInfo.h" +#include "WeaponInfoManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// 0x2ECD50: marks the records stale, then builds them at once (both calls direct). +IPIArmamentKnown::IPIArmamentKnown(Information* information) + : IPIArmament(information) +{ + m_activeWeapon = 0; // [CHOSEN] + IPIArmamentKnown::updateWeapons(); + IPIArmamentKnown::updateWeaponsInternal(); +} + +// 0x2ECDF0: frees every weapon record (no -1 test, as in IPIArmament::updateWeaponsInternal), +// then the base releases the vector. +IPIArmamentKnown::~IPIArmamentKnown() +{ + for (std::vector::iterator it = m_weapons.begin(); it != m_weapons.end(); ++it) + WeaponInfoManager::m_instance->freeInformation(*it); +} + +// 0x2ED0C0: rebuilds stale records, then lets every existing record refresh itself. +void IPIArmamentKnown::setTime(double /*time*/) +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + for (unsigned int i = 0; i < m_weapons.size(); ++i) + { + if (m_weapons[i] == static_cast(-1)) + continue; + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation(m_weapons[i]); + if (weapon) + weapon->update(); // +2 + } +} + +// 0x2ECFE0 (unchecked index). +unsigned int IPIArmamentKnown::getWeapon(int index) +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + return m_weapons[index]; +} + +// 0x2ED010. +std::vector& IPIArmamentKnown::getWeapons() +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + return m_weapons; +} + +// 0x2ED040. +int IPIArmamentKnown::getActiveWeapon() +{ + if (m_weaponsStale) + updateWeaponsInternal(); // +16 + return m_activeWeapon; +} + +// 0x2ED070. +void IPIArmamentKnown::updateWeapons() +{ + m_weaponsStale = true; +} + +// 0x2ED080: the base rebuild with known (not real) weapon records. +void IPIArmamentKnown::updateWeaponsInternal() +{ + IPIArmament::updateWeaponsInternal(false); + m_weaponsStale = false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.h new file mode 100644 index 000000000..8b96eb554 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.h @@ -0,0 +1,40 @@ +// Armament information about an object of another side: the weapon records are rebuilt lazily +// (after updateWeapons marks them stale) and refreshed on every setTime. +// [INFERRED] Source placement beside IPIArmamentReal. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTKNOWN_H + +#include "IPIArmament.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIArmamentKnown : public IPIArmament +{ +public: + explicit IPIArmamentKnown(Information* information); + virtual ~IPIArmamentKnown(); + + virtual void setTime(double time); // +4 + virtual unsigned int getWeapon(int index); // +7 + virtual std::vector& getWeapons(); // +8 + virtual void updateWeapons(); // +12 - marks stale + // +16, the class's own slot: rebuilds the weapon records as known ones. + virtual void updateWeaponsInternal(); + + // Non-virtual; the vtable keeps IPIArmament::getActiveWeapon (+5). + int getActiveWeapon(); + +private: + /* +0x18 */ bool m_weaponsStale; // [INFERRED] name + // Read by getActiveWeapon, written by no audited body (retail reads it uninitialised). + // [CHOSEN, not recovered] zeroed by the constructor here. + /* +0x1C */ int m_activeWeapon; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIARMAMENTKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp new file mode 100644 index 000000000..29b732953 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp @@ -0,0 +1,333 @@ +// IPIControlInfo forwarders. Recovered from libaidll.so 1.5.3153 0x2ED380..0x2EDD50: every +// function is the same 0x30-byte shape, +// mov 0x8(%ebp),%eax; mov 0x4(%eax),%eax; mov 0x20(%eax),%eax; call *0x88(vtbl); +// [push the one reference argument]; call *slot(vtbl); [movzbl %al for the bool ones] +// so the return value (eax, edx:eax for the 64-bit masks, st0 for floats) passes through. + +#include "IPIControlInfo.h" + +#include "Information.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Information +0x20 (the owning AI object), then IAIObject +0x88. +inline IAIObjectControlInfo* controlInfoOf(Information* information) +{ + return information->getAIObject()->getControlInfo(); +} + +} // anonymous namespace + +// ELF 0x2ED380: plug-in slot +0x18. +unsigned long long IPIControlInfo::getDriveControls() +{ + return controlInfoOf(m_information)->getDriveControls(); +} + +// ELF 0x2ED3B0: plug-in slot +0x24. +unsigned long long IPIControlInfo::getAimControls() +{ + return controlInfoOf(m_information)->getAimControls(); +} + +// ELF 0x2ED3E0: plug-in slot +0x30. +unsigned long long IPIControlInfo::getLookControls() +{ + return controlInfoOf(m_information)->getLookControls(); +} + +// ELF 0x2ED410: plug-in slot +0x3C. +float IPIControlInfo::getThrottleSensitivity() +{ + return controlInfoOf(m_information)->getThrottleSensitivity(); +} + +// ELF 0x2ED440: plug-in slot +0x40. +float IPIControlInfo::getPitchSensitivity() +{ + return controlInfoOf(m_information)->getPitchSensitivity(); +} + +// ELF 0x2ED470: plug-in slot +0x7C. +float IPIControlInfo::getLookHorizontalSensitivity() +{ + return controlInfoOf(m_information)->getLookHorizontalSensitivity(); +} + +// ELF 0x2ED4A0: plug-in slot +0x78. +float IPIControlInfo::getLookVerticalSensitivity() +{ + return controlInfoOf(m_information)->getLookVerticalSensitivity(); +} + +// ELF 0x2ED4D0: plug-in slot +0x44. +float IPIControlInfo::getRollSensitivity() +{ + return controlInfoOf(m_information)->getRollSensitivity(); +} + +// ELF 0x2ED500: plug-in slot +0x48. +float IPIControlInfo::getYawSensitivity() +{ + return controlInfoOf(m_information)->getYawSensitivity(); +} + +// ELF 0x2ED530: plug-in slot +0x4C. +float IPIControlInfo::getProportionalConstant() +{ + return controlInfoOf(m_information)->getProportionalConstant(); +} + +// ELF 0x2ED560: plug-in slot +0x50. +float IPIControlInfo::getDerivativeConstant() +{ + return controlInfoOf(m_information)->getDerivativeConstant(); +} + +// ELF 0x2ED590: plug-in slot +0x54. +float IPIControlInfo::getAngleSpeedConstant() +{ + return controlInfoOf(m_information)->getAngleSpeedConstant(); +} + +// ELF 0x2ED5C0: plug-in slot +0x58. +float IPIControlInfo::getThrottleLookAhead() +{ + return controlInfoOf(m_information)->getThrottleLookAhead(); +} + +// ELF 0x2ED5F0: plug-in slot +0x5C. +float IPIControlInfo::getPitchLookAhead() +{ + return controlInfoOf(m_information)->getPitchLookAhead(); +} + +// ELF 0x2ED620: plug-in slot +0x84. +float IPIControlInfo::getLookHorizontalLookAhead() +{ + return controlInfoOf(m_information)->getLookHorizontalLookAhead(); +} + +// ELF 0x2ED650: plug-in slot +0x80. +float IPIControlInfo::getLookVerticalLookAhead() +{ + return controlInfoOf(m_information)->getLookVerticalLookAhead(); +} + +// ELF 0x2ED680: plug-in slot +0x60. +float IPIControlInfo::getRollLookAhead() +{ + return controlInfoOf(m_information)->getRollLookAhead(); +} + +// ELF 0x2ED6B0: plug-in slot +0x64. +float IPIControlInfo::getYawLookAhead() +{ + return controlInfoOf(m_information)->getYawLookAhead(); +} + +// ELF 0x2ED6E0: plug-in slot +0x68. +float IPIControlInfo::getThrottleScale() +{ + return controlInfoOf(m_information)->getThrottleScale(); +} + +// ELF 0x2ED710: plug-in slot +0x6C. +float IPIControlInfo::getPitchScale() +{ + return controlInfoOf(m_information)->getPitchScale(); +} + +// ELF 0x2ED740: plug-in slot +0x8C. +float IPIControlInfo::getLookHorizontalScale() +{ + return controlInfoOf(m_information)->getLookHorizontalScale(); +} + +// ELF 0x2ED770: plug-in slot +0x88. +float IPIControlInfo::getLookVerticalScale() +{ + return controlInfoOf(m_information)->getLookVerticalScale(); +} + +// ELF 0x2ED7A0: plug-in slot +0x70. +float IPIControlInfo::getRollScale() +{ + return controlInfoOf(m_information)->getRollScale(); +} + +// ELF 0x2ED7D0: plug-in slot +0x74. +float IPIControlInfo::getYawScale() +{ + return controlInfoOf(m_information)->getYawScale(); +} + +// ELF 0x2ED800: plug-in slot +0x1C. +io::PlayerInputMap IPIControlInfo::getDriveThrottleControl() +{ + return controlInfoOf(m_information)->getDriveThrottleControl(); +} + +// ELF 0x2ED830: plug-in slot +0x20. +io::PlayerInputMap IPIControlInfo::getDriveTurnControl() +{ + return controlInfoOf(m_information)->getDriveTurnControl(); +} + +// ELF 0x2ED860: plug-in slot +0x28. +io::PlayerInputMap IPIControlInfo::getAimVerticalControl() +{ + return controlInfoOf(m_information)->getAimVerticalControl(); +} + +// ELF 0x2ED890: plug-in slot +0x2C. +io::PlayerInputMap IPIControlInfo::getAimHorizontalControl() +{ + return controlInfoOf(m_information)->getAimHorizontalControl(); +} + +// ELF 0x2ED8C0: plug-in slot +0x34. +io::PlayerInputMap IPIControlInfo::getLookVerticalControl() +{ + return controlInfoOf(m_information)->getLookVerticalControl(); +} + +// ELF 0x2ED8F0: plug-in slot +0x38. +io::PlayerInputMap IPIControlInfo::getLookHorizontalControl() +{ + return controlInfoOf(m_information)->getLookHorizontalControl(); +} + +// ELF 0x2ED920: plug-in slot +0x90. +float IPIControlInfo::getMaxSpeedBumpinessFallOff() +{ + return controlInfoOf(m_information)->getMaxSpeedBumpinessFallOff(); +} + +// ELF 0x2ED950: plug-in slot +0x94. +float IPIControlInfo::getCameraRelativeDofRotationOffset() const +{ + return controlInfoOf(m_information)->getCameraRelativeDofRotationOffset(); +} + +// ELF 0x2ED980: plug-in slot +0x98. +const Vec3& IPIControlInfo::getCameraRelativeMinRotation() const +{ + return controlInfoOf(m_information)->getCameraRelativeMinRotation(); +} + +// ELF 0x2ED9B0: plug-in slot +0x9C. +const Vec3& IPIControlInfo::getCameraRelativeMaxRotation() const +{ + return controlInfoOf(m_information)->getCameraRelativeMaxRotation(); +} + +// ELF 0x2ED9E0: plug-in slot +0xA0. +void IPIControlInfo::getCameraRelativeRotation(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraRelativeRotation(out); +} + +// ELF 0x2EDA10: plug-in slot +0xA4. +const Mat4& IPIControlInfo::getCameraTransformation() const +{ + return controlInfoOf(m_information)->getCameraTransformation(); +} + +// ELF 0x2EDA40: plug-in slot +0xA8. +void IPIControlInfo::getCameraBaseTransformation(Mat4& out) const +{ + controlInfoOf(m_information)->getCameraBaseTransformation(out); +} + +// ELF 0x2EDA70: plug-in slot +0xAC. +void IPIControlInfo::getCameraBaseRight(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBaseRight(out); +} + +// ELF 0x2EDAA0: plug-in slot +0xB0. +void IPIControlInfo::getCameraBaseUp(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBaseUp(out); +} + +// ELF 0x2EDAD0: plug-in slot +0xB4. +void IPIControlInfo::getCameraBaseDof(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBaseDof(out); +} + +// ELF 0x2EDB00: plug-in slot +0xB8. +void IPIControlInfo::getCameraBasePos(Vec3& out) const +{ + controlInfoOf(m_information)->getCameraBasePos(out); +} + +// ELF 0x2EDB30: plug-in slot +0xBC. +bool IPIControlInfo::validateCameraDirection(const Vec3& direction) const +{ + return controlInfoOf(m_information)->validateCameraDirection(direction); +} + +// ELF 0x2EDB70: plug-in slot +0xC0. +bool IPIControlInfo::validateCameraDirectionYaw(const Vec3& direction) const +{ + return controlInfoOf(m_information)->validateCameraDirectionYaw(direction); +} + +// ELF 0x2EDBB0: plug-in slot +0xC4. +bool IPIControlInfo::validateCameraDirectionPitch(const Vec3& direction) const +{ + return controlInfoOf(m_information)->validateCameraDirectionPitch(direction); +} + +// ELF 0x2EDBF0: plug-in slot +0xC8. +bool IPIControlInfo::validateCameraDirectionByPos(const Vec3& position) const +{ + return controlInfoOf(m_information)->validateCameraDirectionByPos(position); +} + +// ELF 0x2EDC30: plug-in slot +0xCC. +float IPIControlInfo::getMaxClimbAngle() +{ + return controlInfoOf(m_information)->getMaxClimbAngle(); +} + +// ELF 0x2EDC60: plug-in slot +0xD0. +float IPIControlInfo::getMaxRollAngle() +{ + return controlInfoOf(m_information)->getMaxRollAngle(); +} + +// ELF 0x2EDC90: plug-in slot +0xD4. +io::PlayerInputMap IPIControlInfo::getDriveRollControl() +{ + return controlInfoOf(m_information)->getDriveRollControl(); +} + +// ELF 0x2EDCC0: plug-in slot +0xD8. +io::PlayerInputMap IPIControlInfo::getDrivePitchControl() +{ + return controlInfoOf(m_information)->getDrivePitchControl(); +} + +// ELF 0x2EDCF0: plug-in slot +0xDC. +io::PlayerInputMap IPIControlInfo::getAimThrottleControl() +{ + return controlInfoOf(m_information)->getAimThrottleControl(); +} + +// ELF 0x2EDD20: plug-in slot +0xE0. +io::PlayerInputMap IPIControlInfo::getAimRollControl() +{ + return controlInfoOf(m_information)->getAimRollControl(); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h index 817f38cd4..1bf3be2e2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h @@ -1,10 +1,14 @@ -// Control information plug-in; adds no virtual methods to InformationPlugIn. -// [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding IPIControlInfo operation. +// Control information plug-in: the AI-side view of an object's control template (input maps, +// regulator constants, camera limits). Every accessor reads through to the engine object. +// ELF: vtable 0x4B7450; the 51 non-virtual forwarders 0x2ED380..0x2EDD50 sit between +// IPIArmamentDummy.cpp and IPICover.cpp (no FILE symbol: no static initialiser), hence +// IPIControlInfo.cpp. #ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPICONTROLINFO_H #define AI_AIDLL_AI_AIKNOWLEDGE_IPICONTROLINFO_H #include "InformationPlugIn.h" +#include "Information.h" // callers rely on it (E, mac-metal bd97c30) +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // io::PlayerInputMap, Vec3, Mat4 namespace dice { namespace hfe { namespace ai { @@ -21,6 +25,62 @@ class IPIControlInfo : public InformationPlugIn // through to the engine object on every call, so there is nothing to refresh. virtual void setTime() {} virtual void setTime(double /*time*/) {} + + // Non-virtual forwarders, out of line in the image. Each body is + // `m_information(+4)->m_object(+0x20)->getControlInfo()(IAIObject +0x88)->slot()`, the + // arguments passed through unchanged (IAIObjectControlInfo slot named on the right). + // Constness follows the mangled names: only the camera block is const. + unsigned long long getDriveControls(); // ELF 0x2ED380 -> slot +0x18 + unsigned long long getAimControls(); // ELF 0x2ED3B0 -> slot +0x24 + unsigned long long getLookControls(); // ELF 0x2ED3E0 -> slot +0x30 + float getThrottleSensitivity(); // ELF 0x2ED410 -> slot +0x3C + float getPitchSensitivity(); // ELF 0x2ED440 -> slot +0x40 + float getLookHorizontalSensitivity(); // ELF 0x2ED470 -> slot +0x7C + float getLookVerticalSensitivity(); // ELF 0x2ED4A0 -> slot +0x78 + float getRollSensitivity(); // ELF 0x2ED4D0 -> slot +0x44 + float getYawSensitivity(); // ELF 0x2ED500 -> slot +0x48 + float getProportionalConstant(); // ELF 0x2ED530 -> slot +0x4C + float getDerivativeConstant(); // ELF 0x2ED560 -> slot +0x50 + float getAngleSpeedConstant(); // ELF 0x2ED590 -> slot +0x54 + float getThrottleLookAhead(); // ELF 0x2ED5C0 -> slot +0x58 + float getPitchLookAhead(); // ELF 0x2ED5F0 -> slot +0x5C + float getLookHorizontalLookAhead(); // ELF 0x2ED620 -> slot +0x84 + float getLookVerticalLookAhead(); // ELF 0x2ED650 -> slot +0x80 + float getRollLookAhead(); // ELF 0x2ED680 -> slot +0x60 + float getYawLookAhead(); // ELF 0x2ED6B0 -> slot +0x64 + float getThrottleScale(); // ELF 0x2ED6E0 -> slot +0x68 + float getPitchScale(); // ELF 0x2ED710 -> slot +0x6C + float getLookHorizontalScale(); // ELF 0x2ED740 -> slot +0x8C + float getLookVerticalScale(); // ELF 0x2ED770 -> slot +0x88 + float getRollScale(); // ELF 0x2ED7A0 -> slot +0x70 + float getYawScale(); // ELF 0x2ED7D0 -> slot +0x74 + io::PlayerInputMap getDriveThrottleControl(); // ELF 0x2ED800 -> slot +0x1C + io::PlayerInputMap getDriveTurnControl(); // ELF 0x2ED830 -> slot +0x20 + io::PlayerInputMap getAimVerticalControl(); // ELF 0x2ED860 -> slot +0x28 + io::PlayerInputMap getAimHorizontalControl(); // ELF 0x2ED890 -> slot +0x2C + io::PlayerInputMap getLookVerticalControl(); // ELF 0x2ED8C0 -> slot +0x34 + io::PlayerInputMap getLookHorizontalControl(); // ELF 0x2ED8F0 -> slot +0x38 + float getMaxSpeedBumpinessFallOff(); // ELF 0x2ED920 -> slot +0x90 + float getCameraRelativeDofRotationOffset() const; // ELF 0x2ED950 -> slot +0x94 + const Vec3& getCameraRelativeMinRotation() const; // ELF 0x2ED980 -> slot +0x98 + const Vec3& getCameraRelativeMaxRotation() const; // ELF 0x2ED9B0 -> slot +0x9C + void getCameraRelativeRotation(Vec3& out) const; // ELF 0x2ED9E0 -> slot +0xA0 + const Mat4& getCameraTransformation() const; // ELF 0x2EDA10 -> slot +0xA4 + void getCameraBaseTransformation(Mat4& out) const; // ELF 0x2EDA40 -> slot +0xA8 + void getCameraBaseRight(Vec3& out) const; // ELF 0x2EDA70 -> slot +0xAC + void getCameraBaseUp(Vec3& out) const; // ELF 0x2EDAA0 -> slot +0xB0 + void getCameraBaseDof(Vec3& out) const; // ELF 0x2EDAD0 -> slot +0xB4 + void getCameraBasePos(Vec3& out) const; // ELF 0x2EDB00 -> slot +0xB8 + bool validateCameraDirection(const Vec3& direction) const; // ELF 0x2EDB30 -> slot +0xBC + bool validateCameraDirectionYaw(const Vec3& direction) const; // ELF 0x2EDB70 -> slot +0xC0 + bool validateCameraDirectionPitch(const Vec3& direction) const; // ELF 0x2EDBB0 -> slot +0xC4 + bool validateCameraDirectionByPos(const Vec3& position) const; // ELF 0x2EDBF0 -> slot +0xC8 + float getMaxClimbAngle(); // ELF 0x2EDC30 -> slot +0xCC + float getMaxRollAngle(); // ELF 0x2EDC60 -> slot +0xD0 + io::PlayerInputMap getDriveRollControl(); // ELF 0x2EDC90 -> slot +0xD4 + io::PlayerInputMap getDrivePitchControl(); // ELF 0x2EDCC0 -> slot +0xD8 + io::PlayerInputMap getAimThrottleControl(); // ELF 0x2EDCF0 -> slot +0xDC + io::PlayerInputMap getAimRollControl(); // ELF 0x2EDD20 -> slot +0xE0 }; } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp index db04b4f29..c70b7f821 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPICover.cpp @@ -2,6 +2,10 @@ #include "IPICover.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EE3F0, __tcf_0 0x2EE450, _GLOBAL__I 0x2EE480). +#include + #include "Information.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp index 3f2e45312..7d099a7ce 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp @@ -3,6 +3,10 @@ #include "IPIMobile.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EEAF0, __tcf_0 0x2EEB50, _GLOBAL__I 0x2EEB80). +#include + #include "Information.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h index 9aefdcb60..cfc2498d2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h @@ -57,6 +57,11 @@ class IPIMobile : public InformationPlugIn float getAvoidCollisionLookAhead() const; float getSprintStamina() const; + // [INFERRED] inline reader of +0x08: BFPathfindingCourier::getLastValidSquadleaderPosition + // (ELF 0x2E83BD) reads `mobile+8 != -1` and copies +0x10..+0x18 without a call; also + // BotNavigation::reset / initPathfinding (ELF 0x190A70 / 0x1902B0) read the infantry + // polygon and island (+0x08 / +0x0C) directly. + const ValidPos& getLastValidInfantryPos() const { return m_lastValidInfantryPos; } const ValidPos& getLastValidPosition() const; const ValidPos& getLastValidPosition(int vehicleNumber) const; void setLastValidInfantryPosInternal(const ValidPos& position); diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp new file mode 100644 index 000000000..1aacf4d74 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp @@ -0,0 +1,81 @@ +// IPIMobileDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2EEBA0..0x2EEFCE; the inline +// slots are in IPIMobileDummy.h. + +#include "IPIMobileDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EEE80, __tcf_0 0x2EEEE0, _GLOBAL__I 0x2EEF10). +#include + +#include "Information.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // anonymous namespace + +// ELF 0x2EEBA0 / 0x2EEC30: the speed is copied, the rotational speed zeroed, then the (empty) +// polygon update. +IPIMobileDummy::IPIMobileDummy(Information* information, Vec3& speed) + : IPIMobile(information), m_speed(speed) +{ + m_rotationalSpeed.x = 0.0f; + m_rotationalSpeed.y = 0.0f; + m_rotationalSpeed.z = 0.0f; + updateCurrentPolygon(); +} + +// ELF 0x2EECC0 / 0x2EECE0 / 0x2EED00: nothing of its own. +IPIMobileDummy::~IPIMobileDummy() +{ +} + +// ELF 0x2EED40: never a valid position; `position` is untouched. +bool IPIMobileDummy::getValidPosition(Vec3& /*position*/) +{ + return false; +} + +// ELF 0x2EED50: the information's position (Information +12). +void IPIMobileDummy::getPositionEstimate(Vec3& position) +{ + position = m_information->getPosition(); +} + +// ELF 0x2EED90: the information's position, moved by the speed (through +7) over the time from +// now to `time`. +void IPIMobileDummy::getPositionEstimate(double time, Vec3& position) +{ + position = m_information->getPosition(); + const float dt = static_cast(time - gameTime()); + const Vec3& speed = getSpeed(); + position.x += speed.x * dt; + position.y += speed.y * dt; + position.z += speed.z * dt; +} + +// ELF 0x2EEE30: setTime(double) through the vtable with the game time. +void IPIMobileDummy::setTime() +{ + setTime(gameTime()); +} + +// ELF 0x2EEE70. Empty; the image keeps a 0x148-byte frame and no code (the body's locals were +// compiled out). +void IPIMobileDummy::updateCurrentPolygon() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h new file mode 100644 index 000000000..aeb3e58e9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.h @@ -0,0 +1,54 @@ +// Placeholder mobile plug-in that is not backed by an engine object: it keeps a fixed speed and a +// zero rotational speed and estimates positions from its information's position. The sound, +// sector, portal and valid-position slots (+10, +13..+16) stay pure, so the class is abstract; +// nothing in libaidll.so constructs it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2EEBA0..0x2EEFCE, vtable 0x4BED00 (18 slots); +// FILE symbol IPIMobileDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIMOBILEDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIMOBILEDUMMY_H + +#include + +#include "IPIMobile.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIMobileDummy : public IPIMobile +{ +public: + // The plug-in of `information`, moving at `speed`. + IPIMobileDummy(Information* information, Vec3& speed); + virtual ~IPIMobileDummy(); + + virtual void setTime(); // +3 + virtual void setTime(double) {} // +4 ELF 0x2EEF50 + virtual void setHasContact() {} // +5 ELF 0x2EEF30 + virtual void setLostContact() {} // +6 ELF 0x2EEF40 + virtual const Vec3& getSpeed() { return m_speed; } // +7 ELF 0x2EEF60 + virtual const Vec3& getRotationalSpeed() { return m_rotationalSpeed; } // +8 ELF 0x2EEF70 + virtual float getSpeedMagnitude() // +9 ELF 0x2EEF80 + { + return std::sqrt(m_speed.x * m_speed.x + m_speed.y * m_speed.y + m_speed.z * m_speed.z); + } + virtual void getPositionEstimate(Vec3& position); // +11 + virtual void getPositionEstimate(double time, Vec3& position); // +12 + // +17, new in this class. [INFERRED] bool: the body materializes 0 and has no caller. + virtual bool getValidPosition(Vec3& position); + + // Non-virtual; empty in the image. + void updateCurrentPolygon(); + +protected: + // ELF layout; sizeof 0x60. + /* +0x48 */ Vec3 m_speed; + /* +0x54 */ Vec3 m_rotationalSpeed; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIMOBILEDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp index 22e42b3e6..35d73c7bf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp @@ -2,6 +2,10 @@ #include "IPIMobileKnown.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EF6C0, __tcf_0 0x2EF720, _GLOBAL__I 0x2EF750). +#include + #include #include "Information.h" @@ -111,6 +115,7 @@ void IPIMobileKnown::getPositionEstimate(Vec3& position) position); } +// ELF 0x2EF4B0. void IPIMobileKnown::getPositionEstimate(double time, Vec3& position) { #if defined(_MSC_VER) diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp index b9be8dafd..74051148e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp @@ -2,6 +2,10 @@ #include "IPIMobileReal.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EFB80, __tcf_0 0x2EFBE0, _GLOBAL__I 0x2EFC10). +#include + #include #include "Information.h" @@ -66,6 +70,7 @@ void IPIMobileReal::getPositionEstimate(Vec3& position) position = m_information->getPosition(); } +// ELF 0x2EF900. The information's position moved by the speed over (time - now). void IPIMobileReal::getPositionEstimate(double time, Vec3& position) { position = m_information->getPosition(); diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h index 37bdb0c12..5c534b0ab 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h @@ -40,7 +40,9 @@ class IPIPhysical : public InformationPlugIn virtual Vec3 getSphereLocalOffset() const = 0; // +12 by value (corrected) virtual float getSmallestRadius() const = 0; // +13 - virtual void getSubSpheres2d(std::vector&) const = 0; // +14 + // float: IPIPhysicalReal/Known (ELF 0x2F0CA0 / 0x2F05F0) leave the engine call's x87 result + // as theirs (no pop), and IPIPhysicalDummy (ELF 0x2F0000) loads 0.0f. + virtual float getSubSpheres2d(std::vector&) const = 0; // +14 float (corrected) virtual float getArmour(Vec3&) = 0; // +15 virtual float getBestArmour() = 0; // +16 virtual int getStrengthType() = 0; // +17 diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp new file mode 100644 index 000000000..d5043eef0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp @@ -0,0 +1,93 @@ +// IPIPhysicalDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2EFC50..0x2F018B; the inline +// slots are in IPIPhysicalDummy.h. + +#include "IPIPhysicalDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EFF40, __tcf_0 0x2EFFA0, _GLOBAL__I 0x2EFFD0). +#include +#include + +#include "Information.h" +#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EFC50 / 0x2EFCC0: the arguments in order; m_mod, m_inAir and m_inWater are not written. +IPIPhysicalDummy::IPIPhysicalDummy(Information* information, float health, + BoundingBox* boundingBox, LocalBoundingBox* localBoundingBox, + float radius, float armour, float bestArmour, + int strengthType, float volume, float mass, + bool touchingTerrain, int material) +{ + m_information = information; + m_health = health; + m_boundingBox = boundingBox; + m_localBoundingBox = localBoundingBox; + m_radius = radius; + m_armour = armour; + m_bestArmour = bestArmour; + m_strengthType = strengthType; + m_volume = volume; + m_mass = mass; + m_touchingTerrain = touchingTerrain; + m_material = material; +} + +// ELF 0x2EFD30 / 0x2EFD80 / 0x2EFDD0: deletes the bounding box, then the local bounding box +// (scalar deallocation, no visible destructor call; BoundingBox is incomplete here, as in +// IPICover). +IPIPhysicalDummy::~IPIPhysicalDummy() +{ + ::operator delete(m_boundingBox); + delete m_localBoundingBox; +} + +// ELF 0x2EFE30: setTime(double) through the vtable with the game time. +void IPIPhysicalDummy::setTime() +{ + setTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +// ELF 0x2EFE70. Ignores the time. Takes the health from the information's ENGINE object +// (IAIObject +0x94 physical; the dummy record's object is not tested) when its maximum health is +// positive, else zero, and sets the modifier to 0.5 + 0.5 * SCurve(health), as +// IPIPhysicalReal::setTime does. ELF comparison: a NaN maximum selects zero (PE not compared). +void IPIPhysicalDummy::setTime(double /*time*/) +{ + IAIObjectPhysical* const physical = m_information->getAIObject()->getPhysical(); // +0x94 + if (physical->getMaxHealth() > 0.0f) // +0x1C + m_health = physical->getHealth(); // +0x18 + else + m_health = 0.0f; + const float half = 0.5f; + m_mod = half; + m_mod = SCurve::calculate(m_health) * half + m_mod; +} + +// ELF 0x2EFEF0: the engine object's maximum health (IAIObjectPhysical +0x1C). +float IPIPhysicalDummy::getMaxHealth() +{ + return m_information->getAIObject()->getPhysical()->getMaxHealth(); +} + +// ELF 0x2EFF20. +int IPIPhysicalDummy::getMaterial() const +{ + return m_material; +} + +// ELF 0x2EFF30. Empty; the image keeps a 0x148-byte frame and no code (the body's locals were +// compiled out). +void IPIPhysicalDummy::setHealth(float /*health*/) +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h new file mode 100644 index 000000000..576cbc3f9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.h @@ -0,0 +1,86 @@ +// Placeholder physical plug-in that answers from values given at construction. It owns the +// bounding box and local bounding box it is given. The man-down slots (+21..+23) stay pure, so +// the class is abstract; nothing in libaidll.so constructs it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2EFC50..0x2F018B, vtable 0x4BEEE0 (27 slots); +// FILE symbol IPIPhysicalDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALDUMMY_H + +#include "IPIPhysical.h" +#include "../../../../Math/LocalBoundingBox.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIPhysicalDummy : public IPIPhysical +{ +public: + // Takes ownership of `boundingBox` and `localBoundingBox`. The modifier and the in-air and + // in-water flags are left as allocated. + IPIPhysicalDummy(Information* information, float health, BoundingBox* boundingBox, + LocalBoundingBox* localBoundingBox, float radius, float armour, + float bestArmour, int strengthType, float volume, float mass, + bool touchingTerrain, int material); + virtual ~IPIPhysicalDummy(); + + virtual void setTime(); // +3 + virtual void setTime(double time); // +4 + virtual float getHealth() const { return m_health; } // +5 ELF 0x2F0020 + virtual void setHealth(float health); // +6 + virtual float getMaxHealth(); // +7 + virtual float getMod() { return m_mod; } // +8 ELF 0x2F0030 + virtual BoundingBox* getBoundingBox() { return m_boundingBox; } // +9 ELF 0x2F0040 + virtual const LocalBoundingBox* getLocalBoundingBox() // +10 ELF 0x2F0050 + { + return m_localBoundingBox; + } + virtual float getRadius() { return m_radius; } // +11 ELF 0x2F0060 + virtual Vec3 getSphereLocalOffset() const // +12 ELF 0x2F0070 + { + if (m_localBoundingBox->m_derivedDataDirty) + m_localBoundingBox->calcRadius(); + return m_localBoundingBox->m_centre; + } + virtual float getSmallestRadius() const // +13 ELF 0x2F00D0 + { + if (m_localBoundingBox->m_derivedDataDirty) + m_localBoundingBox->calcRadius(); + return m_localBoundingBox->m_radiusFromCentre; + } + virtual float getSubSpheres2d(std::vector&) const { return 0.0f; } // +14 ELF 0x2F0000 + virtual float getArmour(Vec3&) { return m_armour; } // +15 ELF 0x2F0110 + virtual float getBestArmour() { return m_bestArmour; } // +16 ELF 0x2F0120 + virtual int getStrengthType() { return m_strengthType; } // +17 ELF 0x2F0130 + virtual float getVolume() { return m_volume; } // +18 ELF 0x2F0140 + virtual float getMass() { return m_mass; } // +19 ELF 0x2F0150 + virtual int getMaterial() const; // +20 + // +21..+23 (getManDownTimeLeft, getMaxManDownTime, getManDown) stay pure. + virtual bool isTouchingTerrain(Vec3&) const { return m_touchingTerrain; } // +24 ELF 0x2F0160 + virtual bool isInAir() const { return m_inAir; } // +25 ELF 0x2F0170 + virtual bool isInWater() const { return m_inWater; } // +26 ELF 0x2F0180 + +protected: + // ELF layout; sizeof 0x38. + /* +0x08 */ float m_mod; // set by setTime(double) + /* +0x0C */ float m_health; + /* +0x10 */ BoundingBox* m_boundingBox; // owned + /* +0x14 */ LocalBoundingBox* m_localBoundingBox; // owned + /* +0x18 */ float m_radius; + /* +0x1C */ float m_armour; + /* +0x20 */ float m_bestArmour; + /* +0x24 */ int m_strengthType; + /* +0x28 */ float m_volume; + /* +0x2C */ float m_mass; + /* +0x30 */ bool m_touchingTerrain; + /* +0x31 */ bool m_inAir; // no writer in the image + /* +0x32 */ bool m_inWater; // no writer in the image + /* +0x34 */ int m_material; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp new file mode 100644 index 000000000..db8e2647e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp @@ -0,0 +1,187 @@ +// IPIPhysicalKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2F0190..0x2F07CB; vtable +// 0x4BEFC0 (same 27 slots as IPIPhysicalReal's). The forwarders use the same IAIObjectPhysical +// slots as IPIPhysicalReal's. + +#include "IPIPhysicalKnown.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2F0690, __tcf_0 0x2F06F0, _GLOBAL__I 0x2F0720). +#include + +#include "Information.h" +#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAIObjectPhysical* physicalOf(Information* information) +{ + return information->getAIObject()->getPhysical(); // +0x94 +} + +} // anonymous namespace + +// 0x2F0190: flags false, terrain position zero; health and modifier stay as allocated. +IPIPhysicalKnown::IPIPhysicalKnown(Information* information) +{ + m_information = information; + m_touchingTerrain = false; + m_terrainPosition.x = 0.0f; + m_terrainPosition.y = 0.0f; + m_terrainPosition.z = 0.0f; + m_inAir = false; + m_inWater = false; + m_manDown = false; +} + +IPIPhysicalKnown::~IPIPhysicalKnown() +{ +} + +// 0x2F02B0. +void IPIPhysicalKnown::setTime() +{ + setTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +// 0x2F02F0. Caches man-down, the absolute health (zero unless the maximum is positive; a NaN +// maximum gives zero, the ELF comparison), the modifier 0.5 + 0.5 * SCurve(health) and the +// terrain/air/water state. +void IPIPhysicalKnown::setTime(double /*time*/) +{ + IAIObjectPhysical* const physical = physicalOf(m_information); + m_manDown = physical->getManDown(); // +0x68 + if (physical->getMaxHealth() > 0.0f) // +0x1C + m_health = physical->getHealth(); // +0x18 + else + m_health = 0.0f; + const float half = 0.5f; + m_mod = half; + m_mod = SCurve::calculate(m_health) * half + m_mod; + m_touchingTerrain = physical->isTouchingTerrain(m_terrainPosition); // +0x50 + m_inAir = physical->isInAir(); // +0x54 + m_inWater = physical->isInWater(); // +0x58 +} + +float IPIPhysicalKnown::getHealth() const +{ + return m_health; +} + +void IPIPhysicalKnown::setHealth(float health) +{ + m_health = health; +} + +float IPIPhysicalKnown::getMaxHealth() +{ + return physicalOf(m_information)->getMaxHealth(); // +0x1C +} + +float IPIPhysicalKnown::getMod() +{ + return m_mod; +} + +BoundingBox* IPIPhysicalKnown::getBoundingBox() +{ + return physicalOf(m_information)->getCurrentBoundingBox(); // +0x34 +} + +const LocalBoundingBox* IPIPhysicalKnown::getLocalBoundingBox() +{ + return physicalOf(m_information)->getLocalBoundingBox(); // +0x30 +} + +float IPIPhysicalKnown::getRadius() +{ + return physicalOf(m_information)->getRadius(); // +0x3C +} + +Vec3 IPIPhysicalKnown::getSphereLocalOffset() const +{ + return physicalOf(m_information)->getSphereLocalOffset(); // +0x40 +} + +float IPIPhysicalKnown::getSmallestRadius() const +{ + return physicalOf(m_information)->getSmallestRadius(); // +0x44 +} + +// ELF 0x2F05F0: forwards, returning the engine plug-in's answer. +float IPIPhysicalKnown::getSubSpheres2d(std::vector& out) const +{ + return physicalOf(m_information)->getSubSpheres2d(out); // +0x48 +} + +float IPIPhysicalKnown::getArmour(Vec3& direction) +{ + return physicalOf(m_information)->getArmour(direction); // +0x28 +} + +float IPIPhysicalKnown::getBestArmour() +{ + return physicalOf(m_information)->getBestArmour(); // +0x2C +} + +int IPIPhysicalKnown::getStrengthType() +{ + return physicalOf(m_information)->getStrType(); // +0x4C +} + +float IPIPhysicalKnown::getVolume() +{ + return physicalOf(m_information)->getVolume(); // +0x24 +} + +float IPIPhysicalKnown::getMass() +{ + return physicalOf(m_information)->getMass(); // +0x20 +} + +int IPIPhysicalKnown::getMaterial() const +{ + return physicalOf(m_information)->getMaterial(); // +0x5C +} + +float IPIPhysicalKnown::getManDownTimeLeft() const +{ + return physicalOf(m_information)->getManDownTimeLeft(); // +0x60 +} + +float IPIPhysicalKnown::getMaxManDownTime() const +{ + return physicalOf(m_information)->getMaxManDownTime(); // +0x64 +} + +bool IPIPhysicalKnown::getManDown() const +{ + return m_manDown; +} + +// 0x2F0770: the cached terrain position and flag. +bool IPIPhysicalKnown::isTouchingTerrain(Vec3& position) const +{ + position = m_terrainPosition; + return m_touchingTerrain; +} + +bool IPIPhysicalKnown::isInAir() const +{ + return m_inAir; +} + +bool IPIPhysicalKnown::isInWater() const +{ + return m_inWater; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h new file mode 100644 index 000000000..5a67b79a4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.h @@ -0,0 +1,60 @@ +// Physical information about an object of another side. Health, modifier and the terrain/air/ +// water/man-down flags are cached at each setTime; the shape and armour queries forward to the +// engine object's physical plug-in. Health is cached as the absolute value (InformationReal's +// counterpart answers a fraction). The constructor leaves health and modifier unset. +// [INFERRED] Source placement beside IPIPhysicalReal. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALKNOWN_H + +#include "IPIPhysical.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IPIPhysicalKnown : public IPIPhysical +{ +public: + explicit IPIPhysicalKnown(Information* information); + virtual ~IPIPhysicalKnown(); + + virtual void setTime(); // +3 - now + virtual void setTime(double time); // +4 + virtual float getHealth() const; // +5 - cached + virtual void setHealth(float health); // +6 - stores + virtual float getMaxHealth(); // +7 + virtual float getMod(); // +8 - cached + virtual BoundingBox* getBoundingBox(); // +9 + virtual const LocalBoundingBox* getLocalBoundingBox(); // +10 + virtual float getRadius(); // +11 + virtual Vec3 getSphereLocalOffset() const; // +12 + virtual float getSmallestRadius() const; // +13 + virtual float getSubSpheres2d(std::vector& out) const; // +14 + virtual float getArmour(Vec3& direction); // +15 + virtual float getBestArmour(); // +16 + virtual int getStrengthType(); // +17 + virtual float getVolume(); // +18 + virtual float getMass(); // +19 + virtual int getMaterial() const; // +20 + virtual float getManDownTimeLeft() const; // +21 + virtual float getMaxManDownTime() const; // +22 + virtual bool getManDown() const; // +23 - cached + virtual bool isTouchingTerrain(Vec3& position) const; // +24 - cached + virtual bool isInAir() const; // +25 - cached + virtual bool isInWater() const; // +26 - cached + +private: + /* +0x08 */ float m_mod; // not initialised by the constructor + /* +0x0C */ float m_health; // not initialised by the constructor + /* +0x10 */ bool m_touchingTerrain; + /* +0x14 */ Vec3 m_terrainPosition; + /* +0x20 */ bool m_inAir; + /* +0x21 */ bool m_inWater; + /* +0x22 */ bool m_manDown; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_IPIPHYSICALKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp index bc9a7eb78..29d76a6bd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp @@ -1,6 +1,10 @@ #include "IPIPhysicalReal.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2F0D60, __tcf_0 0x2F0DC0, _GLOBAL__I 0x2F0DF0). +#include + #include "Information.h" #include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) #include "../Main/CommonSingletonServer.h" @@ -104,9 +108,10 @@ float IPIPhysicalReal::getSmallestRadius() const return m_information->getAIObject()->getPhysical()->getSmallestRadius(); // +0x44 } -void IPIPhysicalReal::getSubSpheres2d(std::vector& out) const +// ELF 0x2F0CA0: forwards, returning the engine plug-in's answer. +float IPIPhysicalReal::getSubSpheres2d(std::vector& out) const { - m_information->getAIObject()->getPhysical()->getSubSpheres2d(out); // +0x48 + return m_information->getAIObject()->getPhysical()->getSubSpheres2d(out); // +0x48 } float IPIPhysicalReal::getArmour(Vec3& direction) diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h index 4b0b72cb4..52c8ccfbf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.h @@ -29,7 +29,7 @@ class IPIPhysicalReal : public IPIPhysical virtual float getRadius(); // +11 virtual Vec3 getSphereLocalOffset() const; // +12 virtual float getSmallestRadius() const; // +13 - virtual void getSubSpheres2d(std::vector& out) const; // +14 + virtual float getSubSpheres2d(std::vector& out) const; // +14 virtual float getArmour(Vec3& direction); // +15 virtual float getBestArmour(); // +16 virtual int getStrengthType(); // +17 diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp index de3480d97..190086947 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp @@ -3,6 +3,10 @@ // Retail deliberately omits null and bounds guards in these paths. #include "IPIUnit.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2F1CC0, __tcf_0 0x2F1D20, _GLOBAL__I 0x2F1D50). +#include + #include "Information.h" #include "IPIArmament.h" #include "IPIPhysical.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp index 961210f43..ccecdcaad 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp @@ -1,6 +1,10 @@ // [INFERRED] Source placement. #include "Information.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D9460, __tcf_0 0x2D94C0, _GLOBAL__I 0x2D94F0). +#include + #include "IPIArmament.h" #include "IPIControlInfo.h" #include "IPICover.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h index 0d25ae78e..d81e63a8e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h @@ -108,13 +108,20 @@ class Information IPIUnit* getUnit() const { return m_unit; } unsigned int getObjectTypeFlags() const { return m_objectTypeFlags; } float getStrength() const { return m_strength; } + // BotMain::updateBotVehicle (ELF 0x18BCC0) scales +0x10 inline (x0.75 / x1.3333334). + void setStrength(float strength) { m_strength = strength; } + // [INFERRED] name; SAIMap::updateInformation (ELF 0x3641F0) copies +0x14 into +0x10 inline. + float getBasicTemp() const { return m_basicTemp; } bool hasMobile() const { return m_mobile != nullptr; } IPIMobile* getMobile() const { return m_mobile; } + // [INFERRED] inline reader of +0x34 (InfoCoverPredicate 0x2E7E80 reads it without a call). + IPICover* getCover() const { return m_cover; } IAIObject* getAIObject() const { return m_object; } bool hasArmament() const { return m_armament != nullptr; } // [INFERRED] source-level inline accessor. Both retail images read the same +0x2C member in // InformationFactory::updateInformationPlugin before the virtual updateWeapons call. IPIArmament* getArmament() const { return m_armament; } + IPIControlInfo* getControlInfo() const { return m_controlInfo; } protected: /* +0x00 */ // vptr diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp new file mode 100644 index 000000000..529bab53a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp @@ -0,0 +1,136 @@ +// InformationDummy. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2D9520..0x2D9F3C; the +// inline slots are in InformationDummy.h. + +#include "InformationDummy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2D9D20, __tcf_0 0x2D9D80, _GLOBAL__I 0x2D9DB0). +#include + +#include + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +} // anonymous namespace + +// ELF 0x2D9520 / 0x2D9680. No owner, time -1. The transformation member is zeroed (the shipped +// Mat4 member construction) and then copied; the name is assigned after the side and types. +InformationDummy::InformationDummy(Vec3& position, Mat4& transformation, int side, + unsigned int types) + : Information(0, -1.0), m_position(position) +{ + for (int i = 0; i < 16; ++i) + m_transformation.m[i] = 0.0f; + m_transformation = transformation; + m_objectTypeFlags = types; + m_side = side; + m_name = "DummyInformation"; +} + +// ELF 0x2D97E0 / 0x2D98E0. Zeroed, set to identity, then the three rows are overwritten with +// (0,0,1), (0,1,0), (1,0,0) and the translation with the position. The name stays empty. +InformationDummy::InformationDummy(Vec3& position, int side, unsigned int types) + : Information(0, -1.0), m_position(position) +{ + for (int i = 0; i < 16; ++i) + m_transformation.m[i] = 0.0f; + m_transformation.m[0] = 1.0f; + m_transformation.m[5] = 1.0f; + m_transformation.m[10] = 1.0f; + m_transformation.m[15] = 1.0f; + + m_transformation.m[0] = 0.0f; + m_transformation.m[1] = 0.0f; + m_transformation.m[2] = 1.0f; + m_transformation.m[4] = 0.0f; + m_transformation.m[5] = 1.0f; + m_transformation.m[6] = 0.0f; + m_transformation.m[8] = 1.0f; + m_transformation.m[9] = 0.0f; + m_transformation.m[10] = 0.0f; + m_transformation.m[12] = m_position.x; + m_transformation.m[13] = m_position.y; + m_transformation.m[14] = m_position.z; + m_objectTypeFlags = types; + m_side = side; +} + +// ELF 0x2D99E0 / 0x2D9A50 / 0x2D9AC0: the name, then the base (which destroys the plug-ins). +InformationDummy::~InformationDummy() +{ +} + +// ELF 0x2D9CE0: the terrain's altitude at the position (IAITerrain +0xC). +float InformationDummy::getAltitude() +{ + return terrain()->getAltitude(m_position); +} + +// ELF 0x2D9B30. The lowest terrain altitude sampled along `direction` in sixth steps: the start, +// then from the second step on (the first step is added twice, as InformationReal does with its +// tenth steps). A direction no longer than one step samples only the start. +float InformationDummy::getAltitude(const Vec3& direction) +{ + Vec3 probe; + probe.x = 0.0f; + probe.y = 0.0f; + probe.z = 0.0f; + Vec3 step; + step.x = 0.0f; + step.y = 0.0f; + step.z = 0.0f; + const float length = + std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + probe = m_position; + float lowest = terrain()->getAltitude(probe); + + const float scale = 1.0f / 6.0f; + step.x = direction.x * scale; + step.y = direction.y * scale; + step.z = direction.z * scale; + const float stepLength = length / 6.0f; + probe.x += step.x; + probe.y += step.y; + probe.z += step.z; + float travelled = stepLength; + while (length > travelled) + { + probe.x += step.x; + probe.y += step.y; + probe.z += step.z; + const float altitude = terrain()->getAltitude(probe); + travelled += stepLength; + lowest = altitude > lowest ? lowest : altitude; + } + return lowest; +} + +// ELF 0x2D9CA0: no secondary objects; the iterator is reset to -1. +unsigned int InformationDummy::getSecondaryObject(int& iterator, int /*side*/) +{ + iterator = -1; + return 0xFFFFFFFFu; +} + +// ELF 0x2D9CC0: as getSecondaryObject. +unsigned int InformationDummy::getFirstSecondaryObject(int& iterator, int /*side*/) +{ + iterator = -1; + return 0xFFFFFFFFu; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.h new file mode 100644 index 000000000..cd3633eb1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationDummy.h @@ -0,0 +1,77 @@ +// Placeholder information record that is not backed by an engine object: it answers from its own +// position, transformation, side and name, and owns its plug-ins through Information. The +// contact slots (+6..+9) stay pure, so the class is abstract; nothing in libaidll.so constructs +// it or derives from it. +// Evidence: libaidll.so 1.5.3153 (ia-32) 0x2D9520..0x2D9F3C, vtable 0x4BDF80 (29 slots); +// FILE symbol InformationDummy.cpp. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONDUMMY_H +#define AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONDUMMY_H + +#include + +#include "Information.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class InformationDummy : public Information +{ +public: + // A dummy at `position` with `transformation`, of `side`, carrying the object types `types`; + // named "DummyInformation". + InformationDummy(Vec3& position, Mat4& transformation, int side, unsigned int types); + // A dummy at `position` with a fixed orientation (rows (0,0,1), (0,1,0), (1,0,0)) and an + // empty name. + InformationDummy(Vec3& position, int side, unsigned int types); + virtual ~InformationDummy(); + + virtual int getInformationSort() { return 2; } // +2 ELF 0x2D9DD0 + virtual bool setTime(double) { return false; } // +3 ELF 0x2D9E40 + virtual bool setTime(double, float) { return false; } // +4 ELF 0x2D9E50 + virtual double getTimeStamp() const { return 0.0f; } // +5 ELF 0x2D9E10 + // +6..+9 (addContact, removeContact, removeAllContacts, hasContact) stay pure. + virtual float getSecurity(double) { return 1.0f; } // +10 ELF 0x2D9E60 + virtual float getSecurity() { return 1.0f; } // +11 ELF 0x2D9E80 + virtual Vec3& getPosition() { return m_position; } // +12 ELF 0x2D9E30 + virtual float getAltitude(); // +13 + virtual float getAltitude(const Vec3& direction); // +14 + virtual Mat4& getTransformation() { return m_transformation; } // +15 ELF 0x2D9EA0 + virtual Vec3 getFaceing() // +16 ELF 0x2D9EB0 the third row + { + Vec3 facing; + facing.x = m_transformation.m[8]; + facing.y = m_transformation.m[9]; + facing.z = m_transformation.m[10]; + return facing; + } + virtual int getSide() const { return m_side; } // +17 ELF 0x2D9ED0 + + // New virtual slots. They hide Information's non-virtual forwarders of the same names. + virtual const std::string& getName() const { return m_name; } // +18 ELF 0x2D9F20 + virtual const std::string& getAIName() const { return m_name; } // +19 ELF 0x2D9F30 + virtual const std::string& getObjectTypeName() const { return m_name; } // +20 ELF 0x2D9EE0 + virtual unsigned int getHandle() const { return 0xFFFFFFFFu; } // +21 ELF 0x2D9DE0 + virtual bool isPrimary() const { return true; } // +22 ELF 0x2D9EF0 + virtual unsigned int getPrimaryObject(int) { return 0xFFFFFFFFu; } // +23 ELF 0x2D9F00 + virtual unsigned int getSecondaryObject(int& iterator, int side); // +24 + virtual unsigned int getFirstSecondaryObject(int& iterator, int side); // +25 + virtual int getFirstSecondaryObjectIterator() const { return -1; } // +26 ELF 0x2D9F10 + virtual bool getObjectSpawnerHolding() const { return false; } // +27 ELF 0x2D9DF0 + virtual unsigned int getObjectSpawner(int) const { return 0xFFFFFFFFu; } // +28 ELF 0x2D9E00 + +protected: + // ELF layout; sizeof 0x98. + /* +0x44 */ Vec3 m_position; + /* +0x50 */ Mat4 m_transformation; + /* +0x90 */ int m_side; + /* +0x94 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONDUMMY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp index 25ac28bbc..1f2ba1f65 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp @@ -2,18 +2,26 @@ #include "InformationFactory.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DB350, __tcf_0 0x2DB3B0, _GLOBAL__I 0x2DB3E0). +#include + #include #include "Information.h" #include "InformationManager.h" +#include "InformationKnown.h" #include "InformationReal.h" +#include "IPIArmamentKnown.h" #include "IPIArmamentReal.h" #include "IPIControlInfo.h" #include "IPICover.h" #include "IPIMobileKnown.h" #include "IPIMobileReal.h" +#include "IPIPhysicalKnown.h" #include "IPIPhysicalReal.h" #include "IPIUnit.h" +#include "WeaponInfoKnown.h" #include "WeaponInfoReal.h" #include "WeaponInfoManager.h" #include "../AIUtils/checkPointer.h" @@ -94,13 +102,16 @@ unsigned int InformationFactory::requestInformationReal(unsigned int handle, IAI } // The same with an InformationKnown -// (ELF , PE ; , / , `(object, types, time -// degeneration, basicTemp, allowedTimeDiff, side)`), registered through the same vtable slot. -// [FRONTIER] InformationKnown is not written. -unsigned int InformationFactory::requestInformationKnown(unsigned int, IAIObject*, unsigned int, - double, float, float, float, int) const +// (ELF 0x2DA1B0: `(object, types, time, degeneration, basicTemp, allowedTimeDiff, ownerSide)` +// passed through in order), registered through the same vtable slot. +unsigned int InformationFactory::requestInformationKnown(unsigned int handle, IAIObject* object, + unsigned int types, double time, + float degeneration, float basicTemp, + float allowedTimeDiff, int ownerSide) const { - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestInformationKnown [InformationKnown]"); + return registerInformation(handle, checkPointer(new InformationKnown( + object, types, time, degeneration, basicTemp, + allowedTimeDiff, ownerSide))); } // the plug-in halves @@ -127,7 +138,8 @@ bool InformationFactory::requestInformationPlugin(unsigned int sourceHandle, target->setArmament(checkPointer(new IPIArmamentReal(source))); return true; } - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestInformationPlugin [IPIArmamentKnown]"); + target->setArmament(checkPointer(new IPIArmamentKnown(source))); + return true; case 1: // control info - , built inline in both images, the same for real and known target->setControlInfo(checkPointer(new IPIControlInfo(source))); @@ -150,7 +162,8 @@ bool InformationFactory::requestInformationPlugin(unsigned int sourceHandle, target->setPhysical(checkPointer(new IPIPhysicalReal(source))); return true; } - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestInformationPlugin [IPIPhysicalKnown]"); + target->setPhysical(checkPointer(new IPIPhysicalKnown(source))); + return true; case 5: // unit - IPIUnit , the same for real and known; `real` is ignored target->setUnit(checkPointer(new IPIUnit(source))); @@ -179,13 +192,13 @@ bool InformationFactory::updateInformationPlugin(unsigned int handle, int type) // A WeaponInfoReal for the owning // side, else a WeaponInfoKnown (ELF / PE ), each built on the IWeapon and registered through -// the vtable (registerWeapon, ELF +0x3C / PE +0x38). The Real arm is written; Known remains named. +// the vtable (registerWeapon, ELF +0x3C / PE +0x38). unsigned int InformationFactory::requestWeaponInfo(unsigned int handle, IWeapon* weapon, bool real) const { if (real) return registerWeapon(handle, checkPointer(new WeaponInfoReal(weapon))); - BF2_AI_FRONTIER("dice::hfe::ai::InformationFactory::requestWeaponInfo [WeaponInfoKnown]"); + return registerWeapon(handle, checkPointer(new WeaponInfoKnown(weapon))); } // lookups diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp new file mode 100644 index 000000000..4cd4a5ae3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp @@ -0,0 +1,367 @@ +// InformationKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2DB4B0..0x2DC5F5 +// (Ghidra + 0x10000); vtable 0x4BE100 has the same 18 slots as InformationReal's. + +#include "InformationKnown.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DC4D0, __tcf_0 0x2DC530, _GLOBAL__I 0x2DC560). +#include + +#include + +#include "BFInformationEnvironment.h" // IAIInformationEnvironmentModifiers +#include "IPIMobile.h" +#include "IPIPhysical.h" +#include "IPIUnit.h" +#include "InformationManager.h" +#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +IAITerrain* terrain() +{ + return static_cast(CommonSingletonServer::m_iaiTerrain); +} + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // anonymous namespace + +// 0x2DB4B0. The base time is -1 (never updated); the last update is the given time. The cached +// position starts at zero and the transformation at identity, then both take the object's +// current values; the object's side is cached, contact count 0. +InformationKnown::InformationKnown(IAIObject* object, unsigned int types, double time, + float degeneration, float basicTemp, float allowedTimeDiff, + int ownerSide) + : Information(object, -1.0) +{ + m_lastUpdate = time; + m_degeneration = degeneration; + m_lastPosition.x = 0.0f; + m_lastPosition.y = 0.0f; + m_lastPosition.z = 0.0f; + for (int i = 0; i < 16; ++i) + m_lastTransformation.m[i] = 0.0f; + m_lastTransformation.m[0] = 1.0f; + m_lastTransformation.m[5] = 1.0f; + m_lastTransformation.m[10] = 1.0f; + m_lastTransformation.m[15] = 1.0f; + m_ownerSide = ownerSide; + m_contacts = 0; + m_allowedTimeDiff = allowedTimeDiff; + m_strength = basicTemp; + m_basicTemp = basicTemp; + m_objectTypeFlags = types; + m_side = m_object->getSide(); // +0x12C + storeLastSeen(); +} + +// 0x2DB7F0 / 0x2DB870: the base destroys the plug-ins. +InformationKnown::~InformationKnown() +{ +} + +void InformationKnown::storeLastSeen() +{ + m_lastPosition = m_object->getPosition(); // +0xD4 + m_lastTransformation = m_object->getTransformation(); // +0xDC +} + +// 0x2DC580: a known information is sort 1. +int InformationKnown::getInformationSort() +{ + return 1; +} + +// 0x2DB9B0: setTime(double) through the vtable with the game time. +bool InformationKnown::setTime() +{ + return setTime(gameTime()); // +3 +} + +// 0x2DBA00. Updates are throttled: unless the time is past the last full update plus the +// allowed difference, only the timestamp moves and the answer is false. Otherwise: without +// contact the last-seen state is refreshed and the mobile plug-in is told contact was lost; +// the mobile plug-in gets the time; a primary object passes the time to its secondary +// objects' information (looked up for this record's side); the side is re-read; a unit +// recomputes its strength from the physical plug-in's health (the physical plug-in is not +// null-tested here, unlike InformationReal); all plug-ins get the time; then a primary object +// re-registers its position with the information environment for the owning side. +bool InformationKnown::setTime(double time) +{ + if (!(time > m_time + m_allowedTimeDiff)) + { + m_lastUpdate = time; + return false; + } + if (!m_contacts) + { + storeLastSeen(); + if (m_mobile) + m_mobile->setLostContact(); // +6 + } + if (m_mobile) + m_mobile->setTime(time); // +4 + if (isPrimary()) + { + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->setTime(time); // +3 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } + } + m_side = m_object->getSide(); // +0x12C + if (m_unit) + { + m_physical->setTime(time); // +4 + m_unit->calculateStrMod(m_physical->getHealth()); // +5 + } + setTimeOnPlugIns(time); + m_time = time; + if (isPrimary()) + { + const unsigned int handle = m_object->getInformation(m_ownerSide); // +0xB8 + static_cast( + CommonSingletonServer::m_iaiInformationEnvironmentModifiers) + ->addAndUpdatePosition(m_ownerSide, m_unit != 0, handle); // +0xC + } + m_lastUpdate = time; + return true; +} + +// 0x2DBD20. Raises the record's security to `security` (clamped to [0,1]) if it is lower: +// a full update first, then the timestamp is backdated so getSecurity answers about that +// value, and setTime(double) runs again with the base time reset (its answer is returned). +// Retail backdates by 1 / (security * degeneration), not by the SCurve inverse. A clamped +// security of exactly zero cannot pass the test (security is never below 0) - the branch that +// stores 0.0 as the timestamp is kept as written. +bool InformationKnown::setTime(double time, float security) +{ + float target = 0.0f; + if (!(0.0f > security)) + { + target = security; + if (security > 1.0f) + target = 1.0f; + } + if (!(getSecurity() < target)) // +11 + return false; + setTime(time); // +3 + if (target == 0.0f) + { + m_lastUpdate = target; + return true; + } + const double backdated = time - 1.0 / (static_cast(target) * m_degeneration); + m_time = -1.0; + return setTime(backdated); // +3 +} + +// 0x2DC5D0. +double InformationKnown::getTimeStamp() const +{ + return m_lastUpdate; +} + +// 0x2DBDE0. Counts the contact, tells the mobile plug-in, and passes the contact on to a +// primary object's secondary objects. +void InformationKnown::addContact() +{ + ++m_contacts; + if (m_mobile) + m_mobile->setHasContact(); // +5 + if (!isPrimary()) + return; + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->addContact(); // +6 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } +} + +// 0x2DBEF0. When the last contact goes, the last-seen state is frozen and the mobile plug-in +// told; a primary object passes the removal on to its secondary objects either way. +void InformationKnown::removeContact() +{ + if (m_contacts > 0) + { + if (--m_contacts == 0) + { + storeLastSeen(); + if (m_mobile) + m_mobile->setLostContact(); // +6 + } + } + if (!isPrimary()) + return; + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->removeContact(); // +7 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } +} + +// 0x2DC0D0. As removeContact, dropping every contact at once. +void InformationKnown::removeAllContacts() +{ + if (m_contacts > 0) + { + m_contacts = 0; + storeLastSeen(); + if (m_mobile) + m_mobile->setLostContact(); // +6 + } + if (!isPrimary()) + return; + int iterator = -1; + const int side = getSide(); // +17 + Information* secondary = + informationManager->getInformation(getFirstSecondaryObject(iterator, side)); + while (secondary) + { + secondary->removeAllContacts(); // +8 + secondary = informationManager->getInformation(getSecondaryObject(iterator, side)); + } +} + +// 0x2DC5E0. +bool InformationKnown::hasContact() const +{ + return m_contacts > 0; +} + +// 0x2DB970: one minus the SCurve of the age over the degeneration. +float InformationKnown::getSecurity(double time) +{ + const float age = static_cast(time - m_lastUpdate); + return 1.0f - SCurve::calculate(age / m_degeneration); +} + +// 0x2DB910: full while in contact, else the decay at the current game time. +float InformationKnown::getSecurity() +{ + if (m_contacts > 0) + return 1.0f; + return getSecurity(gameTime()); // +10 +} + +// 0x2DB8B0: live while in contact, else the last seen position. +Vec3& InformationKnown::getPosition() +{ + if (m_contacts) + return const_cast(m_object->getPosition()); // +0xD4 + return m_lastPosition; +} + +// 0x2DC470: the terrain's altitude (IAITerrain +0xC) at getPosition's answer, inlined. +float InformationKnown::getAltitude() +{ + if (m_contacts) + return terrain()->getAltitude(m_object->getPosition()); + return terrain()->getAltitude(m_lastPosition); +} + +// 0x2DC2B0. The lowest terrain altitude along `direction` from the current position, in +// tenth steps; like InformationReal's the first tenth step is skipped, but the samples come +// from IAITerrain::getAltitude, not the aerial height map. +float InformationKnown::getAltitude(const Vec3& direction) +{ + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + Vec3 probe; + if (m_contacts) + probe = m_object->getPosition(); + else + probe = m_lastPosition; + float lowest = terrain()->getAltitude(probe); + + const double tenth = 1.0f / 10.0f; + const float stepX = static_cast(direction.x * tenth); + const float stepY = static_cast(direction.y * tenth); + const float stepZ = static_cast(direction.z * tenth); + const double firstStep = length / 10.0f; + const float step = static_cast(firstStep); + float travelled = step; + probe.x = static_cast(direction.x * tenth + probe.x); + probe.y = static_cast(direction.y * tenth + probe.y); + probe.z = static_cast(direction.z * tenth + probe.z); + if (length > firstStep) + { + double next; + do + { + probe.x = stepX + probe.x; + probe.y = stepY + probe.y; + probe.z = stepZ + probe.z; + const float altitude = terrain()->getAltitude(probe); + if (!(altitude > lowest)) + lowest = altitude; + next = static_cast(travelled) + step; + travelled = static_cast(next); + } + while (length > next); + } + return lowest; +} + +// 0x2DB8E0: live while in contact, else the last seen transformation. +Mat4& InformationKnown::getTransformation() +{ + if (m_contacts) + return const_cast(m_object->getTransformation()); // +0xDC + return m_lastTransformation; +} + +// 0x2DC590: the stored transformation's third row, even while in contact. +Vec3 InformationKnown::getFaceing() +{ + Vec3 facing; + facing.x = m_lastTransformation.m[8]; + facing.y = m_lastTransformation.m[9]; + facing.z = m_lastTransformation.m[10]; + return facing; +} + +// 0x2DC5C0. +int InformationKnown::getSide() const +{ + return m_side; +} + +// 0x2DC440 / 0x2DC450. +int InformationKnown::getOwnerSide() +{ + return m_ownerSide; +} + +void InformationKnown::setOwnerSide(int side) +{ + m_ownerSide = side; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.h new file mode 100644 index 000000000..7305a9cf9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.h @@ -0,0 +1,66 @@ +// Sensed information about an object of another side. While the owning side has contact, the +// position and transformation are read live from the engine object; when the last contact goes, +// they are frozen at the last seen values and the record's security decays with time. +// Owns its attached plug-ins (through Information). +// [INFERRED] Source placement beside InformationReal. + +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONKNOWN_H + +#include "Information.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +class InformationKnown : public Information +{ +public: + // `degeneration` scales the security decay, `basicTemp` and `allowedTimeDiff` fill the base + // prefix as in InformationReal, `ownerSide` is the side that knows the object. + InformationKnown(IAIObject* object, unsigned int types, double time, float degeneration, + float basicTemp, float allowedTimeDiff, int ownerSide); + virtual ~InformationKnown(); + + virtual int getInformationSort(); // +2 - 1 + virtual bool setTime(double time); // +3 + virtual bool setTime(double time, float security); // +4 + virtual double getTimeStamp() const; // +5 - the last update + virtual void addContact(); // +6 + virtual void removeContact(); // +7 + virtual void removeAllContacts(); // +8 + virtual bool hasContact() const; // +9 + virtual float getSecurity(double time); // +10 + virtual float getSecurity(); // +11 + virtual Vec3& getPosition(); // +12 + virtual float getAltitude(); // +13 + virtual float getAltitude(const Vec3& direction); // +14 + virtual Mat4& getTransformation(); // +15 + virtual Vec3 getFaceing(); // +16 + virtual int getSide() const; // +17 - the cached side + + // Non-virtual: updates to the current game time. + bool setTime(); + int getOwnerSide(); + void setOwnerSide(int side); + +private: + // [INFERRED] helper: the same inline copy appears in the constructor, setTime and both + // contact removals. + void storeLastSeen(); + + /* +0x44 */ double m_lastUpdate; // [INFERRED] name; getTimeStamp + /* +0x4C */ float m_degeneration; // [INFERRED] name; divides the age in getSecurity + /* +0x50 */ Vec3 m_lastPosition; // [INFERRED] name + /* +0x5C */ Mat4 m_lastTransformation; // [INFERRED] name + /* +0x9C */ int m_side; // the object's side (IAIObject +0x12C) + /* +0xA0 */ int m_ownerSide; + /* +0xA4 */ int m_contacts; // [INFERRED] name; add/removeContact +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp index da15b9569..bc7cc124d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp @@ -1,6 +1,10 @@ #include "InformationReal.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DCB90, __tcf_0 0x2DCBF0, _GLOBAL__I 0x2DCC20). +#include + #include #include "IPIPhysical.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp index 01da6c24c..d7808322e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp @@ -1,6 +1,10 @@ #include "WeaponInfo.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2DD370, __tcf_0 0x2DD3D0, _GLOBAL__I 0x2DD400). +#include + namespace dice { namespace hfe { namespace ai { WeaponInfo::WeaponInfo(IWeapon* weapon) diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h index cde20e73f..52f6a1e8d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h @@ -70,6 +70,12 @@ class WeaponInfo IAIObject* getLockedTarget() const; const std::string& getName() const; +public: + // [CHOSEN, not recovered] added by ai-w1-e-fire (coord/ai-requests.md): the image reads +0x04 + // inline (BBPFireInfantery::createPlan passes it to IAIPlayer::getNumShotsFired and + // IAIObjectEnvironment::hasIndirectLineOfFire). + IWeapon* getWeapon() const { return m_weapon; } + protected: friend class IPIArmament; // retail IPIArmament::rearm reads both fields directly /* +0x04 */ IWeapon* m_weapon; diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp new file mode 100644 index 000000000..e23bf6b58 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp @@ -0,0 +1,116 @@ +// WeaponInfoKnown. Recovered from libaidll.so 1.5.3153 (ia-32), 0x2DD420..0x2DDAB7; vtable +// 0x4BE2E0 (same 13 slots as WeaponInfoReal's). + +#include "WeaponInfoKnown.h" + +#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { namespace hfe { namespace ai { + +namespace { + +double gameTime() +{ + return static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +} // anonymous namespace + +// [INFERRED] helper: the constructor and update read the same five values in this order. +void WeaponInfoKnown::sample() +{ + m_ammo = m_weapon->getAmmo(); // +0xB8 + m_currentAmmo = m_weapon->getCurrentAmmo(); // +0xBC + m_readyToFire = m_weapon->isReadyToFire(); // +0x100 + m_heat = m_weapon->getHeat(); // +0xF4 + m_timeOfFiring = m_weapon->getTimeOfFiring(); // +0xE8 +} + +// 0x2DD420: samples the weapon now, then the shots of each magazine (the magazine count is +// re-read every iteration). +WeaponInfoKnown::WeaponInfoKnown(IWeapon* weapon) + : WeaponInfo(weapon), m_shotsInMag() +{ + sample(); + m_sampleTime = gameTime(); + for (int i = 0; i < m_weapon->getNumberOfMags(); ++i) // +0xCC + m_shotsInMag.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 +} + +WeaponInfoKnown::~WeaponInfoKnown() +{ +} + +// 0x2DD7B0: re-samples when more than a second has passed since the last sample. Always true. +bool WeaponInfoKnown::update() +{ + const double now = gameTime(); + if (now > m_sampleTime + 1.0f) + { + sample(); + m_sampleTime = now; + m_shotsInMag.resize(0); + for (int i = 0; i < m_weapon->getNumberOfMags(); ++i) // +0xCC + m_shotsInMag.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 + } + return true; +} + +// 0x2DD990 (unchecked index). +int WeaponInfoKnown::getShotsInMag(int magazine) +{ + return m_shotsInMag[magazine]; +} + +int WeaponInfoKnown::getAmmo() const +{ + return m_ammo; +} + +int WeaponInfoKnown::getCurrentAmmo() const +{ + return m_currentAmmo; +} + +// 0x2DD9D0: the number of sampled magazines. +int WeaponInfoKnown::getNumberOfMags() const +{ + return static_cast(m_shotsInMag.size()); +} + +bool WeaponInfoKnown::isReadyToFire() const +{ + return m_readyToFire; +} + +double WeaponInfoKnown::getTimeOfFiring() const +{ + return m_timeOfFiring; +} + +float WeaponInfoKnown::getHeat() const +{ + return m_heat; +} + +// 0x2DDA20: live. +bool WeaponInfoKnown::usesHeat() const +{ + return m_weapon->usesHeat(); // +0xFC +} + +// 0x2DDA40: the decay at the current game time. +float WeaponInfoKnown::getSecurity() const +{ + return getSecurity(gameTime()); // +12 +} + +// 0x2DDA80: one minus the SCurve of a fifth of the sample's age. +float WeaponInfoKnown::getSecurity(double time) const +{ + return 1.0f - SCurve::calculate(static_cast((time - m_sampleTime) * 0.2)); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h new file mode 100644 index 000000000..03a8ed03a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h @@ -0,0 +1,46 @@ +// Weapon information about another side's weapon: ammunition, magazines, readiness, heat and +// firing time are sampled from the engine weapon at most once per second; the record's security +// decays with the age of that sample. +// [INFERRED] Source placement beside WeaponInfoReal. +#ifndef AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOKNOWN_H +#define AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOKNOWN_H + +#include + +#include "WeaponInfo.h" + +namespace dice { namespace hfe { namespace ai { + +class WeaponInfoKnown : public WeaponInfo +{ +public: + explicit WeaponInfoKnown(IWeapon* weapon); + virtual ~WeaponInfoKnown(); + + virtual bool update(); + virtual int getShotsInMag(int magazine); + virtual int getAmmo() const; + virtual int getCurrentAmmo() const; + virtual int getNumberOfMags() const; + virtual bool isReadyToFire() const; + virtual double getTimeOfFiring() const; + virtual float getHeat() const; + virtual bool usesHeat() const; + virtual float getSecurity() const; + virtual float getSecurity(double time) const; + +private: + void sample(); + + /* +0x0C */ std::vector m_shotsInMag; + /* +0x18 */ int m_ammo; + /* +0x1C */ int m_currentAmmo; + /* +0x20 */ bool m_readyToFire; + /* +0x24 */ float m_heat; + /* +0x28 */ double m_timeOfFiring; + /* +0x30 */ double m_sampleTime; // [INFERRED] name +}; + +} } } + +#endif // AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOKNOWN_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp new file mode 100644 index 000000000..a4bf4b87e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp @@ -0,0 +1,39 @@ +// The cluster record's out-of-line members. + +#include "Cluster.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x313DC0, __tcf_0 0x313E20, _GLOBAL__I 0x313E50). +#include + +#include "../../../../../IO/File/File.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x313D10 (C2; C1 0x313D20). Leaves every field unset; ClusterGraph::readFromFile overwrites +// the array it constructs. +Cluster::Cluster() +{ +} + +// ELF 0x313D30 (D2; D1 0x313D40). +Cluster::~Cluster() +{ +} + +// ELF 0x313D50. Reads one cluster's polygon list of a GTS file into `polygons` (count first, then +// the indices) and records where it starts in the graph's list (`first`) and how long it is. +void Cluster::readGTSDataFromFile(unsigned int* polygons, unsigned int& count, unsigned int first, + io::File& file) +{ + file.read(count); + file.read(polygons, count * sizeof(unsigned int)); + m_firstPolygon = first; + m_numberOfPolygons = count; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h index 25490f301..4ba6ac4a7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.h @@ -7,18 +7,28 @@ namespace dice { namespace hfe { + +namespace io { class File; } + namespace ai { class Cluster { public: - Cluster() {} // empty - ~Cluster() {} // empty + Cluster(); + ~Cluster(); + + // Reads the cluster's polygon list of a GTS file; see the definition. + void readGTSDataFromFile(unsigned int* polygons, unsigned int& count, unsigned int first, + io::File& file); - /* +0x00 */ unsigned char m_unread00[8]; // [UNRESOLVED] - see the note above + /* +0x00 */ unsigned int m_firstPolygon; // [INFERRED] name: into ClusterGraph::m_clusterPolygons + /* +0x04 */ unsigned int m_numberOfPolygons; // [INFERRED] name: resetTempMemberSizes copies it /* +0x08 */ unsigned short m_firstPortal; // getClusterPortal's base /* +0x0A */ unsigned short m_numberOfPortals; // getClusterPortal's stride - /* +0x0C */ unsigned char m_unread0C[4]; // index 2 (+0x0E): map-part walkability state + /* +0x0C */ unsigned short m_firstPortalCost; // [INFERRED] name: getCostBetweenClustersPortals' base + /* +0x0E */ unsigned char m_walkable; // [INFERRED] name: map-part walkability state + /* +0x0F */ unsigned char m_unread0F; }; typedef char ClusterIsTheFileRecord[sizeof(Cluster) == 16 ? 1 : -1]; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp index 94c200770..1a55ba214 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp @@ -1,15 +1,775 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining ClusterGraph operations. - #include "ClusterGraph.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x31DAE0, __tcf_0 0x31DB40, _GLOBAL__I 0x31DB70). +#include +#include +#include // drawCluster +#include +#include + +#include "../NavMesh/QuadTree.h" +#include "../NavMesh/GTSDataOptimiser.h" +#include "../Material/MaterialManager.h" +#include "../../Main/AISettingsInterfaces.h" #include "../../AIUtils/checkPointer.h" +#include "../../Main/CommonSingletonServer.h" +#include "../../DrawPrimitives/DPManager.h" // IDPStaticCreator +#include "../../Main/AIPathfinding.h" // getPortalCost, isValidClusterType +#include "../../Main/IAIPathfinding.h" #include "../../../../../IO/File/File.h" namespace dice { namespace hfe { namespace ai { -// Zeroes the six fields at +0x00..+0x14 and the three at +0x24..+0x2C; the two sets +// ELF 0x314380. +void ClusterGraph::readGTSDataFromFile(QuadTree* tree, io::File& file) +{ + clean(); + file.read(m_numberOfClusters); + m_clusters = checkPointer(new Cluster[m_numberOfClusters]); + m_clusterPolygons = checkPointer(new unsigned int[tree->m_numberOfPolygons]); + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + Cluster& cluster = m_clusters[i]; + unsigned int count; + cluster.readGTSDataFromFile(m_clusterPolygons + m_numberOfClusterPolygons, + count, m_numberOfClusterPolygons, file); + const unsigned int first = cluster.m_firstPolygon; + const unsigned int size = cluster.m_numberOfPolygons; + for (unsigned int j = 0; j < size; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + Polygon* polygon = tree->getPolygon(id); + DoublePolygon* doublePolygon = tree->getPolygonDouble(id); + polygon->m_cluster = i; + doublePolygon->m_cluster = i; + } + m_numberOfClusterPolygons += count; + } +} + +// ELF 0x315160. The radius argument is unused in the shipped body. +void ClusterGraph::createPortals(int map, QuadTree* tree, float) +{ + std::list > costTypes; + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + for (unsigned short type = 0; pathfinding->isValidClusterType(map, type); ++type) + costTypes.push_back(std::make_pair(type, + pathfinding->getEquipmentTypeFromClusterCostType(map, type))); + PortalBuildMap portals; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + const Cluster& cluster = m_clusters[i]; + ClusterEdges edges; + VertexClusterEdges vertices; + buildClusterEdges(cluster, i, tree, vertices, edges); + buildPortalsFromClusterEdges(i, tree, vertices, edges, portals); + } + if (portals.empty()) + { + m_numberOfPortals = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + m_clusters[i].m_firstPortal = 0; + m_clusters[i].m_numberOfPortals = 0; + } + return; + } + for (PortalBuildMap::const_iterator i = portals.begin(); i != portals.end(); ++i) + m_numberOfPortals += static_cast(i->second.size()); + m_numberOfPortals *= static_cast(costTypes.size()); + m_portals = checkPointer(new ClusterPortal[m_numberOfPortals]); + unsigned short portalIndex = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + Cluster& cluster = m_clusters[i]; + cluster.m_firstPortal = portalIndex; + PortalBuildMap::const_iterator found = portals.find(i); + if (found == portals.end()) + { + cluster.m_numberOfPortals = 0; + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 468, "") + << static_cast(i) << " is a lost cluster!"; + continue; + } + for (std::list >::const_iterator type = costTypes.begin(); + type != costTypes.end(); ++type) + { + MaterialManager* materials = static_cast(CommonSingletonServer::m_iaiSettings) + ->getVehicleMaterialManager(type->second); + cluster.m_numberOfPortals = static_cast(found->second.size()); + for (std::list::const_iterator p = found->second.begin(); + p != found->second.end(); ++p, ++portalIndex) + { + unsigned int polygon; + ClusterPortal& portal = m_portals[portalIndex]; + if (!calculateMiddleVertex(i, *p, tree, portalIndex, materials, portal.m_position, polygon)) + { + float bestDistance = FLT_MAX; + bool success = false; + bool checkMaterial = true; + const Cluster& neighbour = m_clusters[p->neighbour]; + for (int pass = 0; pass < 2; ++pass) + { + for (int side = 0; side < 2; ++side) + { + const Cluster& candidateCluster = side == 0 ? cluster : neighbour; + const unsigned int first = candidateCluster.m_firstPolygon; + const unsigned int count = candidateCluster.m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + const Polygon* candidate = tree->getPolygon(id); + if (!candidate->m_material || + (checkMaterial && !materials->isValidMaterial(candidate->m_material))) + continue; + const Vec3& a = tree->m_vertices[p->firstVertex]; + const Vec3& b = tree->m_vertices[p->secondVertex]; + Vec3 midpoint; + midpoint.x = (b.x + a.x) * 0.5f; + midpoint.y = (b.y + a.y) * 0.5f; + midpoint.z = (b.z + a.z) * 0.5f; + Vec3 centre = {}; + tree->getCentreOfPolygon(centre, id); + // shipped defect: compares against the changing output position, not centre. + const float dx = midpoint.x - portal.m_position.x; + const float dy = midpoint.y - portal.m_position.y; + const float dz = midpoint.z - portal.m_position.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (bestDistance > distance) + { + portal.m_position = centre; + bestDistance = distance; + success = true; + polygon = id; + } + } + } + checkMaterial = false; + if (success) break; + } + if (!success) + { + portal.m_neighbourCluster = 0xFFFF; + portal.m_position.x = portal.m_position.y = portal.m_position.z = 0.0f; + portal.m_polygon = 0xFFFFFFFF; + continue; + } + } + portal.m_neighbourCluster = p->neighbour; + portal.m_polygon = polygon; + } + } + } +} + +// ELF 0x315DE0. +void ClusterGraph::buildClusterEdges(const Cluster& cluster, unsigned short clusterId, + QuadTree* tree, VertexClusterEdges& vertices, ClusterEdges& edges) +{ + const unsigned int first = cluster.m_firstPolygon; + const unsigned int count = cluster.m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + const Polygon* polygon = tree->getPolygon(id); + for (unsigned char edge = 0; edge < polygon->m_numberOfVertices; ++edge) + { + const unsigned int neighbourId = tree->getNeighbourOfPolygon(id, edge); + const Polygon* neighbour = tree->getPolygon(neighbourId); + if (!neighbour || neighbour->m_cluster == polygon->m_cluster) continue; + const unsigned int a = tree->getVertexIndexForPolygon(id, edge); + const unsigned int b = tree->getVertexIndexForPolygon(id, + static_cast((edge + 1) % polygon->m_numberOfVertices)); + for (int endpoint = 0; endpoint < 2; ++endpoint) + { + const unsigned int vertex = endpoint == 0 ? a : b; + VertexClusterEdges::iterator found = vertices.find(vertex); + if (found == vertices.end()) + { + std::map clusters; + clusters.insert(std::make_pair(neighbour->m_cluster, 1U)); + vertices.insert(std::make_pair(vertex, clusters)); + } + else + { + std::map::iterator entry = found->second.find(neighbour->m_cluster); + if (entry == found->second.end()) + found->second.insert(std::make_pair(neighbour->m_cluster, 1U)); + else if (++entry->second > 2) + { + printClusterInfo(clusterId, tree, false); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", + endpoint == 0 ? 510 : 539, "") << "Bailing out!"; + } + } + } + ClusterEdges::iterator found = edges.find(neighbour->m_cluster); + const std::pair edgePair(a, b); + if (found == edges.end()) + { + std::list > list; + list.push_back(edgePair); + edges.insert(std::make_pair(neighbour->m_cluster, list)); + } + else + found->second.push_back(edgePair); + } + } +} + +// ELF 0x316EC0. +void ClusterGraph::buildPortalsFromClusterEdges(unsigned short cluster, QuadTree* tree, + const VertexClusterEdges& vertices, const ClusterEdges& edges, PortalBuildMap& output) +{ + typedef std::pair Edge; + std::list portals; + for (ClusterEdges::const_iterator group = edges.begin(); group != edges.end(); ++group) + { + std::list starts; + for (std::list::const_iterator e = group->second.begin(); e != group->second.end(); ++e) + { + VertexClusterEdges::const_iterator a = vertices.find(e->first); + VertexClusterEdges::const_iterator b = vertices.find(e->second); + std::map::const_iterator ac = a->second.find(group->first); + std::map::const_iterator bc = b->second.find(group->first); + if (ac->second == 1 || bc->second == 1) starts.push_back(*e); + } + std::set visitedEdges; + if (starts.empty()) + { + // shipped defect: takes the first group, even when processing a later group. + const ClusterEdges::const_iterator first = edges.begin(); + ClusterPortalBuildInfo portal; + portal.firstVertex = first->second.begin()->first; + portal.secondVertex = first->second.begin()->first; + portal.neighbour = first->first; + portals.push_back(portal); + output.insert(std::make_pair(cluster, portals)); + continue; + } + for (std::list::const_iterator start = starts.begin(); start != starts.end(); ++start) + { + if (visitedEdges.find(*start) != visitedEdges.end()) continue; + if (visitedEdges.find(Edge(start->second, start->first)) != visitedEdges.end()) continue; + VertexClusterEdges::const_iterator a = vertices.find(start->first); + VertexClusterEdges::const_iterator b = vertices.find(start->second); + std::map::const_iterator ac = a->second.find(group->first); + std::map::const_iterator bc = b->second.find(group->first); + unsigned int first; + unsigned int current; + unsigned int last = 0xFFFFFFFF; + bool complete = false; + if (ac->second == 1) + { + first = start->first; + current = start->second; + if (bc->second == 1) { last = start->second; complete = true; } + } + else { first = start->second; current = start->first; } + std::set visited; + visited.insert(first); + visited.insert(current); + while (!complete) + { + bool progressed = false; + for (std::list::const_iterator e = group->second.begin(); e != group->second.end(); ++e) + { + VertexClusterEdges::const_iterator va = vertices.find(e->first); + VertexClusterEdges::const_iterator vb = vertices.find(e->second); + std::map::const_iterator ea = va->second.find(group->first); + std::map::const_iterator eb = vb->second.find(group->first); + if (visited.find(e->first) != visited.end() && visited.find(e->second) != visited.end()) continue; + unsigned int next; + unsigned int degree; + if (e->first == current) { next = e->second; degree = eb->second; } + else if (e->second == current) { next = e->first; degree = ea->second; } + else continue; + if (degree == 1) + { + last = next; + visitedEdges.insert(*start); + visitedEdges.insert(Edge(current, last)); + complete = true; + } + else + { + current = next; + visited.insert(current); + progressed = true; + } + break; + } + if (complete) break; + if (progressed) continue; + for (VertexClusterEdges::const_iterator v = vertices.begin(); v != vertices.end(); ++v) + for (std::map::const_iterator c = v->second.begin(); c != v->second.end(); ++c) {} + printClusterInfo(cluster, tree, false); + printClusterInfo(group->first, tree, false); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 756, "") << "Bailing out!"; + break; + } + if (complete) + { + ClusterPortalBuildInfo portal; + portal.firstVertex = first < last ? first : last; + portal.secondVertex = first < last ? last : first; + portal.neighbour = group->first; + portals.push_back(portal); + } + } + } + if (!portals.empty() && portals.size()) output.insert(std::make_pair(cluster, portals)); + else + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 782, "") + << "Could not find any portals for cluster: " << static_cast(cluster); +} + +// ELF 0x318270. The portal index argument is unused. +bool ClusterGraph::calculateMiddleVertex(unsigned short cluster, const ClusterPortalBuildInfo& info, + QuadTree* tree, unsigned short, MaterialManager* materials, Vec3& point, unsigned int& polygon) const +{ + const Vec3& a = tree->m_vertices[info.firstVertex]; + const Vec3& b = tree->m_vertices[info.secondVertex]; + point.x = (b.x + a.x) * 0.5f; + point.y = (b.y + a.y) * 0.5f; + point.z = (b.z + a.z) * 0.5f; + const bool found = tree->findPolygon(point, polygon, materials, 100.0f); + const Polygon* result = tree->getPolygon(polygon); + if (found) + { + const bool valid = materials->isValidMaterial(result->m_material); + const bool rightCluster = result->m_cluster == cluster || result->m_cluster == info.neighbour; + if (valid && rightCluster) return true; + } + Vec3 direction; + direction.x = -(b.z - a.z); + direction.y = b.y - a.y; + direction.z = b.x - a.x; + const float lengthSquared = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (!(FLT_EPSILON > std::fabs(1.0f - lengthSquared))) + { + if (!(FLT_EPSILON > std::fabs(lengthSquared))) + { + const float scale = 1.0f / std::sqrt(lengthSquared); + direction.x *= scale; direction.y *= scale; direction.z *= scale; + } + else direction.x = direction.y = direction.z = 0.0f; + } + const Vec3 origin = point; + for (unsigned int side = 0; side <= 1; ++side) + { + float distance = 0.1f; + for (int step = 0; step <= 999; ++step) + { + point.x = direction.x * distance + origin.x; + point.y = direction.y * distance + origin.y; + point.z = direction.z * distance + origin.z; + if (tree->findPolygon(point, polygon, materials, 100.0f)) + { + result = tree->getPolygon(polygon); + const bool valid = materials->isValidMaterial(result->m_material); + const bool rightCluster = result->m_cluster == cluster || result->m_cluster == info.neighbour; + if (valid && rightCluster) return true; + } + distance += 0.1f; + } + direction.x = -direction.x; direction.y = -direction.y; direction.z = -direction.z; + } + return false; +} + +// ELF 0x318610. Only polygon ranges are rebuilt; other Cluster fields remain uninitialised. +void ClusterGraph::adjustPolygonsInClusters() +{ + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters]); + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + const Cluster& old = m_clusters[i]; + const unsigned int count = old.m_numberOfPolygons; + const unsigned int oldFirst = old.m_firstPolygon; + adjusted[i].m_numberOfPolygons = count; + for (unsigned int j = 0; j < count; ++j) + if (m_set18.find(m_clusterPolygons[oldFirst + j]) != m_set18.end()) + --adjusted[i].m_numberOfPolygons; + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + m_clusters = adjusted; +} + +// ELF 0x318910. +void ClusterGraph::movePolygonBetweenClusters(unsigned short source, unsigned short destination, + unsigned int polygon) +{ + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters]); + unsigned int* polygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + if (i == source) adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons - 1; + else if (i == destination) adjusted[i].m_numberOfPolygons = m_clusters[destination].m_numberOfPolygons + 1; + else adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + } + for (unsigned int i = 0; i < m_numberOfClusterPolygons; ++i) + { + // shipped defect: skipped entries leave holes; insertion also skips the old destination entry. + if (m_clusterPolygons[i] == polygon) continue; + if (m_clusterPolygons[i] == m_clusterPolygons[m_clusters[destination].m_firstPolygon]) + polygons[i++] = polygon; + polygons[i] = m_clusterPolygons[i]; + } + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + m_clusters = adjusted; + delete[] m_clusterPolygons; + m_clusterPolygons = polygons; +} + +// ELF 0x318D30. +void ClusterGraph::addPolygonsToNewCluster(const std::set& selected, + std::list& mesh) +{ + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters + 1]); + unsigned int* polygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + unsigned int write = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + const unsigned int first = m_clusters[i].m_firstPolygon; + const unsigned int count = m_clusters[i].m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + { + const unsigned int id = m_clusterPolygons[first + j]; + if (selected.find(id) == selected.end()) polygons[write++] = id; + else --adjusted[i].m_numberOfPolygons; + } + } + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + adjusted[m_numberOfClusters].m_numberOfPolygons = static_cast(selected.size()); + // shipped defect: the empty-graph case reads the preceding record. + adjusted[m_numberOfClusters].m_firstPolygon = + adjusted[m_numberOfClusters - 1].m_firstPolygon + adjusted[m_numberOfClusters - 1].m_numberOfPolygons; + first = adjusted[m_numberOfClusters].m_firstPolygon; + const unsigned int count = adjusted[m_numberOfClusters].m_numberOfPolygons; + std::set::const_iterator id = selected.begin(); + for (unsigned int j = 0; j < count; ++j, ++id) polygons[first + j] = *id; + for (std::list::iterator p = mesh.begin(); p != mesh.end(); ++p) + if (selected.find((*p)->m_index) != selected.end()) + (*p)->m_cluster = static_cast(m_numberOfClusters); + ++m_numberOfClusters; + delete[] m_clusters; + m_clusters = adjusted; + delete[] m_clusterPolygons; + m_clusterPolygons = polygons; +} + +// ELF 0x319330. +void ClusterGraph::updateClustersAfterOptimisation(const DynamicPolygonMap& dynamicPolygons, + std::list& mesh, ClusterPolygonMap& clusters) +{ + adjustPolygonsInClusters(); + setPolygonIndices(clusters); + moveDynamicObjectPolygonsToSeparateClusters(mesh, dynamicPolygons, clusters); + clearEmptyClusters(mesh); + setPolygonIndices(clusters); + fixClusterGraphConnectivity(mesh, false); + m_set18.clear(); +} + +// ELF 0x319400. +void ClusterGraph::clearEmptyClusters(std::list& mesh) +{ + std::list empty; + unsigned int count = m_numberOfClusters; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + if (!m_clusters[i].m_numberOfPolygons) { empty.push_back(i); --count; } + if (empty.empty() || !empty.size()) return; + while (!empty.empty() && empty.size()) + { + const unsigned short removed = *empty.begin(); + for (std::list::iterator p = mesh.begin(); p != mesh.end(); ++p) + if ((*p)->m_cluster > removed) --(*p)->m_cluster; + empty.erase(empty.begin()); + for (std::list::iterator i = empty.begin(); i != empty.end(); ++i) --*i; + } + Cluster* adjusted = checkPointer(new Cluster[count]); + unsigned int write = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + if (m_clusters[i].m_numberOfPolygons) + { + adjusted[write].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + adjusted[write].m_firstPolygon = m_clusters[i].m_firstPolygon; + ++write; + } + m_numberOfClusters = count; + delete[] m_clusters; + m_clusters = adjusted; +} + +// ELF 0x319870. +void ClusterGraph::splitClustersCutByDeepWater(const std::list& mesh) +{ + bool split; + do + { + std::set checked; + split = false; + for (std::list::const_iterator p = mesh.begin(); p != mesh.end(); ++p) + { + OptPolygon* seed = *p; + if (checked.find(seed) != checked.end()) continue; + std::set connected; + floodFillPolygonsInCluster(seed, connected, true); + if (connected.empty()) continue; + std::set invalid; + getAllDeepWaterAndInvalidPolygonsInCluster(seed->m_cluster, mesh, invalid); + if (connected.size() + invalid.size() == m_clusters[seed->m_cluster].m_numberOfPolygons) + { + checked.insert(connected.begin(), connected.end()); + continue; + } + split = true; + std::set other; + for (std::list::const_iterator q = mesh.begin(); q != mesh.end(); ++q) + if ((*q)->m_cluster == seed->m_cluster && connected.find(*q) == connected.end()) + other.insert(*q); + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters + 1]); + unsigned int first = 0; + for (unsigned short i = 0; i < m_numberOfClusters; ++i) + { + if (i == seed->m_cluster) + { + // shipped defect: decrements once regardless of the size of other; leaves the range unset. + adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons - 1; + for (std::set::iterator q = other.begin(); q != other.end(); ++q) + (*q)->m_cluster = static_cast(m_numberOfClusters); + } + else adjusted[i].m_firstPolygon = first; + // shipped defect: other counts and the new record were never initialised. + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + ++m_numberOfClusters; + m_clusters = adjusted; + break; + } + } while (split); +} + +// ELF 0x31A020. +void ClusterGraph::moveDynamicObjectPolygonsToSeparateClusters(const std::list& mesh, + const DynamicPolygonMap& dynamicPolygons, ClusterPolygonMap& clusters) +{ + typedef std::map > ObjectPolygons; + ObjectPolygons objects; + for (DynamicPolygonMap::const_iterator p = dynamicPolygons.begin(); p != dynamicPolygons.end(); ++p) + { + ObjectPolygons::iterator object = objects.find(p->second.first); + if (object == objects.end()) + { + std::vector polygons; + polygons.push_back(p->first); + objects.insert(std::make_pair(p->second.first, polygons)); + } + else object->second.push_back(p->first); + } + const int objectCount = static_cast(objects.size()); + if (!objectCount) return; + Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters + objectCount]); + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_walkable = 1; + adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; + } + unsigned int newCluster = m_numberOfClusters; + for (ObjectPolygons::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + const DynamicPolygonMap::const_iterator first = dynamicPolygons.find(object->second[0]); + adjusted[newCluster].m_numberOfPolygons = static_cast(object->second.size()); + adjusted[newCluster].m_walkable = first->second.second; + std::list empty; + clusters.insert(std::make_pair(static_cast(newCluster), empty)); + for (std::list::const_iterator p = mesh.begin(); p != mesh.end(); ++p) + { + OptPolygon* polygon = *p; + for (std::vector::const_iterator id = object->second.begin(); id != object->second.end(); ++id) + { + if (*id != polygon->m_index) continue; + --adjusted[polygon->m_cluster].m_numberOfPolygons; + ClusterPolygonMap::iterator old = clusters.find(polygon->m_cluster); + std::list::iterator entry = old->second.begin(); + while (entry != old->second.end()) + { + if (*entry == *id) + { + std::list::iterator removed = entry++; + old->second.erase(removed); + clusters.find(static_cast(newCluster))->second.push_back(*id); + } + else ++entry; + } + polygon->m_cluster = static_cast(newCluster); + } + } + ++newCluster; + } + m_numberOfClusters += objectCount; + unsigned int first = 0; + for (unsigned int i = 0; i < m_numberOfClusters; ++i) + { + adjusted[i].m_firstPolygon = first; + first += adjusted[i].m_numberOfPolygons; + } + delete[] m_clusters; + m_clusters = adjusted; +} + +// ELF 0x31AC20. +void ClusterGraph::fixClusterGraphConnectivity(std::list& mesh, bool reportOnly) +{ + std::set checked; + if (m_numberOfClusters == 1 && m_clusters[0].m_numberOfPolygons == 1) return; + for (;;) + { + bool fixed = true; + for (std::list::iterator p = mesh.begin(); p != mesh.end(); ++p) + { + OptPolygon* polygon = *p; + if (checked.find(polygon->m_cluster) != checked.end()) continue; + std::set connected; + if (validateClusterConnectivityFromPolygon(polygon->m_cluster, polygon, + m_clusters[polygon->m_cluster].m_numberOfPolygons, connected, true)) + { + checked.insert(polygon->m_cluster); + continue; + } + if (reportOnly) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 1294, "") + << "Non connected cluster " << static_cast(polygon->m_cluster) + << ". Found " << static_cast(connected.size()) + << " polygons, should be " << static_cast(m_clusters[polygon->m_cluster].m_numberOfPolygons) + << " polygons"; + return; + } + unsigned int unconnected = 0xFFFFFFFF; + const Cluster& cluster = m_clusters[polygon->m_cluster]; + const unsigned int first = cluster.m_firstPolygon; + const unsigned int count = cluster.m_numberOfPolygons; + for (unsigned int j = 0; j < count; ++j) + if (connected.find(m_clusterPolygons[first + j]) == connected.end()) + { + unconnected = m_clusterPolygons[first + j]; + break; + } + OptPolygon* seed = 0; + for (std::list::iterator q = mesh.begin(); q != mesh.end(); ++q) + if ((*q)->m_index == unconnected) { seed = *q; break; } + std::set selected; + selected.insert(unconnected); + for (unsigned int edge = 0; edge < seed->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = seed->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == seed->m_cluster) + recurseFloodFill(neighbour, seed, selected); + } + addPolygonsToNewCluster(selected, mesh); + fixed = false; + break; + } + if (fixed) return; + } +} + +// ELF 0x31B3F0. +void ClusterGraph::floodFillPolygonsInCluster(OptPolygon* polygon, std::set& filled, + bool filter) const +{ + if (filled.find(polygon) != filled.end()) return; + // shipped defect: with filter true the material must simultaneously equal zero and four. + if (filter && polygon->m_material != 0) return; + if (polygon->m_material != 4) return; + filled.insert(polygon); + for (unsigned int edge = 0; edge < polygon->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == polygon->m_cluster) + floodFillPolygonsInCluster(neighbour, filled, filter); + } +} + +// ELF 0x31B510. +void ClusterGraph::getAllDeepWaterAndInvalidPolygonsInCluster(unsigned short cluster, + const std::list& mesh, std::set& polygons) const +{ + for (std::list::const_iterator p = mesh.begin(); p != mesh.end(); ++p) + if ((*p)->m_cluster == cluster && ((*p)->m_material == 0 || (*p)->m_material == 4)) + polygons.insert(*p); +} + +// ELF 0x31B5B0. +void ClusterGraph::setPolygonIndices(const ClusterPolygonMap& clusters) +{ + m_numberOfClusterPolygons = 0; + for (ClusterPolygonMap::const_iterator i = clusters.begin(); i != clusters.end(); ++i) + m_numberOfClusterPolygons += static_cast(i->second.size()); + unsigned int* polygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); + unsigned int write = 0; + for (ClusterPolygonMap::const_iterator i = clusters.begin(); i != clusters.end(); ++i) + for (std::list::const_iterator p = i->second.begin(); p != i->second.end(); ++p) + polygons[write++] = *p; + delete[] m_clusterPolygons; + m_clusterPolygons = polygons; +} + +// ELF 0x31BC80. +void ClusterGraph::recurseFloodFill(OptPolygon* polygon, OptPolygon* origin, + std::set& filled) const +{ + if (polygon == origin) return; + if (filled.find(polygon->m_index) != filled.end()) return; + filled.insert(polygon->m_index); + for (unsigned int edge = 0; edge < polygon->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == origin->m_cluster) + recurseFloodFill(neighbour, origin, filled); + } +} + +// ELF 0x31BD70. The cluster argument is unused. +bool ClusterGraph::validateClusterConnectivityFromPolygon(unsigned short, OptPolygon* polygon, + unsigned int count, std::set& filled, bool all) const +{ + if (all) filled.insert(polygon->m_index); + for (unsigned int edge = 0; edge < polygon->m_numberOfVertices; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (neighbour && neighbour->m_cluster == polygon->m_cluster) + { + recurseFloodFill(neighbour, polygon, filled); + if (!all) break; + } + } + return filled.size() == count; +} + +// ELF 0x313E70 (C2; C1 0x314010). Zeroes the six fields at +0x00..+0x14 and the three at +0x24..+0x2C; the two sets // construct empty (their sentinel allocations are the only calls). is bigger only because the // SGI node allocator is inlined into it - same source, two inlining decisions. ClusterGraph::ClusterGraph() @@ -19,19 +779,19 @@ ClusterGraph::ClusterGraph() , m_numberOfClusters(0) , m_numberOfPortals(0) , m_portals(0) - , m_array24(0) + , m_tempMemberSizes(0) , m_numberOfPortalCosts(0) , m_portalCosts(0) { } -// clean, then the two sets in reverse declaration order. +// ELF 0x3140F0 (D2; D1 0x3141D0). clean, then the two sets in reverse declaration order. ClusterGraph::~ClusterGraph() { clean(); } -// Releases arrays and clears counts, but leaves four freed pointers unchanged. +// ELF 0x3142B0. Releases arrays and clears counts, but leaves four freed pointers unchanged. // Do not clean twice without repopulating those pointers; readFromFile assigns them // immediately after cleanup. Only the pointer at +0x24 is cleared. void ClusterGraph::clean() @@ -45,14 +805,14 @@ void ClusterGraph::clean() delete[] m_portals; m_numberOfPortals = 0; - delete[] m_array24; - m_array24 = 0; + delete[] m_tempMemberSizes; + m_tempMemberSizes = 0; delete[] m_portalCosts; m_numberOfPortalCosts = 0; } -// Loads a version-5 cluster graph. Unsupported versions leave the existing graph unchanged. +// ELF 0x314830. Loads a version-5 cluster graph. Unsupported versions leave the existing graph unchanged. void ClusterGraph::readFromFile(io::File& file) { int version = 0; @@ -94,6 +854,466 @@ void ClusterGraph::readFromFile(io::File& file) } } +// ELF 0x314E10. An out-of-range polygon dereferences null, as in retail. +unsigned short ClusterGraph::getClusterId(QuadTree* quadTree, unsigned int polygon) const +{ + return quadTree->getPolygon(polygon)->m_cluster; +} + +// ELF 0x31DA70. True when one of the cluster's portals leads to `neighbour`. +bool ClusterGraph::areNeighbours(unsigned short cluster, unsigned short neighbour) const +{ + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + if (m_portals[record.m_firstPortal + i].m_neighbourCluster == neighbour) + return true; + } + return false; +} + +// ELF 0x314E50. +ClusterPortal* ClusterGraph::getClusterPortal(unsigned short cluster, unsigned short costType, + unsigned short index) const +{ + const Cluster& record = m_clusters[cluster]; + return &m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + index]; +} + +// ELF 0x314EA0. The index of the cluster's first portal into `neighbour`, or 0xFFFF. The +// cost-type offset plus index is truncated to 16 bits before the base is added, as in retail. +unsigned short ClusterGraph::getPortalForNeighbour(unsigned short cluster, + unsigned short costType, + unsigned short neighbour) const +{ + if (cluster == 0xFFFF) + return 0xFFFF; + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + const unsigned short offset = + static_cast(costType * record.m_numberOfPortals + i); + if (m_portals[record.m_firstPortal + offset].m_neighbourCluster == neighbour) + return i; + } + return 0xFFFF; +} + +// ELF 0x314F30. The neighbour cluster's index of the same portal: the same polygon key and a +// position within 0.1 (squared distance under 0.01). +unsigned short ClusterGraph::getCorrespongingPortalInNeighbour(ClusterPortal* portal, + unsigned short costType) const +{ + const unsigned short neighbour = portal->m_neighbourCluster; + if (neighbour == 0xFFFF) + return 0xFFFF; + const Cluster& record = m_clusters[neighbour]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + const ClusterPortal& candidate = + m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + i]; + if (candidate.m_polygon != portal->m_polygon) + continue; + const float dx = candidate.m_position.x - portal->m_position.x; + const float dy = candidate.m_position.y - portal->m_position.y; + const float dz = candidate.m_position.z - portal->m_position.z; + if (0.01f > dx * dx + dy * dy + dz * dz) + return i; + } + return 0xFFFF; +} + +// ELF 0x31CEE0. Portal-to-portal costs are a triangular table per cluster and cost type: the pair +// (lo, hi) is entry T(n) - T(n - lo) + (hi - lo) after the cluster's base, T(k) = k(k - 1) / 2, +// read one before that position. Every intermediate is truncated to 16 bits as in retail. +float ClusterGraph::getCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, + unsigned short costType) const +{ + const Cluster& record = m_clusters[cluster]; + const unsigned short lo = first < second ? first : second; + const unsigned short hi = first < second ? second : first; + const int count = record.m_numberOfPortals; + const unsigned short pairs = static_cast(count * (count - 1) / 2); + const int remaining = static_cast(count - lo); + const unsigned short tail = static_cast(remaining * (remaining - 1) / 2); + const unsigned short within = static_cast( + pairs - tail + static_cast(hi - lo)); + const int index = record.m_firstPortalCost + pairs * costType + within; + return m_portalCosts[index - 1]; +} + +// ELF 0x315050. Appends the cluster's portals of one cost type; an unknown cluster adds none. +void ClusterGraph::getClusterPortals(unsigned short cluster, unsigned short costType, + std::list& portals) const +{ + if (cluster >= m_numberOfClusters) + return; + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + portals.push_back( + &m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + i]); +} + +// ELF 0x31CF90. Like getPortalForNeighbour, without the 0xFFFF guard or the 16-bit truncation. +unsigned short ClusterGraph::findClusterPortalWithNeighbour(unsigned short cluster, + unsigned short costType, + unsigned short neighbour) const +{ + const Cluster& record = m_clusters[cluster]; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + if (m_portals[record.m_firstPortal + costType * record.m_numberOfPortals + i] + .m_neighbourCluster == neighbour) + return i; + } + return 0xFFFF; +} + +// ELF 0x31CE30. Mirrors getCostBetweenClustersPortals: the smaller portal index first, the +// same 16-bit truncations, and the store at index - 1. +void ClusterGraph::setCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, unsigned short costType, + float cost) +{ + const Cluster& record = m_clusters[cluster]; + const unsigned short lo = first < second ? first : second; + const unsigned short hi = first < second ? second : first; + const int count = record.m_numberOfPortals; + const unsigned short pairs = static_cast(count * (count - 1) / 2); + const int remaining = static_cast(count - lo); + const unsigned short tail = static_cast(remaining * (remaining - 1) / 2); + const unsigned short within = static_cast( + pairs - tail + static_cast(hi - lo)); + const int index = record.m_firstPortalCost + pairs * costType + within; + m_portalCosts[index - 1] = cost; +} + +// ELF 0x31CA80. One step of the incremental portal-cost update of `cluster`: `state` is +// (first portal, second portal, cost type), starting at (0, 1, 0) when the caller has no search +// resource yet (one is acquired for owner 1234; none free -> false). The step restricts the +// search to the cluster and both portals' neighbour clusters (m_set30) and asks +// AIPathfinding::getPortalCost; while that search runs the answer is false. A finished pair is +// stored, the resource is released and re-acquired, and the state advances: next cost type, +// then next second portal (cost type 0), then next first portal (second = first + 1). True once +// the first portal passes the last one. Retail also constructs and frees an unused local +// std::vector (4-byte elements; -0x3C..-0x34) and has an unused static `clusterUpdate`. +bool ClusterGraph::updatePortalCosts(unsigned int& resource, + triple& state, + int map, unsigned int island, unsigned short cluster) +{ + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + const Cluster& record = m_clusters[cluster]; + const unsigned short numberOfPortals = record.m_numberOfPortals; + const unsigned int firstPortal = record.m_firstPortal; + + if (resource == 0xFFFFFFFFu) + { + state.first = 0; + state.second = 1; + state.third = 0; + pathfinding->acquireResource(resource, 1234); + if (resource == 0xFFFFFFFFu) + return false; + } + + const ClusterPortal* const from = &m_portals[state.first + firstPortal]; + const ClusterPortal* const to = &m_portals[state.second + firstPortal]; + m_set30.clear(); + m_set30.insert(cluster); + m_set30.insert(from->m_neighbourCluster); + m_set30.insert(to->m_neighbourCluster); + + float cost; + if (!pathfinding->getPortalCost(cost, resource, map, island, state.third, from->m_position, + from->m_polygon, to->m_position, to->m_polygon, m_set30)) + return false; + + pathfinding->releaseResource(resource, 1234); + setCostBetweenClustersPortals(cluster, state.first, state.second, state.third, cost); + ++state.third; + if (!pathfinding->isValidClusterType(map, state.third)) + { + state.third = 0; + ++state.second; + if (state.second >= numberOfPortals) + { + const unsigned short previous = state.first; + ++state.first; + if (state.first >= numberOfPortals) + return true; + state.second = static_cast(previous + 2); + } + } + pathfinding->acquireResource(resource, 1234); + return false; +} + +// ELF 0x314740. Writes the version-5 record readFromFile reads; empty portal and cost arrays are +// written as their zero count alone. +void ClusterGraph::saveToFile(io::File& file) const +{ + file.write(5); + file.write(m_numberOfClusters); + file.write(m_clusters, sizeof(Cluster) * m_numberOfClusters); + file.write(m_numberOfClusterPolygons); + file.write(m_clusterPolygons, sizeof(unsigned int) * m_numberOfClusterPolygons); + file.write(m_numberOfPortals); + if (m_numberOfPortals) + file.write(m_portals, sizeof(ClusterPortal) * m_numberOfPortals); + file.write(m_numberOfPortalCosts); + if (m_numberOfPortalCosts) + file.write(m_portalCosts, sizeof(float) * m_numberOfPortalCosts); +} + +// ELF 0x31C2E0. Rebuilds the whole portal-to-portal cost table: for every cluster (its base is +// the running table size) and every valid cluster cost type, one blocking search per portal pair +// (i < j), restricted to the cluster and both portals' neighbour clusters. The old table is freed +// first; its count is only rewritten at the end. Retail also keeps a per-cluster +// std::list > whose iterator is stepped once per appended cost and never read, +// and a final pass that recomputes each pair's distance and stored cost without using either. +void ClusterGraph::calculatePortalCosts(int map, unsigned int island) +{ + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + delete[] m_portalCosts; + + std::vector portalCosts; + std::vector costs; + for (unsigned int cluster = 0; cluster < m_numberOfClusters; ++cluster) + { + std::list > unusedCosts; + Cluster& record = m_clusters[cluster]; + const unsigned short count = record.m_numberOfPortals; + record.m_firstPortalCost = static_cast(portalCosts.size()); + unsigned int first = record.m_firstPortal; + for (unsigned int costType = 0; pathfinding->isValidClusterType(map, costType); + ++costType, first += count) + { + for (unsigned short i = 0; i < count; ++i) + { + const ClusterPortal* const from = &m_portals[first + i]; + for (unsigned short j = static_cast(i + 1); j < count; ++j) + { + const ClusterPortal* const to = &m_portals[first + j]; + std::set allowedClusters; + allowedClusters.insert(static_cast(cluster)); + allowedClusters.insert(from->m_neighbourCluster); + allowedClusters.insert(to->m_neighbourCluster); + costs.resize(0); + pathfinding->getPortalCost(costs, static_cast(costType), map, + island, to->m_position, to->m_polygon, + from->m_position, from->m_polygon, + allowedClusters); + std::list >::iterator unused = unusedCosts.begin(); + for (std::vector::iterator cost = costs.begin(); cost != costs.end(); + ++cost, ++unused) + portalCosts.push_back(*cost); + } + } + } + } + + m_portalCosts = new float[portalCosts.size()]; + m_numberOfPortalCosts = portalCosts.size(); + for (unsigned int i = 0; i < portalCosts.size(); ++i) + m_portalCosts[i] = portalCosts[i]; + + for (unsigned int cluster = 0; cluster < m_numberOfClusters; ++cluster) + { + const Cluster& record = m_clusters[cluster]; + const unsigned short count = record.m_numberOfPortals; + const unsigned int first = record.m_firstPortal; + for (unsigned short i = 0; i < count; ++i) + { + for (unsigned short j = static_cast(i + 1); j < count; ++j) + { + for (unsigned int costType = 0; pathfinding->isValidClusterType(map, costType); + ++costType) + { + const Vec3 a = m_portals[first + i + costType * count].m_position; + const Vec3 b = m_portals[first + j + costType * count].m_position; + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + const float cost = getCostBetweenClustersPortals( + static_cast(cluster), i, j, + static_cast(costType)); + (void)distance; + (void)cost; + } + } + } + } +} + +// ELF 0x31B7F0. Snapshots every cluster's polygon count into a new array (the previous one is +// not freed). +void ClusterGraph::resetTempMemberSizes() +{ + m_tempMemberSizes = checkPointer(new unsigned int[m_numberOfClusters]); + for (unsigned int cluster = 0; cluster < m_numberOfClusters; ++cluster) + m_tempMemberSizes[cluster] = m_clusters[cluster].m_numberOfPolygons; +} + +// ELF 0x31B970. False as soon as the cluster's polygons border more than one other (assigned) +// cluster. +bool ClusterGraph::allNeighboursOfClusterInSameCluster(QuadTree* quadTree, + unsigned short cluster) const +{ + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + std::set neighbours; + for (unsigned int i = 0; i < count; ++i) + { + const unsigned int polygon = m_clusterPolygons[first + i]; + const Polygon* const candidate = quadTree->getPolygon(polygon); + for (unsigned char edge = 0; edge < candidate->m_numberOfVertices; ++edge) + { + const Polygon* const neighbour + = quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); + if (neighbour && neighbour->m_cluster != cluster && neighbour->m_cluster != 0xFFFF) + { + neighbours.insert(neighbour->m_cluster); + if (neighbours.size() > 1) + return false; + } + } + } + return true; +} + +// ELF 0x31BB90. A cluster of more than one polygon holds when every polygon has a neighbour in +// the same cluster. +bool ClusterGraph::checkClusterCondition(QuadTree* quadTree, unsigned short cluster) const +{ + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + if (count == 1) + return true; + + for (unsigned int i = 0; i < count; ++i) + { + const unsigned int polygon = m_clusterPolygons[first + i]; + const Polygon* const candidate = quadTree->getPolygon(polygon); + unsigned char edge = 0; + for (; edge < candidate->m_numberOfVertices; ++edge) + { + const Polygon* const neighbour + = quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); + if (neighbour && neighbour->m_cluster == cluster) + break; + } + if (edge >= candidate->m_numberOfVertices) + return false; + } + return true; +} + +// ELF 0x31BE50. Reports (printClusterInfo, then an error) every cluster whose member list holds a +// polygon assigned elsewhere; always true. +bool ClusterGraph::validateClusterGraphConnectivity(QuadTree* quadTree, bool verbose) +{ + for (unsigned short cluster = 0; cluster < m_numberOfClusters; ++cluster) + { + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + unsigned int members = 0; + for (unsigned int i = 0; i < count; ++i) + { + if (quadTree->getPolygon(m_clusterPolygons[first + i])->m_cluster == cluster) + ++members; + } + if (members != count) + { + printClusterInfo(cluster, quadTree, verbose); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 1578, "") + << "Bailing out in validateClusterGraphConnectivity()!"; + } + } + return true; +} + +// ELF 0x31C080. Reports the cluster id; the walk over its polygons reads each corner index and +// neighbour without printing them. +void ClusterGraph::printClusterInfo(unsigned short cluster, QuadTree* quadTree, bool) const +{ + if (cluster >= m_numberOfClusters) + return; + + const Cluster& record = m_clusters[cluster]; + const unsigned int first = record.m_firstPolygon; + const unsigned int count = record.m_numberOfPolygons; + // operator<<(int): the listing carries its inlined oct/hex test. + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp", 1596, "") + << "Cluster info for cluster " << static_cast(cluster); + + for (unsigned int i = 0; i < count; ++i) + { + const unsigned int polygon = m_clusterPolygons[first + i]; + const Polygon* const candidate = quadTree->getPolygon(polygon); + for (unsigned char edge = 0; edge < candidate->m_numberOfVertices; ++edge) + { + quadTree->getVertexIndexForPolygon(polygon, edge); + quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); + } + } +} + +// ELF 0x31D000. Debug view of one cluster and cost type (30 s): its id above the first portal, +// a red circle per portal, and per portal pair a line and the stored cost at its midpoint. The +// first portal is read even for a cluster without portals. +void ClusterGraph::drawCluster(unsigned short cluster, int costType) const +{ + Vec3 up; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + const Cluster& record = m_clusters[cluster]; + IDPStaticCreator* const creator + = static_cast(CommonSingletonServer::m_iDPStaticCreator); + const unsigned short count = record.m_numberOfPortals; + const unsigned int first = record.m_firstPortal + costType * count; + const ClusterPortal* const firstPortal = &m_portals[first]; + + { + std::stringstream text; + text << cluster; + Vec3 position; + position.x = up.x + firstPortal->m_position.x; + position.y = up.y + firstPortal->m_position.y; + position.z = up.z + firstPortal->m_position.z; + creator->createStatic3dText(30.0f, 0x5588u, position, text.str(), 0, + static_cast(0), + static_cast(0)); + } + + for (unsigned short i = 0; i < count; ++i) + { + const ClusterPortal* const portal = &m_portals[first + i]; + creator->createStaticCircle(30.0f, 0xFFFF0000u, portal->m_position, 0.5f, up, false, 10); + for (unsigned short j = static_cast(i + 1); j < count; ++j) + { + const ClusterPortal* const other = &m_portals[first + j]; + creator->createStaticLine(30.0f, 0xAAAA0000u, portal->m_position, other->m_position, + 0.25f); + Vec3 middle; + middle.x = (portal->m_position.x + other->m_position.x) * 0.5f; + middle.y = (portal->m_position.y + other->m_position.y) * 0.5f; + middle.z = (portal->m_position.z + other->m_position.z) * 0.5f; + std::stringstream text; + text << getCostBetweenClustersPortals(cluster, i, j, + static_cast(costType)); + creator->createStatic3dText(30.0f, 0x88u, middle, text.str(), 0, + static_cast(0), + static_cast(0)); + } + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h index 6cf66e128..368f71036 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h @@ -1,13 +1,15 @@ -// Navigation cluster graph with file loading and cleanup. -// [FRONTIER] Remaining graph queries and mesh generation require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// Navigation cluster graph with GTS construction, optimisation fix-ups and portal queries. #ifndef AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERGRAPH_H #define AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERGRAPH_H +#include #include +#include +#include #include "../../Main/AIDllTypes.h" // Vec3 +#include "../../Main/IAIPathfinding.h" // ai::triple #include "Cluster.h" namespace dice { @@ -18,6 +20,8 @@ namespace io { class File; } namespace ai { class QuadTree; +class OptPolygon; +class MaterialManager; // Portal record used by the cluster graph and its serialized format. class ClusterPortal @@ -25,8 +29,10 @@ class ClusterPortal public: ClusterPortal() { m_position.x = 0.0f; m_position.y = 0.0f; m_position.z = 0.0f; } - /* +0x00 */ Vec3 m_position; // [INFERRED] name - /* +0x0C */ unsigned char m_unread0C[8]; // [UNRESOLVED] - see the note above + /* +0x00 */ Vec3 m_position; // [INFERRED] name + /* +0x0C */ unsigned short m_neighbourCluster; // [INFERRED] name; areNeighbours compares it + /* +0x0E */ unsigned char m_unread0E[2]; // [UNRESOLVED] - see the note above + /* +0x10 */ unsigned int m_polygon; // [INFERRED] name: ClusterNodePath::getPoint hands it out }; typedef char ClusterPortalIsTheFileRecord[sizeof(ClusterPortal) == 20 ? 1 : -1]; @@ -34,27 +40,98 @@ typedef char ClusterPortalIsTheFileRecord[sizeof(ClusterPortal) == 20 ? 1 : -1]; class ClusterGraph { public: + struct ClusterPortalBuildInfo + { + // Field names are inferred from the portal builder; ia-32 offsets are 0, 4 and 8. + unsigned int firstVertex; + unsigned int secondVertex; + unsigned short neighbour; + }; + typedef std::map > VertexClusterEdges; + typedef std::map > > ClusterEdges; + typedef std::map > PortalBuildMap; + typedef std::map > DynamicPolygonMap; + typedef std::map > ClusterPolygonMap; + ClusterGraph(); ~ClusterGraph(); void clean(); void readFromFile(io::File& file); + void readGTSDataFromFile(QuadTree* quadTree, io::File& file); + void createPortals(int map, QuadTree* quadTree, float radius); + void buildClusterEdges(const Cluster&, unsigned short, QuadTree*, VertexClusterEdges&, ClusterEdges&); + void buildPortalsFromClusterEdges(unsigned short, QuadTree*, const VertexClusterEdges&, + const ClusterEdges&, PortalBuildMap&); + bool calculateMiddleVertex(unsigned short, const ClusterPortalBuildInfo&, QuadTree*, + unsigned short, MaterialManager*, Vec3&, unsigned int&) const; + void adjustPolygonsInClusters(); + void movePolygonBetweenClusters(unsigned short, unsigned short, unsigned int); + void addPolygonsToNewCluster(const std::set&, std::list&); + void updateClustersAfterOptimisation(const DynamicPolygonMap&, std::list&, ClusterPolygonMap&); + void clearEmptyClusters(std::list&); + void splitClustersCutByDeepWater(const std::list&); + void moveDynamicObjectPolygonsToSeparateClusters(const std::list&, + const DynamicPolygonMap&, ClusterPolygonMap&); + void fixClusterGraphConnectivity(std::list&, bool); + void floodFillPolygonsInCluster(OptPolygon*, std::set&, bool) const; + void getAllDeepWaterAndInvalidPolygonsInCluster(unsigned short, const std::list&, + std::set&) const; + void setPolygonIndices(const ClusterPolygonMap&); + void recurseFloodFill(OptPolygon*, OptPolygon*, std::set&) const; + bool validateClusterConnectivityFromPolygon(unsigned short, OptPolygon*, unsigned int, + std::set&, bool) const; + void saveToFile(io::File& file) const; + // Recomputes every portal-to-portal cost of the map's island with blocking searches. + void calculatePortalCosts(int map, unsigned int island); + void resetTempMemberSizes(); + bool allNeighboursOfClusterInSameCluster(QuadTree* quadTree, unsigned short cluster) const; + bool checkClusterCondition(QuadTree* quadTree, unsigned short cluster) const; + bool validateClusterGraphConnectivity(QuadTree* quadTree, bool verbose); + void printClusterInfo(unsigned short cluster, QuadTree* quadTree, bool verbose) const; + void drawCluster(unsigned short cluster, int costType) const; // [CHOSEN name] Returns the stored cluster count used by QuadTreeManager. unsigned int getNumberOfClusters() const { return m_numberOfClusters; } + unsigned short getClusterId(QuadTree* quadTree, unsigned int polygon) const; + bool areNeighbours(unsigned short cluster, unsigned short neighbour) const; + // Portal queries. A cluster's portals are stored once per cost type: portal `index` of cost + // type `costType` is m_portals[first + costType * count + index]. + ClusterPortal* getClusterPortal(unsigned short cluster, unsigned short costType, + unsigned short index) const; + unsigned short getPortalForNeighbour(unsigned short cluster, unsigned short costType, + unsigned short neighbour) const; + unsigned short getCorrespongingPortalInNeighbour(ClusterPortal* portal, + unsigned short costType) const; + float getCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, unsigned short costType) const; + void getClusterPortals(unsigned short cluster, unsigned short costType, + std::list& portals) const; + unsigned short findClusterPortalWithNeighbour(unsigned short cluster, unsigned short costType, + unsigned short neighbour) const; + // ELF 0x31CE30. The setter twin of getCostBetweenClustersPortals (same pair index). + void setCostBetweenClustersPortals(unsigned short cluster, unsigned short first, + unsigned short second, unsigned short costType, float cost); + bool updatePortalCosts(unsigned int& resource, triple& portal, + int map, unsigned int island, unsigned short costType); + private: + friend class GTSDataOptimiser; + friend class ClusterNodeManager; friend class QuadTree; + friend class QuadTreeManager; /* +0x00 */ unsigned int* m_clusterPolygons; // [INFERRED] polygon indices grouped by cluster /* +0x04 */ unsigned int m_numberOfClusterPolygons; // (Dalian Infantry: 18,512, every polygon once) /* +0x08 */ Cluster* m_clusters; // getClusterPortal /* +0x0C */ unsigned int m_numberOfClusters; // loadQuadTrees' empty walk bound /* +0x10 */ unsigned int m_numberOfPortals; /* +0x14 */ ClusterPortal* m_portals; // getClusterPortal - /* +0x18 */ std::set m_set18; // [UNRESOLVED] roles for both sets and - /* +0x24 */ unsigned char* m_array24; // the +0x24 array: only the GTS - // generation path (not written) fills - // them; clean frees and nulls +0x24 + /* +0x18 */ std::set m_set18; // [INFERRED] removed polygon indices + /* +0x24 */ unsigned int* m_tempMemberSizes; // [INFERRED] name: resetTempMemberSizes + // fills it with every cluster's polygon + // count; clean frees and nulls it /* +0x28 */ unsigned int m_numberOfPortalCosts; // float: the PE allocates it through its own checkPointer instantiation (, not the // uint one at the +0x00 list uses), and the shipped values are plainly floats diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp new file mode 100644 index 000000000..bf37c5fb0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp @@ -0,0 +1,67 @@ +// The cluster A* node's out-of-line members. [INFERRED] file name: the image keeps them in their +// own translation unit (own static initialisation) between ClusterGraph's and +// ClusterNodeManager's. + +#include "ClusterNodeManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x31FBB0, __tcf_0 0x31FC10, _GLOBAL__I 0x31FC40). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x31F9B0 (C2; C1 0x31FA00). +ClusterNode::ClusterNode(unsigned short cluster, unsigned int depth) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_g(0.0f) + , m_f(0.0f) + , m_key(cluster) + , m_portal(0xFFFF) + , m_depth(static_cast(depth)) +{ +} + +// ELF 0x31FA50 (C2; C1 0x31FAA0). +ClusterNode::ClusterNode(const ClusterNode& other) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_g(0.0f) + , m_f(0.0f) + , m_key(other.m_key) + , m_portal(other.m_portal) + , m_depth(0) +{ +} + +// ELF 0x31FAF0 (D2; D1 0x31FB00): empty. +ClusterNode::~ClusterNode() +{ +} + +// ELF 0x31FB10. +ClusterNode* ClusterNode::expandFirst(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal) +{ + portal = 0; + ClusterNode* const neighbour = manager->getNeighbourOfNode(this, portal, status); + ++portal; + return neighbour; +} + +// ELF 0x31FB60. +ClusterNode* ClusterNode::expand(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal) +{ + ClusterNode* const neighbour = manager->getNeighbourOfNode(this, portal, status); + ++portal; + return neighbour; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp index 22f14ce44..120d58b50 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp @@ -2,44 +2,469 @@ #include "ClusterNodeManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3215F0, __tcf_0 0x321650, _GLOBAL__I 0x321680). +#include + +#include + +#include "ClusterGraph.h" +#include "../NavMesh/QuadTree.h" #include "../../AIUtils/checkPointer.h" -#include "../../Main/AIDllFrontier.h" +#include "../../Main/IAIPathfinding.h" +#include "../../../../../Core/Debug.h" namespace dice { namespace hfe { namespace ai { -// Initializes empty node lists and a 313-bucket hash linked to this manager. +namespace { + +// ELF 0x31FC60. Reports a node that is its own ancestor within ten generations. The result is +// discarded by both retail callers. +bool checkHeritage(ClusterNode* node) +{ + int generation = 0; + for (ClusterNode* ancestor = node->m_parent; ancestor != 0; ancestor = ancestor->m_parent) + { + if (ancestor == node) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp", 38, "") + << "Circular heritage for " << static_cast(ancestor->m_key); + return false; + } + ++generation; + if (generation > 9) + break; + } + return true; +} + +} // namespace + +// ClusterNodeManager +// ELF 0x31FDD0 (C2; C1 0x320010). Positions zeroed, empty pools, a 313-bucket status hash linked to this manager. ClusterNodeManager::ClusterNodeManager() : m_quadTree(0) , m_clusterGraph(0) - , m_i8(0) - , m_i12(0) - , m_i16(0) - , m_i20(0) - , m_i24(0) - , m_i28(0) - , m_i32(0) - , m_i36(0) - , m_i40(0) + , m_goal(0) + , m_freeNodes(0) + , m_numberOfNodes(0) , m_freeOCData(0) - , m_i48(0) + , m_numberOfOCData(0) , m_ocDataHash(checkPointer(new Hash(kOCDataBuckets))) - , m_i56(0) - , m_i60(0) - , m_i64(0) - , m_i68(0) + , m_costType(0) { + m_start.x = 0.0f; + m_start.y = 0.0f; + m_start.z = 0.0f; + m_goalPosition.x = 0.0f; + m_goalPosition.y = 0.0f; + m_goalPosition.z = 0.0f; m_ocDataHash->m_nodeManager = this; } -// [FRONTIER] Cleanup of the hash, buckets, and OCData chain remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when ordered node-manager teardown is recovered. +// ELF 0x3201E0 (D2; D1 0x320370). Frees the node pool, the record pool, every hashed record and its node, the hash +// and the goal copy. Retail reads each hashed record's chain link after deleting it; the link is +// read first here ([CHOSEN], the same walk without the use after free). ClusterNodeManager::~ClusterNodeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::ClusterNodeManager::~ClusterNodeManager"); + while (m_freeNodes != 0) + { + ClusterNode* const node = m_freeNodes; + m_freeNodes = node->m_next; + delete node; + --m_numberOfNodes; + } + + while (m_freeOCData != 0) + { + OCData* const data = m_freeOCData; + m_freeOCData = data->m_next; + delete data; + --m_numberOfOCData; + } + + Hash* const hash = m_ocDataHash; + Hash::iterator it = hash->begin(); + while (it != hash->end()) + { + OCData* const data = it.m_node; + OCData* const next = data->m_next; + if (data->m_node != 0) + delete data->m_node; + delete data; + --m_numberOfOCData; + --m_numberOfNodes; + it.m_node = next; + if (it.m_node == 0) + { + it.m_bucket = it.m_bucket->m_nextUsed; + if (it.m_bucket != 0) + it.m_node = it.m_bucket->m_head; + } + } + if (hash != 0) + { + if (hash->m_buckets != 0) + delete[] hash->m_buckets; + delete hash; + } + + if (m_goal != 0) + { + delete m_goal; + --m_numberOfNodes; + } +} + +// ELF 0x320500. +void ClusterNodeManager::setQuadTree(QuadTree* quadTree) +{ + m_quadTree = quadTree; +} + +// ELF 0x320510. +void ClusterNodeManager::setClusterGraph(ClusterGraph* clusterGraph) +{ + m_clusterGraph = clusterGraph; +} + +// ELF 0x320520. Keeps a private copy of the goal's cluster and portal and recycles `node`. +void ClusterNodeManager::setGoal(ClusterNode* node) +{ + if (m_goal == 0) + m_goal = getNewNode(node); + else + { + m_goal->m_key = node->m_key; + m_goal->m_portal = node->m_portal; + } + recycleNode(node); +} + +// ELF 0x320590. A probe record is built first; an existing record is marked open and the probe +// recycled, otherwise the probe itself is hashed as the node's open record. +void ClusterNodeManager::setNodeOpen(ClusterNode* node) +{ + OCData* const probe = getNewOCData(); + probe->m_open = true; + probe->m_node = node; + probe->m_closed = false; + + OCData* const existing = m_ocDataHash->get(probe); + if (existing != 0) + { + recycleOCData(probe); + existing->m_open = true; + return; + } + m_ocDataHash->insert(probe); +} + +// ELF 0x3206B0. The record must exist: retail writes through the lookup unchecked. +void ClusterNodeManager::setNodeClosed(ClusterNode* node) +{ + OCData* const probe = getNewOCData(); + probe->m_open = true; + probe->m_closed = false; + probe->m_node = node; + OCData* const existing = m_ocDataHash->get(probe); + recycleOCData(probe); + existing->m_open = false; + existing->m_closed = true; +} + +// ELF 0x320730. The neighbour cluster behind the first usable portal at or after `portal`. A portal +// is usable when the best route to its neighbour cluster costs something non-negative, does not +// start from the portal this node was entered through, and is not an earlier portal (so each +// neighbour is reached once, through its cheapest portal). The new node enters the neighbour +// through the matching portal there; unseen neighbours are costed (the goal only flagged). +ClusterNode* ClusterNodeManager::getNeighbourOfNode(ClusterNode* node, unsigned short& portal, + nodeStatus::Status& status) +{ + const Cluster& cluster = m_clusterGraph->m_clusters[node->m_key]; + unsigned short neighbourPortal = 0xFFFF; + unsigned short bestPortal; + if (portal >= cluster.m_numberOfPortals) + { + status = nodeStatus::kInvalid; + return 0; + } + + float cost = findBestPortalAndCost(bestPortal, neighbourPortal, node, node->m_portal, portal, + node->m_key); + for (;;) + { + if (cluster.m_numberOfPortals <= portal) + { + status = nodeStatus::kInvalid; + return 0; + } + if (cost >= 0.0f && neighbourPortal != 0xFFFF && node->m_portal != portal && + bestPortal >= portal) + break; + ++portal; + cost = findBestPortalAndCost(bestPortal, neighbourPortal, node, node->m_portal, portal, + node->m_key); + } + + const ClusterPortal* const exit = m_clusterGraph->getClusterPortal( + node->m_key, static_cast(m_costType), bestPortal); + ClusterNode* const neighbour = getNewNode(exit->m_neighbourCluster, node, node->m_depth + 1); + + OCData* const probe = getNewOCData(); + probe->m_open = true; + probe->m_closed = false; + probe->m_node = neighbour; + OCData* const existing = m_ocDataHash->get(probe); + if (existing != 0) + { + if (existing->m_open) + status = nodeStatus::kOpen; + else if (existing->m_closed) + status = nodeStatus::kClosed; + else + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp", 233, "") + << "This case should not exists!"; + status = nodeStatus::kInvalid; + } + recycleOCData(probe); + return neighbour; + } + + checkHeritage(neighbour); + neighbour->m_portal = neighbourPortal; + if (neighbour->m_key == m_goal->m_key) + status = nodeStatus::kGoal; + else + { + status = nodeStatus::kUnvisited; + neighbour->m_g = cost; + neighbour->m_f = calculateHeuristicCost(cost, neighbourPortal, neighbour); + } + recycleOCData(probe); + return neighbour; +} + +// ELF 0x320B10. A recycled node keeps its costs, links and entry portal except the parent. +ClusterNode* ClusterNodeManager::getNewNode(unsigned short cluster, ClusterNode* parent, + unsigned int depth) +{ + ClusterNode* node = m_freeNodes; + if (node != 0) + { + node->m_key = cluster; + node->m_depth = static_cast(depth); + m_freeNodes = m_freeNodes->m_next; + } + else + { + node = new ClusterNode(cluster, depth); + ++m_numberOfNodes; + } + node->m_parent = parent; + return node; +} + +// ELF 0x320B90. A recycled node is assigned every field of `source`; a new one is copy +// constructed, which keeps only the cluster and the entry portal. +ClusterNode* ClusterNodeManager::getNewNode(ClusterNode* source) +{ + ClusterNode* node = m_freeNodes; + if (node != 0) + { + m_freeNodes = node->m_next; + *node = *source; + } + else + { + node = new ClusterNode(*source); + ++m_numberOfNodes; + } + return node; +} + +// ELF 0x320C30. Returns every hashed record's node to the pool, unhashes and recycles the records, +// then the goal copy. +void ClusterNodeManager::reset() +{ + Hash::iterator it = m_ocDataHash->begin(); + while (it != m_ocDataHash->end()) + { + OCData* const data = it.m_node; + recycleNode(data->m_node); + ++it; + m_ocDataHash->remove(data); + recycleOCData(data); + } + + if (m_goal != 0) + { + recycleNode(m_goal); + m_goal = 0; + } +} + +// ELF 0x320DE0: empty. +void ClusterNodeManager::returnReset() +{ +} + +// ELF 0x320DF0. Re-costs `existing` as reached from `parent` through the portal between them; +// taken only when strictly cheaper. Refused at the depth limit and for the start node. +bool ClusterNodeManager::updateNode(ClusterNode* parent, ClusterNode* existing, + unsigned int maxDepth) +{ + const int depth = parent->m_depth + 1; + if (maxDepth == static_cast(depth) || existing->m_parent == 0) + return false; + + const unsigned short costType = static_cast(m_costType); + const unsigned short portal = + m_clusterGraph->findClusterPortalWithNeighbour(parent->m_key, costType, existing->m_key); + unsigned short bestPortal; + unsigned short neighbourPortal; + const float cost = findBestPortalAndCost(bestPortal, neighbourPortal, parent, + parent->m_portal, portal, parent->m_key); + if (0.0f > cost) + return false; + + const float f = calculateHeuristicCost(cost, neighbourPortal, existing); + if (f >= existing->m_f) + return false; + + existing->m_portal = + m_clusterGraph->getPortalForNeighbour(existing->m_key, costType, parent->m_key); + existing->m_parent = parent; + checkHeritage(existing); + existing->m_g = cost; + existing->m_f = f; + existing->m_depth = depth; + existing->m_portal = neighbourPortal; + return true; +} + +// ELF 0x320F30. The accumulated cost of leaving `node` through `portal`: from the start position +// for the start node, otherwise the cluster's portal-to-portal table (-1 when negative). +float ClusterNodeManager::calculateCost(ClusterNode* node, unsigned short portal) const +{ + if (node == 0) + return 0.0f; + + const unsigned short costType = static_cast(m_costType); + if (node->m_portal != 0xFFFF) + { + const float step = m_clusterGraph->getCostBetweenClustersPortals(node->m_key, + node->m_portal, portal, + costType); + if (0.0f > step) + return -1.0f; + return step + node->m_g; + } + + const ClusterPortal* const exit = m_clusterGraph->getClusterPortal(node->m_key, costType, portal); + const float dx = exit->m_position.x - m_start.x; + const float dy = exit->m_position.y - m_start.y; + const float dz = exit->m_position.z - m_start.z; + return std::sqrt(dx * dx + dy * dy + dz * dz) + node->m_g; +} + +// ELF 0x321060. g plus the straight distance from the node's entry point to the goal position. +float ClusterNodeManager::calculateHeuristicCost(float cost, unsigned short portal, + ClusterNode* node) const +{ + const Vec3* const entry = getEntryPoint(portal, node); + const float dx = m_goalPosition.x - entry->x; + const float dy = m_goalPosition.y - entry->y; + const float dz = m_goalPosition.z - entry->z; + return cost + std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// ELF 0x321110. Appends (cluster, entry portal) from the start to `goal`. The path's nodes are not +// cleared first; no cost is stored. +void ClusterNodeManager::buildPath(ClusterNodePath& path, ClusterNode* goal) +{ + m_pathNodes.resize(0); + for (ClusterNode* node = goal; node != 0; node = node->m_parent) + m_pathNodes.push_back(node); + + for (int i = static_cast(m_pathNodes.size()) - 1; i >= 0; --i) + path.m_nodes.push_back(std::make_pair(m_pathNodes[i]->m_key, m_pathNodes[i]->m_portal)); +} + +// ELF 0x321280. checkPointer guards the allocation (checkPointer.h line 46). +ClusterNodeManager::OCData* ClusterNodeManager::getNewOCData() +{ + if (m_freeOCData != 0) + { + OCData* const data = m_freeOCData; + m_freeOCData = data->m_next; + return data; + } + + ++m_numberOfOCData; + OCData* const data = new OCData; + data->m_open = true; + data->m_closed = false; + data->m_node = 0; + data->m_next = 0; + return checkPointer(data); +} + +// ELF 0x3213F0. +void ClusterNodeManager::recycleOCData(OCData* data) +{ + data->m_next = m_freeOCData; + m_freeOCData = data; +} + +// ELF 0x321410. The start position for a node without a parent, else the portal's position. +const Vec3* ClusterNodeManager::getEntryPoint(unsigned short portal, ClusterNode* node) const +{ + if (node->m_parent == 0) + return &m_start; + return &m_clusterGraph + ->getClusterPortal(node->m_key, static_cast(m_costType), portal) + ->m_position; +} + +// ELF 0x321470. Among the cluster's portals into the same neighbour as `portal`, the cheapest +// non-negative calculateCost; its index goes to `bestPortal` and the neighbour's matching portal +// to `neighbourPortal` (0xFFFF when none). -1 when the neighbour is not a valid, walkable +// cluster or nothing qualifies. `entryPortal` is not read. +float ClusterNodeManager::findBestPortalAndCost(unsigned short& bestPortal, + unsigned short& neighbourPortal, + ClusterNode* node, unsigned short, + unsigned short portal, + unsigned short cluster) const +{ + const Cluster& record = m_clusterGraph->m_clusters[cluster]; + const unsigned short costType = static_cast(m_costType); + const unsigned int neighbour = + m_clusterGraph->getClusterPortal(cluster, costType, portal)->m_neighbourCluster; + if (neighbour >= m_clusterGraph->m_numberOfClusters || + m_clusterGraph->m_clusters[neighbour].m_walkable == 0) + return -1.0f; + + float best = 1e9f; + neighbourPortal = 0xFFFF; + for (unsigned short i = 0; i < record.m_numberOfPortals; ++i) + { + ClusterPortal* const candidate = m_clusterGraph->getClusterPortal(cluster, costType, i); + if (candidate->m_neighbourCluster != neighbour) + continue; + const float cost = calculateCost(node, i); + if (best > cost && cost >= 0.0f) + { + bestPortal = i; + neighbourPortal = m_clusterGraph->getCorrespongingPortalInNeighbour(candidate, costType); + best = cost; + } + } + return neighbourPortal == 0xFFFF ? -1.0f : best; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h index 0f8dbf2e7..37f34ccf3 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h @@ -1,57 +1,120 @@ -// Node pool for cluster-graph A* searches, including an intrusive free list for open/closed records. -// returnReset is intentionally empty. -// [FRONTIER] Remaining search operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the node-pool lifecycle and search operations. +// Cluster-graph A* search nodes and their manager: node and open/closed-record pools, portal +// expansion, costs and path building. Placement of ClusterNode and ClusterNodePath's methods in +// this file is [INFERRED]: their functions sit beside the manager's in the ELF. #ifndef AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERNODEMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AIPATHFINDING_CLUSTER_CLUSTERNODEMANAGER_H -#include "../../Main/AIPathfindingSearchTypes.h" // Hash +#include + +#include "../../Main/AIPathfindingSearchTypes.h" // Hash, nodeStatus namespace dice { namespace hfe { namespace ai { class ClusterGraph; +class ClusterNodeManager; class QuadTree; -class ClusterNode; + +// One A* node: a cluster entered through one of its portals. 28 bytes (operator new(0x1C)). +class ClusterNode +{ +public: + ClusterNode(unsigned short cluster, unsigned int depth); + // Copies the cluster and the entry portal; links, costs and depth start cleared. + ClusterNode(const ClusterNode& other); + ~ClusterNode(); + + // Portal iteration for AStarResource::update: expandFirst starts at portal 0. Both advance + // `portal` past the one they report. + ClusterNode* expandFirst(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal); + ClusterNode* expand(ClusterNodeManager* manager, nodeStatus::Status& status, + unsigned short& portal); + + /* +0x00 */ ClusterNode* m_next; // hash chain / free-list link + /* +0x04 */ ClusterNode* m_prev; + /* +0x08 */ ClusterNode* m_parent; + /* +0x0C */ float m_g; + /* +0x10 */ float m_f; + /* +0x14 */ unsigned short m_key; // the cluster + /* +0x16 */ unsigned short m_portal; // entry portal index in this cluster; 0xFFFF for the start + /* +0x18 */ int m_depth; +}; class ClusterNodeManager { public: - // The open/closed record. Its only recovered field is the free-list link at +8, which - // `recycleOCData` writes, so the type stays incomplete here rather than guessing a size. - // Attested as a nested type by the mangled names of `getNewOCData`, `recycleOCData` and - // `HashIterator`. - class OCData; + // The open/closed record of one cluster node, kept in a hash keyed by the node's cluster. + // 16 bytes; +12 is not written on allocation. Names [INFERRED]; the nested type is attested by + // the mangled names of getNewOCData, recycleOCData and HashIterator. + class OCData + { + public: + /* +0 */ bool m_open; + /* +1 */ bool m_closed; + /* +4 */ ClusterNode* m_node; + /* +8 */ OCData* m_next; // hash chain / free-list link + /* +12 */ OCData* m_prev; + }; // the same prime the cluster search resource'S two hashes use. A literal in the binary. enum { kOCDataBuckets = 313 }; ClusterNodeManager(); - ~ClusterNodeManager(); // , [FRONTIER] + ~ClusterNodeManager(); + + void setQuadTree(QuadTree* quadTree); + void setClusterGraph(ClusterGraph* clusterGraph); + void setGoal(ClusterNode* node); + void setNodeOpen(ClusterNode* node); + void setNodeClosed(ClusterNode* node); + ClusterNode* getNeighbourOfNode(ClusterNode* node, unsigned short& portal, + nodeStatus::Status& status); + ClusterNode* getNewNode(unsigned short cluster, ClusterNode* parent, unsigned int depth); + ClusterNode* getNewNode(ClusterNode* source); + void reset(); + void returnReset(); + bool updateNode(ClusterNode* parent, ClusterNode* existing, unsigned int maxDepth); + float calculateCost(ClusterNode* node, unsigned short portal) const; + float calculateHeuristicCost(float cost, unsigned short portal, ClusterNode* node) const; + void buildPath(ClusterNodePath& path, ClusterNode* goal); + OCData* getNewOCData(); + void recycleOCData(OCData* data); + const Vec3* getEntryPoint(unsigned short portal, ClusterNode* node) const; + float findBestPortalAndCost(unsigned short& bestPortal, unsigned short& neighbourPortal, + ClusterNode* node, unsigned short entryPortal, + unsigned short portal, unsigned short cluster) const; + + // [INFERRED] Inlined in every retail user: returns a node to the free list. + void recycleNode(ClusterNode* node) + { + node->m_next = m_freeNodes; + m_freeNodes = node; + } - // layout, on the ELF, read store by store out of the constructor + // layout, on the ELF /* +0 */ QuadTree* m_quadTree; // = 0; `setQuadTree` writes it /* +4 */ ClusterGraph* m_clusterGraph; // = 0; `setClusterGraph` writes it - /* +8 */ int m_i8; // = 0 [UNRESOLVED] - /* +12 */ int m_i12; // = 0 [UNRESOLVED] - /* +16 */ int m_i16; // = 0 [UNRESOLVED] - /* +20 */ int m_i20; // = 0 [UNRESOLVED] - /* +24 */ int m_i24; // = 0 [UNRESOLVED] - /* +28 */ int m_i28; // = 0 [UNRESOLVED] - /* +32 */ int m_i32; // = 0 [UNRESOLVED] - /* +36 */ int m_i36; // = 0 [UNRESOLVED] - /* +40 */ int m_i40; // = 0 [UNRESOLVED] + /* +8 */ Vec3 m_start; // the search's start position + /* +20 */ Vec3 m_goalPosition; // the search's goal position + /* +32 */ ClusterNode* m_goal; // = 0; setGoal's copy of the goal node + /* +36 */ ClusterNode* m_freeNodes; // = 0 + /* +40 */ int m_numberOfNodes; // = 0 /* +44 */ OCData* m_freeOCData; // = 0 the intrusive free list `recycleOCData` pushes to - /* +48 */ int m_i48; // = 0 [UNRESOLVED] + /* +48 */ int m_numberOfOCData; // = 0 /* +52 */ Hash* m_ocDataHash; // new Hash(313), then ->this - /* +56 */ int m_i56; // = 0 [UNRESOLVED] - /* +60 */ int m_i60; // = 0 [UNRESOLVED] - /* +64 */ int m_i64; // = 0 [UNRESOLVED] - /* +68 */ int m_i68; // = 0 [UNRESOLVED] + /* +56 */ std::vector m_pathNodes; // buildPath's goal-to-start scratch list + /* +68 */ int m_costType; // the vehicle's cluster cost type; read as 16 bits }; +// The status records hash by their node's cluster. +inline int hashKeyOf(const ClusterNodeManager::OCData* data) +{ + return static_cast(data->m_node->m_key); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp new file mode 100644 index 000000000..0b2f41f4d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp @@ -0,0 +1,66 @@ +// The cluster path result's out-of-line members. [INFERRED] file name: the image keeps them in +// their own translation unit (own static initialisation) after ClusterNodeManager's. + +#include "ClusterNodeManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x322170, __tcf_0 0x3221D0, _GLOBAL__I 0x322200). +#include + +#include "ClusterGraph.h" +#include "../../Main/IAIPathfinding.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x321E90 (C2; C1 0x321EC0). Only the step index and the node vector are set; map, cost +// type and island are left to setVehicle and clusterSearch. +ClusterNodePath::ClusterNodePath() + : m_i0(0) +{ +} + +// ELF 0x321EF0 (D2; D1 0x321F50). +ClusterNodePath::~ClusterNodePath() +{ +} + +// ELF 0x321FB0. +void ClusterNodePath::setVehicle(int map, int vehicleId) +{ + m_map = map; + m_costType = IAIPathfinding::instance->getClusterCostType(m_map, vehicleId); +} + +// ELF 0x322000. +bool ClusterNodePath::getPoint(Vec3& position, unsigned int& polygon, unsigned int index) const +{ + if (index >= m_nodes.size() || m_nodes[index].second == 0xFFFF) + return false; + ClusterGraph* const graph = + static_cast(IAIPathfinding::instance->getClusterGraph(m_map, m_island)); + const ClusterPortal* const portal = graph->getClusterPortal( + m_nodes[index].first, static_cast(m_costType), m_nodes[index].second); + position = portal->m_position; + polygon = portal->m_polygon; + return true; +} + +// ELF 0x3220D0. +const Vec3& ClusterNodePath::getPoint(unsigned int index) const +{ + const unsigned int step = m_i0 + index; + if (step >= m_nodes.size() || m_nodes[step].second == 0xFFFF) + return Vec3::getZero(); + ClusterGraph* const graph = + static_cast(IAIPathfinding::instance->getClusterGraph(m_map, m_island)); + return graph + ->getClusterPortal(m_nodes[step].first, static_cast(m_costType), + m_nodes[step].second) + ->m_position; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp index 18e3bf616..0b35ba88c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp @@ -2,6 +2,10 @@ #include "Material.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3227D0, __tcf_0 0x322830, _GLOBAL__I 0x322860). +#include + #include "../../../../../Core/Debug.h" #include "../../../../../Core/StringUtil.h" @@ -12,6 +16,7 @@ namespace dice { namespace hfe { namespace ai { +// ELF 0x322220. std::istream& operator>>(std::istream& stream, materialId& material) { std::string token; @@ -37,9 +42,9 @@ std::istream& operator>>(std::istream& stream, materialId& material) material = 9; else { - // Both ports report this exact source line and abort through DebugTypeError. There is no + // The image reports source line 66 and aborts through DebugTypeError. There is no // fallback assignment for an unknown token. - Debug(DebugTypeError, __FILE__, __LINE__, "") + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/Material/Material.cpp", 66, "") << token << " is not recognised as a proper materialId."; } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp index fd9ea642e..3ce216e13 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp @@ -1,16 +1,21 @@ #include "MaterialManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x322E90, __tcf_0 0x322EF0, _GLOBAL__I 0x322F20). +#include + #include "../../AIUtils/checkPointer.h" namespace dice { namespace hfe { namespace ai { -// Initializes the navigation material table and its default traversal costs. +// ELF 0x322880 (C2; C1 0x322AF0). Nine materials at cost 1, then Invalid -1 and both danger +// objects 1000. MaterialManager::MaterialManager() { - for (unsigned int i = 0; i <= 8u; ++i) + for (unsigned char i = 0; i < 9; ++i) { MaterialContainer* const container = new MaterialContainer(); checkPointer(container); @@ -22,7 +27,7 @@ MaterialManager::MaterialManager() setMaterialCost(7, 1000.0f); } -// Deletes each owned material-cost record. +// ELF 0x322D60 (D2; D1 0x322DC0). Deletes each owned material-cost record. MaterialManager::~MaterialManager() { for (std::vector::iterator i = m_materials.begin(); @@ -32,16 +37,19 @@ MaterialManager::~MaterialManager() // A material is walkable when its cost compares >= 0; material zero starts at -1. // All accessors require a valid material index. +// ELF 0x322E60. bool MaterialManager::isValidMaterial(unsigned char material) const { return m_materials[material]->m_cost >= 0.0f; } +// ELF 0x322E20. void MaterialManager::setMaterialCost(unsigned char material, float cost) { m_materials[material]->m_cost = cost; } +// ELF 0x322E40. float MaterialManager::getMaterialCost(unsigned char material) const { return m_materials[material]->m_cost; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp new file mode 100644 index 000000000..8005a1d6c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp @@ -0,0 +1,1167 @@ +// ELF FILE symbol GTSDataOptimiser.cpp; OptPolygon methods occur in this translation unit. +#include "GTSDataOptimiser.h" +#include "QuadTree.h" +#include "../Cluster/ClusterGraph.h" +#include "../../AIUtils/checkPointer.h" +#include "../../../../../IO/File/File.h" +#include +#include +#include +// ELF static init 0x2FC5A0, __tcf_0 0x2FC600, _GLOBAL__I 0x2FC630: ios_base::Init lifetime. +#include + +namespace dice { namespace hfe { namespace ai { + +namespace { +// Inlined vector operations in the optimiser bodies; the helper names are inferred. +DoubleVec3 difference(const DoubleVec3& a, const DoubleVec3& b) +{ + DoubleVec3 result = { a.x - b.x, a.y - b.y, a.z - b.z }; + return result; +} +double scalarProduct(const DoubleVec3& a, const DoubleVec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} +DoubleVec3 vectorProduct(const DoubleVec3& a, const DoubleVec3& b) +{ + DoubleVec3 result = { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x }; + return result; +} +void normaliseDouble(DoubleVec3& vector) +{ + const double lengthSquared = scalarProduct(vector, vector); + if (static_cast(FLT_EPSILON) > std::fabs(1.0 - lengthSquared)) return; + if (!(static_cast(FLT_EPSILON) > std::fabs(lengthSquared))) + { + const double scale = 1.0 / std::sqrt(lengthSquared); + vector.x *= scale; vector.y *= scale; vector.z *= scale; + } + else vector.x = vector.y = vector.z = 0.0; +} +int wrappedIndex(int index, int count) +{ + // shipped defect: a negative multiple produces count rather than zero. + return index < 0 ? count + index % count : index % count; +} +float normalAngle(const DoubleVec3& a, const DoubleVec3& b) +{ + float dot = static_cast(scalarProduct(a, b)); + if (dot < -1.0f) dot = -1.0f; + else if (dot > 1.0f) dot = 1.0f; + return std::acos(dot); +} +} + +// ELF 0x2F2390 (C2), 0x2F2490 (C1). +GTSDataOptimiser::GTSDataOptimiser(ClusterGraph* graph) : m_current(), m_graph(graph) {} + +// ELF 0x2F24E0 (D2), 0x2F2550 (D1). +GTSDataOptimiser::~GTSDataOptimiser() +{ + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + destroyPolygon(*i); +} + +// ELF 0x2F3EB0. +void GTSDataOptimiser::destroyPolygon(OptPolygon* polygon) { delete polygon; } + +// ELF 0x2F62F0. Shipped code dereferences begin without checking for an empty list. +OptPolygon* GTSDataOptimiser::initPolygonIteration() +{ + m_current = m_polygons.begin(); + return *m_current; +} + +// ELF 0x2F6310. +OptPolygon* GTSDataOptimiser::getNextPolygon() +{ + ++m_current; + return m_current == m_polygons.end() ? 0 : *m_current; +} + +// ELF 0x2F6340. +unsigned int GTSDataOptimiser::getNumberOfVertices() const +{ + unsigned int count = 0; + for (std::list::const_iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + count += (*i)->m_numberOfVertices; + return count; +} + +// ELF 0x2F25C0 (C2), 0x2F25F0 (C1). m_index is left uninitialized. +OptPolygon::OptPolygon() : m_numberOfVertices(0), m_vertices(0), m_neighbours(0), + m_material(0), m_originalMaterial(0), m_normal(0), m_cluster(0) {} + +// ELF 0x2F2620 (D2), 0x2F2650 (D1). +OptPolygon::~OptPolygon() { deleteMembers(); } + +// ELF 0x2F2680. Only the cached normal pointer is nulled after freeing. +void OptPolygon::deleteMembers() +{ + delete m_normal; + m_normal = 0; + delete[] m_vertices; + delete[] m_neighbours; +} + +// ELF 0x2F2F30. +const DoubleVec3* OptPolygon::getNormal() const +{ + if (!m_normal) + calculateNormal(); + return m_normal; +} + +// ELF 0x2F26E0. Calculates and caches a polygon normal from its vertex fan. +void OptPolygon::calculateNormal() const +{ + const DoubleVec3 origin = m_vertices[0]; + const DoubleVec3 firstEdge = difference(m_vertices[1], origin); + DoubleVec3 secondEdge = difference(m_vertices[2], origin); + m_normal = checkPointer(new DoubleVec3(vectorProduct(firstEdge, secondEdge))); + DoubleVec3 firstUnit = firstEdge; + normaliseDouble(firstUnit); + DoubleVec3 secondUnit = secondEdge; + normaliseDouble(secondUnit); + float dot = static_cast(scalarProduct(secondUnit, firstUnit)); + float angle = std::fabs(std::fabs(dot) - 1.0f); + int corner = 2; + while (static_cast(0.01f) > scalarProduct(*m_normal, *m_normal) || 0.01f > angle) + { + if (corner >= m_numberOfVertices - 1) break; + ++corner; + secondEdge = difference(m_vertices[corner], origin); + *m_normal = vectorProduct(firstEdge, secondEdge); + secondUnit = secondEdge; + normaliseDouble(secondUnit); + dot = static_cast(scalarProduct(secondUnit, firstUnit)); + // shipped defect: subsequent fan triangles omit the outer absolute value. + angle = std::fabs(dot) - 1.0f; + } + normaliseDouble(*m_normal); +} + +// ELF 0x2F2F70. +unsigned char OptPolygon::findFirstNeighbourIndex(OptPolygon* neighbour) const +{ + for (int edge = 0; edge < m_numberOfVertices; ++edge) + if (m_neighbours[edge] == neighbour) return static_cast(edge); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 103, "") + << "Couldn't find first neighbour index in " << static_cast(this) + << " of " << static_cast(neighbour); + return 0xFF; +} + +// ELF 0x2F30F0. +void OptPolygon::changeVertex(const DoubleVec3& oldVertex, const DoubleVec3& newVertex) +{ + for (int corner = 0; corner < m_numberOfVertices; ++corner) + { + const DoubleVec3 delta = difference(oldVertex, m_vertices[corner]); + if (!(scalarProduct(delta, delta) > DBL_EPSILON)) + { + delete m_normal; + m_normal = 0; + m_vertices[corner] = newVertex; + return; + } + } +} + +// ELF 0x2F3210. +void OptPolygon::changeNeighbour(const DoubleVec3& vertex, OptPolygon* oldNeighbour, + OptPolygon* newNeighbour) +{ + for (int corner = 0; corner < m_numberOfVertices; ++corner) + { + const DoubleVec3 delta = difference(vertex, m_vertices[corner]); + if (!(scalarProduct(delta, delta) > DBL_EPSILON)) + { + const int previous = corner - 1; + const int edge = previous < 0 ? m_numberOfVertices + previous % m_numberOfVertices + : previous % m_numberOfVertices; + if (m_neighbours[edge] == oldNeighbour) + { + m_neighbours[edge] = newNeighbour; + return; + } + } + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 138, "") + << "Couldn't change neighbour in " << static_cast(this) + << " from " << static_cast(oldNeighbour) + << " to " << static_cast(newNeighbour); +} + +// ELF 0x2F36E0. Appends the polygon's XZ coordinates and diagnostic pointer to the file. +void OptPolygon::printPolygon(io::File& file, int id) const +{ + file.seek(static_cast(2), 0); + std::stringstream text; + const unsigned int count = m_numberOfVertices; + text << static_cast(count) << " " << id << std::endl; + text << static_cast(this) << std::endl; + for (unsigned int corner = 0; corner < count; ++corner) + text << m_vertices[corner].x << " " << m_vertices[corner].z << std::endl; + file.write(text.str()); +} + +// ELF 0x2F3C40. +bool OptPolygon::checkForDuplicateVertices() const +{ + const unsigned int count = m_numberOfVertices; + for (unsigned int first = 0; first < count; ++first) + for (unsigned int second = first + 1; second < count; ++second) + { + const DoubleVec3 delta = difference(m_vertices[second], m_vertices[first]); + if (DBL_EPSILON > scalarProduct(delta, delta)) return true; + } + return false; +} + +// ELF 0x2F3450. +void GTSDataOptimiser::removeVerticesAndRebuildPolygon(const VertexRemovalMap& removals) +{ + for (VertexRemovalMap::const_iterator i = removals.begin(); i != removals.end(); ++i) + { + OptPolygon* polygon = i->first; + const unsigned char oldCount = polygon->m_numberOfVertices; + const unsigned char count = static_cast(oldCount - i->second.size()); + DoubleVec3* vertices = new DoubleVec3[count](); + OptPolygon** neighbours = new OptPolygon*[count]; + unsigned char output = 0; + for (unsigned char corner = 0; corner < oldCount; ++corner) + { + bool remove = false; + for (std::vector::const_iterator v = i->second.begin(); + v != i->second.end(); ++v) + { + const DoubleVec3 delta = difference(polygon->m_vertices[corner], **v); + if (DBL_EPSILON > scalarProduct(delta, delta)) { remove = true; break; } + } + if (!remove) + { + vertices[output] = polygon->m_vertices[corner]; + neighbours[output++] = polygon->m_neighbours[corner]; + } + } + polygon->deleteMembers(); + polygon->m_numberOfVertices = count; + polygon->m_vertices = vertices; + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours = neighbours; + } +} + +// ELF 0x2F3D60. +OptPolygon* GTSDataOptimiser::createPolygon() const { return checkPointer(new OptPolygon); } + +// ELF 0x2F3EF0. Only the two-to-one pass is enabled in the shipped optimiser. +void GTSDataOptimiser::optimise(const std::vector& parts) +{ + m_graph->resetTempMemberSizes(); + std::set removed; + while (twoToOneMerge(removed)) {} + delete[] m_graph->m_tempMemberSizes; + m_graph->m_tempMemberSizes = 0; + setPolygonIndices(parts); +} + +// ELF 0x2F5340. +void GTSDataOptimiser::setPolygonIndices(const std::vector& parts) +{ + ClusterGraph::ClusterPolygonMap clusters; + const std::set& removed = m_graph->m_set18; + std::map oldParts; + unsigned int part = 0; + for (std::vector::const_iterator p = parts.begin(); p != parts.end(); ++p, ++part) + for (std::vector::const_iterator i = (*p)->m_polygons.begin(); + i != (*p)->m_polygons.end(); ++i) + oldParts.insert(std::make_pair(*i, part)); + ClusterGraph::DynamicPolygonMap newParts; + unsigned int index = 0; + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i, ++index) + { + OptPolygon* polygon = *i; + if (removed.find(polygon->m_index) == removed.end()) + { + for (unsigned short cluster = 0; cluster < m_graph->m_numberOfClusters; ++cluster) + if (polygon->m_cluster == cluster) + { + ClusterGraph::ClusterPolygonMap::iterator entry = clusters.find(cluster); + if (entry == clusters.end()) + { + std::list indices; + indices.insert(indices.end(), index); + clusters.insert(std::make_pair(cluster, indices)); + } + else entry->second.insert(entry->second.end(), index); + } + } + else + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 623, "") + << "We shouldn't come here!"; + std::map::iterator entry = oldParts.find(polygon->m_index); + if (entry != oldParts.end()) + newParts.insert(std::make_pair(index, + std::make_pair(entry->second, parts[entry->second]->m_initiallyWalkable))); + polygon->m_index = index; + } + m_graph->updateClustersAfterOptimisation(newParts, m_polygons, clusters); +} + +// ELF 0x2F5D20. Dropping a previous list does not destroy its polygons, as shipped. +void GTSDataOptimiser::buildOptMeshFromTriangles(DoublePolygon* triangles, DoubleVec3* vertices, + unsigned int* vertexIndices, unsigned int* neighbourIndices, unsigned int count, QuadTree* tree) +{ + m_polygons.resize(0, static_cast(0)); + std::vector polygons; + std::set dynamic; + for (std::vector::const_iterator p = tree->m_destroyableMapParts.begin(); + p != tree->m_destroyableMapParts.end(); ++p) + { + const std::vector indices = (*p)->m_polygons; + for (std::vector::const_iterator i = indices.begin(); i != indices.end(); ++i) + dynamic.insert(*i); + } + for (unsigned int i = 0; i < count; ++i) + { + OptPolygon* polygon = createPolygon(); + polygon->m_numberOfVertices = triangles[i].m_numberOfVertices; + polygon->m_vertices = new DoubleVec3[polygon->m_numberOfVertices](); + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours = new OptPolygon*[polygon->m_numberOfVertices]; + polygon->m_originalMaterial = triangles[i].m_material; + polygon->m_material = dynamic.find(i) == dynamic.end() ? triangles[i].m_material : 8; + if (polygon->m_normal) *polygon->m_normal = triangles[i].m_normal; + else polygon->m_normal = new DoubleVec3(triangles[i].m_normal); + polygon->m_index = i; + polygon->m_cluster = triangles[i].m_cluster; + for (unsigned int corner = 0; corner < triangles[i].m_numberOfVertices; ++corner) + { + polygon->m_vertices[corner] = vertices[vertexIndices[triangles[i].m_firstIndex + corner]]; + delete polygon->m_normal; + polygon->m_normal = 0; + } + m_polygons.insert(m_polygons.end(), polygon); + polygons.push_back(polygon); + } + unsigned int i = 0; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p, ++i) + for (unsigned int corner = 0; corner < triangles[i].m_numberOfVertices; ++corner) + { + const unsigned int neighbour = neighbourIndices[triangles[i].m_firstIndex + corner]; + (*p)->m_neighbours[corner] = neighbour == ~0u ? 0 : polygons[neighbour]; + } +} + +// ELF 0x2FB170. The two counters are diagnostic inputs unused by the shipped body. +void GTSDataOptimiser::cleanPolygon(OptPolygon* polygon, unsigned int, unsigned int) +{ + std::list vertices; + std::list neighbours; + VertexRemovalMap removals; + const unsigned char count = polygon->m_numberOfVertices; + unsigned char next = 1; + unsigned char previous = static_cast(count - 1); + for (unsigned char corner = 0; corner < count; ++corner) + { + OptPolygon* neighbour = polygon->m_neighbours[corner]; + bool remove = false; + if (neighbour == polygon->m_neighbours[previous] && + (!neighbour || neighbour->m_numberOfVertices > 3)) + { + DoubleVec3 forward = difference(polygon->m_vertices[next], polygon->m_vertices[corner]); + normaliseDouble(forward); + DoubleVec3 backward = difference(polygon->m_vertices[previous], polygon->m_vertices[corner]); + normaliseDouble(backward); + remove = static_cast(0.01f) > scalarProduct(backward, forward) + 1.0; + } + if (remove) + { + if (neighbour) + { + VertexRemovalMap::iterator entry = removals.find(neighbour); + if (entry == removals.end()) + { + std::vector indices; + indices.push_back(&polygon->m_vertices[corner]); + removals.insert(std::make_pair(neighbour, indices)); + } + else entry->second.push_back(&polygon->m_vertices[corner]); + } + // shipped defect: previous advances only when a vertex is retained. + } + else + { + vertices.insert(vertices.end(), polygon->m_vertices[corner]); + neighbours.insert(neighbours.end(), polygon->m_neighbours[corner]); + previous = static_cast(previous + 1) % count; + } + next = static_cast(next + 1) % count; + } + removeVerticesAndRebuildPolygon(removals); + polygon->deleteMembers(); + polygon->m_numberOfVertices = static_cast(vertices.size()); + polygon->m_neighbours = new OptPolygon*[polygon->m_numberOfVertices]; + polygon->m_vertices = new DoubleVec3[polygon->m_numberOfVertices](); + delete polygon->m_normal; + polygon->m_normal = 0; + unsigned int corner = 0; + std::list::const_iterator n = neighbours.begin(); + for (std::list::const_iterator v = vertices.begin(); v != vertices.end(); ++v, ++n, ++corner) + { + polygon->m_vertices[corner] = *v; + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours[corner] = *n; + } +} + +// ELF 0x2F6380. +bool GTSDataOptimiser::twoToOneMerge(std::set& removed) +{ + std::set created; + static unsigned int callTimes = 0; + ++callTimes; + bool merged = false; + unsigned int ordinal = 0; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p) + { + ++ordinal; + OptPolygon* polygon = *p; + OptPolygon* output = 0; + if (removed.find(polygon) != removed.end()) continue; + const int count = polygon->m_numberOfVertices; + for (int edge = 0; edge < count; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (!neighbour || neighbour->m_material != polygon->m_material || + neighbour->m_material == 8 || polygon->m_material == 8) continue; + const DoubleVec3* neighbourNormal = neighbour->getNormal(); + const DoubleVec3* polygonNormal = polygon->getNormal(); + if (normalAngle(*polygonNormal, *neighbourNormal) > 0.08726646f) continue; + if (polygon->m_neighbours[wrappedIndex(edge - 1, count)] == neighbour) continue; + if (created.find(neighbour) != created.end()) continue; + if (removed.find(neighbour) != removed.end()) + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 955, "") + << "Neighbour " << static_cast(neighbour) << " has previously been removed!"; + const int otherCount = neighbour->m_numberOfVertices; + DoubleVec2 backward = {}; + getVectorToXZDouble(polygon->m_vertices[edge], + polygon->m_vertices[wrappedIndex(edge - 1, count)], backward); + int firstOther = otherCount - 1; + for (; firstOther >= 0; --firstOther) + if (neighbour->m_neighbours[firstOther] != polygon && + neighbour->m_neighbours[wrappedIndex(firstOther - 1, otherCount)] == polygon) + break; + DoubleVec2 normal = {}; + DoubleVec3 vertex = neighbour->m_vertices[firstOther]; + getVectorToXZDouble(vertex, neighbour->m_vertices[wrappedIndex(firstOther + 1, otherCount)], normal); + getNormalDouble(normal, normal); + if (normal.x * backward.x + normal.y * backward.y < 0.0) continue; + DoubleVec2 forward = {}; + int last = edge; + int lastOther = firstOther; + do + { + last = wrappedIndex(last + 1, count); + lastOther = wrappedIndex(lastOther - 1, otherCount); + } while (polygon->m_neighbours[last] == neighbour); + getVectorToXZDouble(polygon->m_vertices[last], + polygon->m_vertices[wrappedIndex(last + 1, count)], forward); + normal = DoubleVec2{}; + vertex = neighbour->m_vertices[lastOther]; + getVectorToXZDouble(neighbour->m_vertices[wrappedIndex(lastOther - 1, otherCount)], vertex, normal); + getNormalDouble(normal, normal); + if (normal.x * forward.x + normal.y * forward.y < 0.0) continue; + + OptPolygon* retained = neighbour; + OptPolygon* discarded = polygon; + unsigned short retainedCluster = neighbour->m_cluster; + unsigned short discardedCluster = polygon->m_cluster; + unsigned int remaining = m_graph->m_tempMemberSizes[discardedCluster]; + const unsigned int otherSize = m_graph->m_tempMemberSizes[retainedCluster]; + if (remaining <= otherSize) + { + retained = polygon; + discarded = neighbour; + retainedCluster = polygon->m_cluster; + discardedCluster = neighbour->m_cluster; + remaining = otherSize; + } + --remaining; + if (retainedCluster != discardedCluster && remaining > 1) + { + std::set visited; + if (!m_graph->validateClusterConnectivityFromPolygon(discardedCluster, discarded, + remaining, visited, false)) + { + visited.clear(); + continue; + } + } + output = createPolygon(); + output->m_index = retained->m_index; + output->m_cluster = retainedCluster; + m_graph->m_set18.insert(discarded->m_index); + m_graph->m_tempMemberSizes[discardedCluster] = remaining; + std::list vertices; + std::list neighbours; + for (int corner = firstOther; corner != lastOther; corner = wrappedIndex(corner + 1, otherCount)) + { + vertices.insert(vertices.end(), &neighbour->m_vertices[corner]); + OptPolygon* next = neighbour->m_neighbours[corner]; + if (next) + { + next->changeNeighbour(neighbour->m_vertices[corner], neighbour, output); + neighbour->changeNeighbour(neighbour->m_vertices[(corner + 1) % neighbour->m_numberOfVertices], next, 0); + } + neighbours.insert(neighbours.end(), next); + } + for (int corner = 0; corner < neighbour->m_numberOfVertices; ++corner) + if (neighbour->m_neighbours[corner]) + neighbour->m_neighbours[corner]->changeNeighbour(neighbour->m_vertices[corner], neighbour, 0); + for (int corner = last; corner != edge; corner = wrappedIndex(corner + 1, count)) + { + vertices.insert(vertices.end(), &polygon->m_vertices[corner]); + OptPolygon* next = polygon->m_neighbours[corner]; + if (next) + { + next->changeNeighbour(polygon->m_vertices[corner], polygon, output); + polygon->changeNeighbour(polygon->m_vertices[(corner + 1) % polygon->m_numberOfVertices], next, 0); + } + neighbours.insert(neighbours.end(), next); + } + for (int corner = 0; corner < polygon->m_numberOfVertices; ++corner) + if (polygon->m_neighbours[corner]) + polygon->m_neighbours[corner]->changeNeighbour(polygon->m_vertices[corner], polygon, 0); + output->m_numberOfVertices = static_cast(vertices.size()); + output->m_neighbours = new OptPolygon*[output->m_numberOfVertices]; + output->m_vertices = new DoubleVec3[output->m_numberOfVertices](); + delete output->m_normal; + output->m_normal = 0; + int corner = 0; + std::list::const_iterator n = neighbours.begin(); + for (std::list::const_iterator v = vertices.begin(); v != vertices.end(); ++v, ++n, ++corner) + { + output->m_vertices[corner] = **v; + delete output->m_normal; + output->m_normal = 0; + output->m_neighbours[corner] = *n; + } + output->m_material = polygon->m_material; + output->m_originalMaterial = polygon->m_originalMaterial; + cleanPolygon(output, ordinal, callTimes); + removed.insert(neighbour); + removed.insert(polygon); + created.insert(output); + merged = true; + break; + } + } + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end();) + { + if (removed.find(*p) == removed.end()) { ++p; continue; } + OptPolygon* polygon = *p; + m_polygons.erase(p++); + destroyPolygon(polygon); + } + removed.clear(); + for (std::set::const_iterator p = created.begin(); p != created.end(); ++p) + m_polygons.insert(m_polygons.end(), *p); + return merged; +} + +// ELF 0x2F4000. Retail dead code: every polygon is treated as a triangle without checking its size. +void GTSDataOptimiser::removeTooThinTriangles() +{ + std::set removed; + const double minimumSquared = 0.0025000000000000005; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p) + { + OptPolygon* polygon = *p; + if (removed.find(polygon) != removed.end()) continue; + double shortest = DBL_MAX; + bool shortEdge = false; + unsigned char edge = 0; + OptPolygon* neighbour = 0; + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 delta = difference(polygon->m_vertices[i], polygon->m_vertices[(i + 1) % 3]); + const double lengthSquared = scalarProduct(delta, delta); + if (minimumSquared > lengthSquared && shortest > lengthSquared) + { + shortEdge = true; + neighbour = polygon->m_neighbours[i]; + edge = i; + shortest = lengthSquared; + } + } + if (shortEdge) + { + for (unsigned char i = 0; i <= 2; ++i) + { + if (i == edge) + { + const unsigned char first = (edge + 1) % 3; + const unsigned char second = (edge + 2) % 3; + OptPolygon* a = polygon->m_neighbours[first]; + OptPolygon* b = polygon->m_neighbours[second]; + if (a) a->changeNeighbour(polygon->m_vertices[first], polygon, b); + if (b) b->changeNeighbour(polygon->m_vertices[second], polygon, a); + } + if (neighbour && neighbour->m_neighbours[i] == polygon) + { + const unsigned char first = (i + 1) % 3; + const unsigned char second = (i + 2) % 3; + OptPolygon* a = neighbour->m_neighbours[first]; + OptPolygon* b = neighbour->m_neighbours[second]; + if (a) a->changeNeighbour(neighbour->m_vertices[first], neighbour, b); + if (b) b->changeNeighbour(neighbour->m_vertices[second], neighbour, a); + } + } + const DoubleVec3 oldVertex = polygon->m_vertices[edge]; + const DoubleVec3 newVertex = polygon->m_vertices[(edge + 1) % 3]; + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + if (removed.find(*i) == removed.end()) (*i)->changeVertex(oldVertex, newVertex); + removed.insert(polygon); + if (neighbour) removed.insert(neighbour); + } + else + { + unsigned char longestEdge = 0; + double longest = 0.0; + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 delta = difference(polygon->m_vertices[(i + 1) % 3], polygon->m_vertices[i % 3]); + const double lengthSquared = scalarProduct(delta, delta); + if (lengthSquared > longest) { longest = lengthSquared; longestEdge = i; } + } + const unsigned char end = (longestEdge + 1) % 3; + const unsigned char opposite = (longestEdge + 2) % 3; + const DoubleVec3* a = &polygon->m_vertices[longestEdge]; + const DoubleVec3* b = &polygon->m_vertices[end]; + DoubleVec3 direction = difference(*b, *a); + normaliseDouble(direction); + const DoubleVec3 toOpposite = difference(polygon->m_vertices[opposite], *a); + const double projection = scalarProduct(direction, toOpposite); + if (!(minimumSquared > scalarProduct(toOpposite, toOpposite) - projection * projection)) continue; + OptPolygon* before = polygon->m_neighbours[opposite]; + OptPolygon* across = polygon->m_neighbours[longestEdge]; + OptPolygon* after = polygon->m_neighbours[end]; + OptPolygon* split[2] = {}; + const DoubleVec3 midpoint = { (b->x + a->x) * 0.5, (b->y + a->y) * 0.5, (b->z + a->z) * 0.5 }; + if (across) + { + split[0] = createPolygon(); + split[1] = createPolygon(); + for (unsigned char half = 0; half <= 1; ++half) + { + OptPolygon* output = split[half]; + output->m_numberOfVertices = 3; + output->m_vertices = new DoubleVec3[output->m_numberOfVertices](); + delete output->m_normal; + output->m_normal = 0; + output->m_neighbours = new OptPolygon*[output->m_numberOfVertices]; + // shipped defect: material stays at its constructor value of zero. + output->m_originalMaterial = across->m_material; + const DoubleVec3* normal = across->getNormal(); + if (output->m_normal) *output->m_normal = *normal; + else output->m_normal = new DoubleVec3(*normal); + output->m_index = static_cast(m_polygons.size()); + output->m_cluster = across->m_cluster; + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 delta = difference(across->m_vertices[i], half == 0 ? *b : *a); + output->m_vertices[i] = DBL_EPSILON > scalarProduct(delta, delta) ? midpoint : across->m_vertices[i]; + delete output->m_normal; + output->m_normal = 0; + } + for (unsigned char i = 0; i <= 2; ++i) + { + const DoubleVec3 current = difference(output->m_vertices[i], midpoint); + const DoubleVec3 next = difference(output->m_vertices[(i + 1) % 3], midpoint); + if (half == 0) + { + if (DBL_EPSILON > scalarProduct(next, next)) output->m_neighbours[i] = split[1]; + else if (DBL_EPSILON > scalarProduct(current, current)) output->m_neighbours[i] = before; + else + { + output->m_neighbours[i] = across->m_neighbours[i]; + if (output->m_neighbours[i]) + output->m_neighbours[i]->changeNeighbour(across->m_vertices[i], across, output); + } + } + else + { + if (DBL_EPSILON > scalarProduct(current, current)) output->m_neighbours[i] = split[0]; + else if (DBL_EPSILON > scalarProduct(next, next)) output->m_neighbours[i] = after; + else + { + output->m_neighbours[i] = across->m_neighbours[i]; + if (output->m_neighbours[i]) + output->m_neighbours[i]->changeNeighbour(across->m_vertices[i], across, output); + } + } + } + m_polygons.insert(m_polygons.end(), split[half]); + } + ++m_graph->m_tempMemberSizes[across->m_cluster]; + removed.insert(across); + } + if (before) before->changeNeighbour(polygon->m_vertices[opposite], polygon, split[0]); + if (after) after->changeNeighbour(polygon->m_vertices[end], polygon, split[1]); + const DoubleVec3 oldVertex = polygon->m_vertices[opposite]; + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end(); ++i) + if (removed.find(*i) == removed.end()) (*i)->changeVertex(oldVertex, midpoint); + removed.insert(polygon); + } + } + for (std::list::iterator i = m_polygons.begin(); i != m_polygons.end();) + { + if (removed.find(*i) == removed.end()) { ++i; continue; } + OptPolygon* polygon = *i; + m_graph->m_set18.insert(polygon->m_index); + --m_graph->m_tempMemberSizes[polygon->m_cluster]; + m_polygons.erase(i++); + destroyPolygon(polygon); + } +} + +// ELF 0x2F7650. Retail dead code; cluster membership and original material are not repaired here. +bool GTSDataOptimiser::threeToTwoMerge() +{ + // Names of these inlined list/array operations are inferred. + const auto append = [](OptPolygon* source, int corner, OptPolygon* output, + std::list& vertices, std::list& neighbours) + { + vertices.insert(vertices.end(), source->m_vertices[corner]); + OptPolygon* neighbour = source->m_neighbours[corner]; + if (neighbour) neighbour->changeNeighbour(source->m_vertices[corner], source, output); + neighbours.insert(neighbours.end(), neighbour); + }; + const auto range = [&append](OptPolygon* source, int start, int end, OptPolygon* output, + std::list& vertices, std::list& neighbours) + { + for (int i = start; i != end; i = wrappedIndex(i + 1, source->m_numberOfVertices)) + append(source, i, output, vertices, neighbours); + }; + const auto install = [](OptPolygon* output, const std::list& vertices, + const std::list& neighbours, unsigned char material) + { + const int count = static_cast(vertices.size()); + DoubleVec3* v = new DoubleVec3[count](); + OptPolygon** n = new OptPolygon*[count]; + std::list::const_iterator vi = vertices.begin(); + std::list::const_iterator ni = neighbours.begin(); + for (int i = 0; i < count; ++i, ++vi, ++ni) { v[i] = *vi; n[i] = *ni; } + output->m_numberOfVertices = static_cast(count); + output->m_vertices = v; + delete output->m_normal; + output->m_normal = 0; + output->m_neighbours = n; + output->m_material = material; + }; + const auto splitExternal = [](OptPolygon* polygon, OptPolygon* target, OptPolygon* first, + OptPolygon* second, const DoubleVec3& intersection, bool wrap) + { + const int count = polygon->m_numberOfVertices; + DoubleVec3* vertices = new DoubleVec3[count + 1](); + OptPolygon** neighbours = new OptPolygon*[count + 1]; + int corner = 0; + if (wrap && polygon->m_neighbours[count - 1] == target && polygon->m_neighbours[0] == target) + { + for (; corner < count - 1; ++corner) + { + vertices[corner] = polygon->m_vertices[corner]; + neighbours[corner] = polygon->m_neighbours[corner]; + } + } + else + { + for (; polygon->m_neighbours[corner] != target; ++corner) + { + vertices[corner] = polygon->m_vertices[corner]; + neighbours[corner] = polygon->m_neighbours[corner]; + } + } + vertices[corner] = polygon->m_vertices[corner]; + neighbours[corner] = first; + ++corner; + vertices[corner] = intersection; + neighbours[corner] = second; + for (; corner < count; ++corner) + { + vertices[corner + 1] = polygon->m_vertices[corner]; + neighbours[corner + 1] = polygon->m_neighbours[corner]; + } + polygon->deleteMembers(); + if (wrap) + { + polygon->m_vertices = vertices; + polygon->m_numberOfVertices = static_cast(count + 1); + } + else + { + polygon->m_numberOfVertices = static_cast(count + 1); + polygon->m_vertices = vertices; + } + delete polygon->m_normal; + polygon->m_normal = 0; + polygon->m_neighbours = neighbours; + }; + const auto replaceAll = [](OptPolygon* polygon, OptPolygon* old, OptPolygon* replacement) + { + if (polygon) + for (int i = 0; i < polygon->m_numberOfVertices; ++i) + if (polygon->m_neighbours[i] == old) polygon->m_neighbours[i] = replacement; + }; + const auto eraseInputs = [this](OptPolygon* a, OptPolygon* b, OptPolygon* c, bool stopAtThree) + { + int count = 0; + for (std::list::iterator i = m_polygons.begin(); + i != m_polygons.end() && (!stopAtThree || count < 3);) + { + if (*i == a || *i == b || *i == c) + { + ++count; + destroyPolygon(*i); + m_polygons.erase(i++); + } + else ++i; + } + }; + const auto sign = [](double value) { return value > 0.0 ? 1.0 : value < 0.0 ? -1.0 : 0.0; }; + for (std::list::iterator p = m_polygons.begin(); p != m_polygons.end(); ++p) + { + OptPolygon* polygon = *p; + const unsigned char material = polygon->m_material; + const int count = polygon->m_numberOfVertices; + if (count <= 3) continue; + for (int edge = 0; edge < count; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (!neighbour) continue; + OptPolygon* third = polygon->m_neighbours[wrappedIndex(edge + 1, count)]; + if (neighbour == third) continue; + OptPolygon* previous = polygon->m_neighbours[wrappedIndex(edge - 1, count)]; + if (neighbour == previous || neighbour->m_numberOfVertices <= 3) continue; + const int otherCount = neighbour->m_numberOfVertices; + int otherEdge = 0; + for (; otherEdge < otherCount; ++otherEdge) + if (neighbour->m_neighbours[otherEdge] == polygon) break; + if (!third || neighbour->m_neighbours[wrappedIndex(otherEdge - 1, otherCount)] != third) + { + third = previous; + if (!third || neighbour->m_neighbours[wrappedIndex(otherEdge + 1, otherCount)] != third) continue; + } + if (neighbour->m_material != polygon->m_material || third->m_material != polygon->m_material) continue; + const DoubleVec3* normal = polygon->getNormal(); + const DoubleVec3* otherNormal = neighbour->getNormal(); + const DoubleVec3* thirdNormal = third->getNormal(); + if (normalAngle(*otherNormal, *normal) > 0.08726646f) continue; + // shipped defect: the second angle compares the neighbour's normal with itself. + if (normalAngle(*otherNormal, *otherNormal) > 0.08726646f) continue; + if (normalAngle(*otherNormal, *thirdNormal) > 0.08726646f) continue; + const int thirdCount = third->m_numberOfVertices; + int thirdEdge = 0; + bool swap = false; + for (; thirdEdge < thirdCount; ++thirdEdge) + { + if (third->m_neighbours[thirdEdge] == polygon) + { + if (thirdEdge <= 0 && third->m_neighbours[thirdCount - 1] == neighbour) + { thirdEdge = thirdCount - 1; swap = true; } + break; + } + if (third->m_neighbours[thirdEdge] == neighbour) + { + swap = true; + if (thirdEdge <= 0 && third->m_neighbours[thirdCount - 1] == polygon) + { thirdEdge = thirdCount - 1; swap = false; } + break; + } + } + OptPolygon* a = swap ? neighbour : polygon; + OptPolygon* b = swap ? polygon : neighbour; + const int ac = swap ? otherCount : count; + const int bc = swap ? count : otherCount; + const int ai = wrappedIndex((swap ? otherEdge : edge) + 1, ac); + const int bi = swap ? edge : otherEdge; + const int aBegin = wrappedIndex(ai + 1, ac); + const int aEnd = wrappedIndex(ai - 1, ac); + const int bBegin = wrappedIndex(bi + 1, bc); + const int bEnd = wrappedIndex(bi - 1, bc); + const int cBegin = wrappedIndex(thirdEdge + 2, thirdCount); + DoubleVec2 vector = {}, perpendicular = {}; + getVectorToXZDouble(a->m_vertices[aBegin], a->m_vertices[wrappedIndex(ai + 2, ac)], vector); + getVectorToXZDouble(third->m_vertices[wrappedIndex(thirdEdge - 1, thirdCount)], + third->m_vertices[thirdEdge], perpendicular); + getNormalDouble(perpendicular, perpendicular); + if (perpendicular.x * vector.x + perpendicular.y * vector.y > 0.0) continue; + vector = DoubleVec2{}; + getVectorToXZDouble(b->m_vertices[wrappedIndex(bi - 2, bc)], b->m_vertices[bEnd], vector); + perpendicular = DoubleVec2{}; + getVectorToXZDouble(third->m_vertices[cBegin], + third->m_vertices[wrappedIndex(thirdEdge + 3, thirdCount)], perpendicular); + getNormalDouble(perpendicular, perpendicular); + if (perpendicular.x * vector.x + perpendicular.y * vector.y < 0.0) continue; + vector = DoubleVec2{}; + getVectorToXZDouble(b->m_vertices[bBegin], b->m_vertices[wrappedIndex(bi + 2, bc)], vector); + perpendicular = DoubleVec2{}; + getVectorToXZDouble(a->m_vertices[aEnd], a->m_vertices[wrappedIndex(ai - 2, ac)], perpendicular); + getNormalDouble(perpendicular, perpendicular); + if (perpendicular.x * vector.x + perpendicular.y * vector.y <= 0.0) + { + OptPolygon* output = createPolygon(); + std::list vertices; + std::list neighbours; + range(a, aBegin, aEnd, output, vertices, neighbours); + range(b, bBegin, bEnd, output, vertices, neighbours); + range(third, cBegin, thirdEdge, output, vertices, neighbours); + eraseInputs(a, b, third, false); + install(output, vertices, neighbours, material); + m_polygons.insert(m_polygons.end(), output); + return true; + } + DoubleVec3 intersection = {}; + const DoubleVec3* lineEnd = &a->m_vertices[aEnd]; + const DoubleVec3* lineStart = &a->m_vertices[wrappedIndex(ai - 2, ac)]; + perpendicular = DoubleVec2{}; + getVectorToXZDouble(*lineStart, *lineEnd, perpendicular); + getNormalDouble(perpendicular, perpendicular); + vector = DoubleVec2{}; + getVectorToXZDouble(a->m_vertices[ai], *lineEnd, vector); + if (perpendicular.x * vector.x + perpendicular.y * vector.y != 0.0) + for (int cut = wrappedIndex(bi + 2, bc); cut != bEnd; cut = wrappedIndex(cut + 1, bc)) + { + const int next = wrappedIndex(cut + 1, bc); + DoubleVec2 currentSide = {}, nextSide = {}; + getVectorToXZDouble(*lineEnd, b->m_vertices[cut], currentSide); + const double firstSide = currentSide.x * perpendicular.x + currentSide.y * perpendicular.y; + getVectorToXZDouble(*lineEnd, b->m_vertices[next], nextSide); + const double secondSide = nextSide.x * perpendicular.x + nextSide.y * perpendicular.y; + if (sign(firstSide) == sign(secondSide) || secondSide == 0.0) continue; + lineIntersect(b->m_vertices[cut], b->m_vertices[next], *lineStart, *lineEnd, intersection); + const DoubleVec3 delta = difference(b->m_vertices[cut], intersection); + const bool split = !(static_cast(0.1f) > scalarProduct(delta, delta)); + if (!split) intersection = b->m_vertices[cut]; + OptPolygon* first = createPolygon(); + OptPolygon* second = createPolygon(); + { + std::list vertices; + std::list neighbours; + range(a, aBegin, aEnd, first, vertices, neighbours); + vertices.insert(vertices.end(), a->m_vertices[aEnd]); + neighbours.insert(neighbours.end(), second); + if (split) + { + vertices.insert(vertices.end(), intersection); + neighbours.insert(neighbours.end(), b->m_neighbours[cut]); + } + else append(b, cut, first, vertices, neighbours); + range(b, next, bEnd, first, vertices, neighbours); + range(third, cBegin, thirdEdge, first, vertices, neighbours); + install(first, vertices, neighbours, material); + } + { + std::list vertices; + std::list neighbours; + range(b, bBegin, cut, second, vertices, neighbours); + if (split) + { + append(b, cut, second, vertices, neighbours); + vertices.insert(vertices.end(), intersection); + neighbours.insert(neighbours.end(), first); + } + else + { + vertices.insert(vertices.end(), b->m_vertices[cut]); + neighbours.insert(neighbours.end(), first); + } + install(second, vertices, neighbours, material); + } + if (split && b->m_neighbours[cut]) + splitExternal(b->m_neighbours[cut], second, first, second, intersection, false); + eraseInputs(a, b, third, false); + m_polygons.insert(m_polygons.end(), first); + m_polygons.insert(m_polygons.end(), second); + return true; + } + lineEnd = &b->m_vertices[bBegin]; + lineStart = &b->m_vertices[wrappedIndex(bi + 2, bc)]; + perpendicular = DoubleVec2{}; + getVectorToXZDouble(*lineStart, *lineEnd, perpendicular); + getNormalDouble(perpendicular, perpendicular); + vector = DoubleVec2{}; + getVectorToXZDouble(b->m_vertices[bi], *lineEnd, vector); + if (perpendicular.x * vector.x + perpendicular.y * vector.y == 0.0) continue; + for (int cut = aBegin; cut != wrappedIndex(ai - 2, ac); cut = wrappedIndex(cut + 1, ac)) + { + const int next = wrappedIndex(cut + 1, ac); + DoubleVec2 currentSide = {}, nextSide = {}; + getVectorToXZDouble(*lineEnd, a->m_vertices[cut], currentSide); + const double firstSide = currentSide.x * perpendicular.x + currentSide.y * perpendicular.y; + getVectorToXZDouble(*lineEnd, a->m_vertices[next], nextSide); + const double secondSide = nextSide.x * perpendicular.x + nextSide.y * perpendicular.y; + if (sign(firstSide) == sign(secondSide) || secondSide == 0.0) continue; + lineIntersect(a->m_vertices[cut], a->m_vertices[next], *lineStart, *lineEnd, intersection); + const DoubleVec3 delta = difference(a->m_vertices[cut], intersection); + const bool split = !(static_cast(0.1f) > scalarProduct(delta, delta)); + if (!split) intersection = a->m_vertices[cut]; + OptPolygon* first = createPolygon(); + OptPolygon* second = createPolygon(); + { + std::list vertices; + std::list neighbours; + range(a, aBegin, next, first, vertices, neighbours); + if (split) + { + vertices.insert(vertices.end(), intersection); + neighbours.insert(neighbours.end(), second); + } + else + { + replaceAll(a->m_neighbours[wrappedIndex(next - 1, ac)], a, first); + neighbours.back() = second; + } + range(b, bBegin, bEnd, first, vertices, neighbours); + range(third, cBegin, wrappedIndex(thirdEdge, thirdCount), first, vertices, neighbours); + install(first, vertices, neighbours, material); + } + { + std::list vertices; + std::list neighbours; + range(a, next, aEnd, second, vertices, neighbours); + vertices.insert(vertices.end(), a->m_vertices[aEnd]); + neighbours.insert(neighbours.end(), first); + OptPolygon* neighbour = a->m_neighbours[cut]; + if (split) + { + vertices.insert(vertices.end(), intersection); + replaceAll(neighbour, a, second); + } + else + { + vertices.insert(vertices.end(), a->m_vertices[cut]); + if (neighbour) neighbour->changeNeighbour(a->m_vertices[cut], a, second); + } + neighbours.insert(neighbours.end(), neighbour); + install(second, vertices, neighbours, material); + } + if (split && a->m_neighbours[cut]) + splitExternal(a->m_neighbours[cut], first, second, first, intersection, true); + eraseInputs(a, b, third, true); + m_polygons.insert(m_polygons.end(), first); + m_polygons.insert(m_polygons.end(), second); + return true; + } + } + } + return false; +} + +// ELF 0x2FBBA0. +DoubleVec2& GTSDataOptimiser::getVectorToXZDouble(const DoubleVec3& from, const DoubleVec3& to, + DoubleVec2& result) +{ + result.x = to.x - from.x; + result.y = to.z - from.z; + return result; +} + +// ELF 0x2FBBC0. Preserve the read before either write for aliased input/output. +DoubleVec2& GTSDataOptimiser::getNormalDouble(const DoubleVec2& vector, DoubleVec2& result) +{ + const double negativeX = -vector.x; + result.x = vector.y; + result.y = negativeX; + return result; +} + +// ELF 0x2FBBE0. +bool GTSDataOptimiser::lineIntersect(const DoubleVec3& a, const DoubleVec3& b, + const DoubleVec3& c, const DoubleVec3& d, DoubleVec3& result) +{ + const DoubleVec3 first = difference(b, a); + DoubleVec3 firstUnit = first; + normaliseDouble(firstUnit); + const DoubleVec3 second = difference(d, c); + DoubleVec3 secondUnit = second; + normaliseDouble(secondUnit); + if (static_cast(0.001f) > std::fabs(std::fabs(scalarProduct(firstUnit, secondUnit)) - 1.0)) + return false; + const DoubleVec3 origin = a; + const DoubleVec3 separation = difference(c, a); + const DoubleVec3 cross = vectorProduct(first, second); + const DoubleVec3 numerator = vectorProduct(separation, second); + const double denominator = scalarProduct(cross, cross); + if (denominator != 0.0) + { + const double scale = scalarProduct(cross, numerator) / denominator; + const DoubleVec3 displacement = { first.x * scale, first.y * scale, first.z * scale }; + result = displacement; + // shipped defect: output aliasing a adds the displacement to itself. + result.x = displacement.x + a.x; + result.y = displacement.y + a.y; + result.z = displacement.z + a.z; + return true; + } + if (scalarProduct(numerator, numerator) == 0.0) { result = origin; return true; } + return false; +} + +// ELF 0x2FC080. Tests whether first occurs in second's neighbour array. +bool GTSDataOptimiser::isNeighbourOfPolygon(OptPolygon* first, OptPolygon* second) const +{ + const unsigned char count = second->m_numberOfVertices; + for (unsigned char edge = 0; edge < count; ++edge) + if (second->m_neighbours[edge] == first) return true; + return false; +} + +// ELF 0x2FC0C0. +void GTSDataOptimiser::validateNeighbours(OptPolygon* polygon) const +{ + unsigned char count = polygon->m_numberOfVertices; + for (unsigned int edge = 0; edge < count; ++edge) + { + OptPolygon* neighbour = polygon->m_neighbours[edge]; + if (!neighbour) continue; + bool found = false; + const DoubleVec3& vertex = polygon->m_vertices[edge]; + for (unsigned int corner = 0; corner < neighbour->m_numberOfVertices; ++corner) + { + const DoubleVec3 delta = difference(vertex, neighbour->m_vertices[corner]); + if (DBL_EPSILON > scalarProduct(delta, delta)) { found = true; break; } + } + if (!found) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 2429, "") + << "Couldn't find common neighbour vertex for polygon " << static_cast(polygon); + count = polygon->m_numberOfVertices; + } + } +} + +// ELF 0x2FC320. +void GTSDataOptimiser::validateNeighbourRelations(const std::set& removed) +{ + for (OptPolygon* polygon = initPolygonIteration(); polygon; polygon = getNextPolygon()) + { + if (removed.find(polygon) != removed.end()) continue; + validateNeighbours(polygon); + const unsigned char count = polygon->m_numberOfVertices; + for (unsigned char edge = 0; edge < count; ++edge) + if (removed.find(polygon->m_neighbours[edge]) != removed.end()) + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp", 2455, "") + << "Reference to removed polygon!"; + } +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h new file mode 100644 index 000000000..0ea4e0fc7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h @@ -0,0 +1,81 @@ +// Navigation mesh optimisation records. +#ifndef AI_AIDLL_GTS_DATA_OPTIMISER_H +#define AI_AIDLL_GTS_DATA_OPTIMISER_H + +#include +#include +#include +#include +#include "../../../../../Math/DoubleVec3.h" + +namespace dice { namespace hfe { +// Two-double record used by the optimiser's projected edge operations; member names [INFERRED]. +struct DoubleVec2 { double x, y; }; +namespace io { class File; } +namespace ai { + +class ClusterGraph; +class QuadTree; +class DoublePolygon; +class DestroyableMapPart; + +class OptPolygon +{ +public: + OptPolygon(); + ~OptPolygon(); + void deleteMembers(); + void calculateNormal() const; + const DoubleVec3* getNormal() const; + unsigned char findFirstNeighbourIndex(OptPolygon*) const; + void changeVertex(const DoubleVec3&, const DoubleVec3&); + void changeNeighbour(const DoubleVec3&, OptPolygon*, OptPolygon*); + void printPolygon(io::File&, int) const; + bool checkForDuplicateVertices() const; + + // Field names are inferred from the optimiser and QuadTree readers; offsets are ia-32. + /* +0x00 */ unsigned char m_numberOfVertices; + /* +0x04 */ DoubleVec3* m_vertices; + /* +0x08 */ OptPolygon** m_neighbours; + /* +0x0C */ unsigned char m_material; + /* +0x0D */ unsigned char m_originalMaterial; + /* +0x10 */ mutable DoubleVec3* m_normal; + /* +0x14 */ unsigned int m_index; + /* +0x18 */ unsigned short m_cluster; +}; + +class GTSDataOptimiser +{ +public: + explicit GTSDataOptimiser(ClusterGraph* graph); + ~GTSDataOptimiser(); + void destroyPolygon(OptPolygon* polygon); + void buildOptMeshFromTriangles(DoublePolygon*, DoubleVec3*, unsigned int*, unsigned int*, + unsigned int, QuadTree*); + void optimise(const std::vector&); + OptPolygon* initPolygonIteration(); + OptPolygon* getNextPolygon(); + unsigned int getNumberOfVertices() const; + typedef std::map > VertexRemovalMap; + void removeVerticesAndRebuildPolygon(const VertexRemovalMap&); + OptPolygon* createPolygon() const; + void removeTooThinTriangles(); + void setPolygonIndices(const std::vector&); + bool twoToOneMerge(std::set&); + bool threeToTwoMerge(); + void cleanPolygon(OptPolygon*, unsigned int, unsigned int); + DoubleVec2& getVectorToXZDouble(const DoubleVec3&, const DoubleVec3&, DoubleVec2&); + DoubleVec2& getNormalDouble(const DoubleVec2&, DoubleVec2&); + bool lineIntersect(const DoubleVec3&, const DoubleVec3&, const DoubleVec3&, + const DoubleVec3&, DoubleVec3&); + bool isNeighbourOfPolygon(OptPolygon*, OptPolygon*) const; + void validateNeighbours(OptPolygon*) const; + void validateNeighbourRelations(const std::set&); + + /* +0x00 */ std::list m_polygons; + /* +0x04 */ std::list::iterator m_current; + /* +0x08 */ ClusterGraph* m_graph; +}; + +} } } +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp index 839dd7f44..21771d8dd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp @@ -1,13 +1,16 @@ #include "MapProperties.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2FE200, __tcf_0 0x2FE260, _GLOBAL__I 0x2FE290). +#include #include namespace dice { namespace hfe { namespace ai { -// Initializes map traversal properties and their default limits. +// ELF 0x2FDE80 (C2; C1 0x2FDFA0). Initializes map traversal properties and their default limits. MapProperties::MapProperties() : m_maxSlopeCos(0.0f) , m_radius(0.0f) @@ -16,19 +19,19 @@ MapProperties::MapProperties() { } -// The whole body is the set's own teardown, which a C++ destructor does on its own. Empty here. +// ELF 0x2FE020 (D2; D1 0x2FE090). The whole body is the set's own teardown, which a C++ destructor does on its own. Empty here. MapProperties::~MapProperties() { } -// Tests only the Y component against the slope cosine. Requires a unit surface normal +// ELF 0x2FE100. Tests only the Y component against the slope cosine. Requires a unit surface normal // for slope semantics; the material argument is ignored. bool MapProperties::isValidGroundMesh(const Vec3& normal, unsigned char /*material*/) const { return m_maxSlopeCos <= normal.y; } -// Stores maximum slope as a cosine. The getter clamps it to [-1, 1] before acosf +// ELF 0x2FE130 / 0x2FE160. Stores maximum slope as a cosine. The getter clamps it to [-1, 1] before acosf // and returns the resulting angle in radians. void MapProperties::setMaxSlope(float radians) { @@ -46,27 +49,31 @@ float MapProperties::getMaxSlope() const return acosf(cosine); } +// ELF 0x2FE1B0. void MapProperties::setHeadClearance(float clearance) { m_headClearance = clearance; } +// ELF 0x2FE1C0. float MapProperties::getHeadClearance() const { return m_headClearance; } +// ELF 0x2FE1D0. void MapProperties::setRadius(float radius) { m_radius = radius; } +// ELF 0x2FE1E0. float MapProperties::getRadius() const { return m_radius; } -// no matching getter ships - see the header. +// ELF 0x2FE1F0. No matching getter ships - see the header. void MapProperties::setAllowedHeightDiff(float diff) { m_allowedHeightDiff = diff; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp new file mode 100644 index 000000000..855065245 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp @@ -0,0 +1,59 @@ +// [INFERRED] Source placement from the translation unit's static initializer symbol. +#include "MeshImporterExporter.h" + +// static init: ELF 0x2FE770, __tcf_0 0x2FE7D0, _GLOBAL__I 0x2FE800. +#include + +#include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../../../IO/File/File.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x2FE320. +bool MeshImporterExporter::exportMesh(const std::vector& vertices, + const std::vector>& edges, + const std::list>& faces, + const std::string& name) +{ + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::File file; + if (!file.open(levelPath + "/GTSData/Meshes/" + name + ".gts", + static_cast(0), static_cast(1), 0)) + return false; + + file.write(static_cast(vertices.size())); + file.write(static_cast(edges.size())); + file.write(static_cast(faces.size())); + + for (std::vector::const_iterator it = vertices.begin(); it != vertices.end(); ++it) + file.write(0); + for (std::vector::const_iterator it = vertices.begin(); it != vertices.end(); ++it) + { + file.write(static_cast(it->x)); + file.write(static_cast(it->y)); + file.write(static_cast(it->z)); + } + + for (std::vector>::const_iterator it = edges.begin(); it != edges.end(); ++it) + file.write(0); + for (std::vector>::const_iterator it = edges.begin(); it != edges.end(); ++it) + { + file.write(it->first); + file.write(it->second); + } + + for (std::list>::const_iterator it = faces.begin(); it != faces.end(); ++it) + file.write(0); + for (std::list>::const_iterator it = faces.begin(); it != faces.end(); ++it) + { + file.write(it->first); + file.write(it->second); + file.write(it->third); + } + file.close(); + return true; +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.h new file mode 100644 index 000000000..79178228f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.h @@ -0,0 +1,26 @@ +// GTS mesh serialization. [INFERRED] Source placement. +#ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_MESHIMPORTEREXPORTER_H +#define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_MESHIMPORTEREXPORTER_H + +#include "../../Main/IAIPathfinding.h" +#include +#include +#include +#include + +namespace dice { namespace hfe { namespace ai { + +class MeshImporterExporter +{ +public: + // Writes a binary GTS mesh beneath the current level's GTSData/Meshes directory. + // Returns false if opening fails; individual write results are discarded. + static bool exportMesh(const std::vector& vertices, + const std::vector>& edges, + const std::list>& faces, + const std::string& name); +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp new file mode 100644 index 000000000..e8b828a25 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp @@ -0,0 +1,30 @@ +// The local path result's out-of-line members. [INFERRED] file name: the image keeps them in their +// own translation unit (own static initialisation) between MeshImporterExporter's and +// QTSearchNode's. + +#include "../../Main/AIPathfindingSearchTypes.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2FE9F0, __tcf_0 0x2FEA50, _GLOBAL__I 0x2FEA80). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2FE870 (C2; C1 0x2FE8C0). No step yet, no island, zero cost. +QTPath::QTPath() + : m_i0(0) + , m_island(-1) + , m_i20(0.0f) +{ +} + +// ELF 0x2FE910 (D2; D1 0x2FE980). +QTPath::~QTPath() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp new file mode 100644 index 000000000..ce49c5c0b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp @@ -0,0 +1,71 @@ +// The local (nav-mesh) A* node's out-of-line members. [INFERRED] file name: the image keeps them +// in their own translation unit (own static initialisation) between QTPath's and +// QTSearchNodeManager's. + +#include "QTSearchNodeManager.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2FED20, __tcf_0 0x2FED80, _GLOBAL__I 0x2FEDB0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2FEAA0 (C2; C1 0x2FEB00). +QTSearchNode::QTSearchNode(unsigned int polygon, unsigned int depth) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_expandedFrom(0) + , m_key(polygon) + , m_g(0.0f) + , m_f(0.0f) + , m_depth(static_cast(depth)) +{ + m_position.x = 0.0f; + m_position.y = 0.0f; + m_position.z = 0.0f; +} + +// ELF 0x2FEB60 (C2; C1 0x2FEBE0). +QTSearchNode::QTSearchNode(const QTSearchNode& other) + : m_next(0) + , m_prev(0) + , m_parent(0) + , m_expandedFrom(0) + , m_key(other.m_key) + , m_g(0.0f) + , m_f(0.0f) + , m_depth(0) + , m_position(other.m_position) +{ +} + +// ELF 0x2FEC60 (D2; D1 0x2FEC70): empty. +QTSearchNode::~QTSearchNode() +{ +} + +// ELF 0x2FEC80. +QTSearchNode* QTSearchNode::expandFirst(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge) +{ + edge = 0; + QTSearchNode* const neighbour = manager->getNeighbourOfNode(this, edge, status); + ++edge; + return neighbour; +} + +// ELF 0x2FECD0. +QTSearchNode* QTSearchNode::expand(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge) +{ + QTSearchNode* const neighbour = manager->getNeighbourOfNode(this, edge, status); + ++edge; + return neighbour; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp index 08e7ad29e..f0c255e05 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp @@ -2,57 +2,532 @@ #include "QTSearchNodeManager.h" -#include "../../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x300590, __tcf_0 0x3005F0, _GLOBAL__I 0x300620). +#include + +#include + +#include "QuadTree.h" +#include "../Material/MaterialManager.h" +#include "../../../../../Core/Debug.h" namespace dice { namespace hfe { namespace ai { -// Constructors share initialization except for the optional quad-tree pointer. -// Keep both overloads; observed stores do not establish member declaration order. +namespace { + +// ELF 0x2FEDD0. False when the node is its own m_expandedFrom ancestor within ten generations. +// Nothing in the image calls it. +bool checkNodeHeritage(QTSearchNode* node) +{ + int generation = 0; + for (QTSearchNode* ancestor = node->m_expandedFrom; ancestor != 0 && generation < 10; + ancestor = ancestor->m_expandedFrom, ++generation) + { + if (ancestor == node) + return false; + } + return true; +} +} // namespace + +// QTSearchNodeManager + +// ELF 0x2FEE00 (C2; C1 0x2FEEC0) and 0x2FEF80 (C2; C1 0x2FF040). Constructors share +// initialization except for the optional quad-tree pointer. +// Keep both overloads; observed stores do not establish member declaration order. QTSearchNodeManager::QTSearchNodeManager() : m_quadTree(0) - , m_i4(0) + , m_goal(0) , m_nodeCache(0) - , m_i12(0) - , m_i16(0) - , m_i20(0) + , m_numberOfNodes(0) + , m_freeEntries(0) + , m_usedBuckets(0) , m_table(new CacheEntry[kCacheEntries]) - , m_i28(0) - , m_i32(0) - , m_i36(0) - , m_i40(0) - , m_i44(0) - , m_b48(false) - , m_i52(0) + , m_additionalGoals(0) + , m_allowedClusters(0) + , m_usePathTopologySmoothing(false) + , m_materials(0) { } QTSearchNodeManager::QTSearchNodeManager(QuadTree* quadTree) : m_quadTree(quadTree) - , m_i4(0) + , m_goal(0) , m_nodeCache(0) - , m_i12(0) - , m_i16(0) - , m_i20(0) + , m_numberOfNodes(0) + , m_freeEntries(0) + , m_usedBuckets(0) , m_table(new CacheEntry[kCacheEntries]) - , m_i28(0) - , m_i32(0) - , m_i36(0) - , m_i40(0) - , m_i44(0) - , m_b48(false) - , m_i52(0) + , m_additionalGoals(0) + , m_allowedClusters(0) + , m_usePathTopologySmoothing(false) + , m_materials(0) { } -// [FRONTIER] Node-manager table and cache-chain teardown remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when all owned-resource cleanup is recovered. +// ELF 0x2FF100 (D2; D1 0x2FF290). Frees the node pool, every bucket's status records and the nodes they hold, the +// recycled records, the table and the goal copy. QTSearchNodeManager::~QTSearchNodeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::QTSearchNodeManager::~QTSearchNodeManager"); + while (m_nodeCache != 0) + { + QTSearchNode* const node = m_nodeCache; + m_nodeCache = node->m_next; + delete node; + --m_numberOfNodes; + } + + for (unsigned int i = 0; i < kCacheEntries; ++i) + { + StatusEntry* entry = m_table[i].m_head; + while (entry != 0) + { + StatusEntry* const next = entry->m_next; + if (entry->m_node != 0) + delete entry->m_node; + delete entry; + entry = next; + } + } + + while (m_freeEntries != 0) + { + StatusEntry* const entry = m_freeEntries; + m_freeEntries = entry->m_next; + delete entry; + } + + if (m_table != 0) + delete[] m_table; + + if (m_goal != 0) + { + delete m_goal; + --m_numberOfNodes; + } +} + +// ELF 0x2FF420. +void QTSearchNodeManager::setQuadTree(QuadTree* quadTree) +{ + m_quadTree = quadTree; +} + +// ELF 0x2FF430. Keeps a private copy of the goal's polygon and position and recycles `node`. +void QTSearchNodeManager::setGoal(QTSearchNode* node) +{ + if (m_goal == 0) + m_goal = getNewNode(node); + else + m_goal->m_key = node->m_key; + m_goal->m_position = node->m_position; + recycleNode(node); +} + +// ELF 0x2FF4C0. Finds or creates the polygon's status record and marks it open. A recycled record +// keeps its old closed flag; a new one starts not closed. +void QTSearchNodeManager::setNodeOpen(QTSearchNode* node) +{ + const int key = static_cast(node->m_key); + int index = key % kCacheEntries; + if (key < 0) + index += kCacheEntries; + CacheEntry& bucket = m_table[index]; + + for (StatusEntry* entry = bucket.m_head; entry != 0; entry = entry->m_next) + { + if (entry->m_node->m_key == node->m_key) + { + entry->m_open = true; + return; + } + } + + StatusEntry* entry = m_freeEntries; + if (entry != 0) + { + m_freeEntries = entry->m_next; + entry->m_open = true; + entry->m_node = node; + } + else + { + entry = new StatusEntry; + entry->m_open = true; + entry->m_closed = false; + entry->m_node = node; + } + + entry->m_next = bucket.m_head; + if (bucket.m_head == 0) + { + bucket.m_nextUsed = m_usedBuckets; + m_usedBuckets = &bucket; + } + bucket.m_head = entry; +} + +// ELF 0x2FF5A0. The record must exist: retail writes through the search result unchecked. +void QTSearchNodeManager::setNodeClosed(QTSearchNode* node) +{ + const int key = static_cast(node->m_key); + int index = key % kCacheEntries; + if (key < 0) + index += kCacheEntries; + + StatusEntry* entry = m_table[index].m_head; + while (entry != 0 && entry->m_node->m_key != node->m_key) + entry = entry->m_next; + entry->m_open = false; + entry->m_closed = true; +} + +// ELF 0x2FF610. The neighbour across the first bordered edge at or after `edge` (which is left on +// that edge), as a new node one step deeper, with what is known about it in `status`. Impassable +// material, a cluster outside the allowed set and an exhausted polygon report kInvalid; the last +// returns null, the others the node. Unseen neighbours are costed: the entry point is the crossed +// edge's midpoint and, for the goal or an additional goal, f is the exact remaining cost. +QTSearchNode* QTSearchNodeManager::getNeighbourOfNode(QTSearchNode* node, unsigned short& edge, + nodeStatus::Status& status) +{ + unsigned int neighbourPolygon = + m_quadTree->getNeighbourOfPolygon(node->m_key, static_cast(edge)); + while (neighbourPolygon == 0xFFFFFFFFu) + { + ++edge; + if (edge >= m_quadTree->getPolygon(node->m_key)->m_numberOfVertices) + { + status = nodeStatus::kInvalid; + return 0; + } + neighbourPolygon = + m_quadTree->getNeighbourOfPolygon(node->m_key, static_cast(edge)); + } + + QTSearchNode* const neighbour = getNewNode(neighbourPolygon, node, node->m_depth + 1); + + const int key = static_cast(neighbour->m_key); + int index = key % kCacheEntries; + if (key < 0) + index += kCacheEntries; + StatusEntry* entry = m_table[index].m_head; + while (entry != 0 && entry->m_node->m_key != neighbour->m_key) + entry = entry->m_next; + + const Polygon* const polygon = m_quadTree->getPolygon(neighbourPolygon); + if (0.0f > m_materials->getMaterialCost(polygon->m_material)) + { + status = nodeStatus::kInvalid; + return neighbour; + } + + if (m_allowedClusters != 0 && m_allowedClusters->find(polygon->m_cluster) == m_allowedClusters->end()) + { + status = nodeStatus::kInvalid; + return neighbour; + } + + if (entry != 0) + { + if (entry->m_open) + { + status = nodeStatus::kOpen; + return neighbour; + } + if (entry->m_closed) + { + status = nodeStatus::kClosed; + return neighbour; + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp", 289, "") + << "This case should not exists!"; + status = nodeStatus::kInvalid; + return neighbour; + } + + Vec3 entryPoint; + entryPoint.x = 0.0f; + entryPoint.y = 0.0f; + entryPoint.z = 0.0f; + calculateEntryPoint(entryPoint, edge, node); + neighbour->m_position = entryPoint; + neighbour->m_g = calculateCost(node, neighbour, neighbour->m_position); + + if (neighbour->m_key == m_goal->m_key || + (m_additionalGoals != 0 && + m_additionalGoals->find(neighbourPolygon) != m_additionalGoals->end())) + { + neighbour->m_f = calculateCostBetweenPolygons(node->m_key, entryPoint, neighbourPolygon, + m_goal->m_position) + + neighbour->m_g; + status = nodeStatus::kGoal; + return neighbour; + } + + neighbour->m_f = calculateHeuristicCost(neighbour->m_g, entryPoint); + status = nodeStatus::kUnvisited; + return neighbour; +} + +// ELF 0x2FFA70. A recycled node keeps its costs, position and links except the two parents. +QTSearchNode* QTSearchNodeManager::getNewNode(unsigned int polygon, QTSearchNode* parent, + unsigned int depth) +{ + QTSearchNode* node = m_nodeCache; + if (node != 0) + { + node->m_key = polygon; + node->m_depth = static_cast(depth); + m_nodeCache = m_nodeCache->m_next; + } + else + { + node = new QTSearchNode(polygon, depth); + ++m_numberOfNodes; + } + node->m_parent = parent; + node->m_expandedFrom = parent; + return node; +} + +// ELF 0x2FFAF0. A recycled node is assigned every field of `source`; a new one is copy +// constructed, which keeps only the key and the position. +QTSearchNode* QTSearchNodeManager::getNewNode(QTSearchNode* source) +{ + QTSearchNode* node = m_nodeCache; + if (node != 0) + { + m_nodeCache = node->m_next; + *node = *source; + } + else + { + node = new QTSearchNode(*source); + ++m_numberOfNodes; + } + return node; +} + +// ELF 0x2FFBA0. Returns every status record's node to the pool and the records to their free list, +// one bucket chain at a time, then the goal copy, and drops the allowed-cluster set. +void QTSearchNodeManager::reset() +{ + while (m_usedBuckets != 0) + { + StatusEntry* const first = m_usedBuckets->m_head; + StatusEntry* entry = first; + while (entry->m_next != 0) + { + recycleNode(entry->m_node); + entry = entry->m_next; + } + recycleNode(entry->m_node); + entry->m_next = m_freeEntries; + m_freeEntries = first; + + m_usedBuckets->m_head = 0; + m_usedBuckets = m_usedBuckets->m_nextUsed; + } + + if (m_goal != 0) + { + recycleNode(m_goal); + m_goal = 0; + } + m_allowedClusters = 0; +} + +// ELF 0x2FFC20. +void QTSearchNodeManager::returnReset() +{ + m_usePathTopologySmoothing = false; + m_additionalGoals = 0; +} + +// ELF 0x2FFC40. Re-costs `existing` as reached from `parent` (through the edge between them). The +// route is taken only when it is cheaper by more than half a unit; it then becomes the node's +// parent chain. Refused at the depth limit, for the parent's own predecessor and for a node +// without a parent (the start). +bool QTSearchNodeManager::updateNode(QTSearchNode* parent, QTSearchNode* existing, + unsigned int maxDepth) +{ + const int depth = parent->m_depth + 1; + if (maxDepth == static_cast(depth) || parent->m_expandedFrom == existing || + existing->m_parent == 0) + return false; + + Vec3 entryPoint; + entryPoint.x = 0.0f; + entryPoint.y = 0.0f; + entryPoint.z = 0.0f; + unsigned char edge; + m_quadTree->getNeighbourIndexForPolygon(edge, parent->m_key, existing->m_key); + + QTSearchNode* from = parent; + if (!checkIfNodeHasAdequateSize(existing, edge)) + { + from = parent->m_parent; + if (from == 0) + return false; + } + + calculateEntryPoint(entryPoint, edge, parent); + const float g = calculateCost(from, existing, entryPoint); + const float f = calculateHeuristicCost(g, entryPoint); + if (f + 0.5f >= existing->m_f) + return false; + + existing->m_expandedFrom = parent; + existing->m_position = entryPoint; + existing->m_f = f; + existing->m_g = g; + existing->m_parent = from; + existing->m_depth = depth; + return true; +} + +// ELF 0x2FFDA0. Accumulated cost: the step cost plus `from`'s g when the step cost is positive +// (an impassable -1 is returned as is). No predecessor costs nothing. +float QTSearchNodeManager::calculateCost(QTSearchNode* from, QTSearchNode* to, + const Vec3& entry) const +{ + if (from == 0) + return 0.0f; + float cost = calculateCostBetweenPolygons(from->m_key, from->m_position, to->m_key, entry); + if (cost > 0.0f) + cost += from->m_g; + return cost; +} + +// ELF 0x2FFE20. The straight distance weighted by the material cost of the polygon left; -1 for +// impassable material. With topology smoothing, steps of at least 0.25 also weigh the slope of the +// polygon left and the change of normal between the two polygons. +float QTSearchNodeManager::calculateCostBetweenPolygons(unsigned int fromPolygon, + const Vec3& from, + unsigned int toPolygon, + const Vec3& to) const +{ + float cost = m_materials->getMaterialCost(m_quadTree->getMaterialOfPolygon(fromPolygon)); + if (cost < 0.0f) + return -1.0f; + + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (!m_usePathTopologySmoothing) + return distance * cost; + + float extra = 0.0f; + if (distance >= 0.25f) + { + const Vec3* const fromNormal = m_quadTree->getNormalOfPolygon(fromPolygon); + const Vec3* const toNormal = m_quadTree->getNormalOfPolygon(toPolygon); + const float turn = + toNormal->x * fromNormal->x + toNormal->y * fromNormal->y + toNormal->z * fromNormal->z; + const float upright = m_quadTree->getNormalOfPolygon(fromPolygon)->y; + + float slope = upright * 5.0f - 4.0f; + if (!(slope > 0.0f)) + slope = 0.0f; + float bend = turn * 5.0f - 4.0f; + if (!(bend > 0.0f)) + bend = 0.0f; + const float slopeFactor = 4.0f - slope * slope * 3.0f; + const float bendTerm = 2.0f - bend * bend; + extra = bendTerm * bendTerm; + cost = slopeFactor * slopeFactor * cost; + } + return cost * distance + extra; +} + +// ELF 0x300060. g plus the straight distance to the goal's position. +float QTSearchNodeManager::calculateHeuristicCost(float cost, const Vec3& position) const +{ + const float dx = m_goal->m_position.x - position.x; + const float dy = m_goal->m_position.y - position.y; + const float dz = m_goal->m_position.z - position.z; + return cost + std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// ELF 0x300100. Appends the chain from the start to `goal` (at most 201 nodes walked back from the +// goal) and the goal's f cost. Each step records its polygon, the polygon it was entered from +// (UINT_MAX for the start) and its entry point. The path's nodes are not cleared first. +void QTSearchNodeManager::buildPath(QTPath& path, QTSearchNode* goal) +{ + m_pathNodes.resize(0); + + QTSearchNode* node = goal; + int count = 0; + while (node != 0) + { + ++count; + m_pathNodes.push_back(node); + node = node->m_parent; + if (count > 200) + break; + } + + for (int i = static_cast(m_pathNodes.size()) - 1; i >= 0; --i) + { + const unsigned int polygon = m_pathNodes[i]->m_key; + const unsigned int enteredFrom = m_pathNodes[i]->m_expandedFrom != 0 + ? m_pathNodes[i]->m_expandedFrom->m_key + : 0xFFFFFFFFu; + path.m_nodes.push_back(make_triple(polygon, enteredFrom, m_pathNodes[i]->m_position)); + } + path.m_i20 = goal->m_f; +} + +// ELF 0x300310. Sums the step costs from the path's current index. The loop runs size - 1 steps +// from there regardless of that start, so a non-zero start reads past the end (a null position); +// retail behaviour. +float QTSearchNodeManager::calculateCostOfPath(const QTPath& path) const +{ + float total = 0.0f; + const unsigned int steps = static_cast(path.m_nodes.size()); + unsigned int polygon = path.getPolygon(path.m_i0); + const Vec3* position = path.getPosition(path.m_i0); + for (unsigned int i = 1; i < steps; ++i) + { + const Vec3* const nextPosition = path.getPosition(path.m_i0 + i); + const unsigned int nextPolygon = path.getPolygon(path.m_i0 + i); + total += calculateCostBetweenPolygons(polygon, *position, nextPolygon, *nextPosition); + polygon = path.getPolygon(path.m_i0 + i); + position = path.getPosition(path.m_i0 + i); + } + return total; +} + +// ELF 0x3004B0. The midpoint of the polygon edge from corner `edge` to the next (wrapping). +void QTSearchNodeManager::calculateEntryPoint(Vec3& entry, unsigned short edge, QTSearchNode* node) +{ + const Vec3* const first = + m_quadTree->getVertexForPolygon(node->m_key, static_cast(edge)); + const Vec3* const second = m_quadTree->getSafeVertexForPolygon( + node->m_key, static_cast(static_cast(edge) + 1)); + entry.x = (second->x + first->x) * 0.5f; + entry.y = (second->y + first->y) * 0.5f; + entry.z = (second->z + first->z) * 0.5f; +} + +// ELF 0x300560. +int QTSearchNodeManager::getSizeOfNodeCache() const +{ + int size = 0; + for (QTSearchNode* node = m_nodeCache; node != 0; node = node->m_next) + ++size; + return size; +} + +// ELF 0x300580: always true in the shipped build. +bool QTSearchNodeManager::checkIfNodeHasAdequateSize(QTSearchNode*, unsigned char) const +{ + return true; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h index 290e79627..0e5404fa1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.h @@ -1,35 +1,77 @@ -// Node pool for navigation-mesh A* searches. Spare nodes form an intrusive free list. -// [UNRESOLVED] Meaning of the separate 1031-entry table. -// [FRONTIER] Remaining search operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the node-pool lifecycle and search operations. - +// Navigation-mesh A* search nodes and their manager: node pool, per-polygon open/closed status, +// neighbour expansion, costs and path building. +// Placement of QTSearchNode in this file is [INFERRED]: its functions sit beside the manager's in +// the ELF and the anonymous `checkNodeHeritage` helper is between them. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QTSEARCHNODEMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QTSEARCHNODEMANAGER_H +#include +#include + +#include "../../Main/AIPathfindingSearchTypes.h" // QTPath, nodeStatus + namespace dice { namespace hfe { namespace ai { +class MaterialManager; class QuadTree; -class QTSearchNode; +class QTSearchNodeManager; + +// One A* node: a polygon reached through a polygon edge. 44 bytes on the ELF (operator new(0x2C)). +class QTSearchNode +{ +public: + QTSearchNode(unsigned int polygon, unsigned int depth); + // Copies only the key and the position; links, costs and depth start cleared. + QTSearchNode(const QTSearchNode& other); + ~QTSearchNode(); + + // Neighbour iteration for AStarResource::update: expandFirst starts at edge 0. Both advance + // `edge` past the edge they report. + QTSearchNode* expandFirst(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge); + QTSearchNode* expand(QTSearchNodeManager* manager, nodeStatus::Status& status, + unsigned short& edge); + + /* +0x00 */ QTSearchNode* m_next; // hash chain / free-list link + /* +0x04 */ QTSearchNode* m_prev; // hash chain back link + /* +0x08 */ QTSearchNode* m_parent; // the node the path continues from + /* +0x0C */ QTSearchNode* m_expandedFrom; // [INFERRED] name: the node whose edge gave m_position + /* +0x10 */ unsigned int m_key; // the polygon + /* +0x14 */ float m_g; // cost from the start + /* +0x18 */ float m_f; // g plus the heuristic + /* +0x1C */ int m_depth; // steps from the start + /* +0x20 */ Vec3 m_position; // entry point: the midpoint of the crossed edge +}; class QTSearchNodeManager { public: - // The eight-byte record of the table at +24. `operator new[]` is called without an array cookie - // so the element is trivially destructible; the constructor zeroes both of its words. Name and - // field names [INFERRED] - see the header note, the identity is [UNRESOLVED]. + // One per-polygon status record, chained per bucket. 12 bytes (operator new(0xC)). Names + // [INFERRED]. + struct StatusEntry + { + bool m_open; + bool m_closed; + QTSearchNode* m_node; + StatusEntry* m_next; + }; + + // The eight-byte record of the table at +24: a link in the used-bucket list and the bucket's + // entry chain. `operator new[]` is called without an array cookie; the constructor zeroes + // both words. Names [INFERRED]. class CacheEntry { public: CacheEntry() - : m_w0(0) - , m_w1(0) + : m_nextUsed(0) + , m_head(0) { } - int m_w0; - int m_w1; + CacheEntry* m_nextUsed; + StatusEntry* m_head; }; // the same prime the search resource'S two hashes use. Written out as a literal in the binary. @@ -37,23 +79,51 @@ class QTSearchNodeManager QTSearchNodeManager(); explicit QTSearchNodeManager(QuadTree* quadTree); - ~QTSearchNodeManager(); // , [FRONTIER] + ~QTSearchNodeManager(); + + void setQuadTree(QuadTree* quadTree); + void setGoal(QTSearchNode* node); + void setNodeOpen(QTSearchNode* node); + void setNodeClosed(QTSearchNode* node); + QTSearchNode* getNeighbourOfNode(QTSearchNode* node, unsigned short& edge, + nodeStatus::Status& status); + QTSearchNode* getNewNode(unsigned int polygon, QTSearchNode* parent, unsigned int depth); + QTSearchNode* getNewNode(QTSearchNode* source); + void reset(); + // Clears the per-search additional goals and the smoothing flag. + void returnReset(); + bool updateNode(QTSearchNode* parent, QTSearchNode* existing, unsigned int maxDepth); + float calculateCost(QTSearchNode* from, QTSearchNode* to, const Vec3& entry) const; + float calculateCostBetweenPolygons(unsigned int fromPolygon, const Vec3& from, + unsigned int toPolygon, const Vec3& to) const; + float calculateHeuristicCost(float cost, const Vec3& position) const; + void buildPath(QTPath& path, QTSearchNode* goal); + float calculateCostOfPath(const QTPath& path) const; + void calculateEntryPoint(Vec3& entry, unsigned short edge, QTSearchNode* node); + int getSizeOfNodeCache() const; + bool checkIfNodeHasAdequateSize(QTSearchNode* node, unsigned char edge) const; + + // [INFERRED] Inlined in every retail user: returns a node to the free list. + void recycleNode(QTSearchNode* node) + { + node->m_next = m_nodeCache; + m_nodeCache = node; + } // layout, on the ELF, read store by store out of the constructor /* +0 */ QuadTree* m_quadTree; // the one argument the second constructor takes - /* +4 */ int m_i4; // = 0 [UNRESOLVED] + /* +4 */ QTSearchNode* m_goal; // = 0; setGoal's copy of the goal node /* +8 */ QTSearchNode* m_nodeCache; // = 0 the intrusive free list `getSizeOfNodeCache` walks - /* +12 */ int m_i12; // = 0 [UNRESOLVED] - /* +16 */ int m_i16; // = 0 [UNRESOLVED] - /* +20 */ int m_i20; // = 0 [UNRESOLVED] + /* +12 */ int m_numberOfNodes; // = 0; nodes allocated and not yet deleted + /* +16 */ StatusEntry* m_freeEntries;// = 0; recycled status records + /* +20 */ CacheEntry* m_usedBuckets; // = 0; buckets holding status records /* +24 */ CacheEntry* m_table; // new CacheEntry[kCacheEntries] - /* +28 */ int m_i28; // = 0 [UNRESOLVED] - /* +32 */ int m_i32; // = 0 [UNRESOLVED] - /* +36 */ int m_i36; // = 0 [UNRESOLVED] - /* +40 */ int m_i40; // = 0 `returnReset` clears this one and m_b48 - /* +44 */ int m_i44; // = 0 [UNRESOLVED] - /* +48 */ bool m_b48; // = false also cleared by `returnReset` - /* +52 */ int m_i52; // = 0 [UNRESOLVED] + /* +28 */ std::vector m_pathNodes; // buildPath's goal-to-start scratch list + // Per-search options set through AIPathfinding; the two sets are borrowed, not owned. + /* +40 */ const std::set* m_additionalGoals; // = 0; returnReset clears it + /* +44 */ const std::set* m_allowedClusters; // = 0; reset clears it + /* +48 */ bool m_usePathTopologySmoothing; // = false; returnReset clears it + /* +52 */ MaterialManager* m_materials; // = 0; the searching vehicle's material costs }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp index 96052edd7..dcc8dcc8c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp @@ -1,13 +1,23 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTree operations. +// Navigation quad-tree queries, GTS import, construction and destroyable-map-part state. #include "QuadTree.h" +#include "GTSDataOptimiser.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x309940, __tcf_0 0x3099A0, _GLOBAL__I 0x3099D0). +#include +#include +#include +#include // drawPolygonIds #include "../Cluster/ClusterGraph.h" #include "../Material/MaterialManager.h" #include "../../AIUtils/checkPointer.h" // and, through it, Core/Debug.h #include "../../DrawPrimitives/DPManager.h" // IDPManager::deleteMesh #include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../../../IO/File/File.h" +#include "../../../../../Math/Vec3.h" // vec3ToVec2XZ, lineIntersect, pointWithinPolygon2d #include "../../../../../Math/Mat4.h" #include "../../../../../Math/Plane3.h" @@ -15,8 +25,396 @@ namespace dice { namespace hfe { namespace ai { -// Initializes the island, bounds, array pointers, selected counts, timing values, and -// debug mesh. Size and node/vertex-index/neighbor counts remain unset until clean, +namespace { + +// ELF 0x300ED0. +void setAllMaterialsToGround(unsigned int count, Polygon* polygons) +{ + for (unsigned int i = 0; i < count; ++i) + polygons[i].m_material = 1; +} + +// [INFERRED] Helper name/grouping for the inlined normalisation at ELF 0x30255B, +// 0x3037BC and 0x303869. Both precisions use the single-precision epsilon. +template +void normalizeGTSNormal(Vector& normal, Scalar) +{ + const Scalar squared = normal.x * normal.x + normal.y * normal.y + normal.z * normal.z; + const Scalar epsilon = 1.1920928955078125e-7f; + if (std::fabs(squared - Scalar(1)) < epsilon) + return; + if (std::fabs(squared) < epsilon) + { + normal.x = 0; + normal.y = 0; + normal.z = 0; + return; + } + const Scalar inverse = Scalar(1) / std::sqrt(squared); + normal.y *= inverse; + normal.z *= inverse; + normal.x *= inverse; +} + +} // namespace + +// ELF 0x3031C0. Retains double vertices and normals for the subsequent optimiser. +void QuadTree::readGTSDataFromFileDoubles(io::File& file) +{ + clean(); + file.read(m_numberOfVertices); + file.read(m_numberOfPolygons); + m_numberOfVertexIndices = m_numberOfPolygons * 3; + m_numberOfNeighbours = m_numberOfPolygons * 3; + file.read(m_double8C); + file.read(m_double94); + file.read(m_double9C); + file.read(m_doubleA4); + const double xSize = m_double9C - m_double8C; + const double zSize = m_doubleA4 - m_double94; + m_doubleAC = zSize > xSize ? zSize : xSize; + m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); + m_array88 = checkPointer(new DoublePolygon[m_numberOfPolygons]); + m_array84 = checkPointer(new DoubleVec3[m_numberOfVertices]()); + m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); + m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); + file.read(m_array84, m_numberOfVertices * 24); + file.read(m_vertexIndices, m_numberOfVertexIndices * 4); + std::vector polygons; + DoubleVec3* normals = checkPointer(new DoubleVec3[m_numberOfPolygons]()); + file.read(normals, m_numberOfPolygons * 24); + unsigned char* materials = checkPointer(new unsigned char[m_numberOfPolygons]); + file.read(materials, m_numberOfPolygons); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (unsigned int p = 0; p < m_numberOfPolygons; ++p) + { + polygons.push_back(p); + m_array88[p].m_numberOfVertices = 3; + m_array88[p].m_firstIndex = p * 3; + m_polygons[p].m_numberOfVertices = 3; + m_polygons[p].m_firstIndex = p * 3; + const DoubleVec3& av = m_array84[m_vertexIndices[p * 3]]; + const DoubleVec3& bv = m_array84[m_vertexIndices[p * 3 + 1]]; + const DoubleVec3& cv = m_array84[m_vertexIndices[p * 3 + 2]]; + const Vec3 a = {static_cast(av.x), static_cast(av.y), static_cast(av.z)}; + const Vec3 b = {static_cast(bv.x), static_cast(bv.y), static_cast(bv.z)}; + const Vec3 c = {static_cast(cv.x), static_cast(cv.y), static_cast(cv.z)}; + if (environment->isAiPositionInsideCombatArea(a) && + environment->isAiPositionInsideCombatArea(b) && + environment->isAiPositionInsideCombatArea(c)) + { + m_array88[p].m_material = static_cast(materials[p] + 1); + m_polygons[p].m_material = static_cast(materials[p] + 1); + } + else + { + m_array88[p].m_material = 0; + m_polygons[p].m_material = 0; + } + m_array88[p].m_normal = normals[p]; + normalizeGTSNormal(m_array88[p].m_normal, double()); + m_polygons[p].m_normal = Vec3{static_cast(normals[p].x), + static_cast(normals[p].y), static_cast(normals[p].z)}; + normalizeGTSNormal(m_polygons[p].m_normal, float()); + } + delete[] normals; + delete[] materials; + file.read(m_neighbours, m_numberOfNeighbours * 4); +} + +// ELF 0x302130. The single-precision reader constructs the tree immediately. +void QuadTree::readGTSDataFromFile(io::File& file) +{ + clean(); + file.read(m_numberOfVertices); + file.read(m_numberOfPolygons); + m_numberOfVertexIndices = m_numberOfPolygons * 3; + m_numberOfNeighbours = m_numberOfPolygons * 3; + file.read(m_min); + file.read(m_max); + const float xSize = m_max.x - m_min.x; + const float zSize = m_max.y - m_min.y; + m_size = zSize > xSize ? zSize : xSize; + m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); + m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); + m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); + m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); + file.read(m_vertices, m_numberOfVertices * 12); + file.read(m_vertexIndices, m_numberOfVertexIndices * 4); + std::vector polygons; + Vec3* normals = checkPointer(new Vec3[m_numberOfPolygons]()); + file.read(normals, m_numberOfPolygons * 12); + unsigned char* materials = checkPointer(new unsigned char[m_numberOfPolygons]); + file.read(materials, m_numberOfPolygons); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (unsigned int p = 0; p < m_numberOfPolygons; ++p) + { + polygons.push_back(p); + m_polygons[p].m_numberOfVertices = 3; + m_polygons[p].m_firstIndex = p * 3; + if (environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3]]) && + environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3 + 1]]) && + environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3 + 2]])) + m_polygons[p].m_material = static_cast(materials[p] + 1); + else + m_polygons[p].m_material = 0; + m_polygons[p].m_normal = normals[p]; + normalizeGTSNormal(m_polygons[p].m_normal, float()); + } + delete[] normals; + delete[] materials; + file.read(m_neighbours, m_numberOfNeighbours * 4); + buildQuadTree(polygons); +} + +// ELF 0x304160. +void QuadTree::optimiseGTSData(ClusterGraph* graph) +{ + validateNeighbourRelations(); + GTSDataOptimiser* optimiser = checkPointer(new GTSDataOptimiser(graph)); + optimiser->buildOptMeshFromTriangles(m_array88, m_array84, m_vertexIndices, m_neighbours, + m_numberOfPolygons, this); + optimiser->optimise(m_destroyableMapParts); + clean(); + buildQuadTreeMeshFromOptMesh(optimiser); + delete optimiser; +} + +// ELF 0x304B80; the same construction is inlined into ELF 0x302661..0x302869. +void QuadTree::buildQuadTree(const std::vector& polygons) +{ + m_nodes = checkPointer(new QuadTreeNode[0x1555A]); + m_numberOfNodes = 0; + m_nodes->create(this, m_numberOfNodes, m_min, m_size, 0, polygons, m_numberOfPolygons); + QuadTreeNode* nodes = checkPointer(new QuadTreeNode[m_numberOfNodes]); + for (unsigned int i = 0; i < m_numberOfNodes; ++i) + nodes[i] = m_nodes[i]; + delete[] m_nodes; + m_nodes = nodes; + m_numberOfNodePolygons = static_cast(m_vector18.size()); + m_nodePolygons = checkPointer(new unsigned int[m_numberOfNodePolygons]); + for (unsigned int i = 0; i < m_numberOfNodePolygons; ++i) + m_nodePolygons[i] = m_vector18[i]; + m_vector18.erase(m_vector18.begin(), m_vector18.end()); +} + +// ELF 0x3069C0. +DoublePolygon* QuadTree::getPolygonDouble(unsigned int polygon) const +{ + return polygon < m_numberOfPolygons ? m_array88 + polygon : 0; +} + +// ELF 0x304350. The optimiser owns the source polygons; this tree receives independent arrays. +void QuadTree::buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser) +{ + m_numberOfPolygons = static_cast(optimiser->m_polygons.size()); + m_numberOfVertices = optimiser->getNumberOfVertices(); + m_numberOfVertexIndices = m_numberOfVertices; + m_numberOfNeighbours = m_numberOfVertices; + m_min.x = static_cast(m_double8C); + m_min.y = static_cast(m_double94); + m_max.x = static_cast(m_double9C); + m_max.y = static_cast(m_doubleA4); + const float xSize = m_max.x - m_min.x; + const float zSize = m_max.y - m_min.y; + m_size = zSize > xSize ? zSize : xSize; + delete[] m_polygons; + m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); + delete[] m_vertices; + m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); + delete[] m_vertexIndices; + m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); + delete[] m_neighbours; + m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); + std::vector polygons; + unsigned int polygon = 0; + unsigned int first = 0; + for (OptPolygon* p = optimiser->initPolygonIteration(); p; p = optimiser->getNextPolygon()) + { + if (p->m_material != 0) + p->m_material = p->m_originalMaterial; + polygons.push_back(polygon); + m_polygons[polygon].m_numberOfVertices = p->m_numberOfVertices; + m_polygons[polygon].m_firstIndex = first; + m_polygons[polygon].m_material = p->m_material; + const DoubleVec3* normal = p->getNormal(); + m_polygons[polygon].m_normal = Vec3{static_cast(normal->x), + static_cast(normal->y), static_cast(normal->z)}; + m_polygons[polygon].m_cluster = p->m_cluster; + const unsigned char count = p->m_numberOfVertices; + for (unsigned char corner = 0; corner < count; ++corner) + { + const unsigned int index = first + corner; + const DoubleVec3& vertex = p->m_vertices[corner]; + m_vertices[index] = Vec3{static_cast(vertex.x), + static_cast(vertex.y), static_cast(vertex.z)}; + m_vertexIndices[index] = index; + m_neighbours[index] = p->m_neighbours[corner] ? + p->m_neighbours[corner]->m_index : 0xFFFFFFFFu; + } + ++polygon; + first += count; + } + removeDuplicateVerticesFromOptMesh(); + buildQuadTree(polygons); +} + +// ELF 0x305060. A duplicate points forward to another original vertex; follow the whole chain. +void QuadTree::removeDuplicateVerticesFromOptMesh() +{ + std::vector > mapping( + m_numberOfVertexIndices, std::make_pair(false, 0u)); + unsigned int count = 0; + buildQuadTreesForDuplicateVertices(mapping, count); + Vec3* vertices = checkPointer(new Vec3[count]()); + for (unsigned int i = 0; i < m_numberOfVertexIndices; ++i) + { + if (mapping[i].first) + { + vertices[mapping[i].second] = m_vertices[i]; + m_vertexIndices[i] = mapping[i].second; + } + else + { + unsigned int source = i; + while (!mapping[source].first) + source = mapping[source].second; + m_vertexIndices[i] = mapping[source].second; + } + } + delete[] m_vertices; + m_vertices = vertices; + m_numberOfVertices = count; +} + +// ELF 0x305360. +void QuadTree::buildQuadTreesForDuplicateVertices( + std::vector >& mapping, unsigned int& nextVertex) +{ + std::vector vertices[4]; + std::vector indices[4]; + std::vector > bounds; + initialDivideQuadsAndTestForDuplicateVertices(vertices, indices, bounds); + for (unsigned int i = 0; i < 4; ++i) + recurseQuadTreeForDuplicateVertices(vertices[i], indices[i], bounds[i], 0, + mapping, nextVertex); +} + +namespace { + +// [INFERRED] Name/grouping for the identical inlined subdivision in ELF 0x30556D..0x3057FC +// and 0x305A6A..0x305CF2. The four pairs are appended, without clearing the output. +void appendDuplicateVertexQuadrants(const Vec2& minimum, const Vec2& maximum, + std::vector >& bounds) +{ + Vec2 a = minimum; + Vec2 b = {(minimum.x + maximum.x) * 0.5f, (minimum.y + maximum.y) * 0.5f}; + bounds.push_back(std::make_pair(a, b)); + a = Vec2{minimum.x, (minimum.y + maximum.y) * 0.5f}; + b = Vec2{(minimum.x + maximum.x) * 0.5f, maximum.y}; + bounds.push_back(std::make_pair(a, b)); + a = Vec2{(minimum.x + maximum.x) * 0.5f, (minimum.y + maximum.y) * 0.5f}; + b = maximum; + bounds.push_back(std::make_pair(a, b)); + a = Vec2{(minimum.x + maximum.x) * 0.5f, minimum.y}; + b = Vec2{maximum.x, (minimum.y + maximum.y) * 0.5f}; + bounds.push_back(std::make_pair(a, b)); +} + +} // namespace + +// ELF 0x305550. Inclusive edges choose the first matching quadrant, with no overlap margin. +void QuadTree::initialDivideQuadsAndTestForDuplicateVertices(std::vector* vertices, + std::vector* indices, std::vector >& bounds) +{ + appendDuplicateVertexQuadrants(m_min, m_max, bounds); + for (unsigned int i = 0; i < m_numberOfVertices; ++i) + { + Vec3* vertex = m_vertices + i; + for (unsigned int q = 0; q < 4; ++q) + { + if (bounds[q].first.x <= vertex->x && bounds[q].first.y <= vertex->z && + vertex->x <= bounds[q].second.x && vertex->z <= bounds[q].second.y) + { + vertices[q].push_back(vertex); + indices[q].push_back(m_vertexIndices[i]); + break; + } + } + } +} + +// ELF 0x305A50. +void QuadTree::divideQuadsAndTestForDuplicateVertices(const Vec2& minimum, const Vec2& maximum, + const std::vector& inputVertices, const std::vector& inputIndices, + std::vector* vertices, std::vector* indices, + std::vector >& bounds) +{ + appendDuplicateVertexQuadrants(minimum, maximum, bounds); + for (unsigned int i = 0; i < inputVertices.size(); ++i) + { + for (unsigned int q = 0; q < 4; ++q) + { + Vec3* vertex = inputVertices[i]; + if (bounds[q].first.x <= vertex->x && bounds[q].first.y <= vertex->z && + vertex->x <= bounds[q].second.x && vertex->z <= bounds[q].second.y) + { + vertices[q].push_back(vertex); + indices[q].push_back(inputIndices[i]); + break; + } + } + } +} + +// ELF 0x305FA0. Subdivision stops at depth four or nine vertices, then compares forward pairs. +void QuadTree::recurseQuadTreeForDuplicateVertices(const std::vector& vertices, + const std::vector& indices, const std::pair& boundary, + unsigned int depth, std::vector >& mapping, + unsigned int& nextVertex) +{ + const unsigned int count = static_cast(vertices.size()); + if (depth != 4 && count > 9) + { + std::vector children[4]; + std::vector childIndices[4]; + std::vector > bounds; + divideQuadsAndTestForDuplicateVertices(boundary.first, boundary.second, vertices, + indices, children, childIndices, bounds); + for (unsigned int q = 0; q < 4; ++q) + recurseQuadTreeForDuplicateVertices(children[q], childIndices[q], bounds[q], + depth + 1, mapping, nextVertex); + return; + } + for (unsigned int i = 0; i < count; ++i) + { + bool duplicate = false; + for (unsigned int j = i + 1; j < count; ++j) + { + const Vec3 difference = {vertices[i]->x - vertices[j]->x, + vertices[i]->y - vertices[j]->y, vertices[i]->z - vertices[j]->z}; + if (difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z < 1.1920928955078125e-7f) + { + mapping[indices[i]] = std::make_pair(false, indices[j]); + duplicate = true; + break; + } + } + if (!duplicate) + { + mapping[indices[i]] = std::make_pair(true, nextVertex); + ++nextVertex; + } + } +} + +// ELF 0x300EF0 (C2; C1 0x301010). Initializes the island, bounds, array pointers, selected +// counts, timing values, and debug mesh. Size and node/vertex-index/neighbor counts remain unset until clean, // which readFromFile calls before loading. QuadTree::QuadTree(unsigned int island) : m_island(island) @@ -46,13 +444,13 @@ QuadTree::QuadTree(unsigned int island) // initialised - both binaries step over them. } -// clean, then the five vectors in reverse declaration order. +// ELF 0x301130 (D2; D1 0x301230). clean, then the five vectors in reverse declaration order. QuadTree::~QuadTree() { clean(); } -// Releases mesh arrays, resets their counts and pointers, and removes debug drawing. +// ELF 0x301330. Releases mesh arrays, resets their counts and pointers, and removes debug drawing. void QuadTree::clean() { delete[] m_nodes; @@ -87,7 +485,7 @@ void QuadTree::clean() undraw(); } -// Reads a version-3 navigation tree. Unsupported versions leave the existing tree unchanged. +// ELF 0x3016C0. Reads a version-3 navigation tree. Unsupported versions leave the existing tree unchanged. void QuadTree::readFromFile(io::File& file) { int version = 0; @@ -137,7 +535,7 @@ void QuadTree::readFromFile(io::File& file) file.read(m_neighbours, sizeof(unsigned int) * m_numberOfNeighbours); } -// Finds a polygon for a position. Empty trees and points outside the island bounds return false. +// ELF 0x306350. Finds a polygon for a position. Empty trees and points outside the island bounds return false. bool QuadTree::findPolygon(const Vec3& position, unsigned int& polygon, MaterialManager* materials, float allowedHeightDiff) const { @@ -152,6 +550,7 @@ bool QuadTree::findPolygon(const Vec3& position, unsigned int& polygon, allowedHeightDiff); } +// ELF 0x306630. bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) const { Vec2 point2; @@ -188,6 +587,7 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons return true; } +// ELF 0x3064B0. bool QuadTree::withinPolygon(Polygon* polygon, const Vec3& point, float& distanceSquared, float allowedHeightDiff) const { @@ -217,13 +617,14 @@ bool QuadTree::withinPolygon(Polygon* polygon, const Vec3& point, float& distanc const float dx = point.x - intersection.x; const float dy = point.y - intersection.y; const float dz = point.z - intersection.z; - distanceSquared = dz * dz + dy * dy + dx * dx; + distanceSquared = dy * dy + dx * dx + dz * dz; // the listing's summation order static const float maxDistanceAbove = 1.0f; const float limit = point.y > intersection.y ? allowedHeightDiff : maxDistanceAbove; - return distanceSquared <= limit * limit; + return !(distanceSquared > limit * limit); // setbe 0x306619: unordered counts as inside } +// ELF 0x308100. bool QuadTree::isPointInPolygon(const Vec3& point, unsigned int polygon, float allowedHeightDiff, MaterialManager* materials) const { @@ -237,6 +638,7 @@ bool QuadTree::isPointInPolygon(const Vec3& point, unsigned int polygon, float a return withinPolygon(candidate, point, distanceSquared, allowedHeightDiff); } +// ELF 0x307780. void QuadTree::getVerticiesOfPolygon(std::vector& vertices, unsigned int polygon) const { @@ -253,14 +655,472 @@ void QuadTree::getVerticiesOfPolygon(std::vector& vertices, while (corner < candidate->m_numberOfVertices); } -// Retail directly indexes the polygon array; there is no bounds or +// ELF 0x3081A0. Retail directly indexes the polygon array; there is no bounds or // null guard between the caller-supplied polygon id and the material byte. unsigned char QuadTree::getMaterialOfPolygon(unsigned int polygon) const { return m_polygons[polygon].m_material; } +// ELF 0x3081C0. Unchecked, like the getter. +void QuadTree::setMaterialOfPolygon(unsigned int polygon, unsigned char material) +{ + m_polygons[polygon].m_material = material; +} + +// Polygon topology accessors. Each polygon's corners and neighbours share one run of indices +// starting at m_firstIndex: corner i is m_vertices[m_vertexIndices[first + i]], and the polygon +// across the edge from corner i to corner i + 1 is m_neighbours[first + i] (UINT_MAX on a border). +// None of these checks the polygon id; the "safe" variants only wrap the corner index. + +// ELF 0x3069A0. The only bounds-checked lookup: null past the last polygon. +Polygon* QuadTree::getPolygon(unsigned int polygon) const +{ + if (polygon >= m_numberOfPolygons) + return 0; + return &m_polygons[polygon]; +} + +// ELF 0x3068B0. UINT_MAX when the edge index is not below the polygon's corner count. +unsigned int QuadTree::getNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const +{ + const Polygon* const record = &m_polygons[polygon]; + if (edge >= record->m_numberOfVertices) + return 0xFFFFFFFFu; + return m_neighbours[record->m_firstIndex + edge]; +} + +// ELF 0x306F80. The start polygon is appended unconditionally (no sentinel or duplicate test, +// unlike the internal walk), then each neighbour is walked in edge order. +void QuadTree::getPolygonsInRadius(std::list& polygons, unsigned int polygon, + const Vec3& centre, float radius) const +{ + polygons.insert(polygons.end(), polygon); + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) + getPolygonsInRadiusInternal(polygons, m_neighbours[record->m_firstIndex + edge], centre, + radius); +} + +// ELF 0x307030. A polygon is taken when corner 0, or the corner `previous` of any pass, is +// strictly closer than the radius, or when the centre projects onto the edge previous -> i +// (0 <= t <= length) at a perpendicular distance within the radius. Retail quirks kept: +// `previous` only advances when the projection lands on the edge (a degenerate edge, length +// <= 1e-8, or an off-edge projection keeps the old corner), and corner 0 is read before the +// corner count is tested. A taken polygon is appended and its neighbours walked in edge order. +void QuadTree::getPolygonsInRadiusInternal(std::list& polygons, + unsigned int polygon, const Vec3& centre, + float radius) const +{ + if (polygon == 0xFFFFFFFFu) + return; + if (std::find(polygons.begin(), polygons.end(), polygon) != polygons.end()) + return; + + const float radiusSqr = radius * radius; + const Polygon* const record = &m_polygons[polygon]; + unsigned char previous = static_cast(record->m_numberOfVertices - 1); + + const Vec3& first = m_vertices[m_vertexIndices[record->m_firstIndex]]; + float dx = centre.x - first.x; + float dy = centre.y - first.y; + float dz = centre.z - first.z; + bool touches = radiusSqr > dx * dx + dy * dy + dz * dz; + + if (!touches) + { + for (unsigned char i = 0; i < record->m_numberOfVertices; ++i) + { + const Vec3& a = m_vertices[m_vertexIndices[record->m_firstIndex + i]]; + const Vec3& b = m_vertices[m_vertexIndices[record->m_firstIndex + previous]]; + + dx = centre.x - b.x; + dy = centre.y - b.y; + dz = centre.z - b.z; + if (radiusSqr > dx * dx + dy * dy + dz * dz) + { + touches = true; + break; + } + + float ex = b.x - a.x; + float ey = b.y - a.y; + float ez = b.z - a.z; + const float length = std::sqrt(ex * ex + ey * ey + ez * ez); + if (length > 1e-08f) + { + const float inverse = 1.0f / length; + ex *= inverse; + ey *= inverse; + ez *= inverse; + const float wx = centre.x - a.x; + const float wy = centre.y - a.y; + const float wz = centre.z - a.z; + const float t = ex * wx + ey * wy + ez * wz; + if (!(0.0f > t) && !(t > length)) + { + if (radiusSqr >= (wx * wx + wy * wy + wz * wz) - t * t) + { + touches = true; + break; + } + previous = i; + } + } + } + if (!touches) + return; + } + + polygons.insert(polygons.end(), polygon); + for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) + getPolygonsInRadiusInternal(polygons, m_neighbours[record->m_firstIndex + edge], centre, + radius); +} + +// ELF 0x3069E0. Same shape as getPolygonsInRadius. +void QuadTree::getPolygonsInTriangle(std::list& polygons, unsigned int polygon, + const Vec3& a, const Vec3& b, const Vec3& c) const +{ + polygons.insert(polygons.end(), polygon); + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) + getPolygonsInTriangleInternal(polygons, m_neighbours[record->m_firstIndex + edge], a, b, c); +} + +// ELF 0x306AA0. A polygon is taken when corner 0, or the corner `previous` of a pass, lies in the +// triangle (pointWithinPolygon2d, XZ), or when the edge current -> previous crosses a triangle +// edge (lineIntersect with both parameters in [0, 1]). Any tested corner more than 2 m above +// or below the triangle's first vertex rejects the whole polygon (corner 0 after its inside +// test, the others before theirs). `previous` advances on every pass here. +void QuadTree::getPolygonsInTriangleInternal(std::list& polygons, + unsigned int polygon, const Vec3& a, const Vec3& b, + const Vec3& c) const +{ + Vec3 triangle[3]; + triangle[0] = a; + triangle[1] = b; + triangle[2] = c; + if (polygon == 0xFFFFFFFFu) + return; + if (std::find(polygons.begin(), polygons.end(), polygon) != polygons.end()) + return; + + const Polygon* const record = &m_polygons[polygon]; + unsigned char previous = static_cast(record->m_numberOfVertices - 1); + const Vec3& first = m_vertices[m_vertexIndices[record->m_firstIndex]]; + bool touches = pointWithinPolygon2d(first, triangle, 3); + if (std::fabs(first.y - a.y) > 2.0f) + return; + + Vec2 triangle2d[3]; + for (int i = 0; i < 3; ++i) + { + triangle2d[i].x = 0.0f; // retail Vec2 constructors + triangle2d[i].y = 0.0f; + } + vec3ToVec2XZ(a, triangle2d[0]); + vec3ToVec2XZ(b, triangle2d[1]); + vec3ToVec2XZ(c, triangle2d[2]); + + if (!touches) + { + for (unsigned char i = 0; i < record->m_numberOfVertices; ++i) + { + const Vec3& current = m_vertices[m_vertexIndices[record->m_firstIndex + i]]; + const Vec3& corner = m_vertices[m_vertexIndices[record->m_firstIndex + previous]]; + if (std::fabs(corner.y - a.y) > 2.0f) + return; + if (pointWithinPolygon2d(corner, triangle, 3)) + { + touches = true; + break; + } + + Vec2 from = { 0.0f, 0.0f }; + Vec2 to = { 0.0f, 0.0f }; + vec3ToVec2XZ(current, from); + vec3ToVec2XZ(corner, to); + for (int j = 0; j < 3; ++j) + { + float t; + float s; + if (lineIntersect(from, to, triangle2d[j], triangle2d[(j + 1) % 3], t, s) + && t >= 0.0f && t <= 1.0f && s >= 0.0f && s <= 1.0f) + { + touches = true; + break; + } + } + if (touches) + break; + previous = i; + } + if (!touches) + return; + } + + polygons.insert(polygons.end(), polygon); + for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) + getPolygonsInTriangleInternal(polygons, m_neighbours[record->m_firstIndex + edge], a, b, c); +} + +// ELF 0x3068F0. +bool QuadTree::isNeighbourOfPolygon(unsigned int polygon, unsigned int neighbour) const +{ + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) + { + if (m_neighbours[record->m_firstIndex + edge] == neighbour) + return true; + } + return false; +} + +// ELF 0x306950. The edge index wraps modulo the corner count. +unsigned int QuadTree::getSafeNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const +{ + const Polygon* const record = &m_polygons[polygon]; + return m_neighbours[record->m_firstIndex + edge % record->m_numberOfVertices]; +} + +// ELF 0x307530. +const Vec3* QuadTree::getVertexForPolygon(unsigned int polygon, unsigned char corner) const +{ + return &m_vertices[m_vertexIndices[m_polygons[polygon].m_firstIndex + corner]]; +} + +// ELF 0x307560. +bool QuadTree::isVertexOfPolygon(unsigned int polygon, unsigned int vertex) const +{ + const Polygon* const record = &m_polygons[polygon]; + for (unsigned char corner = 0; corner < record->m_numberOfVertices; ++corner) + { + if (m_vertexIndices[record->m_firstIndex + corner] == vertex) + return true; + } + return false; +} + +// ELF 0x3075C0. The corner index wraps modulo the corner count. +const Vec3* QuadTree::getSafeVertexForPolygon(unsigned int polygon, unsigned char corner) const +{ + const Polygon* const record = &m_polygons[polygon]; + return &m_vertices[m_vertexIndices[record->m_firstIndex + corner % record->m_numberOfVertices]]; +} + +// ELF 0x307610. +unsigned int QuadTree::getVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const +{ + return m_vertexIndices[m_polygons[polygon].m_firstIndex + corner]; +} + +// ELF 0x307640. The corner index wraps modulo the corner count. +unsigned int QuadTree::getSafeVertexIndexForPolygon(unsigned int polygon, + unsigned char corner) const +{ + const Polygon* const record = &m_polygons[polygon]; + return m_vertexIndices[record->m_firstIndex + corner % record->m_numberOfVertices]; +} + +// ELF 0x307680. The corner average. A polygon without corners divides by zero, as in retail. +void QuadTree::getCentreOfPolygon(Vec3& centre, unsigned int polygon) const +{ + const Polygon* const record = &m_polygons[polygon]; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + for (unsigned char corner = 0; corner < record->m_numberOfVertices; ++corner) + { + const Vec3& vertex = m_vertices[m_vertexIndices[record->m_firstIndex + corner]]; + centre.x += vertex.x; + centre.y += vertex.y; + centre.z += vertex.z; + } + const float inverse = 1.0f / static_cast(record->m_numberOfVertices); + centre.x *= inverse; + centre.y *= inverse; + centre.z *= inverse; +} + +// ELF 0x307760. +const Vec3* QuadTree::getNormalOfPolygon(unsigned int polygon) const +{ + return &m_polygons[polygon].m_normal; +} + +// ELF 0x307F90. Finds the edge of `polygon` that borders `neighbour`. Retail tests edge 0 before +// comparing against the corner count, so a polygon without corners still reads its first entry. +bool QuadTree::getNeighbourIndexForPolygon(unsigned char& edge, unsigned int polygon, + unsigned int neighbour) const +{ + const Polygon* const record = &m_polygons[polygon]; + edge = 0; + if (m_neighbours[record->m_firstIndex] == neighbour) + return true; + for (;;) + { + ++edge; + if (edge >= record->m_numberOfVertices) + return false; + if (m_neighbours[record->m_firstIndex + edge] == neighbour) + return true; + } +} + +// ELF 0x307830. Walks the polygon's edges (skipping the one shared with `previousPolygon`) and +// intersects the XZ ray origin + t * (direction.x, 0, direction.z) with each. The first edge hit +// with t >= 0 inside the edge wins; within 0.001 of a corner the edge only counts when the ray +// leaves through it (its 2D normal faces against the ray). Otherwise the smallest near miss under +// `minInvalid` is used. The result lies on the ray in XZ; its height follows `direction.y` over +// the XZ distance. `edge` is left on the hit edge (or past the last one). For a direct hit +// `edgeClearance` receives the distance to the nearer edge end. +bool QuadTree::getLineIntersectionOnEdgeInPolygon(Vec3& intersection, unsigned int polygon, + unsigned char& edge, + unsigned int previousPolygon, + const Vec3& origin, const Vec3& direction, + float* edgeClearance, float*) const +{ + static float minInvalid = 0.001f; + + Vec2 start; + start.x = 0.0f; + start.y = 0.0f; + Vec2 corner; + corner.x = 0.0f; + corner.y = 0.0f; + Vec2 nextCorner; + nextCorner.x = 0.0f; + nextCorner.y = 0.0f; + Vec2 end; + end.x = 0.0f; + end.y = 0.0f; + Vec2 hit; + hit.x = 0.0f; + hit.y = 0.0f; + vec3ToVec2XZ(origin, start); + + float bestMiss = 99999.0f; + float bestT = 0.0f; + Vec2 bestEnd; + bestEnd.x = 0.0f; + bestEnd.y = 0.0f; + + const Polygon* const record = &m_polygons[polygon]; + edge = 0; + if (record->m_numberOfVertices != 0) + { + do + { + if (previousPolygon == 0xFFFFFFFFu || + m_neighbours[record->m_firstIndex + edge] != previousPolygon) + { + vec3ToVec2XZ(m_vertices[m_vertexIndices[record->m_firstIndex + edge]], corner); + vec3ToVec2XZ(m_vertices[m_vertexIndices[record->m_firstIndex + + (edge + 1) % record->m_numberOfVertices]], + nextCorner); + + const float scale = 1.0f; + Vec3 flat; + flat.x = direction.x * scale; + flat.y = 0.0f * scale; + flat.z = direction.z * scale; + Vec3 ahead; + ahead.x = origin.x + flat.x; + ahead.y = origin.y + flat.y; + ahead.z = origin.z + flat.z; + vec3ToVec2XZ(ahead, end); + + float t; + float s; + if (lineIntersect(start, end, corner, nextCorner, t, s)) + { + bool onEdge = false; + if (t >= 0.0f && s >= 0.0f && 1.0f >= s) + { + if (0.001f >= s || !(s < 0.999f)) + { + Vec2 heading; + heading.x = 0.0f; + heading.y = 0.0f; + vec3ToVec2XZ(direction, heading); + Vec2 side; + side.x = nextCorner.x - corner.x; + side.y = nextCorner.y - corner.y; + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + getNormal(side, normal); + onEdge = !(normal.x * heading.x + normal.y * heading.y >= 0.0f); + } + else + onEdge = true; + + if (onEdge) + { + Vec2 point; + point.x = start.x * (1.0f - t) + end.x * t; + point.y = start.y * (1.0f - t) + end.y * t; + vec2ToVec3XZ(point, intersection); + vec3ToVec2XZ(intersection, hit); + const float hx = hit.x - start.x; + const float hy = hit.y - start.y; + intersection.y = + std::sqrt(hx * hx + hy * hy) * direction.y + origin.y; + if (edgeClearance != 0) + { + const float ex = corner.x - nextCorner.x; + const float ey = corner.y - nextCorner.y; + const float length = std::sqrt(ex * ex + ey * ey); + const float nearer = (1.0f - s) > s ? s : 1.0f - s; + *edgeClearance = nearer * length; + } + return true; + } + } + else + { + // How far outside the ray (t < 0) or the edge (s outside [0, 1]). + const float behind = 0.0f > t ? std::fabs(t) : 9999.0f; + float miss; + if (0.0f > s && behind > -s) + miss = -s; + else if (s > 1.0f) + miss = behind > s - 1.0f ? s - 1.0f : behind; + else + miss = behind; + + if (minInvalid > miss && bestMiss > miss) + { + bestMiss = miss; + bestT = t; + bestEnd = end; + } + } + } + } + ++edge; + } + while (record->m_numberOfVertices > edge); + } + + if (!(minInvalid > bestMiss)) + return false; + + Vec2 point; + point.x = start.x * (1.0f - bestT) + bestEnd.x * bestT; + point.y = start.y * (1.0f - bestT) + bestEnd.y * bestT; + vec2ToVec3XZ(point, intersection); + vec3ToVec2XZ(intersection, hit); + const float hx = hit.x - start.x; + const float hy = hit.y - start.y; + intersection.y = std::sqrt(hx * hx + hy * hy) * direction.y + origin.y; + return true; +} + // Tracks polygons affected by destroyable map parts and restores their original materials. + +// ELF 0x308EE0. void QuadTree::getPolygonsWithinBoundary(const Vec3& minimum, const Vec3& maximum, const Mat4& transformation, std::vector& polygons) const @@ -294,6 +1154,7 @@ void QuadTree::getPolygonsWithinBoundary(const Vec3& minimum, const Vec3& maximu } } +// ELF 0x3093B0. void QuadTree::getPolygonsWithinBoundaryDoubles(const Vec3& minimum, const Vec3& maximum, const Mat4& transformation, std::vector& polygons) const @@ -327,6 +1188,7 @@ void QuadTree::getPolygonsWithinBoundaryDoubles(const Vec3& minimum, const Vec3& } } +// ELF 0x308860. void QuadTree::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkable, const Vec3& minimum, const Vec3& maximum, const Mat4& transformation, ClusterGraph* graph, @@ -372,6 +1234,7 @@ void QuadTree::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkabl part->m_destroyed = false; } +// ELF 0x308C60. void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) { if (!m_destroyableMapParts.empty()) @@ -388,7 +1251,7 @@ void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_unread0C[2] + graph->m_clusters[m_polygons[first].m_cluster].m_walkable = static_cast(!part->m_initiallyWalkable); } part->m_destroyed = true; @@ -396,6 +1259,7 @@ void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) } } +// ELF 0x308D20. void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) { if (mapPartId != -1) @@ -412,7 +1276,7 @@ void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_unread0C[2] + graph->m_clusters[m_polygons[first].m_cluster].m_walkable = static_cast(part->m_initiallyWalkable); } part->m_destroyed = false; @@ -420,6 +1284,7 @@ void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) } } +// ELF 0x308E30. void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterGraph* graph) { if (mapPartId != -1) @@ -433,7 +1298,7 @@ void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterG if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_unread0C[2] + graph->m_clusters[m_polygons[first].m_cluster].m_walkable = static_cast(part->m_initiallyWalkable); } part->m_destroyed = false; @@ -441,13 +1306,157 @@ void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterG } } +// ELF 0x308DC0. void QuadTree::resetDestroyableMapParts(ClusterGraph* graph) { for (unsigned int mapPartId = 0; mapPartId < m_destroyableMapParts.size(); ++mapPartId) restoreMapPart(mapPartId, graph); } -// QuadTree::undraw - , (const); inlined into the PE's clean. +// ELF 0x301550. Writes the version-3 record readFromFile reads: bounds, size, then each array +// behind its count. +void QuadTree::saveToFile(io::File& file) +{ + file.write(3); + file.write(&m_min, sizeof(m_min)); + file.write(&m_max, sizeof(m_max)); + file.write(m_size); + + file.write(m_numberOfNodes); + file.write(m_nodes, sizeof(QuadTreeNode) * m_numberOfNodes); + file.write(m_numberOfPolygons); + file.write(m_polygons, sizeof(Polygon) * m_numberOfPolygons); + file.write(m_numberOfNodePolygons); + file.write(m_nodePolygons, sizeof(unsigned int) * m_numberOfNodePolygons); + file.write(m_numberOfVertices); + file.write(m_vertices, sizeof(Vec3) * m_numberOfVertices); + file.write(m_numberOfVertexIndices); + file.write(m_vertexIndices, sizeof(unsigned int) * m_numberOfVertexIndices); + file.write(m_numberOfNeighbours); + file.write(m_neighbours, sizeof(unsigned int) * m_numberOfNeighbours); +} + +// ELF 0x306400. The debug walk of findPolygon: the same empty-tree and bounds gates (written as +// inclusive acceptance tests here), then the root node's printPolygonsInNode. +void QuadTree::printPolygonsInNode(const Vec3& position, unsigned int& polygon, + MaterialManager* materials, float allowedHeightDiff) const +{ + if (!m_nodes) + return; + + if (m_min.x <= position.x && position.x <= m_max.x + && m_min.y <= position.z && position.z <= m_max.y) + m_nodes[0].printPolygonsInNode(this, m_min, m_size, position, polygon, materials, + allowedHeightDiff); +} + +// ELF 0x306790. One static line per edge (red, 0.3 wide). With `height` both ends are drawn at +// that height instead of the vertices' own. +void QuadTree::drawPolygon(unsigned int polygon, float* height, float time) +{ + const Polygon* const candidate = &m_polygons[polygon]; + unsigned char corner = 0; + if (candidate->m_numberOfVertices == 0) + return; + + do + { + Vec3 start = m_vertices[m_vertexIndices[candidate->m_firstIndex + corner]]; + const unsigned char next = static_cast( + (corner + 1) % candidate->m_numberOfVertices); + Vec3 end = m_vertices[m_vertexIndices[candidate->m_firstIndex + next]]; + if (height) + { + end.y = *height; + start.y = end.y; + } + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(time, 0xFF0000u, start, end, 0.3f); + ++corner; + } + while (corner < candidate->m_numberOfVertices); +} + +// ELF 0x3068A0. Empty in the shipped image. +void QuadTree::drawPolygonEdge(unsigned int, unsigned char) const +{ +} + +// ELF 0x308010. The corner average, accumulated through getVertexForPolygon. A polygon without +// corners divides by zero, as in retail. +Vec3 QuadTree::getPolygonMidPoint(unsigned int polygon) +{ + Vec3 midPoint; + midPoint.x = 0.0f; + midPoint.y = 0.0f; + midPoint.z = 0.0f; + + const Polygon* const candidate = &m_polygons[polygon]; + for (unsigned char corner = 0; corner < candidate->m_numberOfVertices; ++corner) + { + const Vec3* const vertex = getVertexForPolygon(polygon, corner); + midPoint.x += vertex->x; + midPoint.y += vertex->y; + midPoint.z += vertex->z; + } + + const float scale = 1.0f / static_cast(candidate->m_numberOfVertices); + midPoint.x *= scale; + midPoint.y *= scale; + midPoint.z *= scale; + return midPoint; +} + +// ELF 0x3081E0. Replaces the debug mesh with one static mesh of every polygon (60 s). Unlike +// undraw, neither manager is null-tested. +void QuadTree::draw() const +{ + IDPStaticCreator* const creator + = static_cast(CommonSingletonServer::m_iDPStaticCreator); + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(m_debugMesh); + // DPStaticMesh is not defined in this tree; the image stores the returned pointer unadjusted + // as the DrawPrimitive handle. [CHOSEN, not recovered] cast. + m_debugMesh = reinterpret_cast( + creator->createStaticMesh(60.0f, 0, m_polygons, m_vertices, m_vertexIndices, + static_cast(m_numberOfPolygons), true)); +} + +// ELF 0x3082B0. Each polygon's id as 3D text (white, 30 s) 2 m above its centre. +void QuadTree::drawPolygonIds() const +{ + IDPStaticCreator* const creator + = static_cast(CommonSingletonServer::m_iDPStaticCreator); + for (unsigned long polygon = 0; polygon < m_numberOfPolygons; ++polygon) + { + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + getCentreOfPolygon(centre, polygon); + centre.y += 2.0f; + + std::stringstream text; + text << polygon; + creator->createStatic3dText(30.0f, 0xFFFFFFFFu, centre, text.str(), 0, + static_cast(0), + static_cast(0)); + } +} + +// ELF 0x3098F0. Walks every polygon's edges and checks nothing: the shipped body is the empty +// loop nest. +void QuadTree::validateNeighbourRelations() const +{ + for (unsigned int polygon = 0; polygon < m_numberOfPolygons; ++polygon) + { + const Polygon& candidate = m_polygons[polygon]; + for (unsigned char edge = 0; edge < candidate.m_numberOfVertices; ++edge) + { + } + } +} + +// ELF 0x308270. Inlined into the PE's clean. // Hands the debug mesh to IDPManager::deleteMesh (ELF slot +0x50, PE +0x4C) when the draw-primitive // manager exists; deleteMesh takes the handle by reference. The bool it answers is discarded. void QuadTree::undraw() const diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h index 23a96f250..1c05815c5 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h @@ -1,13 +1,15 @@ // Navigation quad tree with file loading, polygon lookup and destroyable-map-part state. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREE_H #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREE_H +#include #include +#include #include "../../Main/AIDllTypes.h" // Vec2, Vec3, DrawPrimitive #include "QuadTreeNode.h" +#include "../../../../../Math/DoubleVec3.h" namespace dice { namespace hfe { @@ -17,6 +19,7 @@ namespace io { class File; } namespace ai { class ClusterGraph; +class GTSDataOptimiser; class MaterialManager; // Polygon - one navigation-mesh polygon, 20 bytes on disk and in memory. The array is constructed @@ -51,16 +54,19 @@ class DestroyableMapPart bool m_destroyed; // [INFERRED] name }; -// [INFERRED] source name. readGTSDataFromFileDoubles allocates exactly 24 bytes per element and -// getPolygonsWithinBoundaryDoubles reads three consecutive doubles from each one. -struct DoubleVec3 +// Double-precision GTS polygon: ELF 0x303316 allocates 32 bytes per element. +class DoublePolygon { - double x; - double y; - double z; +public: + DoublePolygon() : m_normal() {} + /* +0x00 */ unsigned char m_numberOfVertices; + /* +0x01 */ unsigned char m_material; + /* +0x02 */ unsigned short m_cluster; + /* +0x04 */ unsigned int m_firstIndex; + /* +0x08 */ DoubleVec3 m_normal; }; -typedef char DoubleVec3IsTheFileRecord[sizeof(DoubleVec3) == 24 ? 1 : -1]; +typedef char DoublePolygonIsTheFileRecord[sizeof(DoublePolygon) == 32 ? 1 : -1]; class QuadTree { @@ -69,13 +75,67 @@ class QuadTree ~QuadTree(); void clean(); + void saveToFile(io::File& file); void readFromFile(io::File& file); + void readGTSDataFromFileDoubles(io::File& file); + void readGTSDataFromFile(io::File& file); + void optimiseGTSData(ClusterGraph* graph); + void buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser); + void buildQuadTree(const std::vector& polygons); + void removeDuplicateVerticesFromOptMesh(); + void buildQuadTreesForDuplicateVertices(std::vector >&, + unsigned int&); + void initialDivideQuadsAndTestForDuplicateVertices(std::vector*, + std::vector*, std::vector >&); + void divideQuadsAndTestForDuplicateVertices(const Vec2&, const Vec2&, + const std::vector&, const std::vector&, + std::vector*, std::vector*, std::vector >&); + void recurseQuadTreeForDuplicateVertices(const std::vector&, + const std::vector&, const std::pair&, unsigned int, + std::vector >&, unsigned int&); + void draw() const; void undraw() const; + void drawPolygonIds() const; + void drawPolygon(unsigned int polygon, float* height, float time); + void drawPolygonEdge(unsigned int polygon, unsigned char edge) const; + void validateNeighbourRelations() const; bool findPolygon(const Vec3&, unsigned int&, MaterialManager*, float) const; + void printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager*, float) const; + Vec3 getPolygonMidPoint(unsigned int polygon); bool isPointInPolygon(const Vec3&, unsigned int, float, MaterialManager*) const; void getVerticiesOfPolygon(std::vector&, unsigned int) const; unsigned char getMaterialOfPolygon(unsigned int polygon) const; + void setMaterialOfPolygon(unsigned int polygon, unsigned char material); + + // ClusterGraph's GTS importer writes cluster ids through both returned pointers. + Polygon* getPolygon(unsigned int polygon) const; + DoublePolygon* getPolygonDouble(unsigned int polygon) const; + unsigned int getNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const; + bool isNeighbourOfPolygon(unsigned int polygon, unsigned int neighbour) const; + unsigned int getSafeNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const; + const Vec3* getVertexForPolygon(unsigned int polygon, unsigned char corner) const; + bool isVertexOfPolygon(unsigned int polygon, unsigned int vertex) const; + const Vec3* getSafeVertexForPolygon(unsigned int polygon, unsigned char corner) const; + unsigned int getVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const; + unsigned int getSafeVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const; + void getCentreOfPolygon(Vec3& centre, unsigned int polygon) const; + const Vec3* getNormalOfPolygon(unsigned int polygon) const; + bool getNeighbourIndexForPolygon(unsigned char& edge, unsigned int polygon, + unsigned int neighbour) const; + // Where the XZ ray from `origin` along `direction` leaves the polygon; see the definition. + bool getLineIntersectionOnEdgeInPolygon(Vec3& intersection, unsigned int polygon, + unsigned char& edge, unsigned int previousPolygon, + const Vec3& origin, const Vec3& direction, + float* edgeClearance, float*) const; + + // Flood fills from `polygon` over neighbours: the start polygon always, then every polygon a + // vertex or edge of which lies within the radius (XYZ) / that overlaps the triangle (XZ, with + // a 2 m height window); see the definitions. + void getPolygonsInRadius(std::list& polygons, unsigned int polygon, + const Vec3& centre, float radius) const; + void getPolygonsInTriangle(std::list& polygons, unsigned int polygon, + const Vec3& a, const Vec3& b, const Vec3& c) const; void initializeDestroyableMapPart(int, bool, const Vec3&, const Vec3&, const Mat4&, ClusterGraph*, bool); @@ -85,8 +145,15 @@ class QuadTree void resetOriginalMaterialOfDestroyableMapPart(int, ClusterGraph*); private: + friend class GTSDataOptimiser; friend class QuadTreeNode; + friend class QuadTreeManager; + friend class ClusterGraph; + void getPolygonsInRadiusInternal(std::list& polygons, unsigned int polygon, + const Vec3& centre, float radius) const; + void getPolygonsInTriangleInternal(std::list& polygons, unsigned int polygon, + const Vec3& a, const Vec3& b, const Vec3& c) const; bool withinPolygon(Polygon*, const Vec3&, float&, float) const; bool pointWithinPolygonEdges(Polygon*, const Vec3&) const; void getPolygonsWithinBoundary(const Vec3&, const Vec3&, const Mat4&, @@ -95,14 +162,17 @@ class QuadTree std::vector&) const; // Left-hand offsets are the ELF's (sizeof 196; `operator new(0xC4)` in loadQuadTrees). - // [UNRESOLVED] roles for the four vectors, the two byte arrays and the four doubles: only the - // GTS generation path (not written) fills them; the constructor empties them, clean() frees the - // arrays and the destructor the vectors. + // [UNRESOLVED] roles of the scratch vectors except m_vector18, which accumulates leaf + // polygon ids during tree construction. The doubles store min X/Z, max X/Z and extent; + // GTS-only arrays hold double vertices and polygons. clean frees these arrays. /* +0x00 */ std::vector m_vector00; // 12-byte elements, trivial destructor /* +0x0C */ std::vector m_vector0C; /* +0x18 */ std::vector m_vector18; /* +0x24 */ std::vector m_vector24; - /* +0x30 */ unsigned char m_unwritten30[12]; // no constructor, clean or destructor touches it + // Set by QuadTreeManager::loadGTSData; construction and clean leave these untouched. + /* +0x30 */ int m_minPolygonsInLeaf; // [INFERRED] names from the map setup parameters + /* +0x34 */ int m_maxDepthInTree; + /* +0x38 */ int m_gtsBuildValue; // [INFERRED] name; maximum-depth stop applies only at or above this depth /* +0x3C */ Vec2 m_min; // [INFERRED] the island's bounds - Dalian Infantry /* +0x44 */ Vec2 m_max; // (-351.75, -466.75) .. (382.65, 340.53) /* +0x4C */ float m_size; // [INFERRED] the root square's edge - 807.28 there, the larger extent @@ -120,7 +190,7 @@ class QuadTree /* +0x7C */ unsigned int* m_vertexIndices; /* +0x80 */ unsigned int* m_neighbours; /* +0x84 */ DoubleVec3* m_array84; // GTS-only double-precision vertex array - /* +0x88 */ unsigned char* m_array88; + /* +0x88 */ DoublePolygon* m_array88; /* +0x8C */ double m_double8C; /* +0x94 */ double m_double94; /* +0x9C */ double m_double9C; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp index f1f020e39..cf502b48e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp @@ -1,35 +1,69 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTreeManager operations. +// Navigation island ownership, GTS import orchestration and navigation debug meshes. #include "QuadTreeManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x310FA0, __tcf_0 0x311000, _GLOBAL__I 0x311030). +#include + #include // std::abort - the ELF's island trap +#include +#include +#include +#include #include "QuadTree.h" #include "../Cluster/ClusterGraph.h" #include "../../AIUtils/checkPointer.h" -#include "../../Main/AIDllFrontier.h" +#include "../../Main/AIRandom.h" +#include "../../Main/AISettingsInterfaces.h" #include "../../Main/CommonSingletonServer.h" +#include "../../DrawPrimitives/DPManager.h" // IDPManager, IDPStaticCreator #include "../../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getLevelPath +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../../../IO/File/File.h" namespace dice { namespace hfe { namespace ai { -// Initializes an empty quad-tree collection and its island metadata. +// ELF 0x30CACB, 0x30E669, 0x30F9AC, 0x310375: inlined constructor. +QuadTreeManager::DebugMesh::DebugMesh() + : m_numberOfVertices(0), m_numberOfPolygons(0), m_numberOfIndices(0) +{ + // shipped defect: the pointers, including the drawing handle, remain uninitialized. +} + +// ELF 0x30D126..0x30D1FF (inlined); amd-64 ELF 0x3580F0 attests lockSize's name. +void QuadTreeManager::DebugMesh::lockSize() +{ + m_firstIndices = checkPointer(new unsigned int[m_numberOfPolygons]); + m_vertexCounts = checkPointer(new unsigned int[m_numberOfPolygons]); + m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); + m_indices = checkPointer(new unsigned int[m_numberOfIndices]); + m_materials = checkPointer(new unsigned char[m_numberOfPolygons]); + m_colours = checkPointer(new unsigned int[m_numberOfPolygons]); +} + +// ELF 0x30A4A0 (C2; C1 0x30A5F0). Initializes an empty quad-tree collection and its island +// metadata. QuadTreeManager::QuadTreeManager() { // m_numberOfIslands deliberately not initialised - the binary steps over it. } -// [FRONTIER] Manager destruction requires the remaining quad-tree and debug-mesh cleanup. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding QuadTreeManager operation. +// ELF 0x30DD40 (D2; D1 0x30DE30; first recovered on the client track, +// docs/macos-c-singleplayer.md): destroyQuadTrees, unloadDebugMeshes, unloadDebugClusterMeshes, then the four lists and the +// island vector go as members. QuadTreeManager::~QuadTreeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::~QuadTreeManager"); + destroyQuadTrees(); + unloadDebugMeshes(); + unloadDebugClusterMeshes(); } -// Returns the selected island or cluster graph. The caller must supply a valid island index. +// ELF 0x30E530 / 0x30E550. Returns the selected island or cluster graph. The caller must supply +// a valid island index. QuadTree* QuadTreeManager::getIsland(unsigned int island) const { return m_islands[island].first; @@ -40,12 +74,13 @@ ClusterGraph* QuadTreeManager::getClusterGraph(unsigned int island) const return m_islands[island].second; } +// ELF 0x310F80. unsigned int QuadTreeManager::getNumberOfIslands() const { return static_cast(m_islands.size()); } -// Deletes both halves of every island's pair (each `delete` null-tests for itself), then +// ELF 0x30E240. Deletes both halves of every island's pair (each `delete` null-tests for itself), then // `resize(0)` - the shape in both images: g++ 3.x's size test with erase / zero-length // _M_fill_insert, and MSVC's size test with an erase that only moves `end` back. Not clear: the // vector keeps its capacity in both. Called first by loadQuadTrees, so a reload frees the old @@ -62,7 +97,7 @@ void QuadTreeManager::destroyQuadTrees() m_islands.resize(0); } -// Deletes the matching quad tree while retaining its island entry and nulling its pointer. +// ELF 0x30A690. Deletes the matching quad tree while retaining its island entry and nulling its pointer. void QuadTreeManager::destroyQuadTree(QuadTree* quadTree) { std::vector >::iterator it = m_islands.begin(); @@ -79,7 +114,7 @@ void QuadTreeManager::destroyQuadTree(QuadTree* quadTree) } } -// Loads navigation meshes for a map into the managed quad trees. +// ELF 0x30ABA0. Loads navigation meshes for a map into the managed quad trees. void QuadTreeManager::loadQuadTrees(const std::string& name) { destroyQuadTrees(); @@ -134,79 +169,604 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) quadTreeFile.close(); } -// [FRONTIER] Remaining operations require quad-tree, cluster-graph, GTS or debug-mesh support. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -void QuadTreeManager::saveQuadTrees(const std::string&) +// ELF 0x30A700. Writes /AIPathFinding/.qtr and .clb: the island count (also stored in +// m_numberOfIslands) to the tree file, then each island's tree and graph. Nothing is written +// unless both files open. +void QuadTreeManager::saveQuadTrees(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::saveQuadTrees"); + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + + io::File quadTreeFile; + if (!quadTreeFile.open(levelPath + "/AIPathFinding/" + name + ".qtr", + static_cast(0), io::FILEACCESS_1, 0)) + return; + + io::File clusterFile; + if (!clusterFile.open(levelPath + "/AIPathFinding/" + name + ".clb", + static_cast(0), io::FILEACCESS_1, 0)) + return; + + m_numberOfIslands = static_cast(m_islands.size()); + quadTreeFile.write(m_numberOfIslands); + for (std::vector >::iterator it = m_islands.begin(); + it != m_islands.end(); ++it) + { + it->first->saveToFile(quadTreeFile); + it->second->saveToFile(clusterFile); + } + + quadTreeFile.close(); + clusterFile.close(); } -void QuadTreeManager::loadGTSData(const std::string&, int, int, int, float) +// ELF 0x30B390. Imports and optimises each island before publishing it and computing its costs. +bool QuadTreeManager::loadGTSData(const std::string& name, int maxDepth, int minPolygons, + int map, float radius) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::loadGTSData"); + destroyQuadTrees(); + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::File treeFile; + if (!treeFile.open(levelPath + "/GTSData/Output/" + name + ".qti", + io::FILEMODE_READ, static_cast(0), 0)) + return false; + io::File clusterFile; + if (!clusterFile.open(levelPath + "/GTSData/Output/" + name + ".cls", + io::FILEMODE_READ, static_cast(0), 0)) + return false; + unsigned int count; + treeFile.read(count); + if (count == 0) + return false; + + std::vector objects; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getAllDestroyableObjects(objects); + unsigned int island = 0; + do + { + QuadTree* tree = checkPointer(new QuadTree(island)); + tree->m_gtsBuildValue = 1; + tree->m_maxDepthInTree = maxDepth; + tree->m_minPolygonsInLeaf = minPolygons; + tree->readGTSDataFromFileDoubles(treeFile); + for (std::vector::const_iterator i = objects.begin(); + i != objects.end(); ++i) + { + // shipped defect: every object is assigned the same map-part id. + tree->initializeDestroyableMapPart(map, i->initiallyWalkable, i->min, i->max, + i->transform, 0, true); + } + ClusterGraph* graph = checkPointer(new ClusterGraph); + graph->readGTSDataFromFile(tree, clusterFile); + graph->validateClusterGraphConnectivity(tree, true); + tree->optimiseGTSData(graph); + graph->validateClusterGraphConnectivity(tree, false); + graph->createPortals(map, tree, radius); + m_islands.push_back(std::make_pair(tree, graph)); + graph->calculatePortalCosts(map, island); + ++island; + } while (--count != 0); + treeFile.close(); + clusterFile.close(); + return island != 0; } -void QuadTreeManager::recalculatePortalCosts(int) +// ELF 0x30BDA0. Rebuilds every island's portal cost table (island index in vector order). +void QuadTreeManager::recalculatePortalCosts(int map) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::recalculatePortalCosts"); + unsigned int island = 0; + for (std::vector >::iterator it = m_islands.begin(); + it != m_islands.end(); ++it, ++island) + it->second->calculatePortalCosts(map, island); } -void QuadTreeManager::draw() +// ELF 0x30BE00. Re-creates each debug mesh's static mesh (1e9 s); neither manager is null-tested. +// DPStaticMesh is not defined in this tree; the image stores the returned pointer unadjusted as +// the DrawPrimitive handle. [CHOSEN, not recovered] cast. +void QuadTreeManager::draw() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::draw"); + for (std::list::const_iterator it = m_debugMeshes.begin(); + it != m_debugMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + mesh->m_mesh = reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticMesh(1.0e9f, mesh->m_colours, 0, mesh->m_vertices, + mesh->m_indices, mesh->m_numberOfPolygons, true)); + } } -void QuadTreeManager::undraw() +// ELF 0x30BEB0. +void QuadTreeManager::undraw() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::undraw"); + for (std::list::const_iterator it = m_debugMeshes.begin(); + it != m_debugMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + } } +// ELF 0x30BF20. draw on the cluster meshes. void QuadTreeManager::drawCluster() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::drawCluster"); + for (std::list::iterator it = m_debugClusterMeshes.begin(); + it != m_debugClusterMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + mesh->m_mesh = reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticMesh(1.0e9f, mesh->m_colours, 0, mesh->m_vertices, + mesh->m_indices, mesh->m_numberOfPolygons, true)); + } } -void QuadTreeManager::undrawCluster() +// ELF 0x30BFE0. +void QuadTreeManager::undrawCluster() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::undrawCluster"); + for (std::list::const_iterator it = m_debugClusterMeshes.begin(); + it != m_debugClusterMeshes.end(); ++it) + { + DebugMesh* const mesh = *it; + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + } } -void QuadTreeManager::drawClusterNeighbourIndices(const Vec3&) +// ELF 0x30C050. The first drawing handle is a circle; the remaining handles are portal labels. +void QuadTreeManager::drawClusterNeighbourIndices(const Vec3& point) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::drawClusterNeighbourIndices"); + std::list::iterator i = m_drawn.begin(); + if (i != m_drawn.end()) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteCircle(*i); + i = m_drawn.erase(i); + } + while (i != m_drawn.end()) + { + static_cast(CommonSingletonServer::m_iDPManager)->delete3dText(*i); + i = m_drawn.erase(i); + } + const Vec3 up = {0.0f, 1.0f, 0.0f}; + const Vec3 raised = {point.x + 0.0f, point.y + 1.0f, point.z + 0.0f}; + m_drawn.push_back(reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(60.0f, 0xFFFFFFu, raised, 0.5f, up, false, 255))); + + const unsigned int islands = static_cast(m_islands.size()); + for (unsigned int island = 0; island < islands; ++island) + { + QuadTree* tree = m_islands[island].first; + ClusterGraph* graph = m_islands[island].second; + MaterialManager* materials = + static_cast(CommonSingletonServer::m_iaiSettings) + ->getVehicleMaterialManager(1); + unsigned int polygon = 0xFFFFFFFFu; + if (!tree->findPolygon(point, polygon, materials, 100.0f)) + continue; + const unsigned short cluster = graph->getClusterId(tree, polygon); + if (cluster == 0xFFFFu) + return; + std::list portals; + graph->getClusterPortals(cluster, 0, portals); + for (std::list::const_iterator p = portals.begin(); + p != portals.end(); ++p) + { + std::stringstream text; + if ((*p)->m_neighbourCluster == 0xFFFFu) + text << "Inv"; + else + text << static_cast((*p)->m_neighbourCluster); + Vec3 position = (*p)->m_position; + // Preserve the x87 expression's precision until the final float store. + const long double random = static_cast(AIRandom::m_instance->next()) * + 2.3283064365386962890625e-10f; + position.y = static_cast((3.0L - 1.0L) * random + 1.0L + position.y); + m_drawn.push_back( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic3dText(60.0f, 0xFFFFFFu, position, text.str(), 0, + static_cast(0), + static_cast(0))); + } + } } +// ELF 0x30E570. Deduplicates vertices within each island and splits at 0x5555 polygons. void QuadTreeManager::buildDebugMeshes(const std::string&) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::buildDebugMeshes"); + unloadDebugMeshes(); + std::list indices; + std::map vertexMap; + std::list vertices; + std::list materials; + std::vector counts; + const unsigned int islands = static_cast(m_islands.size()); + DebugMesh* mesh = checkPointer(new DebugMesh); + int polygons = 0; + unsigned int nextVertex = 0; + for (unsigned int island = 0; island < islands; ++island) + { + QuadTree* tree = m_islands[island].first; + const unsigned int polygonCount = tree->m_numberOfPolygons; + vertexMap.clear(); + for (unsigned int polygon = 0; polygon < polygonCount; ++polygon) + { + const Polygon* p = tree->getPolygon(polygon); + counts.push_back(p->m_numberOfVertices); + materials.push_back(p->m_material); + for (unsigned char corner = 0; corner < p->m_numberOfVertices; ++corner) + { + const unsigned int index = tree->m_vertexIndices[p->m_firstIndex + corner]; + std::map::iterator v = vertexMap.find(index); + if (v == vertexMap.end()) + { + vertexMap.insert(std::make_pair(index, nextVertex)); + indices.push_back(nextVertex); + vertices.push_back(tree->m_vertices[index]); + ++nextVertex; + } + else + indices.push_back(v->second); + } + ++polygons; + if ((island == islands - 1 && polygon == polygonCount - 1) || polygons == 0x5555) + { + mesh->m_numberOfPolygons = polygons; + mesh->m_numberOfVertices = static_cast(vertices.size()); + mesh->m_numberOfIndices = static_cast(indices.size()); + mesh->lockSize(); + std::copy(vertices.begin(), vertices.end(), mesh->m_vertices); + std::copy(indices.begin(), indices.end(), mesh->m_indices); + std::copy(materials.begin(), materials.end(), mesh->m_materials); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (int p = 0; p < mesh->m_numberOfPolygons; ++p) + { + mesh->m_vertexCounts[p] = counts[p]; + mesh->m_firstIndices[p] = p > 0 ? + mesh->m_firstIndices[p - 1] + counts[p - 1] : 0; + bool outside = false; + for (unsigned int corner = 0; corner < counts[p]; ++corner) + { + if (!environment->isAiPositionInsideCombatArea(mesh->m_vertices[ + mesh->m_indices[mesh->m_firstIndices[p] + corner]])) + { + outside = true; + break; + } + } + if (outside) + mesh->m_colours[p] = 0; + else + { + unsigned int base; + switch (mesh->m_materials[p]) + { + case 1: base = 0x80C000u; break; + case 2: base = 0xE00000u; break; + case 3: base = 0xE0E000u; break; + case 4: base = 0x6020E0u; break; + default: base = 0xE00000u; break; + } + mesh->m_colours[p] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } + } + m_debugMeshes.push_back(mesh); + if (polygons == 0x5555) + { + mesh = checkPointer(new DebugMesh); + polygons = 0; + nextVertex = 0; + vertices.resize(0, Vec3()); + indices.resize(0, 0); + vertexMap.clear(); + materials.resize(0, 0); + counts.resize(0); + } + } + } + } + // shipped defect: an unused mesh leaks for empty input or an exact final chunk. + triangulateDebugMeshes(m_debugMeshes); } +// ELF 0x30C9B0. Clusters share a base colour; each polygon consumes another random value. void QuadTreeManager::buildDebugClusterMeshes(const std::string&) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::buildDebugClusterMeshes"); + unloadDebugClusterMeshes(); + const unsigned int islands = static_cast(m_islands.size()); + int polygons = 0; + std::list indices; + std::list vertices; + std::map vertexMap; + std::vector counts; + std::list materials; + std::list colours; + unsigned int clusterTag = 1; + DebugMesh* mesh = checkPointer(new DebugMesh); + unsigned int nextVertex = 0; + for (unsigned int island = 0; island < islands; ++island) + { + QuadTree* tree = m_islands[island].first; + ClusterGraph* graph = m_islands[island].second; + const unsigned int clusterCount = graph->m_numberOfClusters; + vertexMap.clear(); + for (unsigned short cluster = 0; cluster < clusterCount; ++cluster) + { + const unsigned int first = graph->m_clusters[cluster].m_firstPolygon; + const unsigned int count = graph->m_clusters[cluster].m_numberOfPolygons; + unsigned int base = graph->m_clusters[cluster].m_walkable ? + AIRandom::m_instance->next() & 0xFFFFFFu : 0xFF0000u; + for (unsigned int polygon = 0; polygon < count; ++polygon) + { + const Polygon* p = tree->getPolygon(graph->m_clusterPolygons[first + polygon]); + ++polygons; + counts.push_back(p->m_numberOfVertices); + materials.push_back(static_cast(clusterTag)); + base &= 0xE0E0E0E0u; + colours.push_back((AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base); + for (unsigned char corner = 0; corner < p->m_numberOfVertices; ++corner) + { + const unsigned int index = tree->m_vertexIndices[p->m_firstIndex + corner]; + std::map::iterator v = vertexMap.find(index); + if (v == vertexMap.end()) + { + vertexMap.insert(std::make_pair(index, nextVertex)); + indices.push_back(nextVertex); + vertices.push_back(tree->m_vertices[index]); + ++nextVertex; + } + else + indices.push_back(v->second); + } + if ((island == islands - 1 && cluster == clusterCount - 1 && + polygon == count - 1) || polygons == 0x5555) + { + mesh->m_numberOfPolygons = polygons; + mesh->m_numberOfVertices = static_cast(vertices.size()); + mesh->m_numberOfIndices = static_cast(indices.size()); + mesh->lockSize(); + std::copy(vertices.begin(), vertices.end(), mesh->m_vertices); + std::copy(indices.begin(), indices.end(), mesh->m_indices); + std::copy(materials.begin(), materials.end(), mesh->m_materials); + std::list::const_iterator colour = colours.begin(); + for (int p = 0; p < mesh->m_numberOfPolygons; ++p, ++colour) + { + mesh->m_vertexCounts[p] = counts[p]; + mesh->m_firstIndices[p] = p > 0 ? + mesh->m_firstIndices[p - 1] + counts[p - 1] : 0; + mesh->m_colours[p] = *colour; + } + m_debugClusterMeshes.push_back(mesh); + if (polygons == 0x5555) + { + mesh = checkPointer(new DebugMesh); + nextVertex = 0; + polygons = 0; + vertices.resize(0, Vec3()); + indices.resize(0, 0); + vertexMap.clear(); + materials.resize(0, 0); + counts.resize(0); + colours.resize(0, 0); + } + } + } + ++clusterTag; + } + } + // shipped defect: an unused mesh leaks for empty input or an exact final chunk. + triangulateDebugMeshes(m_debugClusterMeshes); } -void QuadTreeManager::loadGTSDebugMeshes(const std::string&) +// ELF 0x30F630. GTS debug triangles use different material colours from the quad-tree meshes. +void QuadTreeManager::loadGTSDebugMeshes(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::loadGTSDebugMeshes"); + unloadDebugMeshes(); + const std::string levelPath = + static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::File file; + if (!file.open(levelPath + "/GTSData/Output/" + name + ".vbf", + io::FILEMODE_READ, static_cast(0), 0)) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp", 938, "") + << "Could not find file " << levelPath << "/GTSData/Output/" << name << ".vbf"; + return; + } + int count; + file.read(count); + IAIObjectEnvironment* environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + environment->initAiCombatAreas(); + for (int island = 0; island < count; ++island) + { + DebugMesh* mesh = checkPointer(new DebugMesh); + file.read(mesh->m_numberOfVertices); + file.read(mesh->m_numberOfPolygons); + mesh->m_numberOfIndices = mesh->m_numberOfPolygons * 3; + mesh->lockSize(); + file.read(mesh->m_vertices, mesh->m_numberOfVertices * 12); + file.read(mesh->m_indices, mesh->m_numberOfPolygons * 12); + file.read(mesh->m_materials, mesh->m_numberOfPolygons); + for (int polygon = 0; polygon < mesh->m_numberOfPolygons; ++polygon) + { + mesh->m_firstIndices[polygon] = polygon * 3; + mesh->m_vertexCounts[polygon] = 3; + if (!environment->isAiPositionInsideCombatArea( + mesh->m_vertices[mesh->m_indices[polygon * 3]]) || + !environment->isAiPositionInsideCombatArea( + mesh->m_vertices[mesh->m_indices[polygon * 3 + 1]]) || + !environment->isAiPositionInsideCombatArea( + mesh->m_vertices[mesh->m_indices[polygon * 3 + 2]])) + mesh->m_colours[polygon] = 0; + else + { + unsigned int base; + switch (static_cast(mesh->m_materials[polygon]) + 1) + { + case 1: base = 0x80C000u; break; + case 3: base = 0x80C0u; break; + case 4: base = 0x40A0u; break; + default: base = 0xE00000u; break; + } + mesh->m_colours[polygon] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } + } + m_debugMeshes.push_back(mesh); + } + file.close(); } +// ELF 0x310150. Erases every mesh node first, then releases the mesh's static mesh (IDPManager +// +0x50), frees its six arrays and the mesh; finally resize(0). void QuadTreeManager::unloadDebugMeshes() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::unloadDebugMeshes"); + std::list::iterator it = m_debugMeshes.begin(); + while (it != m_debugMeshes.end()) + { + DebugMesh* const mesh = *it; + it = m_debugMeshes.erase(it); + if (mesh) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + delete[] mesh->m_firstIndices; + delete[] mesh->m_vertexCounts; + delete[] mesh->m_vertices; + delete[] mesh->m_indices; + delete[] mesh->m_materials; + delete[] mesh->m_colours; + delete mesh; + } + } + m_debugMeshes.resize(0, 0); } +// ELF 0x30DBD0: the same sequence on the cluster-mesh list. void QuadTreeManager::unloadDebugClusterMeshes() { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::unloadDebugClusterMeshes"); + std::list::iterator it = m_debugClusterMeshes.begin(); + while (it != m_debugClusterMeshes.end()) + { + DebugMesh* const mesh = *it; + it = m_debugClusterMeshes.erase(it); + if (mesh) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + delete[] mesh->m_firstIndices; + delete[] mesh->m_vertexCounts; + delete[] mesh->m_vertices; + delete[] mesh->m_indices; + delete[] mesh->m_materials; + delete[] mesh->m_colours; + delete mesh; + } + } + m_debugClusterMeshes.resize(0, 0); } -void QuadTreeManager::triangulateDebugMeshes(std::list&) +// ELF 0x3102C0. Replaces each polygon mesh with triangle fans, retaining sorted vertex order. +void QuadTreeManager::triangulateDebugMeshes(std::list& meshes) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::triangulateDebugMeshes"); + std::vector triangles; + for (std::list::const_iterator i = meshes.begin(); i != meshes.end(); ++i) + { + DebugMesh* source = *i; + int first = 0; + while (first < source->m_numberOfPolygons) + { + DebugMesh* mesh = checkPointer(new DebugMesh); + std::set vertices; + int polygonCount = 0; + int indexCount = 0; + int end = first; + int prospectiveCount = static_cast(source->m_vertexCounts[end] - 2); + while (prospectiveCount <= 0x5555 && end < source->m_numberOfPolygons) + { + polygonCount = prospectiveCount; + indexCount += source->m_vertexCounts[end] * 3 - 6; + ++end; + // shipped defect: the lookahead reads past the final polygon's count. + prospectiveCount = static_cast(source->m_vertexCounts[end] - 2) + polygonCount; + } + for (int polygon = first; polygon < end; ++polygon) + for (unsigned int corner = 0; corner < source->m_vertexCounts[polygon]; ++corner) + vertices.insert(source->m_indices[source->m_firstIndices[polygon] + corner]); + + mesh->m_numberOfVertices = static_cast(vertices.size()); + mesh->m_numberOfPolygons = polygonCount; + mesh->m_numberOfIndices = indexCount; + mesh->lockSize(); + std::map vertexMap; + unsigned int nextVertex = 0; + for (std::set::const_iterator v = vertices.begin(); v != vertices.end(); ++v) + { + mesh->m_vertices[nextVertex] = source->m_vertices[*v]; + vertexMap.insert(std::make_pair(*v, nextVertex)); + ++nextVertex; + } + unsigned int triangle = 0; + unsigned int index = 0; + unsigned int firstIndex = 0; + for (int polygon = first; polygon < end; ++polygon) + { + const std::map::const_iterator v = vertexMap.find( + source->m_indices[source->m_firstIndices[polygon]]); + for (unsigned int corner = 1; corner < source->m_vertexCounts[polygon] - 1; ++corner) + { + mesh->m_indices[index++] = v->second; + mesh->m_indices[index++] = vertexMap.find( + source->m_indices[source->m_firstIndices[polygon] + corner])->second; + mesh->m_indices[index++] = vertexMap.find( + source->m_indices[source->m_firstIndices[polygon] + corner + 1])->second; + mesh->m_firstIndices[triangle] = firstIndex; + mesh->m_vertexCounts[triangle] = 3; + mesh->m_materials[triangle] = source->m_materials[polygon]; + mesh->m_colours[triangle] = source->m_colours[polygon]; + ++triangle; + firstIndex += 3; + } + } + first = end; + triangles.push_back(mesh); + // shipped defect: a polygon exceeding the chunk limit makes no forward progress. + } + } + + std::list::iterator i = meshes.begin(); + while (i != meshes.end()) + { + DebugMesh* mesh = *i; + i = meshes.erase(i); + if (mesh) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteMesh(mesh->m_mesh); + mesh->m_mesh = 0; + delete[] mesh->m_firstIndices; + delete[] mesh->m_vertexCounts; + delete[] mesh->m_vertices; + delete[] mesh->m_indices; + delete[] mesh->m_materials; + delete[] mesh->m_colours; + delete mesh; + } + } + meshes.resize(0, 0); + for (std::vector::const_iterator mesh = triangles.begin(); + mesh != triangles.end(); ++mesh) + meshes.push_back(*mesh); } -// Visit islands in vector order and return the first +// ELF 0x30DF20. Visit islands in vector order and return the first // whose tree finds a polygon. The polygon output is whatever that tree wrote; a total miss leaves it // untouched and returns UINT_MAX. unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polygon, @@ -221,7 +781,7 @@ unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polyg return 0xFFFFFFFFu; } -// Reuse a known polygon/island only when neither is the +// ELF 0x30DFA0. Reuse a known polygon/island only when neither is the // sentinel and the point still belongs to it; otherwise run the full scan. The island is deliberately // not bounds-checked before indexing the vector. unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polygon, @@ -237,35 +797,46 @@ unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polyg return knownIsland; } -void QuadTreeManager::printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager*, float) const +// ELF 0x30E080. Every island's debug walk, re-reading the vector size each pass. +void QuadTreeManager::printPolygonsInNode(const Vec3& point, unsigned int& polygon, + MaterialManager* materials, float allowedHeightDiff) { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::printPolygonsInNode"); + for (unsigned int island = 0; island < m_islands.size(); ++island) + m_islands[island].first->printPolygonsInNode(point, polygon, materials, + allowedHeightDiff); } -unsigned short QuadTreeManager::getCluster(unsigned int, unsigned int) const +// ELF 0x30E0F0. +unsigned short QuadTreeManager::getCluster(unsigned int island, unsigned int polygon) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getCluster"); + return m_islands[island].second->getClusterId(m_islands[island].first, polygon); } -void QuadTreeManager::getClusterPortals(unsigned int, unsigned short, unsigned short, - std::list&) const +// ELF 0x30E140. +void QuadTreeManager::getClusterPortals(unsigned int island, unsigned short cluster, + unsigned short costType, + std::list& portals) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getClusterPortals"); + m_islands[island].second->getClusterPortals(cluster, costType, portals); } -void QuadTreeManager::getPolygonsInRadius(std::list&, unsigned int, unsigned int, - const Vec3&, float) const +// ELF 0x30E190. The island's tree only; no bounds check. +void QuadTreeManager::getPolygonsInRadius(std::list& polygons, unsigned int island, + unsigned int polygon, const Vec3& centre, + float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getPolygonsInRadius"); + m_islands[island].first->getPolygonsInRadius(polygons, polygon, centre, radius); } -void QuadTreeManager::getPolygonsInTriangle(std::list&, unsigned int, unsigned int, - const Vec3&, const Vec3&, const Vec3&) const +// ELF 0x30E1E0. +void QuadTreeManager::getPolygonsInTriangle(std::list& polygons, unsigned int island, + unsigned int polygon, const Vec3& a, const Vec3& b, + const Vec3& c) const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::getPolygonsInTriangle"); + m_islands[island].first->getPolygonsInTriangle(polygons, polygon, a, b, c); } -// Forward to every island in ascending order, re-reading the vector +// ELF 0x30E320. Forward to every island in ascending order, re-reading the vector // size on each pass. Runtime map parts use the ordinary float-vertex path (`useDoubles=false`). void QuadTreeManager::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkable, const Vec3& minimum, const Vec3& maximum, @@ -277,18 +848,21 @@ void QuadTreeManager::initializeDestroyableMapPart(int mapPartId, bool initially m_islands[island].second, false); } +// ELF 0x30E3C0. void QuadTreeManager::destroyMapPart(int mapPartId) { for (unsigned int island = 0; island < m_islands.size(); ++island) m_islands[island].first->destroyMapPart(mapPartId, m_islands[island].second); } +// ELF 0x30E420. void QuadTreeManager::restoreMapPart(int mapPartId) { for (unsigned int island = 0; island < m_islands.size(); ++island) m_islands[island].first->restoreMapPart(mapPartId, m_islands[island].second); } +// ELF 0x30E480. void QuadTreeManager::resetOriginalMaterialOfDestroyableMapPart(int mapPartId) { for (unsigned int island = 0; island < m_islands.size(); ++island) @@ -296,15 +870,18 @@ void QuadTreeManager::resetOriginalMaterialOfDestroyableMapPart(int mapPartId) mapPartId, m_islands[island].second); } +// ELF 0x30E4E0. void QuadTreeManager::resetDestroyableMapParts() { for (unsigned int island = 0; island < m_islands.size(); ++island) m_islands[island].first->resetDestroyableMapParts(m_islands[island].second); } -void QuadTreeManager::validateNeighbourRelations() +// ELF 0x310F30. +void QuadTreeManager::validateNeighbourRelations() const { - BF2_AI_FRONTIER("dice::hfe::ai::QuadTreeManager::validateNeighbourRelations"); + for (unsigned int island = 0; island < m_islands.size(); ++island) + m_islands[island].first->validateNeighbourRelations(); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h index 066df3774..058e4b7c1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h @@ -1,5 +1,4 @@ // Owns navigation quad trees and loads their per-map data. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREEMANAGER_H #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREEMANAGER_H @@ -23,9 +22,26 @@ class QuadTree; class QuadTreeManager { public: - // Opaque nested debug mesh, referenced by pointer here. Teardown must release six - // arrays at original offsets +12..+32 and its primitive handle at +36. - class DebugMesh; + // One debug mesh: up to 0x5555 polygons of the islands in one static mesh. 40 bytes on the + // ELF (operator new(0x28)), no virtual members. Field names [INFERRED] from buildDebugMeshes, + // which allocates and fills every array, and draw, which hands them to createStaticMesh. + class DebugMesh + { + public: + DebugMesh(); + void lockSize(); + + /* +0x00 */ int m_numberOfVertices; + /* +0x04 */ int m_numberOfPolygons; + /* +0x08 */ int m_numberOfIndices; + /* +0x0C */ unsigned int* m_firstIndices; // per polygon: where its indices start + /* +0x10 */ unsigned int* m_vertexCounts; // per polygon + /* +0x14 */ Vec3* m_vertices; + /* +0x18 */ unsigned int* m_indices; + /* +0x1C */ unsigned char* m_materials; // per polygon + /* +0x20 */ unsigned int* m_colours; // per polygon, the mesh's colour argument + /* +0x24 */ DrawPrimitive* m_mesh; // the static mesh handle while drawn + }; QuadTreeManager(); ~QuadTreeManager(); @@ -40,12 +56,12 @@ class QuadTreeManager void destroyQuadTrees(); void saveQuadTrees(const std::string&); void loadQuadTrees(const std::string&); - void loadGTSData(const std::string&, int, int, int, float); + bool loadGTSData(const std::string&, int, int, int, float); void recalculatePortalCosts(int); - void draw(); - void undraw(); + void draw() const; + void undraw() const; void drawCluster(); - void undrawCluster(); + void undrawCluster() const; void drawClusterNeighbourIndices(const Vec3&); void buildDebugMeshes(const std::string&); void buildDebugClusterMeshes(const std::string&); @@ -58,7 +74,7 @@ class QuadTreeManager unsigned int findPolygon(const Vec3&, unsigned int&, MaterialManager*, float); unsigned int findPolygon(const Vec3&, unsigned int&, unsigned int, unsigned int, MaterialManager*, float); - void printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager *, float) const; + void printPolygonsInNode(const Vec3&, unsigned int&, MaterialManager *, float); unsigned short getCluster(unsigned int, unsigned int) const; void getClusterPortals(unsigned int, unsigned short, unsigned short, std::list&) const; void getPolygonsInRadius(std::list&, unsigned int, unsigned int, const Vec3&, float) const; @@ -68,7 +84,7 @@ class QuadTreeManager void restoreMapPart(int); void resetOriginalMaterialOfDestroyableMapPart(int); void resetDestroyableMapParts(); - void validateNeighbourRelations(); + void validateNeighbourRelations() const; // Offsets describe the original 32-byte ELF object; STL layouts vary by compiler. diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp index 6fd190343..9a95ff2bc 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp @@ -1,16 +1,178 @@ -// [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTreeNode operations. +// Navigation quad-tree node construction and polygon lookup. #include "QuadTreeNode.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x313300, __tcf_0 0x313360, _GLOBAL__I 0x313390). +#include + #include "QuadTree.h" #include "../Material/MaterialManager.h" +#include "../../../../../Math/Vec3.h" namespace dice { namespace hfe { namespace ai { -// A branch selects exactly one quadrant. Child index zero means absent; non-zero indices address +// ELF 0x312900. Retail iterates to the end and ignores the requested value. +void checkVector(const std::vector& values, unsigned int) +{ + for (std::vector::const_iterator i = values.begin(); i != values.end(); ++i) {} +} + +// ELF 0x312930. Reserves a branch before its children; empty children consume no node. +bool QuadTreeNode::create(QuadTree* tree, unsigned int& nodeCount, const Vec2& minimum, + float size, int depth, const std::vector& polygons, int count) +{ + static int maxPolygonCount = 20; // Original .data 0x4BF158. + bool leaf = depth == tree->m_maxDepthInTree; + std::vector children[4]; + if (depth < tree->m_gtsBuildValue) + leaf = false; + if (!leaf) + leaf = count <= tree->m_minPolygonsInLeaf; + int counts[4]; + if (!leaf) + { + const float half = size * 0.5f; + Vec2 childMinimum = minimum; + counts[0] = countPolygonsInside(polygons, tree, childMinimum, half, children[0]); + childMinimum.y += half; + counts[1] = countPolygonsInside(polygons, tree, childMinimum, half, children[1]); + childMinimum.x += half; + childMinimum.y -= half; + counts[2] = countPolygonsInside(polygons, tree, childMinimum, half, children[2]); + childMinimum.y += half; + counts[3] = countPolygonsInside(polygons, tree, childMinimum, half, children[3]); + if (static_cast(count) / + static_cast(counts[0] + counts[1] + counts[2] + counts[3]) < 0.5f && + count < maxPolygonCount) + leaf = true; + } + if (leaf) + { + if (count == 0) + return false; + ++nodeCount; + m_isLeaf = 1; + // shipped defect: the count narrows to a byte, while all supplied polygons are copied. + m_polygonCount = static_cast(count); + m_firstPolygon = static_cast(tree->m_vector18.size()); + for (int i = 0; i < count; ++i) + tree->m_vector18.push_back(polygons[i]); + return true; + } + + ++nodeCount; + const float half = size * 0.5f; + m_children[0] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, minimum, half, depth + 1, + children[0], counts[0])) + m_children[0] = 0; + Vec2 childMinimum = {minimum.x, minimum.y + half}; + m_children[1] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, childMinimum, half, depth + 1, + children[1], counts[1])) + m_children[1] = 0; + childMinimum.x += half; + childMinimum.y -= half; + m_children[2] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, childMinimum, half, depth + 1, + children[2], counts[2])) + m_children[2] = 0; + childMinimum.y += half; + m_children[3] = nodeCount; + if (!tree->m_nodes[nodeCount].create(tree, nodeCount, childMinimum, half, depth + 1, + children[3], counts[3])) + m_children[3] = 0; + return true; +} + +// ELF 0x312850. Appends matches and returns the full resulting vector size. +int QuadTreeNode::countPolygonsInside(const std::vector& polygons, QuadTree* tree, + const Vec2& minimum, float size, std::vector& output) +{ + for (std::vector::const_iterator p = polygons.begin(); p != polygons.end(); ++p) + if (polygonInside(minimum, size, tree, *p)) + output.push_back(*p); + return static_cast(output.size()); +} + +// ELF 0x312480. Tests polygon vertices, square corners, then all projected edge pairs. +bool QuadTreeNode::polygonInside(const Vec2& minimum, float size, QuadTree* tree, + unsigned int polygon) +{ + const Vec3 square[4] = {{minimum.x, 0.0f, minimum.y}, + {minimum.x + size, 0.0f, minimum.y}, + {minimum.x + size, 0.0f, minimum.y + size}, + {minimum.x, 0.0f, minimum.y + size}}; + const Polygon* p = tree->m_polygons + polygon; + const int count = p->m_numberOfVertices; + for (int corner = 0; corner < count; ++corner) + { + const Vec3* v = tree->getVertexForPolygon(polygon, static_cast(corner)); + if (minimum.x <= v->x && v->x <= minimum.x + size && + minimum.y <= v->z && v->z <= minimum.y + size) + return true; + } + for (int corner = 0; corner < 4; ++corner) + { + bool inside = true; + for (int edge = 0; edge < count && inside; ++edge) + { + const Vec3* a = tree->getVertexForPolygon(polygon, static_cast(edge)); + const Vec3* b = tree->getSafeVertexForPolygon(polygon, + static_cast(edge + 1)); + const Vec3 direction = {b->x - a->x, 0.0f, b->z - a->z}; + const Vec3 offset = {square[corner].x - a->x, 0.0f, square[corner].z - a->z}; + const Vec3 cross = {0.0f * direction.z - offset.z * 0.0f, + offset.z * direction.x - direction.z * offset.x, + offset.x * 0.0f - direction.x * 0.0f}; + inside = cross.x * p->m_normal.x + cross.y * p->m_normal.y + + cross.z * p->m_normal.z < 0.0f; + } + if (inside) + return true; + } + for (int edge = 0; edge < count; ++edge) + { + Vec3 a = *tree->getVertexForPolygon(polygon, static_cast(edge)); + const Vec3* next = tree->getSafeVertexForPolygon(polygon, + static_cast(edge + 1)); + Vec3 b = {next->x, 0.0f, next->z}; + a.y = 0.0f; + for (int side = 0; side < 4; ++side) + if (lineSegmentIntersect(a, b, square[side], square[(side + 1) % 4])) + return true; + } + return false; +} + +// ELF 0x312420 (C2; C1 0x312440). The children are left unset. +QuadTreeNode::QuadTreeNode() + : m_isLeaf(0) + , m_polygonCount(0) + , m_firstPolygon(0) +{ +} + +// ELF 0x312460 (D2; D1 0x312470). +QuadTreeNode::~QuadTreeNode() +{ +} + +// ELF 0x3132C0. +QuadTreeNode& QuadTreeNode::operator=(const QuadTreeNode& other) +{ + for (int i = 0; i < 4; ++i) + m_children[i] = other.m_children[i]; + m_isLeaf = other.m_isLeaf; + m_polygonCount = other.m_polygonCount; + m_firstPolygon = other.m_firstPolygon; + return *this; +} + +// ELF 0x312DD0. A branch selects exactly one quadrant. Child index zero means absent; non-zero indices address // QuadTree::m_nodes directly. Equality belongs to the positive-X / positive-Z halves. // A leaf examines its byte-counted slice of m_nodePolygons. It rejects downward/vertical polygon // normals and negative material costs, then keeps the candidate with the smallest squared vertical @@ -97,6 +259,68 @@ bool QuadTreeNode::findPolygon(const QuadTree* tree, const Vec2& minimum, float return true; } +// ELF 0x313080. Descends like findPolygon (child index zero ends the walk); a leaf only reads +// each corner of its polygons through getVertexForPolygon. The child's minimum is the parent's +// plus a 0 / half offset per axis (the zero offsets are real additions in the listing), except +// for the first quadrant, which passes the parent's. +void QuadTreeNode::printPolygonsInNode(const QuadTree* tree, const Vec2& minimum, float size, + const Vec3& point, unsigned int& polygon, + MaterialManager* materials, float allowedHeightDiff) const +{ + if (m_isLeaf) + { + const unsigned char count = m_polygonCount; + for (int i = 0; i < count; ++i) + { + const unsigned int candidate = tree->m_nodePolygons[m_firstPolygon + i]; + const Polygon& candidatePolygon = tree->m_polygons[candidate]; + for (int corner = 0; corner < candidatePolygon.m_numberOfVertices; ++corner) + tree->getVertexForPolygon(candidate, static_cast(corner)); + } + return; + } + + const float half = size * 0.5f; + Vec2 childMinimum; + const Vec2* next = &childMinimum; + unsigned int child; + + if (minimum.x + half > point.x) + { + if (minimum.y + half > point.z) + { + child = m_children[0]; + next = &minimum; + } + else + { + child = m_children[1]; + childMinimum.x = minimum.x + 0.0f; + childMinimum.y = minimum.y + half; + } + } + else + { + childMinimum.x = minimum.x + half; + if (minimum.y + half > point.z) + { + child = m_children[2]; + childMinimum.y = minimum.y + 0.0f; + } + else + { + child = m_children[3]; + childMinimum.y = minimum.y + half; + } + } + + if (!child) + return; + + tree->m_nodes[child].printPolygonsInNode(tree, *next, half, point, polygon, materials, + allowedHeightDiff); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h index f2f80187d..340e5f466 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.h @@ -1,12 +1,11 @@ // Navigation quad-tree node. File loading initializes its stored data. -// [FRONTIER] Generation and debug queries remain incomplete. -// [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining QuadTreeNode operations. +// Generation subdivides the navigation polygons during QuadTree::buildQuadTree. #ifndef AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREENODE_H #define AI_AIDLL_AI_AIPATHFINDING_NAVMESH_QUADTREENODE_H #include "../../Main/AIDllTypes.h" +#include namespace dice { namespace hfe { @@ -18,11 +17,24 @@ class QuadTree; class QuadTreeNode { public: - QuadTreeNode() : m_isLeaf(0), m_polygonCount(0), m_firstPolygon(0) {} - ~QuadTreeNode() {} // empty + QuadTreeNode(); + ~QuadTreeNode(); + + // Copies the children, the leaf flag, the count and the first index; the two bytes at +0x12 + // are not copied. + QuadTreeNode& operator=(const QuadTreeNode& other); + bool create(QuadTree*, unsigned int&, const Vec2&, float, int, + const std::vector&, int); + bool polygonInside(const Vec2&, float, QuadTree*, unsigned int); + int countPolygonsInside(const std::vector&, QuadTree*, const Vec2&, float, + std::vector&); bool findPolygon(const QuadTree*, const Vec2&, float, const Vec3&, unsigned int&, MaterialManager*, float) const; + // The debug twin of findPolygon: descends the same way and reads every corner of the leaf's + // polygons without printing or returning anything. + void printPolygonsInNode(const QuadTree*, const Vec2&, float, const Vec3&, unsigned int&, + MaterialManager*, float) const; // A branch stores four node-array indices, with zero meaning "no child". A leaf instead uses // the byte count and first index to address QuadTree::m_nodePolygons. The two bytes at +0x12 diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h index 2484ce080..afdf47960 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.h @@ -24,6 +24,12 @@ class BAPContext ~BAPContext(); // - , and it leaks; see above void clear(); + // [CHOSEN, not recovered] added by ai-w1-e-fire (coord/ai-requests.md 2026-11-01); the owner may + // rename it. Every plan variable the fire patterns create is put at the front of the list: + // BBPFireInfantery::createPlanInternal calls `std::list::insert(begin(), &v)` + // right after each inlined BAPVariable construction (0x2654C6, 0x265547, ... 0x27127A). + void addVariable(BotScriptVariable* variable) { m_variables.insert(m_variables.begin(), variable); } + private: /* 0 */ std::list m_variables; // the whole object }; diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp new file mode 100644 index 000000000..dc8799369 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp @@ -0,0 +1,159 @@ +// Bot-script debugger: per-statement debug levels for two debug places and a statement stack. +// Evidence: libaidll.so (ia-32) 0x2A83E0..0x2A90DF and 0x2A95D0. Placement attested by the __FILE__ +// string "AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp". + +// static init: ELF 0x2A9030 (__tcf_0 0x2A9090, _GLOBAL__I 0x2A90C0): 's Init object only. +#include + +#include "BAPDebugger.h" + +#include +#include + +#include "../../../../Core/Debug.h" +#include "../AIBotActionPlan/BAPStatement.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A8560 (C1; C2 0x2A83E0). +BAPDebugger::BAPDebugger() + : m_debugLevel(static_cast(3)) +{ +} + +// ELF 0x2A8720 (D1; D2 0x2A8620, D0 0x2A8820). The members are destroyed in reverse order. +BAPDebugger::~BAPDebugger() +{ +} + +// ELF 0x2A8930. Place 0 uses the first map, place 1 the second; any other place does nothing. +void BAPDebugger::debug(BotScriptDebugger::DebugLevel level, BotScript* script, + BotScriptDebugger::DebugPlace place, int value) +{ + switch (place) + { + case 0: + internalDebug(level, script, value, m_placeZeroStatements); + break; + case 1: + internalDebug(level, script, value, m_placeOneStatements); + break; + default: + break; + } +} + +// ELF 0x2A8C90. +void BAPDebugger::clear() +{ + clearDebugStatement(); + clearStack(); +} + +// ELF 0x2A95D0. +int BAPDebugger::getImplementation() +{ + return 1; +} + +// ELF 0x2A89B0. Same place dispatch as debug(). +void BAPDebugger::addDebugStatement(BotScriptDebugger::DebugLevel level, BAPStatement* statement, + BotScriptDebugger::DebugPlace place, int value) +{ + switch (place) + { + case 0: + internalAddStatement(level, statement, value, m_placeZeroStatements); + break; + case 1: + internalAddStatement(level, statement, value, m_placeOneStatements); + break; + default: + break; + } +} + +// ELF 0x2A8A30. +void BAPDebugger::clearDebugStatement() +{ + m_placeZeroStatements.clear(); + m_placeOneStatements.clear(); +} + +// ELF 0x2A8AE0. +void BAPDebugger::pushStatement(BAPStatement* statement) +{ + m_stack.insert(m_stack.begin(), statement); +} + +// ELF 0x2A8B30. Answers 0 on an empty stack (counted with size()). When the back is not the +// statement, it is searched from the front; the search result is dereferenced even when it is +// end() (shipped defect). On a match the back is popped, not the matching element (shipped). +int BAPDebugger::popStatement(BAPStatement* statement) +{ + if (m_stack.size() == 0) + return 0; + if (m_stack.back() != statement) + { + if (*std::find(m_stack.begin(), m_stack.end(), statement) != statement) + return 0; + } + m_stack.pop_back(); + return 1; +} + +// ELF 0x2A8C70. +void BAPDebugger::setDebugLevel(BotScriptDebugger::DebugLevel level) +{ + m_debugLevel = level; +} + +// ELF 0x2A8C80. +int BAPDebugger::getDebugLevel() +{ + return m_debugLevel; +} + +// ELF 0x2A8CD0. +void BAPDebugger::clearStack() +{ + m_stack.clear(); +} + +// ELF 0x2A8D00. A registered statement whose value filter is -1 or matches prints itself at the +// lowest of the requested, registered and debugger levels; level 2 output goes to the error log. +void BAPDebugger::internalDebug(BotScriptDebugger::DebugLevel level, BotScript* script, int value, + std::map >& statements) +{ + std::string text; + BAPStatement* statement = static_cast(script); + StatementMap::iterator found = statements.find(statement); + if (found == statements.end()) + return; + if (found->second.second != -1 && found->second.second != value) + return; + BotScriptDebugger::DebugLevel effective = level; + if (found->second.first <= level) + effective = found->second.first; + if (effective > m_debugLevel) + effective = m_debugLevel; + statement->debug(effective, text); + if (effective == 2) + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp", 248, "") << text; +} + +// ELF 0x2A8F00. Registers a statement once; an existing entry is left unchanged. +void BAPDebugger::internalAddStatement(BotScriptDebugger::DebugLevel level, BAPStatement* statement, + int value, + std::map >& statements) +{ + if (statements.find(statement) != statements.end()) + return; + statements[statement] = std::make_pair(level, value); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.h new file mode 100644 index 000000000..5d71bd237 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.h @@ -0,0 +1,58 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BAPDEBUGGER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BAPDEBUGGER_H + +#include +#include +#include +#include "BotScriptDebugger.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class BotScript; + +// ELF: vtable 0x4BC9C8 (5 words), package H-deferred. +// sizeof == 0x24 on ia-32. Data members from the constructor (0x2A83E0) and the bodies below; +// names [INFERRED]. +class BAPDebugger : public BotScriptDebugger +{ +public: + BAPDebugger(); // 0x2A8560 + virtual ~BAPDebugger(); // 0x2A8720 + + virtual void debug(BotScriptDebugger::DebugLevel, BotScript*, BotScriptDebugger::DebugPlace, int); // 0x2A8930, slot +0x08; from the base declaration + virtual void clear(); // 0x2A8C90, slot +0x0C; from the base declaration + virtual int getImplementation(); // 0x2A95D0, slot +0x10; from the base declaration + + void addDebugStatement(BotScriptDebugger::DebugLevel, BAPStatement*, BotScriptDebugger::DebugPlace, int); // 0x2A89B0; [INFERRED] ELF void + void clearDebugStatement(); // 0x2A8A30; [INFERRED] ELF void + void pushStatement(BAPStatement*); // 0x2A8AE0; [INFERRED] ELF void + int popStatement(BAPStatement*); // 0x2A8B30; [INFERRED] ELF int + void setDebugLevel(BotScriptDebugger::DebugLevel); // 0x2A8C70; [INFERRED] void: only stores (no callers) + int getDebugLevel(); // 0x2A8C80; [INFERRED] ELF int + void clearStack(); // 0x2A8CD0; [INFERRED] ELF void + void internalDebug(BotScriptDebugger::DebugLevel, BotScript*, int, std::map >&); // 0x2A8D00; [INFERRED] ELF void + void internalAddStatement(BotScriptDebugger::DebugLevel, BAPStatement*, int, std::map >&); // 0x2A8F00; [INFERRED] ELF void + +private: + typedef std::map > StatementMap; + /* +0x04 */ StatementMap m_placeZeroStatements; // DebugPlace 0 + /* +0x10 */ StatementMap m_placeOneStatements; // DebugPlace 1 + /* +0x1C */ std::list m_stack; // pushStatement prepends, popStatement pops the back + /* +0x20 */ BotScriptDebugger::DebugLevel m_debugLevel; // = 3 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BAPDEBUGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp deleted file mode 100644 index e8963a53a..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp +++ /dev/null @@ -1,826 +0,0 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BAPEntries operations. - -#include "BAPEntries.h" - -#include "../Main/AIDllFrontier.h" - -namespace dice { -namespace hfe { -namespace ai { - -// Action-plan primitives return their statement type for registry dispatch. - -// Empty body; see BAPEntry.h. -BAPEntry::~BAPEntry() -{ -} - -EntryTankMoveTo::EntryTankMoveTo() -{ -} - -EntryTankMoveTo::~EntryTankMoveTo() -{ -} - -int EntryTankMoveTo::getTargetId() -{ - return 7; -} - -bool EntryTankMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankMoveTo::execute"); -} - - -EntryTankMoveToObject::EntryTankMoveToObject() -{ -} - -EntryTankMoveToObject::~EntryTankMoveToObject() -{ -} - -int EntryTankMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryTankMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankMoveToObject::execute"); -} - - -EntryTankMoveToDirection::EntryTankMoveToDirection() -{ -} - -EntryTankMoveToDirection::~EntryTankMoveToDirection() -{ -} - -int EntryTankMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryTankMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankMoveToDirection::execute"); -} - - -EntryTankResetControls::EntryTankResetControls() -{ -} - -EntryTankResetControls::~EntryTankResetControls() -{ -} - -int EntryTankResetControls::getTargetId() -{ - return 14; -} - -bool EntryTankResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankResetControls::execute"); -} - - -EntryTankTurnTo::EntryTankTurnTo() -{ -} - -EntryTankTurnTo::~EntryTankTurnTo() -{ -} - -int EntryTankTurnTo::getTargetId() -{ - return 24; -} - -bool EntryTankTurnTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankTurnTo::execute"); -} - -void EntryTankTurnTo::getCentreOfFacingSide(const Vec2&, const Vec2&, const Vec2&, - const Vec2&, Vec2&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTankTurnTo::getCentreOfFacingSide"); -} - - -EntryCarMoveTo::EntryCarMoveTo() -{ -} - -EntryCarMoveTo::~EntryCarMoveTo() -{ -} - -int EntryCarMoveTo::getTargetId() -{ - return 7; -} - -bool EntryCarMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryCarMoveTo::execute"); -} - - -EntryCarMoveToDirection::EntryCarMoveToDirection() -{ -} - -EntryCarMoveToDirection::~EntryCarMoveToDirection() -{ -} - -int EntryCarMoveToDirection::getTargetId() -{ - return 8; -} - -// A retail stub - see the block above. , and all it does is succeed. -bool EntryCarMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - return true; -} - - -EntryCarMoveToObject::EntryCarMoveToObject() -{ -} - -EntryCarMoveToObject::~EntryCarMoveToObject() -{ -} - -int EntryCarMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryCarMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryCarMoveToObject::execute"); -} - - -EntryCarResetControls::EntryCarResetControls() -{ -} - -EntryCarResetControls::~EntryCarResetControls() -{ -} - -int EntryCarResetControls::getTargetId() -{ - return 14; -} - -bool EntryCarResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryCarResetControls::execute"); -} - - -EntryPlaneMoveTo::EntryPlaneMoveTo() -{ -} - -EntryPlaneMoveTo::~EntryPlaneMoveTo() -{ -} - -int EntryPlaneMoveTo::getTargetId() -{ - return 7; -} - -bool EntryPlaneMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneMoveTo::execute"); -} - - -EntryPlaneMoveToDirection::EntryPlaneMoveToDirection() -{ -} - -EntryPlaneMoveToDirection::~EntryPlaneMoveToDirection() -{ -} - -int EntryPlaneMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryPlaneMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneMoveToDirection::execute"); -} - - -EntryPlaneMoveToObject::EntryPlaneMoveToObject() -{ -} - -EntryPlaneMoveToObject::~EntryPlaneMoveToObject() -{ -} - -int EntryPlaneMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryPlaneMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneMoveToObject::execute"); -} - - -EntryPlaneAimAt::EntryPlaneAimAt() -{ -} - -EntryPlaneAimAt::~EntryPlaneAimAt() -{ -} - -int EntryPlaneAimAt::getTargetId() -{ - return 6; -} - -bool EntryPlaneAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneAimAt::execute"); -} - - -EntryPlaneResetControls::EntryPlaneResetControls() -{ -} - -EntryPlaneResetControls::~EntryPlaneResetControls() -{ -} - -int EntryPlaneResetControls::getTargetId() -{ - return 14; -} - -bool EntryPlaneResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryPlaneResetControls::execute"); -} - - -EntryBoatMoveTo::EntryBoatMoveTo() -{ -} - -EntryBoatMoveTo::~EntryBoatMoveTo() -{ -} - -int EntryBoatMoveTo::getTargetId() -{ - return 7; -} - -bool EntryBoatMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatMoveTo::execute"); -} - - -EntryBoatMoveToObject::EntryBoatMoveToObject() -{ -} - -EntryBoatMoveToObject::~EntryBoatMoveToObject() -{ -} - -int EntryBoatMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryBoatMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatMoveToObject::execute"); -} - - -EntryBoatMoveToDirection::EntryBoatMoveToDirection() -{ -} - -EntryBoatMoveToDirection::~EntryBoatMoveToDirection() -{ -} - -int EntryBoatMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryBoatMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatMoveToDirection::execute"); -} - - -EntryBoatResetControls::EntryBoatResetControls() -{ -} - -EntryBoatResetControls::~EntryBoatResetControls() -{ -} - -int EntryBoatResetControls::getTargetId() -{ - return 14; -} - -bool EntryBoatResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryBoatResetControls::execute"); -} - - -EntryInfanteryMoveTo::EntryInfanteryMoveTo() -{ -} - -EntryInfanteryMoveTo::~EntryInfanteryMoveTo() -{ -} - -int EntryInfanteryMoveTo::getTargetId() -{ - return 7; -} - -bool EntryInfanteryMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfanteryMoveTo::execute"); -} - - -EntryInfanteryMoveToObject::EntryInfanteryMoveToObject() -{ -} - -EntryInfanteryMoveToObject::~EntryInfanteryMoveToObject() -{ -} - -int EntryInfanteryMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryInfanteryMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfanteryMoveToObject::execute"); -} - - -EntryInfanteryMoveToDirection::EntryInfanteryMoveToDirection() -{ -} - -EntryInfanteryMoveToDirection::~EntryInfanteryMoveToDirection() -{ -} - -int EntryInfanteryMoveToDirection::getTargetId() -{ - return 8; -} - -// A retail stub - see the block above. , and all it does is succeed. -bool EntryInfanteryMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - return true; -} - - -EntryInfanteryResetControls::EntryInfanteryResetControls() -{ -} - -EntryInfanteryResetControls::~EntryInfanteryResetControls() -{ -} - -int EntryInfanteryResetControls::getTargetId() -{ - return 14; -} - -bool EntryInfanteryResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfanteryResetControls::execute"); -} - - -EntryTrigger::EntryTrigger() -{ -} - -EntryTrigger::~EntryTrigger() -{ -} - -int EntryTrigger::getTargetId() -{ - return 11; -} - -bool EntryTrigger::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTrigger::execute"); -} - - -EntryTriggerContinously::EntryTriggerContinously() -{ -} - -EntryTriggerContinously::~EntryTriggerContinously() -{ -} - -int EntryTriggerContinously::getTargetId() -{ - return 12; -} - -bool EntryTriggerContinously::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryTriggerContinously::execute"); -} - - -EntryKeyTurretAimAt::EntryKeyTurretAimAt() -{ -} - -EntryKeyTurretAimAt::~EntryKeyTurretAimAt() -{ -} - -int EntryKeyTurretAimAt::getTargetId() -{ - return 6; -} - -bool EntryKeyTurretAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryKeyTurretAimAt::execute"); -} - - -EntryMouseTurretAimAt::EntryMouseTurretAimAt() -{ -} - -EntryMouseTurretAimAt::~EntryMouseTurretAimAt() -{ -} - -int EntryMouseTurretAimAt::getTargetId() -{ - return 6; -} - -bool EntryMouseTurretAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMouseTurretAimAt::execute"); -} - - -EntryMouseTurretLookAt::EntryMouseTurretLookAt() -{ -} - -EntryMouseTurretLookAt::~EntryMouseTurretLookAt() -{ -} - -int EntryMouseTurretLookAt::getTargetId() -{ - return 23; -} - -bool EntryMouseTurretLookAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMouseTurretLookAt::execute"); -} - - -EntrySense::EntrySense() -{ -} - -EntrySense::~EntrySense() -{ -} - -int EntrySense::getTargetId() -{ - return 20; -} - -bool EntrySense::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntrySense::execute"); -} - - -EntrySoldierPose::EntrySoldierPose() -{ -} - -EntrySoldierPose::~EntrySoldierPose() -{ -} - -int EntrySoldierPose::getTargetId() -{ - return 26; -} - -bool EntrySoldierPose::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntrySoldierPose::execute"); -} - - -EntryMoveToMedium::EntryMoveToMedium() -{ -} - -EntryMoveToMedium::~EntryMoveToMedium() -{ -} - -int EntryMoveToMedium::getTargetId() -{ - return 7; -} - -bool EntryMoveToMedium::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToMedium::execute"); -} - - -EntryMoveToMediumBoat::EntryMoveToMediumBoat() -{ -} - -EntryMoveToMediumBoat::~EntryMoveToMediumBoat() -{ -} - -int EntryMoveToMediumBoat::getTargetId() -{ - return 7; -} - -bool EntryMoveToMediumBoat::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToMediumBoat::execute"); -} - - -EntryMoveToMediumSoldier::EntryMoveToMediumSoldier() -{ -} - -EntryMoveToMediumSoldier::~EntryMoveToMediumSoldier() -{ -} - -int EntryMoveToMediumSoldier::getTargetId() -{ - return 7; -} - -bool EntryMoveToMediumSoldier::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToMediumSoldier::execute"); -} - - -EntryMoveToObjectMedium::EntryMoveToObjectMedium() -{ -} - -EntryMoveToObjectMedium::~EntryMoveToObjectMedium() -{ -} - -int EntryMoveToObjectMedium::getTargetId() -{ - return 9; -} - -bool EntryMoveToObjectMedium::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToObjectMedium::execute"); -} - - -EntryMoveToObjectMediumBoat::EntryMoveToObjectMediumBoat() -{ -} - -EntryMoveToObjectMediumBoat::~EntryMoveToObjectMediumBoat() -{ -} - -int EntryMoveToObjectMediumBoat::getTargetId() -{ - return 9; -} - -bool EntryMoveToObjectMediumBoat::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToObjectMediumBoat::execute"); -} - - -EntryMoveToObjectMediumSoldier::EntryMoveToObjectMediumSoldier() -{ -} - -EntryMoveToObjectMediumSoldier::~EntryMoveToObjectMediumSoldier() -{ -} - -int EntryMoveToObjectMediumSoldier::getTargetId() -{ - return 9; -} - -bool EntryMoveToObjectMediumSoldier::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryMoveToObjectMediumSoldier::execute"); -} - - -EntryInfoWrapper::EntryInfoWrapper() -{ -} - -EntryInfoWrapper::~EntryInfoWrapper() -{ -} - -int EntryInfoWrapper::getTargetId() -{ - return 15; -} - -bool EntryInfoWrapper::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryInfoWrapper::execute"); -} - - -EntryHeliMoveTo::EntryHeliMoveTo() -{ -} - -EntryHeliMoveTo::~EntryHeliMoveTo() -{ -} - -int EntryHeliMoveTo::getTargetId() -{ - return 7; -} - -bool EntryHeliMoveTo::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveTo::execute"); -} - - -EntryHeliMoveToDirection::EntryHeliMoveToDirection() -{ -} - -EntryHeliMoveToDirection::~EntryHeliMoveToDirection() -{ -} - -int EntryHeliMoveToDirection::getTargetId() -{ - return 8; -} - -bool EntryHeliMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveToDirection::execute"); -} - - -EntryHeliMoveToObject::EntryHeliMoveToObject() -{ -} - -EntryHeliMoveToObject::~EntryHeliMoveToObject() -{ -} - -int EntryHeliMoveToObject::getTargetId() -{ - return 9; -} - -bool EntryHeliMoveToObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveToObject::execute"); -} - - -EntryHeliAimAt::EntryHeliAimAt() -{ -} - -EntryHeliAimAt::~EntryHeliAimAt() -{ -} - -int EntryHeliAimAt::getTargetId() -{ - return 6; -} - -bool EntryHeliAimAt::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliAimAt::execute"); -} - - -EntryHeliResetControls::EntryHeliResetControls() -{ -} - -EntryHeliResetControls::~EntryHeliResetControls() -{ -} - -int EntryHeliResetControls::getTargetId() -{ - return 14; -} - -bool EntryHeliResetControls::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliResetControls::execute"); -} - - -EntryHeliMoveAwayFromObject::EntryHeliMoveAwayFromObject() -{ -} - -EntryHeliMoveAwayFromObject::~EntryHeliMoveAwayFromObject() -{ -} - -int EntryHeliMoveAwayFromObject::getTargetId() -{ - return 10; -} - -bool EntryHeliMoveAwayFromObject::execute(BotScript *, Bot *, bool&, bool&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::EntryHeliMoveAwayFromObject::execute"); -} - - -} // namespace ai -} // namespace hfe -} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h index d3d7ce0e2..acc4b1023 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.h @@ -1,487 +1,53 @@ -// Vehicle-specific action-plan primitives registered by statement type. +// The 44 vehicle-specific action-plan entries (one TU each in the image: Entry*.cpp). // Keep registry spellings such as Infantery and TriggerContinously unchanged. -// [CHOSEN, not recovered] These entries are grouped into one translation unit. -// [FRONTIER] Remaining execute methods stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execution, then split entries into their own files. +// S0 split the former single TU into the attested files; this header only gathers them. #ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BAPENTRIES_H #define AI_AIDLL_AI_AIPLANINTERPRETER_BAPENTRIES_H -#include "BAPEntry.h" - -namespace dice { -namespace hfe { -namespace ai { - - -// EntryTankMoveTo - statement type 7. -class EntryTankMoveTo : public BAPEntry -{ -public: - EntryTankMoveTo(); - virtual ~EntryTankMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankMoveToObject - statement type 9. -class EntryTankMoveToObject : public BAPEntry -{ -public: - EntryTankMoveToObject(); - virtual ~EntryTankMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankMoveToDirection - statement type 8. -class EntryTankMoveToDirection : public BAPEntry -{ -public: - EntryTankMoveToDirection(); - virtual ~EntryTankMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankResetControls - statement type 14. -class EntryTankResetControls : public BAPEntry -{ -public: - EntryTankResetControls(); - virtual ~EntryTankResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTankTurnTo - statement type 24. -class EntryTankTurnTo : public BAPEntry -{ -public: - EntryTankTurnTo(); - virtual ~EntryTankTurnTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); - // Everything else on these - // forty-two classes is the four slots below. - void getCentreOfFacingSide(const Vec2&, const Vec2&, const Vec2&, const Vec2&, Vec2&); -}; - -// EntryCarMoveTo - statement type 7. -class EntryCarMoveTo : public BAPEntry -{ -public: - EntryCarMoveTo(); - virtual ~EntryCarMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryCarMoveToDirection - statement type 8. -class EntryCarMoveToDirection : public BAPEntry -{ -public: - EntryCarMoveToDirection(); - virtual ~EntryCarMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryCarMoveToObject - statement type 9. -class EntryCarMoveToObject : public BAPEntry -{ -public: - EntryCarMoveToObject(); - virtual ~EntryCarMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryCarResetControls - statement type 14. -class EntryCarResetControls : public BAPEntry -{ -public: - EntryCarResetControls(); - virtual ~EntryCarResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneMoveTo - statement type 7. -class EntryPlaneMoveTo : public BAPEntry -{ -public: - EntryPlaneMoveTo(); - virtual ~EntryPlaneMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneMoveToDirection - statement type 8. -class EntryPlaneMoveToDirection : public BAPEntry -{ -public: - EntryPlaneMoveToDirection(); - virtual ~EntryPlaneMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneMoveToObject - statement type 9. -class EntryPlaneMoveToObject : public BAPEntry -{ -public: - EntryPlaneMoveToObject(); - virtual ~EntryPlaneMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneAimAt - statement type 6. -class EntryPlaneAimAt : public BAPEntry -{ -public: - EntryPlaneAimAt(); - virtual ~EntryPlaneAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryPlaneResetControls - statement type 14. -class EntryPlaneResetControls : public BAPEntry -{ -public: - EntryPlaneResetControls(); - virtual ~EntryPlaneResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatMoveTo - statement type 7. -class EntryBoatMoveTo : public BAPEntry -{ -public: - EntryBoatMoveTo(); - virtual ~EntryBoatMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatMoveToObject - statement type 9. -class EntryBoatMoveToObject : public BAPEntry -{ -public: - EntryBoatMoveToObject(); - virtual ~EntryBoatMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatMoveToDirection - statement type 8. -class EntryBoatMoveToDirection : public BAPEntry -{ -public: - EntryBoatMoveToDirection(); - virtual ~EntryBoatMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryBoatResetControls - statement type 14. -class EntryBoatResetControls : public BAPEntry -{ -public: - EntryBoatResetControls(); - virtual ~EntryBoatResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryMoveTo - statement type 7. -class EntryInfanteryMoveTo : public BAPEntry -{ -public: - EntryInfanteryMoveTo(); - virtual ~EntryInfanteryMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryMoveToObject - statement type 9. -class EntryInfanteryMoveToObject : public BAPEntry -{ -public: - EntryInfanteryMoveToObject(); - virtual ~EntryInfanteryMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryMoveToDirection - statement type 8. -class EntryInfanteryMoveToDirection : public BAPEntry -{ -public: - EntryInfanteryMoveToDirection(); - virtual ~EntryInfanteryMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfanteryResetControls - statement type 14. -class EntryInfanteryResetControls : public BAPEntry -{ -public: - EntryInfanteryResetControls(); - virtual ~EntryInfanteryResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTrigger - statement type 11. -class EntryTrigger : public BAPEntry -{ -public: - EntryTrigger(); - virtual ~EntryTrigger(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryTriggerContinously - statement type 12. -class EntryTriggerContinously : public BAPEntry -{ -public: - EntryTriggerContinously(); - virtual ~EntryTriggerContinously(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryKeyTurretAimAt - statement type 6. -class EntryKeyTurretAimAt : public BAPEntry -{ -public: - EntryKeyTurretAimAt(); - virtual ~EntryKeyTurretAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMouseTurretAimAt - statement type 6. -class EntryMouseTurretAimAt : public BAPEntry -{ -public: - EntryMouseTurretAimAt(); - virtual ~EntryMouseTurretAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMouseTurretLookAt - statement type 23. -class EntryMouseTurretLookAt : public BAPEntry -{ -public: - EntryMouseTurretLookAt(); - virtual ~EntryMouseTurretLookAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntrySense - statement type 20. -class EntrySense : public BAPEntry -{ -public: - EntrySense(); - virtual ~EntrySense(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntrySoldierPose - statement type 26. -class EntrySoldierPose : public BAPEntry -{ -public: - EntrySoldierPose(); - virtual ~EntrySoldierPose(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToMedium - statement type 7. -class EntryMoveToMedium : public BAPEntry -{ -public: - EntryMoveToMedium(); - virtual ~EntryMoveToMedium(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToMediumBoat - statement type 7. -class EntryMoveToMediumBoat : public BAPEntry -{ -public: - EntryMoveToMediumBoat(); - virtual ~EntryMoveToMediumBoat(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToMediumSoldier - statement type 7. -class EntryMoveToMediumSoldier : public BAPEntry -{ -public: - EntryMoveToMediumSoldier(); - virtual ~EntryMoveToMediumSoldier(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToObjectMedium - statement type 9. -class EntryMoveToObjectMedium : public BAPEntry -{ -public: - EntryMoveToObjectMedium(); - virtual ~EntryMoveToObjectMedium(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToObjectMediumBoat - statement type 9. -class EntryMoveToObjectMediumBoat : public BAPEntry -{ -public: - EntryMoveToObjectMediumBoat(); - virtual ~EntryMoveToObjectMediumBoat(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryMoveToObjectMediumSoldier - statement type 9. -class EntryMoveToObjectMediumSoldier : public BAPEntry -{ -public: - EntryMoveToObjectMediumSoldier(); - virtual ~EntryMoveToObjectMediumSoldier(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryInfoWrapper - statement type 15. -class EntryInfoWrapper : public BAPEntry -{ -public: - EntryInfoWrapper(); - virtual ~EntryInfoWrapper(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveTo - statement type 7. -class EntryHeliMoveTo : public BAPEntry -{ -public: - EntryHeliMoveTo(); - virtual ~EntryHeliMoveTo(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveToDirection - statement type 8. -class EntryHeliMoveToDirection : public BAPEntry -{ -public: - EntryHeliMoveToDirection(); - virtual ~EntryHeliMoveToDirection(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveToObject - statement type 9. -class EntryHeliMoveToObject : public BAPEntry -{ -public: - EntryHeliMoveToObject(); - virtual ~EntryHeliMoveToObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliAimAt - statement type 6. -class EntryHeliAimAt : public BAPEntry -{ -public: - EntryHeliAimAt(); - virtual ~EntryHeliAimAt(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliResetControls - statement type 14. -class EntryHeliResetControls : public BAPEntry -{ -public: - EntryHeliResetControls(); - virtual ~EntryHeliResetControls(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - -// EntryHeliMoveAwayFromObject - statement type 10. -class EntryHeliMoveAwayFromObject : public BAPEntry -{ -public: - EntryHeliMoveAwayFromObject(); - virtual ~EntryHeliMoveAwayFromObject(); - - virtual bool execute(BotScript *, Bot *, bool&, bool&); - virtual int getTargetId(); -}; - - -} // namespace ai -} // namespace hfe -} // namespace dice +#include "EntryBoatMoveTo.h" +#include "EntryBoatMoveToDirection.h" +#include "EntryBoatMoveToObject.h" +#include "EntryBoatResetControls.h" +#include "EntryCarMoveTo.h" +#include "EntryCarMoveToDirection.h" +#include "EntryCarMoveToObject.h" +#include "EntryCarResetControls.h" +#include "EntryHeliAimAt.h" +#include "EntryHeliMoveAwayFromObject.h" +#include "EntryHeliMoveTo.h" +#include "EntryHeliMoveToDirection.h" +#include "EntryHeliMoveToObject.h" +#include "EntryHeliResetControls.h" +#include "EntryInfanteryMoveTo.h" +#include "EntryInfanteryMoveToDirection.h" +#include "EntryInfanteryMoveToObject.h" +#include "EntryInfanteryResetControls.h" +#include "EntryInfoWrapper.h" +#include "EntryKeyTurretAimAt.h" +#include "EntryMouseTurretAimAt.h" +#include "EntryMouseTurretLookAt.h" +#include "EntryMoveToMedium.h" +#include "EntryMoveToMediumBoat.h" +#include "EntryMoveToMediumSoldier.h" +#include "EntryMoveToObjectMedium.h" +#include "EntryMoveToObjectMediumBoat.h" +#include "EntryMoveToObjectMediumSoldier.h" +#include "EntryPlaneAimAt.h" +#include "EntryPlaneMoveTo.h" +#include "EntryPlaneMoveToDirection.h" +#include "EntryPlaneMoveToObject.h" +#include "EntryPlaneResetControls.h" +#include "EntryPlaneRoll.h" +#include "EntrySense.h" +#include "EntrySoldierPose.h" +#include "EntryTankMoveTo.h" +#include "EntryTankMoveToDirection.h" +#include "EntryTankMoveToObject.h" +#include "EntryTankResetControls.h" +#include "EntryTankTurnTo.h" +#include "EntryTrigger.h" +#include "EntryTriggerContinously.h" +#include "EntryTurnToMedium.h" #endif // AI_AIDLL_AI_AIPLANINTERPRETER_BAPENTRIES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h index f7b2d5579..b9de11552 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPEntry.h @@ -16,7 +16,7 @@ class BAPEntry { public: BAPEntry() {} - virtual ~BAPEntry(); + virtual ~BAPEntry() {} // weak in the image (emitted in EntryBoatMoveTo.cpp) // execute reports success as bool; getTargetId returns the entry's integer target id. virtual bool execute(BotScript *, Bot *, bool&, bool&) = 0; diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp new file mode 100644 index 000000000..96503fa70 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp @@ -0,0 +1,165 @@ +// BAPInterpreter: recovered by package A-core from libaidll.so (AI/AIDLL/AI/AIPlanInterpreter/ +// BAPInterpreter.cpp in the image's strings). Every body carries its ELF address. + +// static init: ELF 0x2A9F80 (__tcf_0 0x2A9FE0, _GLOBAL__I 0x2AA010): 's Init object only. +#include + +#include "BAPInterpreter.h" + +#include "BAPEntry.h" +#include "BotScript.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../../../../Core/Debug.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A95E0 (C2; C1 0x2A96A0 is the same body). The rows are filled before the mask array is +// allocated, and neither allocation is checked. +BAPInterpreter::BAPInterpreter(int numStatementTypes) + : m_numStatementTypes(numStatementTypes) +{ + m_entries = new BAPEntry**[numStatementTypes]; + for (int type = 0; type < m_numStatementTypes; ++type) + { + m_entries[type] = new BAPEntry*[NumLodLevels]; + for (int lod = 0; lod < NumLodLevels; ++lod) + m_entries[type][lod] = 0; + } + + m_active = new unsigned long long[NumLodLevels]; + for (int lod = 0; lod < NumLodLevels; ++lod) + m_active[lod] = 0; +} + +// ELF 0x2A9760 (D2; D1 0x2A9830, D0 0x2A9900). The entries are not owned: the slots are cleared, +// not deleted (AIConsole builds the entries and keeps them). +BAPInterpreter::~BAPInterpreter() +{ + for (int type = 0; type < m_numStatementTypes; ++type) + { + for (int lod = 0; lod < NumLodLevels; ++lod) + { + if (m_entries[type][lod]) + m_entries[type][lod] = 0; + } + delete[] m_entries[type]; + m_entries[type] = 0; + } + delete[] m_entries; + m_entries = 0; + delete[] m_active; + m_active = 0; +} + +// ELF 0x2A99D0 (209 instructions). +// 1. A bot that has just spawned (Bot +0x118) interprets nothing this tick: ok, not finished. +// 2. Otherwise the statement type (BotScript* treated as BAPStatement, getId +0x10) and the bot's +// LOD (+0xC) select the active bit; with it set, the registered entry runs, or without an entry +// the statement's own execute (slot 0). The callee's result is returned. +// 3. A type that is not active at that LOD is an Error-level diagnostic (which aborts), then +// ok = false, finished = true, return 0. +bool BAPInterpreter::execute(BotScript* script, Bot* bot, bool& ok, bool& finished) +{ + if (bot->isJustSpawned()) + { + finished = false; + ok = true; + return true; + } + + BAPStatement* statement = static_cast(script); + const BAPStatementType type = statement->getId(); + const BotLodLevel lod = bot->getLodLevel(); + + if ((m_active[lod] >> type) & 1) + { + BAPEntry* entry = m_entries[type][lod]; + if (entry == 0) + return script->execute(bot, ok, finished); + return entry->execute(script, bot, ok, finished); + } + + // Retail: Debug(6, "AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp", 154, "") << getName() + // << " " << getBotId() << " lod level " << lod << " cannot interpret \n" << " (" << type << ") " + // << type << "." with operator<<(ostream&, BotLodLevel) 0x3C78B0 and (ostream&, BAPStatementType) + // 0x3C7D90 (Main/AIStreamOperators.cpp, not in the tree yet; requested from ai-main). Until those + // exist the two enums print as numbers. [CHOSEN, not recovered] [RETIRE-WHEN: ai-stream-operators] + Debug(DebugTypeError, __FILE__, __LINE__, "") + << bot->getName() << " " << static_cast(bot->getBotId()) << " lod level " + << static_cast(lod) << " cannot interpret \n" << " (" << static_cast(type) << ") " + << static_cast(type) << "."; + + finished = true; + ok = false; + return false; +} + +// ELF 0x2A9D10. +bool BAPInterpreter::addEntry(BAPEntry* entry) +{ + return addEntry(static_cast(0), entry); +} + +// ELF 0x2A9D50. The entry's target id (+0xC) is its statement type. It is registered at `lod` and +// at every coarser LOD up to the first one that already has an entry, and activated there. +bool BAPInterpreter::addEntry(BotLodLevel lod, BAPEntry* entry) +{ + const int type = entry->getTargetId(); + if (m_numStatementTypes <= type || m_entries[type][lod] != 0) + return false; + + const unsigned long long bit = 1ULL << type; + for (int level = lod; level < NumLodLevels; ++level) + { + if (m_entries[type][level] != 0) + break; + m_entries[type][level] = entry; + m_active[level] |= bit; + } + return true; +} + +// ELF 0x2A9E10. Clears every slot from `lod` on that holds this entry (no early exit). +bool BAPInterpreter::removeEntry(BotLodLevel lod, BAPEntry* entry) +{ + const int type = entry->getTargetId(); + if (m_numStatementTypes <= type) + return false; + + const unsigned long long bit = 1ULL << type; + for (int level = lod; level < NumLodLevels; ++level) + { + if (m_entries[type][level] == entry) + { + m_entries[type][level] = 0; + m_active[level] &= ~bit; + } + } + return true; +} + +// ELF 0x2A9ED0. Lets a type run its own execute (no entry) at `lod` and the coarser LODs up to the +// first one that has an entry. Refused when an entry is registered at `lod` itself. +bool BAPInterpreter::activateEntry(BAPStatementType type, BotLodLevel lod) +{ + if (m_numStatementTypes <= type || m_entries[type][lod] != 0) + return false; + + const unsigned long long bit = 1ULL << type; + for (int level = lod; level < NumLodLevels; ++level) + { + if (m_entries[type][level] != 0) + break; + m_active[level] |= bit; + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.h new file mode 100644 index 000000000..982174b50 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.h @@ -0,0 +1,52 @@ +// The plan interpreter: per statement type and LOD level, either a registered BAPEntry (the +// vehicle-specific control code) or the statement's own execute. Recovered by package A-core +// (docs/macos-ai-behaviour-plan.md) from libaidll.so; the virtual order is checked by +// tools/macos/ai_behaviour_vtables.py. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BAPINTERPRETER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BAPINTERPRETER_H + +#include "../AIBotActionPlan/BAPTypes.h" +#include "PlanInterpreter.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPEntry; +class Bot; +class BotScript; + +// sizeof 0x10 (`operator new(0x10)` in AISettings::preparePlanInterpreterPool). Layout from the +// constructor 0x2A95E0: +4 = the argument, +0xC = new BAPEntry**[n] each new BAPEntry*[3] zeroed, +// +8 = new u64[3] zeroed. Three LOD rows (BotLodFull 0, Medium 1, Light 2): every loop stops at 2. +// ELF: vtable 0x4BCA48 (3 words), operator new 0x10, package A-core. +class BAPInterpreter : public PlanInterpreter +{ +public: + explicit BAPInterpreter(int numStatementTypes); // 0x2A96A0 + virtual ~BAPInterpreter(); // 0x2A9830 + + virtual bool execute(BotScript*, Bot*, bool& ok, bool& finished); // 0x2A99D0, slot +0x08; from the base declaration + + // The four return `al`: 0 when the type is out of range or (add/activate) the slot at the given + // LOD is already taken, 1 otherwise (also when the LOD is above 2 and nothing is done). + bool addEntry(BAPEntry*); // 0x2A9D10: addEntry(BotLodFull, entry) + bool addEntry(BotLodLevel, BAPEntry*); // 0x2A9D50 + bool removeEntry(BotLodLevel, BAPEntry*); // 0x2A9E10 + bool activateEntry(BAPStatementType, BotLodLevel); // 0x2A9ED0 + +private: + enum { NumLodLevels = 3 }; // [CHOSEN] name for the literal `cmpl $0x2` loop bound + + /* +0x04 */ int m_numStatementTypes; // the constructor argument (45 from AISettings) [INFERRED] name + /* +0x08 */ unsigned long long* m_active; // [lod]: bit `type` set = the type may be interpreted at that LOD + /* +0x0C */ BAPEntry*** m_entries; // [type][lod]: entry or 0 (not owned) +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BAPINTERPRETER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp new file mode 100644 index 000000000..47cc2dd4a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp @@ -0,0 +1,205 @@ +// Boat movement and input reset, recovered from libaidll.so. + +// static init: ELF 0x2AAE90 (__tcf_0 0x2AAEF0, _GLOBAL__I 0x2AAF20): 's Init object only. +#include + +#include "BoatControl.h" + +#include "CarControl.h" +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Inline sign and clamp expansions in ELF 0x2AA090; NaN has sign zero and passes the clamp. +float sign(float value) +{ + return value > 0.0f ? 1.0f : (0.0f > value ? -1.0f : 0.0f); +} + +float clamp(float value, float minimum, float maximum) +{ + return minimum > value ? minimum : (value > maximum ? maximum : value); +} + +float mappedInput(io::PlayerInput* input, io::PlayerInputMap control) +{ + const int index = static_cast(control); + if (index <= 63 && ((input->mappingFlags >> (static_cast(index) & 63)) & 1ULL)) + return input->inputs[index]; + return 0.0f; +} + +} // namespace + +// ELF 0x2AA090 +bool BoatControl::speedControl(Bot* bot, Information* equipment, const Vec2& direction, + float speedFraction, float angle, BAPAMoveTo* move, + float speedLimit, io::PlayerInput* input, float selectedFraction) +{ + IPIMobile* const mobile = equipment->getMobile(); + const float speedMagnitude = mobile->getSpeedMagnitude(); + mobile->getSpeed(); + const Vec3& rotation = mobile->getRotationalSpeed(); + const Mat4& transform = equipment->getTransformation(); + const float yawSpeed = transform.m[4] * rotation.x + transform.m[5] * rotation.y + + transform.m[6] * rotation.z; + Vec2 position = {}; + Vec2 facing = {}; + Vec2 normal = {}; + vec3ToVec2XZ(equipment->getPosition(), position); + vec3ToVec2XZ(equipment->getFaceing(), facing); + getNormal(facing, normal); + vehiclecontrol::normalizeVec2(normal); + equipment->getAIObject()->releaseObjectFromSpawner(); + + if (speedFraction == 0.0f + || (static_cast(bot)->getMoveToStatus() == 0 && std::fabs(angle) > 0.5235988f)) + { + float turn = normal.x * direction.x + normal.y * direction.y; + const float alignment = facing.x * direction.x + facing.y * direction.y; + if (alignment <= 0.0f) + turn = sign(turn); + const Mat4& currentTransform = equipment->getTransformation(); + const Vec3& velocity = mobile->getSpeed(); + const float forwardSpeed = velocity.y * currentTransform.m[9] + velocity.x * currentTransform.m[8] + + velocity.z * currentTransform.m[10]; + input->setInput(static_cast(0), 0.0f); + const float throttle = mappedInput(input, static_cast(3)); + if (alignment > 0.996f) + { + float brake = 0.0f; + if (std::fabs(forwardSpeed) > 1.0f) + brake = -sign(forwardSpeed); + else if (std::fabs(forwardSpeed) > 0.03f) + brake = -sign(forwardSpeed) * log10f(std::fabs(forwardSpeed) * 9.0f + 1.0f); + input->setInput(static_cast(3), brake); + return true; + } + if (std::fabs(forwardSpeed) > 3.0f) + input->setInput(static_cast(3), -sign(forwardSpeed)); + else if (std::fabs(throttle) != 1.0f) + input->setInput(static_cast(3), sign(forwardSpeed)); + input->setInput(static_cast(0), sign(turn) * sign(forwardSpeed)); + return true; + } + + if (speedFraction != 0.0f && speedFraction != selectedFraction && speedMagnitude > 1.0f) + angle = -angle; + const float maximumSpeed = mobile->getMaxSpeed(); + const float targetSpeed = (maximumSpeed > speedLimit ? speedLimit : maximumSpeed) * speedFraction; + float throttle = mappedInput(input, equipment->getControlInfo()->getDriveThrottleControl()); + simpleReg(targetSpeed - speedMagnitude, move->m_previousSpeed - speedMagnitude, 1.0f, throttle); + const float turn = clamp(sinf(clamp(angle, -1.5707964f, 1.5707964f)) + - clamp(yawSpeed, -1.0f, 1.0f) * 0.1f, -1.0f, 1.0f); + move->m_previousHeading = facing; + move->m_previousSpeed = speedMagnitude; + // The template selects the input to read above; the shipped writes still use inputs 0 and 3. + input->setInput(static_cast(0), sign(turn) * log10f(std::fabs(turn) * 9.0f + 1.0f)); + input->setInput(static_cast(3), throttle); + return true; +} + +// ELF 0x2AA910 +bool BoatControl::towardsDirection(Bot* bot, Information* equipment, Vec2 direction, float distance, + BAPAMoveTo* move, io::PlayerInput* input, float speedLimit) +{ + float speedFraction; + float angle; + float selectedFraction; + float unused; + if (!CarControl::actionStatusDecision(bot, equipment, direction, distance, move, + speedFraction, angle, selectedFraction, unused)) + return false; + return speedControl(bot, equipment, direction, speedFraction, angle, move, speedLimit, input, selectedFraction); +} + +// ELF 0x2AA9D0 (listing; Ghidra cross-check). `done` is set first. Moving: the forward speed is +// the mobile's speed dot the transformation's third row (+0x20..+0x28); inputs 0, 2 and 1 are +// released; up to 1.0 the throttle (input 3) is released, above it the throttle is +// -sign(speed) * log10(|speed| * 9 + 1) (-sign alone at or below 0.03, unreachable after the 1.0 +// test, kept as compiled) and `done` is cleared. The information lookup is not null-tested. +// Look releases 4 and 5; trigger 8, 31, 14..30, 38, 37, 10 and 32. Returns 1. +int BoatControl::resetControls(Bot* bot, bool move, bool look, bool trigger, bool& done) +{ + io::PlayerInput* const input = bot->getInput(); + done = true; + if (move) + { + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + const Mat4& transformation = equipment->getTransformation(); // +0x3C + const Vec3& speed = mobile->getSpeed(); // +0x1C + const float forwardSpeed = speed.y * transformation.m[9] + speed.x * transformation.m[8] + + speed.z * transformation.m[10]; + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + if (std::fabs(forwardSpeed) > 1.0f) + { + const float sign = (forwardSpeed > 0.0f) ? 1.0f : ((0.0f > forwardSpeed) ? -1.0f : 0.0f); + float throttle; + if (std::fabs(forwardSpeed) > 0.03f) + throttle = log10f(std::fabs(forwardSpeed) * 9.0f + 1.0f) * -sign; + else + throttle = -sign; + input->setInput(static_cast(3), throttle); + done = false; + } + else + { + input->setInput(static_cast(3), 0.0f); + } + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + input->setInput(static_cast(14), 0.0f); + input->setInput(static_cast(15), 0.0f); + input->setInput(static_cast(16), 0.0f); + input->setInput(static_cast(17), 0.0f); + input->setInput(static_cast(18), 0.0f); + input->setInput(static_cast(19), 0.0f); + input->setInput(static_cast(20), 0.0f); + input->setInput(static_cast(21), 0.0f); + input->setInput(static_cast(22), 0.0f); + input->setInput(static_cast(23), 0.0f); + input->setInput(static_cast(24), 0.0f); + input->setInput(static_cast(25), 0.0f); + input->setInput(static_cast(26), 0.0f); + input->setInput(static_cast(27), 0.0f); + input->setInput(static_cast(28), 0.0f); + input->setInput(static_cast(29), 0.0f); + input->setInput(static_cast(30), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + } + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.h new file mode 100644 index 000000000..6408395c1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.h @@ -0,0 +1,30 @@ +// Boat steering, speed regulation and input reset. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BOATCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BOATCONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace io { class PlayerInput; } +namespace ai { + +class BAPAMoveTo; +class Bot; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace BoatControl +{ + bool speedControl(Bot*, Information*, const Vec2&, float, float, BAPAMoveTo*, float, io::PlayerInput*, float); // 0x2AA090 + bool towardsDirection(Bot*, Information*, Vec2, float, BAPAMoveTo*, io::PlayerInput*, float); // 0x2AA910 + int resetControls(Bot*, bool, bool, bool, bool&); // 0x2AA9D0; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BOATCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScript.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScript.h new file mode 100644 index 000000000..78cc54cc9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScript.h @@ -0,0 +1,47 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPT_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// Root of every plan node. Vtable 0x4B77D8: execute (pure), D1, D0. Inline in the image. +// ELF: vtable 0x4B77D8 (3 words), package S0-skeleton (layout: A-core). +// +// execute(bot, ok, finished) protocol, as every recovered caller and node uses it: +// ok the node ran (BAPInterpreter::execute 0x2A99D0 sets it true and finished false for a +// bot that has just spawned, and false/true when no entry may interpret the statement); +// finished the node is done; a parent combiner advances or resets on it (BAPCombinerSerial +// 0x1E6840, BAPFlowCIf 0x1E3850 drop their active child when it is set). +// The return value is 1 in every recovered node; BAPInterpreter forwards its callee's. +class BotScript +{ +public: + BotScript() : m_owner(0) {} // inline in the image: every BAPStatement constructor stores +4 = 0 + + virtual bool execute(Bot*, bool& ok, bool& finished) = 0; // no body, slot +0x00; from the base declaration + virtual ~BotScript() {} // weak in the image (inline) slots +0x04/+0x08 + + // +0x04: who owns the node. Written through BotScript* by BotBehaviour::generatePlan 0x225C30 + // (the plan root: the behaviour, and the previous plan: the behaviour), by BotMain, and through + // BAPStatement by the combiners (child +4 = parent combiner, 0x1E64D6) and BAPFlowCIf (branches + // +4 = the If, 0x1E35CD). Mixed pointee types, so untyped. [INFERRED] name; public because the + // image writes it inline from several classes. [CHOSEN] visibility. + /* +0x04 */ void* m_owner; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp new file mode 100644 index 000000000..cbb255eca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp @@ -0,0 +1,22 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#include "BotScriptDebugger.h" + + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2A95C0: `xor %eax,%eax` (no implementation; BAPDebugger overrides it). +int BotScriptDebugger::getImplementation() +{ + return 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.h new file mode 100644 index 000000000..ce1625f3f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.h @@ -0,0 +1,36 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPTDEBUGGER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPTDEBUGGER_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class BotScript; + +// ELF: vtable 0x4BC9E8 (5 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class BotScriptDebugger +{ +public: + enum DebugLevel : int; // [UNRESOLVED] enumerators + enum DebugPlace : int; // [UNRESOLVED] enumerators + virtual ~BotScriptDebugger() {} // weak in the image (inline) + + virtual void debug(BotScriptDebugger::DebugLevel, BotScript*, BotScriptDebugger::DebugPlace, int) = 0; // no body, slot +0x08; [INFERRED] from BAPDebugger: ELF void + virtual void clear() = 0; // no body, slot +0x0C; [INFERRED] from BAPDebugger: ELF void + virtual int getImplementation(); // 0x2A95C0, slot +0x10; [INFERRED] ELF int +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_BOTSCRIPTDEBUGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp new file mode 100644 index 000000000..7c4845302 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp @@ -0,0 +1,835 @@ +// Car steering for the plan interpreter (libaidll.so CarControl TU). Every body is recovered. +// static init: the guard object only (ELF 0x2AF060, __tcf_0 0x2AF0C0, _GLOBAL__I 0x2AF0F0). + +#include "CarControl.h" + +#include "CommonControls.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +using namespace vehiclecontrol; + +// The TU's anonymous tweak_* values (.data 0x4BCB04..0x4BCB38: terrainSampleInterval 1, +// terrainLookAhead 20, maxSpeed 20, minSpeed 2, stopAndTurn_maxSpeed 7, +// stopAndTurn_angularDeviationThreshold 30, speedScale 2, speedCompensationFallOff 30, +// speedCompensationScale 1, maxSpeedCompensation 10, rotationalSpeedScale 1, +// rotationalSpeedCompensationFallOff 30, rotationalSpeedCompensationScale 1, +// maxRotationalSpeedCompensation 10) have no reader in the image and are not defined here. + +// ELF 0x2AAF40 (listing; Ghidra cross-check). Turns and throttles a car from the outputs of +// actionStatusDecision: `mode` (0 = turn on the spot towards `angle`, -1 = the same reversed by pi, +// else drive with `mode` as the speed sign), `angle` (the signed angle to the goal, negated while +// driving with mode != reference and faster than 1 m/s), `reference` and `limit` (the largest +// target speed). Physics is enabled for both sides when a speed is asked for. Driving: turn input +// clamp(3 * angle, -1, 1); target speed = speed * mode, reduced by up to 80 % for a sideways or +// forward slope (the larger |rotational speed| x/z above 0.15), capped at `limit`; throttle = +// clamp(min(1, (target - |v| * reference) / 3) + target / 15, -1, 1), and below 1.5 m/s a non-zero +// throttle becomes its sign (1 or -1, as 0 > throttle). Turning on the spot: the turn input (set only +// while mapped, through the inlined setInput) is min(1, |3 * (|angle| [- pi])|) against the angle's +// sign; the throttle input gets `mode`. Returns 1. +int CarControl::controlTowardsDirection(Information* info, IPIControlInfo* controlInfo, IPIMobile* mobile, + IPIPhysical*, io::PlayerInput* input, float speed, float mode, float angle, + float reference, float limit) +{ + const Mat4& transformation = info->getTransformation(); + Vec2 forward; + forward.x = forward.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[8]), forward); + Vec2 right; // read, never used + right.x = right.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[0]), right); + Vec2 position; // read, never used + position.x = position.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[12]), position); + mobile->getMaxSpeed(); // 0x2AAFB8, result discarded + Vec2 velocity; + velocity.x = velocity.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), velocity); + const float velocityLength = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); + Vec2 heading; // computed, never used + if (velocityLength == 0.0f) + { + heading = forward; + } + else + { + const float inverse = 1.0f / velocityLength; + heading.x = velocity.x * inverse; + heading.y = inverse * velocity.y; + } + (void)heading; + if (mode != 0.0f && reference != mode && velocityLength > 1.0f) + angle = -angle; + if (speed != 0.0f) + { + // 0x2AB577 + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + object->enablePhysics(1); + object->enablePhysics(2); + } + float sign = 0.0f; + if (angle <= 0.0f) + { + if (angle < 0.0f) + sign = -1.0f; + } + else + { + sign = 1.0f; + } + + float throttle; + if (mode != 0.0f) + { + // 0x2AB2E8 + const float scaledAngle = angle * 3.0f; + float turn = -1.0f; + if (-1.0f <= scaledAngle) + turn = (1.0f < scaledAngle) ? 1.0f : scaledAngle; + input->setInput(controlInfo->getDriveTurnControl(), turn); + speed = speed * mode; + const Vec3& rotation = mobile->getRotationalSpeed(); + float tilt = std::fabs(rotation.z); + if (std::fabs(rotation.z) <= std::fabs(rotation.x)) + tilt = std::fabs(rotation.x); + if (tilt > 0.15f) + { + float scale = (tilt - 0.15f) / 0.7f; + if (scale > 1.0f) + scale = 1.0f; + speed = (1.0f - scale * 0.8f) * speed; + } + if (std::fabs(speed) > limit) + { + float speedSign = 1.0f; + if (speed <= 0.0f) + speedSign = (speed < 0.0f) ? -1.0f : 0.0f; + speed = speedSign * limit; + } + float response = (speed - velocityLength * reference) / 3.0f; + if (response > 1.0f) + response = 1.0f; + response = response + speed / 15.0f; + throttle = -1.0f; + if (response >= -1.0f) + throttle = (response <= 1.0f) ? response : 1.0f; + if (throttle != 0.0f && !(1.5f <= std::fabs(velocityLength))) + { + float throttleSign = 1.0f; + if (throttle <= 0.0f) + throttleSign = (0.0f <= throttle) ? 0.0f : -1.0f; + throttle = throttleSign; + } + } + else + { + // 0x2AB0C7 + float turnAngle = std::fabs(angle); + if (mode == -1.0f) + turnAngle = turnAngle - 3.1415927f; + float turn = std::fabs(turnAngle * 3.0f); + if (turn > 1.0f) + turn = 1.0f; + input->setInput(controlInfo->getDriveTurnControl(), turn * -sign); + throttle = mode; + } + input->setInput(controlInfo->getDriveThrottleControl(), throttle); + return 1; +} + +// ELF 0x2AB5F0 (listing). Releases the selected input groups in the order move, look, trigger. +// Moving: the strafe/turn inputs 0, 2 and 1 are released, and the throttle (input 3) brakes against +// `forwardSpeed`: the speed is clamped to +-maxThrottle (a function static, 0.7), negated, and +// within 0.05 of zero the throttle is released; otherwise it is the sign times at least 0.4. +// Look releases inputs 4 and 5; trigger releases 8, 31, 14..30, 38, 37, 10 and 32. Returns 1. +int CarControl::resetControls(Bot*, io::PlayerInput* input, bool move, bool look, bool trigger, float forwardSpeed) +{ + static float maxThrottle = 0.7f; + if (move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + float clamped; + if (-maxThrottle > forwardSpeed) + clamped = -maxThrottle; + else + clamped = (forwardSpeed > maxThrottle) ? maxThrottle : forwardSpeed; + const float brake = -clamped; + float throttle = 0.0f; + if (std::fabs(brake) > 0.05f) + { + const float sign = (brake > 0.0f) ? 1.0f : ((0.0f > brake) ? -1.0f : 0.0f); + const float magnitude = std::fabs(brake); + throttle = sign * ((magnitude > 0.4f) ? magnitude : 0.4f); + } + input->setInput(static_cast(3), throttle); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + for (int i = 14; i <= 30; ++i) + input->setInput(static_cast(i), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + } + return 1; +} + +// ELF 0x2AB970 (listing block by block; Ghidra cross-check). The car's move-to state machine. +// Measures the free space around the vehicle with eight IAIPathfinding traces from its last valid +// position (forward, the two front diagonals of the bounding box and the same backwards, each +// diagonal/backward trace shortened by the obstacles the navigation holds, then right and left), +// asks CommonControls for the obstacle ahead and the vehicle to slow down for, picks an avoid +// side for a collided vehicle and then advances the bot's move-to status (0 drive, 2/3 and 9/11 +// turn forwards/backwards, 4/5 and 13/14 pass an obstacle, 6 avoid, 8 reverse, 12 back off). +// Outputs: `mode` (1 forward, -1 reverse, 666 = arrived at the collided object), `angle` (the +// signed steering angle, -2 = the slow-down stop), `speedSign` (the sign of the forward speed) +// and `speedLimit`. Returns 0 without a mobile or physical part, else 1. +// Shipped behaviour kept: the forward-space trace reads 0 when the trace hit is the zero vector, +// the space-with-obstacles front output is an uninitialised local that is never read, the +// collided object's information is dereferenced without a null test, and statuses 2/3 re-test the +// turn direction they are already in. +int CarControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& direction, float speed, + BAPAMoveTo* moveTo, float& mode, float& angle, float& speedSign, + float& speedLimit) +{ + static float spaceTweak = 1.3f; // .data 0x4BCB40 + + IPIMobile* const mobile = info->getMobile(); + IPIPhysical* const physical = info->getPhysical(); + if (mobile == 0 || physical == 0) + return 0; + BotMain* const botMain = static_cast(bot); // slots 0x238.. are declared on BotMain only + const float radius = physical->getRadius(); + Vec2 desired = direction; + const Vec3& position3 = info->getPosition(); + Vec2 position; + position.x = position.y = 0.0f; + Vec2 forward; + forward.x = forward.y = 0.0f; + Vec2 normal; + normal.x = normal.y = 0.0f; + vec3ToVec2XZ(position3, position); + vec3ToVec2XZ(info->getFaceing(), forward); + normalizeVec2(forward); + getNormal(forward, normal); + Vec2 goal; + goal.x = goal.y = 0.0f; + vec3ToVec2XZ(moveTo->getCoordinate(), goal); + float goalDistance = moveTo->getTargetDistance(); + if (goalDistance == 0.0f) + { + Vec2 toGoal; + toGoal.x = position.x - goal.x; + toGoal.y = position.y - goal.y; + goalDistance = std::sqrt(toGoal.x * toGoal.x + toGoal.y * toGoal.y); + } + const float nearDistance = radius * 10.0f; + const float dot = desired.x * forward.x + desired.y * forward.y; + angle = getSignedDiffAngleToDirWithNormal(forward, normal, desired); + const bool angleNegative = 0.0f > angle; + const float speedMagnitude = mobile->getSpeedMagnitude(); + const Vec3& velocity = mobile->getSpeed(); + const Vec3 facing = info->getFaceing(); + if (velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z >= 0.0f) + speedSign = 1.0f; + else + speedSign = -1.0f; + bool slowDownStop; + const float slowDown = CommonControls::checkSlowDown(bot, info, velocity, speedMagnitude * speedSign, position3, + slowDownStop); + Vec3 forward3; + forward3.x = forward3.y = forward3.z = 0.0f; + vec2ToVec3XZ(forward, forward3); + mode = 1.0f; + + // 0x2ABCE4: the eight space traces. + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + mobile->getVehicleNumber(); // result discarded + BotNavigation* const navigation = bot->getBotNavigation(); + const float traceLength = radius + 10.0f; + Vec3 hit; + hit.x = hit.y = hit.z = 0.0f; + const IPIMobile::ValidPos& lastValid = mobile->getLastValidPosition(pathfinding->getTraceMapIndex()); + const int equipmentType = info->getUnit()->getEquipmentType(); + Vec3 right; + right.x = normal.x; + right.y = 0.0f; + right.z = normal.y; + int status = botMain->getMoveToStatus(); + const bool reversing = status > 7; + float back = 0.0f; + float front = 0.0f; + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const Vec3& size = box->getSize(); + const float width = size.x; + const float length = size.z; + const Vec3 origin = lastValid.position; + const Vec3 ahead = forward3; + Vec3 frontLeft; + frontLeft.x = length * forward3.x - right.x * width; + frontLeft.y = length * forward3.y - right.y * width; + frontLeft.z = length * forward3.z - right.z * width; + normalizeVec3(frontLeft); + Vec3 frontRight; + frontRight.x = length * ahead.x + right.x * width; + frontRight.y = ahead.y * length + right.y * width; + frontRight.z = length * ahead.z + right.z * width; + normalizeVec3(frontRight); + unsigned int polygon; + unsigned char traceStatus; + float frontUnused; // -0x2CC: updateSpaceWithObstacles' front output, never initialised or read + + Vec3 target = alongFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + front = distanceVec3(hit, origin); + const float firstFront = front; + target = alongFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > firstFront) ? firstFront : d; + } + target = alongFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > front) ? front : d; + } + target = backFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + back = distanceVec3(hit, origin); + CommonControls::updateSpaceWithObstacles(bot, origin, ahead, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontLeft, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontRight, frontUnused, back, 0xFFFFFFFFu); + target = alongFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float rightSpace = traceLength; + if (traceStatus != 4) + rightSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + target = backFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float leftSpace = traceLength; + if (traceStatus != 4) + leftSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + + // 0x2AD236: the obstacle ahead. + const float spaceRadius = radius * spaceTweak; + unsigned int obstacle = 0xFFFFFFFFu; + unsigned int collided = botMain->getCollidedObject(); + int avoidSide = botMain->getAvoidSide(); + Vec2 desiredVelocity; + desiredVelocity.x = speed * direction.x; + desiredVelocity.y = speed * direction.y; + float dotForward; + float angleToObstacle; + bool outOfOurWay; + bool passing; + bool collidedSeen; + float avoidAngle; + float tangentAngle; + bool touching; + bool collision = CommonControls::checkCollisions(bot, info, physical, forward, dotForward, angleToObstacle, + outOfOurWay, desiredVelocity, desired, speed, passing, obstacle, + collided, collidedSeen, avoidAngle, tangentAngle, speedSign, + touching, static_cast(avoidSide), true); + if (collided != 0xFFFFFFFFu && !collidedSeen) + collision = false; + if (collision) + { + Information* const obstacleInfo = lookupInformation(obstacle); + const float limitSqr = botMain->getIgnoreObstacles() ? 2.5f * 2.5f : 1.0f; + if (obstacle == collided && obstacle != 0xFFFFFFFFu) + { + // 0x2AEB27: drop the collision once the collided object has moved away. + const Vec3& last = botMain->getCollidedObjectPosition(); + const Vec3& now = obstacleInfo->getPosition(); + Vec3 moved; + moved.x = now.x - last.x; + moved.y = now.y - last.y; + moved.z = now.z - last.z; + if (moved.x * moved.x + moved.y * moved.y + moved.z * moved.z > limitSqr) + collision = false; + } + else + { + botMain->setCollidedObjectPosition(obstacleInfo->getPosition()); + } + } + if (!collision) + { + botMain->setCollidedObject(0xFFFFFFFFu); + obstacle = 0xFFFFFFFFu; + collided = 0xFFFFFFFFu; + } + bool tooClose = false; + if (collision) + { + botMain->setCollidedObject(obstacle); + collided = obstacle; + if (avoidSide == 0) + { + // 0x2AD494: choose the side with more room around the collided vehicle. + Information* const other = lookupInformation(collided); + IPIMobile* const otherMobile = other->getMobile(); + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherMobile == 0) + { + avoidSide = 1; + } + else + { + const float clearance = radius + otherPhysical->getSmallestRadius() * 0.5f; + const float reach = clearance + 0.5f; + const int vehicleNumber = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& otherValid = otherMobile->getLastValidPosition(vehicleNumber); + if (otherValid.polygon == 0xFFFFFFFFu || otherValid.quadTree == 0xFFFFFFFFu) + { + avoidSide = 1; + } + else + { + Vec3 hitRight; + hitRight.x = hitRight.y = hitRight.z = 0.0f; + Vec3 hitLeft; + hitLeft.x = hitLeft.y = hitLeft.z = 0.0f; + unsigned int sidePolygon; + Vec3 sideTarget = alongFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + sideTarget, hitRight, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomRight = isZeroVec3(hitRight) ? 0.0f : distanceVec3(hitRight, otherValid.position); + sideTarget = backFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + sideTarget, hitLeft, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomLeft = isZeroVec3(hitLeft) ? 0.0f : distanceVec3(hitLeft, otherValid.position); + bool firstSide = roomRight < roomLeft; // before the obstacles shorten them + CommonControls::updateSpaceWithObstacles(bot, otherValid.position, + rightAxis(info->getTransformation()), roomRight, + roomLeft, collided); + const float smaller = (roomLeft < roomRight) ? roomLeft : roomRight; + const float larger = (roomRight > roomLeft) ? roomRight : roomLeft; + tooClose = clearance > larger; + if (smaller > clearance) + { + // 0x2AEA3E: room on both sides - the side the other vehicle lies on across the desired line. + Vec2 sideNormal; + sideNormal.x = sideNormal.y = 0.0f; + getNormal(desired, sideNormal); + Vec2 toOther; + toOther.x = otherValid.position.x - position.x; + toOther.y = otherValid.position.z - position.y; + firstSide = toOther.x * sideNormal.x + toOther.y * sideNormal.y > 0.0f; + } + else if (!(clearance * 0.7f > larger)) + { + firstSide = roomRight < roomLeft; + } + avoidSide = 2; + if (firstSide) + avoidSide = 1; + } + } + if (botMain->setAvoidSide(avoidSide) && !botMain->getIgnoreObstacles()) + { + status = 0; + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + } + } + else + { + botMain->setAvoidSide(0); + } + + // 0x2ADA40: arrived next to the collided object's goal? + bool hasCollided = collided != 0xFFFFFFFFu; + bot->setUnresolvedCollisionObject(collided); + if (hasCollided) + { + Information* const other = lookupInformation(collided); + if (other == 0) + { + hasCollided = false; + collided = 0xFFFFFFFFu; + } + else + { + Vec2 otherPosition; + otherPosition.x = otherPosition.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&other->getTransformation().m[12]), otherPosition); + const float otherRadius = other->getPhysical()->getRadius(); + Vec2 goalOffset; + goalOffset.x = goal.x - otherPosition.x; + goalOffset.y = goal.y - otherPosition.y; + if (otherRadius * otherRadius > goalOffset.x * goalOffset.x + goalOffset.y * goalOffset.y) + { + Vec2 toOther; + toOther.x = otherPosition.x - position.x; + toOther.y = otherPosition.y - position.y; + const float distanceSqr = toOther.x * toOther.x + toOther.y * toOther.y; + const float reach = other->getPhysical()->getRadius() + radius + 3.0f; + if (reach * reach > distanceSqr) + { + mode = 666.0f; + angle = 0.0f; + return 1; + } + } + } + } + else + { + avoidSide = 0; + botMain->setAvoidSide(0); + } + + // 0x2ADB2D: room flags and the speed limit. + bool wideSpace = false; + const bool obstacleAngleNegative = 0.0f > angleToObstacle; + if (leftSpace + rightSpace > radius * 2.7f && front + back > radius * 2.7f) + wideSpace = true; + bool veryWideSpace = false; + if (leftSpace + rightSpace > radius * 3.0f && front + back > radius * 3.0f) + veryWideSpace = true; + const float backRatio = (back - spaceRadius) / (traceLength - spaceRadius); + const float frontRatio = (front - spaceRadius) / (traceLength - spaceRadius); + bool stuck = false; + if (front == 0.0f && back == 0.0f) + { + stuck = true; + status = !(dot > 0.0f) ? 8 : 0; + } + const float maxSpeed = mobile->getMaxSpeed(); + const float minSpeed = 2.0f; + if (!reversing) + { + if (0.95f > frontRatio) + speedLimit = 5.0f - (1.0f - frontRatio) * (5.0f - minSpeed); + else + speedLimit = maxSpeed - (1.0f - frontRatio) * (maxSpeed - minSpeed); + } + else + { + speedLimit = 5.0f - (1.0f - backRatio) * (5.0f - minSpeed); + } + if (tooClose) + speedLimit = (7.0f > speedLimit) ? speedLimit : 7.0f; + if (!hasCollided) + { + botMain->setIgnoreObstacles(false); + botMain->setAvoidSide(0); + } + bool ignoring = botMain->getIgnoreObstacles(); + if (ignoring) + { + if (hasCollided) + { + // 0x2ADD1E: keep ignoring while we push the collided object, unless it has a human driver. + Information* const other = lookupInformation(collided); + IAIObjectPhysical* const otherObject = other->getAIObject()->getPhysical(); + otherObject->enablePhysics(1); + otherObject->enablePhysics(2); + if (botMain->getSlowDownToTarget() == collided) + ignoring = true; + if (other->getAIObject() != 0 && IBotManager::instance->getBot(other->getAIObject()) == 0 + && other->getUnit() != 0 && other->getUnit()->isOccupied()) + ignoring = false; + } + if (ignoring && (static_cast(status - 4) <= 2u || status == 13 || status == 14)) + { + status = 0; + botMain->setMoveToStatus(0); + } + } + + // 0x2ADE10 + switch (status) + { + case 0: + if (stuck) + { + mode = 1.0f; + speedLimit = maxSpeed * 0.5f; + break; + } + if (!(0.0f > dot) && !(spaceRadius > front)) + { + if (collision && !ignoring) + botMain->setMoveToStatus(6); + else + mode = 1.0f; + break; + } + if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(8); + break; + } + if (0.0f > dot && !wideSpace) + { + botMain->setMoveToStatus(12); + break; + } + botMain->setMoveToStatus(angleNegative ? 9 : 11); + break; + case 2: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(11); + break; + } + if (angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(9); + break; + } + mode = 1.0f; + angle = std::fabs(angle); + break; + case 3: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(9); + break; + } + if (!angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(11); + break; + } + mode = 1.0f; + angle = -std::fabs(angle); + break; + case 4: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || touching) + botMain->setMoveToStatus(13); + else + { + mode = 1.0f; + angle = -2.0f; + } + break; + case 5: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || touching) + botMain->setMoveToStatus(14); + else + { + mode = 1.0f; + angle = 2.0f; + } + break; + case 6: + if (!hasCollided || (passing && 0.3f > dotForward)) + { + botMain->setMoveToStatus(0.0f > angle ? 3 : 2); + break; + } + if (touching && !outOfOurWay && dotForward > 0.0f) + { + botMain->setMoveToStatus(avoidSide == 2 ? 14 : 13); + break; + } + if (front >= spaceRadius) + { + angle = avoidAngle; + break; + } + if (avoidSide == 2) + { + if (botMain->setAvoidSide(1) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(13); + } + } + else + { + if (botMain->setAvoidSide(2) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(14); + } + } + break; + case 8: + if (stuck) + { + mode = -1.0f; + angle = -angle; + reverseAngle(angle); + break; + } + if (dot > -0.5f || goalDistance > nearDistance + 5.0f || spaceRadius > back) + { + botMain->setMoveToStatus(0); + mode = 1.0f; + break; + } + if (-0.6f > dotForward && hasCollided) + { + botMain->setMoveToStatus(obstacleAngleNegative ? 3 : 2); + break; + } + mode = -1.0f; + reverseAngle(angle); + break; + case 9: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f && front > spaceRadius) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(3); + else + { + mode = -1.0f; + angle = std::fabs(angle); + } + break; + case 11: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f && front > spaceRadius) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(2); + else + { + mode = -1.0f; + angle = -std::fabs(angle); + } + break; + case 12: + if (dot > 0.0f) + botMain->setMoveToStatus(0); + else if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + botMain->setMoveToStatus(8); + else if (veryWideSpace) + botMain->setMoveToStatus(angleNegative ? 9 : 11); + else + { + mode = -1.0f; + reverseAngle(angle); + } + break; + case 13: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(4); + mode = -1.0f; + angle = 2.0f; + break; + case 14: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(5); + mode = -1.0f; + angle = -2.0f; + break; + default: + break; + } + // 0x2ADE60 + if (speedLimit > slowDown) + speedLimit = slowDown; + if (slowDownStop) + angle = -2.0f; + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.h new file mode 100644 index 000000000..b44796897 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.h @@ -0,0 +1,37 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_CARCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_CARCONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace io { class PlayerInput; } +namespace ai { + +class BAPAMoveTo; +class Bot; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace CarControl +{ + int controlTowardsDirection(Information*, IPIControlInfo*, IPIMobile*, IPIPhysical*, io::PlayerInput*, float, float, float, float, float); // 0x2AAF40; [INFERRED] ELF int + int resetControls(Bot*, io::PlayerInput*, bool, bool, bool, float); // 0x2AB5F0; [INFERRED] ELF int + int actionStatusDecision(Bot*, Information*, const Vec2&, float, BAPAMoveTo*, float&, float&, float&, float&); // 0x2AB970; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_CARCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp new file mode 100644 index 000000000..bc2c85524 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp @@ -0,0 +1,477 @@ +// Shared vehicle steering helpers for CarControl and TankControl (libaidll.so CommonControls TU). +// static init: the guard object only (ELF 0x2B0910, __tcf_0 0x2B0970, _GLOBAL__I 0x2B09A0). +// Bodies recovered from the ELF listings (objdump with GOT/rodata resolved; Ghidra cross-check). +// Comparisons are written as compiled, so NaN takes the branch the x87/SSE code takes. +// [PLATFORM] the image keeps intermediate sums in x87 extended precision; the native build rounds +// each float operation. + +#include "CommonControls.h" + +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +inline Information* lookupInformation(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +} // namespace + +// ELF 0x2AF110. Shortens the free space ahead (`front`) and behind (`back`) of `origin` along the +// unit direction `direction` by the obstacles the bot's navigation has collected: each other +// non-soldier object with a physical part (except `ignore` and the bot's own vehicle) whose +// smallest-radius sphere crosses the line within the current space limits the space to the +// sphere's near intersection. +void CommonControls::updateSpaceWithObstacles(Bot* bot, const Vec3& origin, const Vec3& direction, float& front, + float& back, unsigned int ignore) +{ + Information* const self = lookupInformation(bot->getCurrentEquipment()); + BotNavigation* const navigation = bot->getBotNavigation(); + const std::vector& obstacles = navigation->getObstacles(); + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + const unsigned int handle = obstacles[i]; + if (handle == ignore) + continue; + Information* const obstacle = lookupInformation(handle); + if (self == obstacle || obstacle == 0) + continue; + IPIPhysical* const physical = obstacle->getPhysical(); + if (physical == 0 || (obstacle->getObjectTypeFlags() & 0x200000u)) + continue; + const float radius = physical->getSmallestRadius(); + const Vec3& position = obstacle->getPosition(); + Vec3 offset; + offset.x = position.x - origin.x; + offset.y = position.y - origin.y; + offset.z = position.z - origin.z; + const float along = direction.x * offset.x + direction.y * offset.y + direction.z * offset.z; + if (along > 0.0f) + { + if (!(along > radius + front)) + { + Vec3 perpendicular; + perpendicular.x = offset.x - direction.x * along; + perpendicular.y = offset.y - direction.y * along; + perpendicular.z = offset.z - direction.z * along; + const float distance = std::sqrt(perpendicular.x * perpendicular.x + perpendicular.y * perpendicular.y + + perpendicular.z * perpendicular.z); + if (!(distance > radius)) + { + const float half = std::sqrt(radius * radius - distance * distance); + const float space = along - half; + if (!(space > front)) + front = space; + } + } + } + else if (!(-along > radius + back)) + { + Vec3 perpendicular; + perpendicular.x = offset.x - direction.x * along; + perpendicular.y = offset.y - direction.y * along; + perpendicular.z = offset.z - direction.z * along; + const float distance = std::sqrt(perpendicular.x * perpendicular.x + perpendicular.y * perpendicular.y + + perpendicular.z * perpendicular.z); + if (!(distance > radius)) + { + const float half = std::sqrt(radius * radius - distance * distance); + const float space = -along - half; + if (!(space > back)) + back = space; + } + } + } +} + +// ELF 0x2AF500. Picks the obstacle the vehicle is about to hit. `forward` and `direction` are the +// unit heading and the desired direction (XZ), `velocity` the desired 2D velocity, `speed` its +// length and `speedSign` the sign of the forward speed (nothing is looked at while reversing). +// A candidate is a non-soldier obstacle within the look-ahead reach, ahead of the heading and +// within the combined radius of the heading line; the one closest to the line wins (low-angle +// ones only when they are the bot's collided object or there is none). With no candidate the +// collided object (`collided`, which also sets `collidedSeen` when it is still an obstacle) is +// kept. For the winner the body writes `dotForward` (its direction against the heading), +// `angleToObstacle`, `outOfOurWay` / `passing` (whether the heading / desired line clear its +// avoid circle), `touching`, the tangent angle `avoidAngle` (`tangentAngle` the direction to it), +// or, inside the avoid circle, the angle to the side's perpendicular (`tangentAngle` -666), and +// `obstacle`. Returns whether an obstacle was chosen; when the desired direction already leads +// away from it both handles are cleared and false is returned. +bool CommonControls::checkCollisions(Bot* bot, Information* info, IPIPhysical* physical, const Vec2& forward, + float& dotForward, float& angleToObstacle, bool& outOfOurWay, + const Vec2& velocity, const Vec2& direction, float speed, bool& passing, + unsigned int& obstacle, unsigned int& collided, bool& collidedSeen, + float& avoidAngle, float& tangentAngle, float speedSign, bool& touching, + AvoidSide side, bool tight) +{ + static float radiusTweak = 0.9f; // .data 0x4BCB84, not read by the body + static float obstacleRadiusTweak = 0.8f; // .data 0x4BCB88 + static float outOfOurWayTweak = 0.7f; // .data 0x4BCB8C + (void)radiusTweak; + + IPIMobile* const mobile = info->getMobile(); + const float radius = physical->getRadius(); + BotNavigation* const navigation = bot->getBotNavigation(); + const std::vector& obstacles = navigation->getObstacles(); + float bestDistanceSqr = 99999.0f; + dotForward = 0.0f; + collidedSeen = false; + const float lookAheadTime = 1.0f; + unsigned int best = 0xFFFFFFFFu; + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + const unsigned int handle = obstacles[i]; + if (collided != 0xFFFFFFFFu && collided == handle) + collidedSeen = true; + if (0.0f > speedSign) + continue; + Information* const other = lookupInformation(handle); + if (info == other || other == 0) + continue; + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherPhysical == 0 || (other->getObjectTypeFlags() & 0x200000u)) + continue; + const float combinedRadius = otherPhysical->getRadius() + radius; + const Vec3& ownPosition = info->getPosition(); + const Vec3& otherPosition = other->getPosition(); + Vec3 offset; + offset.x = otherPosition.x - ownPosition.x; + offset.y = otherPosition.y - ownPosition.y; + offset.z = otherPosition.z - ownPosition.z; + Vec2 offset2; + offset2.x = offset.x; + offset2.y = offset.z; + const float distanceSqr = offset.x * offset.x + offset.y * offset.y + offset.z * offset.z; + const Vec3& ownSpeed = mobile->getSpeed(); + const Vec3 facing = info->getFaceing(); + const float minimumReach = (radius > 5.0f) ? radius : 5.0f; + const float reach = (facing.x * ownSpeed.x + facing.y * ownSpeed.y + facing.z * ownSpeed.z) * lookAheadTime + + minimumReach + combinedRadius; + if (distanceSqr > reach * reach) + continue; + if (distanceSqr > speed * speed) + { + Vec2 predicted; + predicted.x = offset2.x - velocity.x; + predicted.y = offset2.y - velocity.y; + if (predicted.x * predicted.x + predicted.y * predicted.y > combinedRadius * combinedRadius) + continue; + } + const float along = forward.x * offset2.x + forward.y * offset2.y; + if (0.0f > along) + continue; + const float length = std::sqrt(offset2.x * offset2.x + offset2.y * offset2.y); + const float cosine = along / length; + Vec2 perpendicular; + perpendicular.x = offset2.x - forward.x * along; + perpendicular.y = offset2.y - forward.y * along; + const float perpendicularSqr = perpendicular.x * perpendicular.x + perpendicular.y * perpendicular.y; + if (perpendicularSqr > combinedRadius * combinedRadius) + continue; + if (0.5f > cosine && collided != handle && collided != 0xFFFFFFFFu) + continue; + if (bestDistanceSqr > perpendicularSqr) + { + bestDistanceSqr = perpendicularSqr; + best = handle; + } + } + if (best == 0xFFFFFFFFu) + { + if (collidedSeen) + { + const unsigned int handle = collided; + best = lookupInformation(handle) ? handle : best; + } + if (best == 0xFFFFFFFFu) + return false; + } + Information* const target = lookupInformation(best); + if (target == 0) + return best != 0xFFFFFFFFu; + IPIPhysical* const targetPhysical = target->getPhysical(); + IPIMobile* const targetMobile = target->getMobile(); + if (targetMobile) + targetMobile->getSpeedMagnitude(); // result discarded + const float avoidRadius = targetPhysical->getRadius() * obstacleRadiusTweak + radius; + const float avoidRadiusSqr = avoidRadius * avoidRadius; + Vec2 ownPosition; + ownPosition.x = info->getPosition().x; + ownPosition.y = info->getPosition().z; + Vec2 targetPosition; + targetPosition.x = target->getPosition().x; + targetPosition.y = target->getPosition().z; + Vec2 toTarget; + toTarget.x = targetPosition.x - ownPosition.x; + toTarget.y = targetPosition.y - ownPosition.y; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (1e-05f > distance) + return false; + const float inverse = 1.0f / distance; + toTarget.x = toTarget.x * inverse; + toTarget.y = inverse * toTarget.y; + dotForward = toTarget.x * forward.x + toTarget.y * forward.y; + touching = targetPhysical->getRadius() + radius > distance; + Vec2 ahead = ownPosition; + const float aheadTime = tight ? 0.25f : 0.5f; + ahead.x = aheadTime * mobile->getSpeed().x + ahead.x; + ahead.y = aheadTime * mobile->getSpeed().z + ahead.y; + Vec2 toTargetAhead; + toTargetAhead.x = targetPosition.x - ahead.x; + toTargetAhead.y = targetPosition.y - ahead.y; + const float aheadDistance = std::sqrt(toTargetAhead.x * toTargetAhead.x + toTargetAhead.y * toTargetAhead.y); + const float aheadInverse = 1.0f / aheadDistance; + toTargetAhead.x = toTargetAhead.x * aheadInverse; + toTargetAhead.y = aheadInverse * toTargetAhead.y; + if (avoidRadius > aheadDistance) + { + // 0x2AFBAD: inside the avoid circle - steer along the side's perpendicular. + Vec2 sideDirection; + sideDirection.x = 0.0f; + sideDirection.y = 0.0f; + if (side == static_cast(2)) + { + sideDirection.x = toTargetAhead.y; + sideDirection.y = -toTargetAhead.x; + } + else + { + sideDirection.x = -toTargetAhead.y; + sideDirection.y = toTargetAhead.x; + } + avoidAngle = getSignedDiffAngleToDir(forward, sideDirection); + tangentAngle = -666.0f; + } + else + { + // 0x2AFE7D: the tangent past the avoid circle. + const float ratio = avoidRadius / aheadDistance; + float clamped = ratio; + if (-1.0f > ratio) + clamped = -1.0f; + else if (ratio > 1.0f) + clamped = 1.0f; + avoidAngle = std::asin(clamped); + const float angle = getSignedDiffAngleToDir(forward, toTargetAhead); + tangentAngle = angle; + if (side == static_cast(2)) + avoidAngle = angle + avoidAngle; + else + avoidAngle = angle - avoidAngle; + } + // 0x2AFC06: do the heading line and the desired line clear the target? + Vec2 headingPoint; + headingPoint.x = forward.x * dotForward * distance + ownPosition.x; + headingPoint.y = dotForward * forward.y * distance + ownPosition.y; + const float headingX = headingPoint.x - targetPosition.x; + const float headingY = headingPoint.y - targetPosition.y; + outOfOurWay = headingX * headingX + headingY * headingY > avoidRadiusSqr * outOfOurWayTweak; + const float alongDesired = toTarget.x * direction.x + toTarget.y * direction.y; + Vec2 desiredPoint; + desiredPoint.x = direction.x * alongDesired * distance + ownPosition.x; + desiredPoint.y = direction.y * alongDesired * distance + ownPosition.y; + const float desiredX = desiredPoint.x - targetPosition.x; + const float desiredY = desiredPoint.y - targetPosition.y; + bool clear = false; + if (desiredX * desiredX + desiredY * desiredY > avoidRadiusSqr) + clear = true; + else if (-0.1f > alongDesired && speedSign > 0.0f) + clear = true; + passing = clear; + if (0.0f > toTarget.x * direction.x + toTarget.y * direction.y + && forward.x * direction.x + forward.y * direction.y > 0.0f) + { + // 0x2AFD88: the desired direction already leads away from it. + collided = 0xFFFFFFFFu; + passing = true; + obstacle = 0xFFFFFFFFu; + outOfOurWay = true; + return false; + } + const float headingDot = forward.x * direction.x + forward.y * direction.y; + if (std::fabs(headingDot) > 0.85f) + angleToObstacle = getSignedDiffAngleToDir(direction, toTarget); + else + angleToObstacle = getSignedDiffAngleToDir(forward, toTarget); + obstacle = best; + return best != 0xFFFFFFFFu; +} + +// ELF 0x2AFF80. The speed limit for following the slowest vehicle ahead. At or below 2 m/s +// (`speed` is the signed forward speed) nothing is checked and 9999 is returned. Otherwise every +// obstacle whose sphere lies on the projected path within 15 m is rated by its speed along our +// heading minus 1 (at least 0); vehicles beyond 8 m (maxDist) or crossing our path count only +// when the relative speed is above 10 m/s, which also rates -20 and sets `stop` while the bot has +// no move-to status. The lowest rating is returned and its handle stored as the bot's slow-down +// target; a same-side object within 5 m (or a soldier ahead) is honked at when we carry a driver. +float CommonControls::checkSlowDown(Bot* bot, Information* info, const Vec3& velocity, float speed, + const Vec3& position, bool& stop) +{ + static float maxDist = 8.0f; // .data 0x4BCB90 + + stop = false; + if (2.0f >= speed) + return 9999.0f; + BotNavigation* const navigation = bot->getBotNavigation(); + const std::vector& obstacles = navigation->getObstacles(); + const Vec3 facing = info->getFaceing(); + const Vec3 facingAgain = info->getFaceing(); + const float facingDot = facingAgain.x * velocity.x + facingAgain.y * velocity.y + facingAgain.z * velocity.z; + float sign = 1.0f; + if (!(facingDot > 0.0f)) + sign = (0.0f > facingDot) ? -1.0f : 0.0f; + Vec3 heading; + heading.x = facing.x * sign; + heading.y = facing.y * sign; + heading.z = sign * facing.z; + float lowest = 9999.0f; + unsigned int lowestHandle = 0xFFFFFFFFu; + Information* honkTarget = 0; + IPIPhysical* const ownPhysical = info->getPhysical(); + IPIMobile* const ownMobile = info->getMobile(); + const float zero = 0.0f; + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + Information* const other = lookupInformation(obstacles[i]); + if (other == 0 || other == info) + continue; + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherPhysical == 0) + continue; + if ((other->getObjectTypeFlags() & 0x200000u) && 0.0f >= otherPhysical->getHealth()) + continue; + IPIMobile* const otherMobile = other->getMobile(); + if (otherMobile == 0) + continue; + Information* const changeTarget = lookupInformation(bot->getChangeTarget()); + if (changeTarget && !changeTarget->isPrimary() + && changeTarget->getPrimaryObject(bot->getSide()) == obstacles[i]) + continue; + // 0x2B01AB: the centre of the other's sphere. + Vec3 offset; + offset.x = offset.y = offset.z = zero; + const Mat4& transformation = other->getTransformation(); + const Vec3 local = otherPhysical->getSphereLocalOffset(); + const float* const m = transformation.m; + offset.x = m[0] * local.x + m[4] * local.y + m[8] * local.z; + offset.y = m[1] * local.x + m[5] * local.y + m[9] * local.z; + offset.z = m[2] * local.x + m[6] * local.y + m[10] * local.z; + const Vec3& otherPosition = other->getPosition(); + Vec3 centre; + centre.x = offset.x + otherPosition.x; + centre.y = offset.y + otherPosition.y; + centre.z = offset.z + otherPosition.z; + Vec3 toCentre; + toCentre.x = centre.x - position.x; + toCentre.y = centre.y - position.y; + toCentre.z = centre.z - position.z; + float distance = std::sqrt(toCentre.x * toCentre.x + toCentre.y * toCentre.y + toCentre.z * toCentre.z); + const float otherRadius = otherPhysical->getSmallestRadius(); + const float radii = otherRadius + ownPhysical->getSmallestRadius(); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + toCentre.x = toCentre.x * inverse; + toCentre.y = toCentre.y * inverse; + toCentre.z = inverse * toCentre.z; + } + distance = distance - radii; + if (distance > 15.0f) + continue; + const float otherSpeed = otherMobile->getSpeedMagnitude(); + const float along = heading.x * toCentre.x + heading.y * toCentre.y + heading.z * toCentre.z; + const float reach = distance + radii; + Vec3 projected; + projected.x = heading.x * along * reach + position.x; + projected.y = heading.y * along * reach + position.y; + projected.z = heading.z * along * reach + position.z; + Vec3 miss; + miss.x = centre.x - projected.x; + miss.y = centre.y - projected.y; + miss.z = centre.z - projected.z; + if (miss.x * miss.x + miss.y * miss.y + miss.z * miss.z > radii * radii) + continue; + if (other->getObjectTypeFlags() & 0x200000u) + { + // 0x2B049C: a soldier ahead is only a horn candidate. + if (along > 0.0f && info->getSide() == other->getSide()) + honkTarget = other; + continue; + } + if (0.75f > along) + { + if (!(2.0f > distance)) + continue; + if (!(along > 0.0f)) + continue; + if (!(otherSpeed > 2.0f)) + continue; + } + // 0x2B054C + Vec3 otherVelocity = otherMobile->getSpeed(); + const bool moving = otherSpeed > 0.5f; + float rating = heading.x * otherVelocity.x + heading.y * otherVelocity.y + heading.z * otherVelocity.z - 1.0f; + if (!(rating > zero)) + rating = zero; + if (moving) + { + const float inverse = 1.0f / otherSpeed; + otherVelocity.x = otherVelocity.x * inverse; + otherVelocity.y = otherVelocity.y * inverse; + otherVelocity.z = otherVelocity.z * inverse; + } + const Vec3& otherSpeedVector = otherMobile->getSpeed(); + const Vec3& ownSpeedVector = ownMobile->getSpeed(); + Vec3 relative; + relative.x = otherSpeedVector.x - ownSpeedVector.x; + relative.y = otherSpeedVector.y - ownSpeedVector.y; + relative.z = otherSpeedVector.z - ownSpeedVector.z; + const bool fastApproach = relative.x * relative.x + relative.y * relative.y + relative.z * relative.z > 100.0f; + if (fastApproach && static_cast(bot)->getMoveToStatus() == 0) + { + rating = -20.0f; + stop = true; + } + if (distance > maxDist && !fastApproach) + continue; + const float otherDot = otherVelocity.x * heading.x + otherVelocity.y * heading.y + otherVelocity.z * heading.z; + if (moving && 0.6f > otherDot && otherDot > -0.75f && !fastApproach) + continue; + if (static_cast(bot)->getIgnoreObstacles() + && static_cast(bot)->getCollidedObject() == obstacles[i] && !fastApproach) + continue; + if (info->getSide() == other->getSide() && 5.0f > distance) + honkTarget = other; + if (lowest > rating) + { + lowest = rating; + lowestHandle = obstacles[i]; + } + } + if (honkTarget && info->getUnit()->isOccupied()) + bot->getCommunicationAgent()->honkHorn(honkTarget); + static_cast(bot)->setSlowDownToTarget(lowestHandle); + return lowest; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.h new file mode 100644 index 000000000..f90526c2a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.h @@ -0,0 +1,38 @@ +// Shared vehicle steering helpers used by CarControl and TankControl (libaidll.so CommonControls TU). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_COMMONCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_COMMONCONTROLS_H + +#include "../../../../Math/Vec3.h" +#include "../AIBotActionPlan/BAPTypes.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class IPIPhysical; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace CommonControls +{ + void updateSpaceWithObstacles(Bot* bot, const Vec3& origin, const Vec3& direction, float& front, float& back, + unsigned int ignore); // 0x2AF110 + // 0x2AF500. Returns bool: CarControl::actionStatusDecision stores `al` (0x2AD375). + bool checkCollisions(Bot* bot, Information* info, IPIPhysical* physical, const Vec2& forward, float& dotForward, + float& angleToObstacle, bool& outOfOurWay, const Vec2& velocity, const Vec2& direction, + float speed, bool& passing, unsigned int& obstacle, unsigned int& collided, + bool& collidedSeen, float& avoidAngle, float& tangentAngle, float speedSign, + bool& touching, AvoidSide side, bool tight); + // 0x2AFF80. Returns the speed limit in st(0). + float checkSlowDown(Bot* bot, Information* info, const Vec3& velocity, float speed, const Vec3& position, + bool& stop); +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_COMMONCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp new file mode 100644 index 000000000..176cb94ff --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp @@ -0,0 +1,622 @@ +// ControlFunctions: the shared regulator and geometry helpers of the plan-interpreter controls +// (attested TU `AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp`, the path of changeReg's Debug). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32); every body carries its ELF address. x87 code +// was read in Intel syntax (llvm-objdump), which has no fsub(r)p/fdiv(r)p operand swap, and checked +// against the Ghidra decompilation. Parameter names are [INFERRED] from their use. +// +// The *Debug variants are the same computation as their non-debug twins in this build (the debug +// output was compiled out); they stay separate functions because the image has both symbols. + +// static init: ELF 0x2B2080 (__tcf_0 0x2B20E0, _GLOBAL__I 0x2B2110): 's Init object only. +#include + +#include "ControlFunctions.h" + +#include +#include + +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Core/Debug.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] helpers for this TU's readability. The image indexes Vec2 as float[2] +// (`[v + 4*axis]`), and every regulator reads the frame time through IBFTimer slot +0x0C and +// narrows it to float (`fstp dword` / `fld dword` right after the call). +inline float& axisOf(Vec2& v, int axis) { return (&v.x)[axis]; } +inline float axisOf(const Vec2& v, int axis) { return (&v.x)[axis]; } + +inline float frameTime() +{ + return static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); +} + +// The three-way sign the regulators compute inline: 1 above zero, -1 below, 0 at zero. NaN fails +// the `<= 0` test and gives 1, as in the image. +inline float signOf(float v) +{ + if (v <= 0.0f) + return (0.0f <= v) ? 0.0f : -1.0f; + return 1.0f; +} + +// The inline clamp at the end of every regulator (`fld -1; fucomi; ... fcmov`): NaN gives -1. +inline float clampUnit(float v) +{ + if (!(-1.0f <= v)) + return -1.0f; + if (1.0f < v) + return 1.0f; + return v; +} + +// One axis of getBoxIntersections (the image repeats the same code for x and then for y with the +// axes swapped). Box A is [aMin, aMax], box B is [bMin, bMax]. Returns false when the intervals are +// disjoint; lo/hi receive the overlap on `axis`. When one interval contains the other the image +// takes the overlap as a segment at a fixed coordinate of the other axis (`spans`, `other`). +bool boxAxisIntersection(const Vec2& aMin, const Vec2& aMax, const Vec2& bMin, const Vec2& bMax, + int axis, float& lo, float& hi, bool& spans, float& other) +{ + const int o = 1 - axis; + const float aMaxV = axisOf(aMax, axis); + const float bMaxV = axisOf(bMax, axis); + spans = false; + other = 0.0f; + if (bMaxV <= aMaxV) + { + const float aMinV = axisOf(aMin, axis); + if (aMaxV != bMaxV) + { + if (bMaxV < aMinV) + return false; + if (aMinV != bMaxV) + { + const float bMinV = axisOf(bMin, axis); + if (aMinV < bMinV) + { + // B lies strictly inside A on this axis. + spans = true; + other = axisOf(aMax, o); + if (axisOf(bMax, o) <= other) + other = axisOf(aMin, o); + lo = bMinV; + hi = bMaxV; + return true; + } + } + lo = aMinV; + hi = bMaxV; + return true; + } + // aMax == bMax + lo = axisOf(bMin, axis); + if (lo <= aMinV) + lo = aMinV; + hi = bMaxV; + return true; + } + const float bMinV = axisOf(bMin, axis); + if (!(bMinV <= aMaxV)) + return false; + if (aMaxV != bMinV) + { + const float aMinV = axisOf(aMin, axis); + if (!(aMinV < bMinV)) + { + // A lies inside B on this axis. + spans = true; + other = axisOf(bMax, o); + if (axisOf(aMax, o) <= other) + other = axisOf(bMin, o); + lo = aMinV; + hi = aMaxV; + return true; + } + } + lo = bMinV; + hi = aMaxV; + return true; +} + +} // namespace + +// ELF 0x2B09C0. Where the line through `point` (direction perpendicular to `normal`) leaves the box +// boxMin..boxMax; `point` must lie in the box. A box that is flat on either axis returns the point. +int getIntersection(const Vec2& boxMin, const Vec2& boxMax, const Vec2& normal, const Vec2& point, Vec2& out) +{ + const float px = point.x; + const float x0 = boxMin.x; + if (px < x0) + return 0; + const float x1 = boxMax.x; + if (x1 < px) + return 0; + const float py = point.y; + const float y0 = boxMin.y; + if (py < y0) + return 0; + const float y1 = boxMax.y; + if (y1 < py) + return 0; + + const float dx = x1 - x0; + const float dy = y1 - y0; + if (dx == 0.0f || dy == 0.0f) + { + out.x = px; + out.y = py; + return 1; + } + + const float ny = normal.y; + const float nx = normal.x; + const float mnx = -nx; + const float c = -(ny * px + py * mnx); + const float at0 = ny * x0 + mnx * y0 + c; + const float at1 = ny * x1 + mnx * y1 + c; + if (normal.y <= 0.0f) + { + if (normal.y < 0.0f) + { + const float t = -at0 / (dx * ny); + if (0.0f <= t && t <= 1.0f) + { + out.y = y0; + out.x = x0 + dx * t; + return 1; + } + } + } + else + { + const float t = at1 / (dx * ny); + if (0.0f <= t && t <= 1.0f) + { + out.y = y1; + out.x = x1 - dx * t; + return 1; + } + } + + if (0.0f <= nx) + { + if (nx <= 0.0f) + return 0; + const float t = at1 / (dy * mnx); + if (t < 0.0f) + return 0; + if (1.0f < t) + return 0; + out.x = x1; + out.y = y1 - t * dy; + } + else + { + const float t = -at0 / (dy * mnx); + if (t < 0.0f || 1.0f < t) + return 0; + out.x = x0; + out.y = t * dy + y0; + } + return 1; +} + +// ELF 0x2B0C30. Stepped proportional-derivative regulator for a linear quantity: `rate` is the +// change of `current` per second, the error is taken at the look-ahead point, and the step factor +// depends on the error relative to |target| in units of `scale`. `control` is clamped to [-1, 1]. +void updateLinear(float target, float current, float previous, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = (current - previous) / dt; + float error = target - (lookAhead * rate + current); + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + float relative = error; + if (target != 0.0f) + relative = error / std::fabs(target); + + float step; + if (0.0f < rate * sign) + { + // already moving towards the target + if (relative < scale * 0.01f) + step = 0.02f; + else if (relative < scale * 0.05f) + step = 0.27f; + else + step = (relative < scale * 0.1f) ? 0.55f : 1.0f; + } + else + { + if (relative < scale * 0.01f) + return; + if (relative < scale * 0.05f) + step = 0.02f; + else if (relative < scale * 0.1f) + step = 0.27f; + else + step = (relative < scale * 0.4f) ? 0.55f : 1.0f; + } + control = control - step * dt * sign * gain * error; + control = clampUnit(control); +} + +// ELF 0x2B0DF0. Same computation as updateLinear (see the file comment). +void updateLinearDebug(float target, float current, float previous, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = (current - previous) / dt; + float error = target - (lookAhead * rate + current); + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + float relative = error; + if (target != 0.0f) + relative = error / std::fabs(target); + + float step; + if (0.0f < rate * sign) + { + if (relative < scale * 0.01f) + step = 0.02f; + else if (relative < scale * 0.05f) + step = 0.27f; + else + step = (relative < scale * 0.1f) ? 0.55f : 1.0f; + } + else + { + if (relative < scale * 0.01f) + return; + if (relative < scale * 0.05f) + step = 0.02f; + else if (relative < scale * 0.1f) + step = 0.27f; + else + step = (relative < scale * 0.4f) ? 0.55f : 1.0f; + } + control = control - step * dt * sign * gain * error; + control = clampUnit(control); +} + +// ELF 0x2B0FE0. Angle regulator: `angle` is the remaining angle (radians), `angleChange` its change +// over the last frame. The thresholds are 0.5, 1, 2 and 4 degrees times `scale`; the gains are +// 0.01, 0.2, 0.5, 0.8, 1 and 1.5 times 180/pi (57.2957764). +void updateAngle(float angle, float angleChange, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + float error = rate * lookAhead + angle; + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + + float k; + if (0.0f < rate * sign) + { + if (error < scale * 0.0174532924f) + k = 28.6478882f; + else + k = (scale * 0.0349065848f <= error) ? 85.9436646f : 57.2957764f; + } + else + { + if (error < scale * 0.00872664619f) + return; + if (error < scale * 0.0174532924f) + k = 0.572957754f; + else if (error < scale * 0.0349065848f) + k = 11.4591551f; + else + k = (scale * 0.0698131695f <= error) ? 57.2957764f : 45.8366203f; + } + control = control - sign * gain * dt * error * k; + control = clampUnit(control); +} + +// ELF 0x2B1170. Same computation as updateAngle. +void updateAngleDebug(float angle, float angleChange, float& control, float gain, float lookAhead, float scale) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + float error = rate * lookAhead + angle; + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + + float k; + if (0.0f < rate * sign) + { + if (error < scale * 0.0174532924f) + k = 28.6478882f; + else + k = (scale * 0.0349065848f <= error) ? 85.9436646f : 57.2957764f; + } + else + { + if (error < scale * 0.00872664619f) + return; + if (error < scale * 0.0174532924f) + k = 0.572957754f; + else if (error < scale * 0.0349065848f) + k = 11.4591551f; + else + k = (scale * 0.0698131695f <= error) ? 57.2957764f : 45.8366203f; + } + control = control - sign * gain * dt * error * k; + control = clampUnit(control); +} + +// ELF 0x2B1320. Intersection of the axis-aligned segment c..d with the box a..b. When `axis` +// differs from `lineAxis` the result is the single crossing point out1 (isSegment = false); +// otherwise the segment runs along `axis` and the result is the overlap out1..out2 (isSegment = true). +int getLineIntersections(Vec2& a, Vec2& b, Vec2& c, Vec2& d, Vec2& out1, Vec2& out2, bool& isSegment, int axis, int lineAxis) +{ + if (axis != lineAxis) + { + const float fixed = axisOf(a, lineAxis); + if (fixed < axisOf(c, lineAxis)) + return 0; + if (axisOf(d, lineAxis) < fixed) + return 0; + const float v = axisOf(c, axis); + if (v < axisOf(a, axis)) + return 0; + if (v <= axisOf(b, axis)) + { + axisOf(out1, axis) = v; + axisOf(out1, lineAxis) = axisOf(a, lineAxis); + isSegment = false; + return 1; + } + return 0; + } + + const int o = (axis + 1) % 2; + if (axisOf(d, o) != axisOf(c, o)) + return 0; + const float dv = axisOf(d, axis); + if (dv <= axisOf(a, axis)) + return 0; + const float bv = axisOf(b, axis); + if (bv < axisOf(c, axis)) + return 0; + out1 = (axisOf(c, axis) <= axisOf(a, axis)) ? a : c; + out2 = (dv <= bv) ? d : b; + isSegment = true; + return 1; +} + +// ELF 0x2B1490. Overlap of the boxes aMin..aMax and bMin..bMax, as the segment outMin..outMax. +int getBoxIntersections(Vec2& aMin, Vec2& aMax, Vec2& bMin, Vec2& bMax, Vec2& outMin, Vec2& outMax) +{ + float lo, hi, other; + bool spans; + if (!boxAxisIntersection(aMin, aMax, bMin, bMax, 0, lo, hi, spans, other)) + return 0; + outMin.x = lo; + outMax.x = hi; + if (spans) + { + outMin.y = other; + outMax.y = other; + return 1; + } + if (!boxAxisIntersection(aMin, aMax, bMin, bMax, 1, lo, hi, spans, other)) + return 0; + outMin.y = lo; + outMax.y = hi; + if (spans) + { + outMin.x = other; + outMax.x = other; + } + return 1; +} + +// ELF 0x2B17E0 +bool isInBox(const Vec2& point, const Vec2& boxMin, const Vec2& boxMax) +{ + bool aboveMin = false; + if (boxMin.x <= point.x && boxMin.y <= point.y) + aboveMin = true; + bool insideX = false; + if (aboveMin && point.x <= boxMax.x) + insideX = true; + return insideX && point.y <= boxMax.y; +} + +// ELF 0x2B1870. The angle regulator with an outer limit: the level is the larger of the remaining +// angle in units of `limitDegrees` and |limitValue| / limitRange. +void updateAngleOuterLimit(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float limitValue, float limitRange) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(limitValue) / limitRange; + if (std::fabs(limitValue) / limitRange <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1930. Same computation as updateAngleOuterLimit. +void updateAngleOuterLimitDebug(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float limitValue, float limitRange) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(limitValue) / limitRange; + if (std::fabs(limitValue) / limitRange <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1A00. The angle regulator limited by the angular rate: the level is the larger of the +// remaining angle in units of `limitDegrees` and |rate| / maxRate. +void updateAngleAccelerationLimit(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float maxRate) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(rate) / maxRate; + if (std::fabs(rate) / maxRate <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1AC0. Same computation as updateAngleAccelerationLimit. +void updateAngleAccelerationLimitDebug(float angle, float angleChange, float& control, float gain, float lookAhead, float limitDegrees, float maxRate) +{ + const float dt = frameTime(); + const float rate = angleChange / dt; + const float error = rate * lookAhead + angle; + float sign; + if (error <= 0.0f) + sign = (error < 0.0f) ? -1.0f : 0.0f; + else + sign = 1.0f; + const float ratio = error / (limitDegrees * 0.0174532924f); + float level = std::fabs(rate) / maxRate; + if (std::fabs(rate) / maxRate <= ratio) + level = ratio; + internalAngle(error, level, sign * gain * dt, rate, control); +} + +// ELF 0x2B1B90. The stepped gain of the limited angle regulators; `level` is in limit units +// (thresholds 0.5, 1, 2, 4). +void internalAngle(float error, float level, float factor, float rate, float& control) +{ + const float sign = signOf(error); + if (error < 0.0f) + error = -error; + + float k; + if (0.0f < sign * rate) + { + if (level < 1.0f) + k = 28.6478882f; + else + k = (level < 2.0f) ? 57.2957764f : 85.9436646f; + } + else + { + if (level < 0.5f) + return; + if (level < 1.0f) + k = 0.572957754f; + else if (level < 2.0f) + k = 11.4591551f; + else + k = (level < 4.0f) ? 45.8366203f : 57.2957764f; + } + control = control - factor * error * k; + control = clampUnit(control); +} + +// ELF 0x2B1CE0. Adaptive bang-bang regulator. It estimates the response `gain` (rate change per +// second per unit of the last control change, low-pass 0.8/0.2, accepted only when it is below +// twice the current estimate or the estimate is still ~0), predicts the travel until the rate is +// zero and pushes, brakes or coasts. `previousValue`/`previousRate` are the caller's state. +void regulator(float target, float current, float& previousValue, float& previousRate, float& controlChange, float& gain, float strength, float& control) +{ + const float dt = frameTime(); + const float rate = (previousValue - current) / dt; + float g; + if (controlChange == 0.0f) + { + g = gain; + } + else + { + const float measured = ((rate - previousRate) / dt) / controlChange; + g = gain; + if (std::fabs(measured) < std::fabs(g) + std::fabs(g) || g < 1e-06f) + { + g = g * 0.8f + measured * 0.2f; + gain = g; + } + } + + const float diff = target - current; + const float sign = signOf(diff); + const float time = rate / std::fabs(g); + const float travel = -sign * g * time * time + rate * time; + const float remaining = target - (current + travel); + const float remainingSign = signOf(remaining); + if (remaining != 0.0f) + { + float next; + if (sign != remainingSign) + { + controlChange = strength * sign + control; + next = -sign * strength; + } + else + { + if (std::fabs(travel) * 10.0f <= std::fabs(diff)) + { + controlChange = control - sign * strength; + control = sign * strength; + previousValue = current; + previousRate = rate; + return; + } + next = (((rate * time + std::fabs(diff)) * -2.0f) / (time * time)) * strength * sign; + controlChange = control - next; + } + control = next; + } + previousValue = current; + previousRate = rate; +} + +// ELF 0x2B1EF0. A retired regulator: it clamps `value` into `control` and then reports that it +// must not be used (an Error Debug, which aborts in this build). +void changeReg(float value, float, float, float, float&, float& control) +{ + static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); // result unused + control = value; + control = clampUnit(value); + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp", 1065, "") + << "Not using changeReg!"; +} + +// ELF 0x2B2030. Clamped proportional step: -1 below -1, else 1 above 1, else the difference (NaN +// passes through, unlike clampUnit: the order of the two tests is reversed here). +void simpleReg(float target, float current, float, float& control) +{ + const float diff = target - current; + if (-1.0f > diff) + control = -1.0f; + else + control = (diff > 1.0f) ? 1.0f : diff; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.h new file mode 100644 index 000000000..9b66ceaf3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.h @@ -0,0 +1,47 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_CONTROLFUNCTIONS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_CONTROLFUNCTIONS_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class BAPAMoveTo; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +int getIntersection(const Vec2&, const Vec2&, const Vec2&, const Vec2&, Vec2&); // 0x2B09C0; [INFERRED] ELF int +void updateLinear(float, float, float, float&, float, float, float); // 0x2B0C30; [INFERRED] ELF void +void updateLinearDebug(float, float, float, float&, float, float, float); // 0x2B0DF0; [INFERRED] ELF void +void updateAngle(float, float, float&, float, float, float); // 0x2B0FE0; [INFERRED] ELF void +void updateAngleDebug(float, float, float&, float, float, float); // 0x2B1170; [INFERRED] ELF void +int getLineIntersections(Vec2&, Vec2&, Vec2&, Vec2&, Vec2&, Vec2&, bool&, int, int); // 0x2B1320; [INFERRED] ELF int +int getBoxIntersections(Vec2&, Vec2&, Vec2&, Vec2&, Vec2&, Vec2&); // 0x2B1490; [INFERRED] ELF int +bool isInBox(const Vec2&, const Vec2&, const Vec2&); // 0x2B17E0; [INFERRED] ELF bool +void updateAngleOuterLimit(float, float, float&, float, float, float, float, float); // 0x2B1870; [INFERRED] ELF void +void updateAngleOuterLimitDebug(float, float, float&, float, float, float, float, float); // 0x2B1930; [INFERRED] ELF void +void updateAngleAccelerationLimit(float, float, float&, float, float, float, float); // 0x2B1A00; [INFERRED] ELF void +void updateAngleAccelerationLimitDebug(float, float, float&, float, float, float, float); // 0x2B1AC0; [INFERRED] ELF void +void internalAngle(float, float, float, float, float&); // 0x2B1B90; [INFERRED] ELF void +void regulator(float, float, float&, float&, float&, float&, float, float&); // 0x2B1CE0; [INFERRED] ELF void +void changeReg(float, float, float, float, float&, float&); // 0x2B1EF0; [INFERRED] ELF void +void simpleReg(float, float, float, float&); // 0x2B2030; [INFERRED] ELF void + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_CONTROLFUNCTIONS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp new file mode 100644 index 000000000..caca2d08d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp @@ -0,0 +1,101 @@ +// Boat movement entry for BAPAMoveTo. Attested TU: EntryBoatMoveTo.cpp. + +// static init: ELF 0x2B2520 (__tcf_0 0x2B2580, _GLOBAL__I 0x2B25B0): 's Init object only. +#include + +#include "EntryBoatMoveTo.h" + +#include "BoatControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B2150 (C1; C2 0x2B2130). +EntryBoatMoveTo::EntryBoatMoveTo() +{ +} + +// ELF 0x2B2190 (D1; D2 0x2B2170, D0 0x2B21B0). +EntryBoatMoveTo::~EntryBoatMoveTo() +{ +} + +// ELF 0x2B2630. +int EntryBoatMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B21F0. The boat entry updates the path, releases movement inputs on arrival or failure, +// and otherwise steers towards the next point. resetControls may also update done. +bool EntryBoatMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Vec2 point; + point.x = point.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info || !info->getMobile() || !info->getPhysical()) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + if (!info->getMobile() || !info->getControlInfo()) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + done = true; + return true; + } + if (arrived || done) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + Vec2 direction; + direction.x = point.x - position.x; + direction.y = point.y - position.y; + const float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + ok = static_cast(BoatControl::towardsDirection(bot, info, direction, distance, moveTo, bot->getInput(), 1e9f)) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.h new file mode 100644 index 000000000..1cb834cf9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.h @@ -0,0 +1,27 @@ +// Boat movement entry for BAPAMoveTo. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatMoveTo - statement type 7. +class EntryBoatMoveTo : public BAPEntry +{ +public: + EntryBoatMoveTo(); + virtual ~EntryBoatMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp new file mode 100644 index 000000000..3f72730b2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp @@ -0,0 +1,129 @@ +// EntryBoatMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B31E0 (__tcf_0 0x2B3240, _GLOBAL__I 0x2B3270): 's Init object only. +#include + +#include "EntryBoatMoveToDirection.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveToDirection.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B2660 (C1; C2 0x2B2640). +EntryBoatMoveToDirection::EntryBoatMoveToDirection() +{ +} + +// ELF 0x2B26A0 (D1; D2 0x2B2680, D0 0x2B26C0). +EntryBoatMoveToDirection::~EntryBoatMoveToDirection() +{ +} + +// ELF 0x2B3290. +int EntryBoatMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2B2700. +bool EntryBoatMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveToDirection* const moveTo = static_cast(script); + Vec2 position = {0.0f, 0.0f}; + Vec2 facing = {0.0f, 0.0f}; + Vec2 normal = {0.0f, 0.0f}; + Vec2 point = {0.0f, 0.0f}; + Vec2 targetFacing = {0.0f, 0.0f}; + Vec2 targetNormal = {0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + const Mat4 transformation = info->getTransformation(); + const Vec3 forward = {transformation.m[8], transformation.m[9], transformation.m[10]}; + const Vec3 position3 = info->getPosition(); + const float magnitude = info->getMobile()->getSpeedMagnitude(); + const Vec3& speed = info->getMobile()->getSpeed(); + const float speedDot = forward.x * speed.x + forward.y * speed.y + forward.z * speed.z; + const float sign = speedDot > 0.0f ? 1.0f : (speedDot < 0.0f ? -1.0f : 0.0f); + const float signedSpeed = sign * magnitude; + const float radius = info->getMobile()->getTurnRadius(); + // The shipped caller stores only al and continues regardless of the update result. + ok = static_cast(moveTo->update(point, done)) != 0; + vec3ToVec2XZ(position3, position); + vec3ToVec2XZ(forward, facing); + vec3ToVec2XZ(moveTo->m_direction, targetFacing); + getNormal(facing, normal); + vehiclecontrol::normalizeVec2(normal); + getNormal(targetFacing, targetNormal); + vehiclecontrol::normalizeVec2(targetNormal); + Vec2 direction = {(radius * targetNormal.x + point.x) - (radius * normal.x + position.x), + (radius * targetNormal.y + point.y) - (radius * normal.y + position.y)}; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (length > 1e-05f) + { + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + } + const auto clampCos = [](float value) { + if (value < -1.0f) return -1.0f; + if (value > 1.0f) return 1.0f; + return value; + }; + float targetAngle = 0.0f; + if (length < radius * 0.2f) + moveTo->unimplementedDirectionSlot11(2); + else + { + targetAngle = std::acos(clampCos(direction.x * normal.x + direction.y * normal.y)) - 1.5707964f; + if (direction.x * facing.x + direction.y * facing.y < 0.0f) + { + const float angleSign = targetAngle > 0.0f ? 1.0f : (targetAngle < 0.0f ? -1.0f : 0.0f); + targetAngle = angleSign * 3.1415927f - targetAngle; + } + if (moveTo->unimplementedDirectionSlot10() == 1 || std::fabs(targetAngle) < 0.18325958f) + moveTo->unimplementedDirectionSlot11(1); + else + targetAngle = -1.5707964f; + } + const float maximum = info->getMobile()->getMaxSpeed(); + info->getMobile()->getVehicleNumber(); + io::PlayerInput* const input = bot->getInput(); + float turnInput = (input->mappingFlags & 1ULL) ? input->inputs[0] : 0.0f; + float throttle = (input->mappingFlags & 8ULL) ? input->inputs[3] : 0.0f; + const float previousDot = normal.x * moveTo->m_state68.y + normal.y * moveTo->m_state68.z; + updateAngle(targetAngle, std::acos(clampCos(previousDot)) - 1.5707964f, turnInput, 1.0f, 1.0f, 1.5f); + updateLinear(maximum, signedSpeed, moveTo->m_state68.x, throttle, -1.0f, 1.0f, 1.0f); + moveTo->m_state68.y = facing.x; + moveTo->m_state68.z = facing.y; + moveTo->m_state68.x = signedSpeed; + io::PlayerInput* const output = bot->getInput(); + if (output->mappingFlags & 1ULL) + output->inputs[0] = turnInput; + bot->getInput()->setInput(static_cast(3), throttle); + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.h new file mode 100644 index 000000000..65a4f8831 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryBoatMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatMoveToDirection - statement type 8. +class EntryBoatMoveToDirection : public BAPEntry +{ +public: + EntryBoatMoveToDirection(); + virtual ~EntryBoatMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp new file mode 100644 index 000000000..27e918c28 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp @@ -0,0 +1,108 @@ +// Boat movement entry for an object target. Attested TU: EntryBoatMoveToObject.cpp. + +// static init: ELF 0x2B3710 (__tcf_0 0x2B3770, _GLOBAL__I 0x2B37A0): 's Init object only. +#include + +#include "EntryBoatMoveToObject.h" + +#include "BoatControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B32C0 (C1; C2 0x2B32A0). +EntryBoatMoveToObject::EntryBoatMoveToObject() +{ +} + +// ELF 0x2B3300 (D1; D2 0x2B32E0, D0 0x2B3320). +EntryBoatMoveToObject::~EntryBoatMoveToObject() +{ +} + +// ELF 0x2B37C0. +int EntryBoatMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B3360. A missing target finishes successfully. On the movement path the position is +// read both before isFinished and after update; a stuck move asks the game effector to suicide. +bool EntryBoatMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Vec2 point; + point.x = point.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info || !info->getMobile() || !info->getPhysical()) + { + done = true; + ok = false; + return true; + } + if (!informationManager->getInformation(moveTo->getObject())) + { + done = true; + ok = true; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + vec3ToVec2XZ(info->getPosition(), position); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + done = true; + return true; + } + if (arrived || done) + { + ok = static_cast(BoatControl::resetControls(bot, true, false, false, done)) != 0; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + Vec2 direction; + direction.x = point.x - position.x; + direction.y = point.y - position.y; + const float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + ok = static_cast(BoatControl::towardsDirection(bot, info, direction, distance, moveTo, bot->getInput(), 1e9f)) != 0; + if (moveTo->isStuck()) + { + IAIPlayer* const player = bot->getPlayer(); + static_cast(CommonSingletonServer::m_iaiGameEffector)->suicide(player); + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.h new file mode 100644 index 000000000..f69ff5d17 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.h @@ -0,0 +1,27 @@ +// Boat movement entry for an object target. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatMoveToObject - statement type 9. +class EntryBoatMoveToObject : public BAPEntry +{ +public: + EntryBoatMoveToObject(); + virtual ~EntryBoatMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp new file mode 100644 index 000000000..900f610f8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp @@ -0,0 +1,56 @@ +// EntryBoatResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B3AC0 (__tcf_0 0x2B3B20, _GLOBAL__I 0x2B3B50): 's Init object only. +#include + +#include "EntryBoatResetControls.h" + +#include "BoatControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryBoatResetControls::EntryBoatResetControls() +{ +} + +EntryBoatResetControls::~EntryBoatResetControls() +{ +} + +int EntryBoatResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B3890 (Ghidra). A single-input reset releases that one input and succeeds. The group +// form hands `done` to BoatControl::resetControls, which clears it while the boat still has to +// brake; `ok` is that call's answer. +bool EntryBoatResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + ok = BoatControl::resetControls(bot, reset->m_resetMove, reset->m_resetLook, reset->m_resetTrigger, + done) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.h new file mode 100644 index 000000000..91de4a7f4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.h @@ -0,0 +1,28 @@ +// EntryBoatResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryBoatResetControls - statement type 14. +class EntryBoatResetControls : public BAPEntry +{ +public: + EntryBoatResetControls(); + virtual ~EntryBoatResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYBOATRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp new file mode 100644 index 000000000..d1de33927 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp @@ -0,0 +1,199 @@ +// EntryCarMoveTo (attested TU `EntryCarMoveTo.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a car +// along a BAPAMoveTo. execute's flags follow the BotScript convention: `ok` (the step ran) and +// `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2B43A0 (__tcf_0 0x2B4400, _GLOBAL__I 0x2B4430): the guard object only. + +#include "EntryCarMoveTo.h" + +#include "CarControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarMoveTo::EntryCarMoveTo() +{ +} + +EntryCarMoveTo::~EntryCarMoveTo() +{ +} + +int EntryCarMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B3C40 (listing; Ghidra cross-check). Every second at most it asks the move whether it is +// finished; otherwise it updates the move and steers towards the returned point: +// CarControl::actionStatusDecision chooses the action (a first output of 666 means stop: reset the +// controls and finish), then controlTowardsDirection drives at the mobile's max speed scaled by +// the slower of a turn factor (1 - min(1, 1.8 * max(0, |largest angle diff| - startAngle)) * +// speedScale, while faster than 1 m/s) and an approach factor ((distance - smallest radius - 0.5)^2 +// / 225, at least 0.2, inside 15 m). Arrival, a finished move and a failed update reset the +// controls with the speed along the facing. +bool EntryCarMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float startAngle = 0.2f; // .data 0x4BCD64 + static float speedScale = 0.8f; // .data 0x4BCD68 + + BAPAMoveTo* const moveTo = static_cast(script); + ok = true; + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + IPIMobile* const mobile = info->getMobile(); + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double last = static_cast(bot)->getLastCheckMoveToFinishedTime(); // Bot +0x274 (pure in Bot, declared on BotMain in this tree) + done = false; + if (now - last > 1.0) + { + static_cast(bot)->setLastCheckMoveToFinishedTime(now); // +0x270 + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + } + + Vec2 target; + target.x = target.y = 0.0f; + bool arrived; + ok = moveTo->update(target, done, arrived, 0.0f) != 0; + if (!ok) + { + // 0x2B42CD + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + // 0x2B3DF3 + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + // 0x2B3E6E + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = target.x - position.x; + toTarget.y = target.y - position.y; + Vec2 direction = toTarget; + float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-06f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + // A -0.0f store to an otherwise unread local follows here (0x2B3F81). + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 1.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + // 0x2B4266 + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - startAngle) + excess = std::fabs(largestAngle) - startAngle; + float scaled = excess * 1.8f; + if (1.0f < excess * 1.8f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * speedScale; + } + + float mode; + float angle; + float reference; + float limit; + ok = CarControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + // 0x2B41C2 + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + // 0x2B4012 + const float maxSpeed = mobile->getMaxSpeed(); + float approachFactor = 1.0f; + Vec2 speed2d; // computed, never read + speed2d.x = speed2d.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), speed2d); + Vec2 remaining; + remaining.x = target.x - position.x; + remaining.y = target.y - position.y; + const float remainingDistance = std::sqrt(remaining.x * remaining.x + remaining.y * remaining.y); + float gap = remainingDistance - physical->getSmallestRadius() - 0.5f; + if (gap <= 0.0f) + gap = 0.0f; + if (gap * gap < 225.0f) + { + float scale = gap * gap / 225.0f; + if (scale <= 0.2f) + scale = 0.2f; + approachFactor = scale; + } + if (turnFactor <= approachFactor) + approachFactor = turnFactor; + ok = CarControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), + approachFactor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.h new file mode 100644 index 000000000..9a28b31a4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.h @@ -0,0 +1,28 @@ +// EntryCarMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarMoveTo - statement type 7. +class EntryCarMoveTo : public BAPEntry +{ +public: + EntryCarMoveTo(); + virtual ~EntryCarMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp new file mode 100644 index 000000000..d1b34f557 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp @@ -0,0 +1,36 @@ +// EntryCarMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B4540 (__tcf_0 0x2B45A0, _GLOBAL__I 0x2B45D0): 's Init object only. +#include + +#include "EntryCarMoveToDirection.h" + +#include "../Main/AIDllFrontier.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarMoveToDirection::EntryCarMoveToDirection() +{ +} + +EntryCarMoveToDirection::~EntryCarMoveToDirection() +{ +} + +int EntryCarMoveToDirection::getTargetId() +{ + return 8; +} + +// A retail stub - see the block above. , and all it does is succeed. +bool EntryCarMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.h new file mode 100644 index 000000000..28f852f39 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.h @@ -0,0 +1,28 @@ +// EntryCarMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarMoveToDirection - statement type 8. +class EntryCarMoveToDirection : public BAPEntry +{ +public: + EntryCarMoveToDirection(); + virtual ~EntryCarMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp new file mode 100644 index 000000000..e396e1c36 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp @@ -0,0 +1,180 @@ +// EntryCarMoveToObject (attested TU `EntryCarMoveToObject.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a car +// to an object (a BAPAMoveTo with a target object). execute's flags follow the BotScript convention: `ok` (the step ran) and +// `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2B4E50 (__tcf_0 0x2B4EB0, _GLOBAL__I 0x2B4EE0): the guard object only. + +#include "EntryCarMoveToObject.h" + +#include "CarControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarMoveToObject::EntryCarMoveToObject() +{ +} + +EntryCarMoveToObject::~EntryCarMoveToObject() +{ +} + +int EntryCarMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B46C0 (Ghidra; listing for the statics). EntryCarMoveTo's steering for a move to an +// object: fails (done, not ok) without the target's information, the equipment or its mobile or +// physical part (the control part is not tested); asks isFinished on every call (no one-second +// throttle); the direction is normalised above 1e-05. +bool EntryCarMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float startAngle = 0.2f; // .data 0x4BCE24 + static float speedScale = 0.8f; // .data 0x4BCE28 + + BAPAMoveTo* const moveTo = static_cast(script); + ok = true; + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile; + IPIPhysical* physical; + if (!informationManager->getInformation(moveTo->getObject()) || !info || !(mobile = info->getMobile()) + || !(physical = info->getPhysical())) + { + done = true; + ok = false; + return true; + } + IPIControlInfo* const controlInfo = info->getControlInfo(); + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + if (!informationManager->getInformation(moveTo->getObject())) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + + Vec2 target; + target.x = target.y = 0.0f; + done = false; + bool arrived; + ok = moveTo->update(target, done, arrived, 0.0f) != 0; + if (!ok) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = target.x - position.x; + toTarget.y = target.y - position.y; + Vec2 direction = toTarget; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 1.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - startAngle) + excess = std::fabs(largestAngle) - startAngle; + float scaled = excess * 1.8f; + if (1.0f < excess * 1.8f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * speedScale; + } + + float mode; + float angle; + float reference; + float limit; + ok = CarControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = CarControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + const float maxSpeed = mobile->getMaxSpeed(); + float approachFactor = 1.0f; + Vec2 speed2d; // computed, never read + speed2d.x = speed2d.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), speed2d); + Vec2 remaining; + remaining.x = target.x - position.x; + remaining.y = target.y - position.y; + const float remainingDistance = std::sqrt(remaining.x * remaining.x + remaining.y * remaining.y); + float gap = remainingDistance - physical->getSmallestRadius() - 0.5f; + if (gap <= 0.0f) + gap = 0.0f; + if (gap * gap < 225.0f) + { + float scale = gap * gap / 225.0f; + if (scale <= 0.2f) + scale = 0.2f; + approachFactor = scale; + } + if (turnFactor <= approachFactor) + approachFactor = turnFactor; + ok = CarControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), + approachFactor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.h new file mode 100644 index 000000000..c9c825c68 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.h @@ -0,0 +1,28 @@ +// EntryCarMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarMoveToObject - statement type 9. +class EntryCarMoveToObject : public BAPEntry +{ +public: + EntryCarMoveToObject(); + virtual ~EntryCarMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp new file mode 100644 index 000000000..5f1a8632d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp @@ -0,0 +1,67 @@ +// EntryCarResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B52A0 (__tcf_0 0x2B5300, _GLOBAL__I 0x2B5330): 's Init object only. +#include + +#include "EntryCarResetControls.h" + +#include "CarControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryCarResetControls::EntryCarResetControls() +{ +} + +EntryCarResetControls::~EntryCarResetControls() +{ +} + +int EntryCarResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B4FD0 (listing). A single-input reset releases that one input (setInput inlined with its +// range diagnostic) and succeeds. The group form resets through CarControl::resetControls with +// the equipment's forward speed (mobile speed dot facing); the information lookup is not +// null-tested, and the mobile's speed, the facing and the transformation are asked for once more +// beforehand and discarded, as compiled. `ok` is that call's answer; `done` is always set. +bool EntryCarResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + done = true; + mobile->getSpeed(); // +0x1C, discarded + equipment->getFaceing(); // +0x40, discarded + equipment->getTransformation(); // +0x3C, discarded + const Vec3 facing = equipment->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + const float forwardSpeed = speed.y * facing.y + speed.x * facing.x + speed.z * facing.z; + ok = CarControl::resetControls(bot, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger, forwardSpeed) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.h new file mode 100644 index 000000000..663b2523a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.h @@ -0,0 +1,28 @@ +// EntryCarResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryCarResetControls - statement type 14. +class EntryCarResetControls : public BAPEntry +{ +public: + EntryCarResetControls(); + virtual ~EntryCarResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYCARRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp new file mode 100644 index 000000000..ef2034667 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp @@ -0,0 +1,201 @@ +// EntryHeliAimAt (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B6400 (__tcf_0 0x2B6460, _GLOBAL__I 0x2B6490): 's Init object only. +#include + +#include "EntryHeliAimAt.h" + +#include "HeliControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B5380 (C1; C2 0x2B5360). +EntryHeliAimAt::EntryHeliAimAt() +{ +} + +// ELF 0x2B53C0 (D1; D2 0x2B53A0, D0 0x2B53E0). +EntryHeliAimAt::~EntryHeliAimAt() +{ +} + +// ELF 0x2B64B0. +int EntryHeliAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2B5420. +bool EntryHeliAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt3d* const aim = static_cast(script); + ok = true; + done = false; + if (aim->m_condition->evaluate(bot)) + done = true; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + IPIArmament* const armament = info->getArmament(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + IPIMobile* const mobile = info->getMobile(); + Information* target = 0; + if (aim->getAimAtType() == 1) + { + target = informationManager->getInformation(static_cast(aim)->m_target); + if (!target) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + } + Vec3 direction = {0.0f, 0.0f, 1.0f}; + Vec3 firingDirection = {0.0f, 0.0f, 0.0f}; + const Mat4& origin = weapon->getProjectileOrigin(); + const Vec3& velocity = mobile->getSpeed(); + const Vec3& position = info->getPosition(); + // shipped defect: point-aim statements leave target null, yet it is read here. + const Vec3& targetPosition = target->getPosition(); + const float x = position.x - targetPosition.x; + const float y = position.y - targetPosition.y; + const float z = position.z - targetPosition.z; + const float distance = std::sqrt(x * x + y * y + z * z); + const bool airborne = (target->getObjectTypeFlags() & 0x10) != 0; + bool solved; + if (airborne) + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + solved = aim->getAimVec(origin, mobile->getSpeed(), direction, 0.5f, drag, speed, gravity, indirect); + if (solved) + { + firingDirection = direction; + vehiclecontrol::normalizeVec3(direction); + } + } + else + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + if (indirect) + { + const Vec3 stationary = {0.0f, 0.0f, 0.0f}; + solved = aim->getAimVec(origin, stationary, direction, 0.75f, drag, speed, gravity, false); + } + else + solved = aim->getAimVec(origin, velocity, direction, 0.5f, drag, speed, gravity, false); + if (solved) + { + firingDirection = direction; + if (indirect) + direction.y = 0.0f; + vehiclecontrol::normalizeVec3(direction); + } + } + if (!solved) + { + const bool found = aim->getVectorToTarget(info->getPosition(), direction); + if (!found && !airborne) + { + ok = false; + done = true; + } + vehiclecontrol::normalizeVec3(direction); + if (!found) + { + if (airborne) + { + ok = false; + done = true; + } + return true; + } + } + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const Vec3& speed = mobile->getSpeed(); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {(speed.x - aim->m_vecA8.x) * inverse, + (speed.y - aim->m_vecA8.y) * inverse, + (speed.z - aim->m_vecA8.z) * inverse}; + aim->m_vecA8 = speed; + Mat4 inverseOrigin = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + inverseOrigin.setInverse(origin); + const Vec3 localDirection = { + direction.x * inverseOrigin.m[0] + direction.y * inverseOrigin.m[4] + direction.z * inverseOrigin.m[8], + direction.x * inverseOrigin.m[1] + direction.y * inverseOrigin.m[5] + direction.z * inverseOrigin.m[9], + direction.x * inverseOrigin.m[2] + direction.y * inverseOrigin.m[6] + direction.z * inverseOrigin.m[10]}; + const Mat4& transform = info->getTransformation(); + const Vec3 steeringDirection = { + localDirection.x * transform.m[0] + localDirection.y * transform.m[4] + localDirection.z * transform.m[8], + localDirection.x * transform.m[1] + localDirection.y * transform.m[5] + localDirection.z * transform.m[9], + localDirection.x * transform.m[2] + localDirection.y * transform.m[6] + localDirection.z * transform.m[10]}; + // [INFERRED] inline clamp expansion; unordered input passes through these two tests. + const auto clamp = [](float value, float low, float high) { + return low > value ? low : (value > high ? high : value); + }; + if (aim->isAimVecValid()) + { + const Mat4& weaponUp = weapon->getAbsoluteTransformation(); + float dot = firingDirection.x * weaponUp.m[4] + firingDirection.y * weaponUp.m[5] + firingDirection.z * weaponUp.m[6]; + const float pitch = std::acos(clamp(clamp(dot, -1.0f, 1.0f), -1.0f, 1.0f)) - 1.5707964f; + const Mat4& weaponRight = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponRight.m[0] + firingDirection.y * weaponRight.m[1] + firingDirection.z * weaponRight.m[2]; + float yaw = std::acos(clamp(clamp(dot, -1.0f, 1.0f), -1.0f, 1.0f)) - 1.5707964f; + const Mat4& weaponForward = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponForward.m[8] + firingDirection.y * weaponForward.m[9] + firingDirection.z * weaponForward.m[10]; + if (dot < 0.0f) + yaw = (yaw < 0.0f ? -3.1415927f : 3.1415927f) - yaw; + aim->m_floats1AC[1] = pitch; + aim->m_floats1AC[0] = yaw; + } + else + { + aim->m_floats1AC[1] = 3.1415927f; + aim->m_floats1AC[0] = 3.1415927f; + } + aim->m_vec24 = info->getFaceing(); + const Mat4& right = info->getTransformation(); + aim->m_vec30 = {right.m[0], right.m[1], right.m[2]}; + const Mat4& up = info->getTransformation(); + aim->m_vec3C = {up.m[4], up.m[5], up.m[6]}; + aim->m_floats1AC[3] = info->getPosition().y; + const float difference = direction.y - aim->m_vec1C8.y; + // 0x2B5C45..0x2B5C59: ja then fcmovnbe, so a NaN difference passes through to asin. + const float asinInput = clamp(difference, -1.0f, 1.0f); + const float pitchRate = clamp(std::asin(asinInput) / dt, -0.1f, 0.1f); + aim->m_vec1C8 = direction; + ok = HeliControl::aimAtDirection(bot, steeringDirection, distance, aim->m_float1A4, acceleration, pitchRate) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.h new file mode 100644 index 000000000..22226cc07 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.h @@ -0,0 +1,27 @@ +// EntryHeliAimAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliAimAt - statement type 6. +class EntryHeliAimAt : public BAPEntry +{ +public: + EntryHeliAimAt(); + virtual ~EntryHeliAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp new file mode 100644 index 000000000..c8e4503d9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp @@ -0,0 +1,82 @@ +// EntryHeliMoveAwayFromObject (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B6830 (__tcf_0 0x2B6890, _GLOBAL__I 0x2B68C0): 's Init object only. +#include + +#include "EntryHeliMoveAwayFromObject.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveAwayFrom3dObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B64E0 (C1; C2 0x2B64C0). +EntryHeliMoveAwayFromObject::EntryHeliMoveAwayFromObject() +{ +} + +// ELF 0x2B6520 (D1; D2 0x2B6500, D0 0x2B6540). +EntryHeliMoveAwayFromObject::~EntryHeliMoveAwayFromObject() +{ +} + +// ELF 0x2B68E0. +int EntryHeliMoveAwayFromObject::getTargetId() +{ + return 10; +} + +// ELF 0x2B6580. +bool EntryHeliMoveAwayFromObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveAwayFrom3dObject* const moveAway = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + Information* const object = informationManager->getInformation(moveAway->m_object); + if (!info || !object) + { + done = true; + ok = false; + return true; + } + if (moveAway->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement continues and overwrites both flags. + } + else + done = false; + IPIMobile* const mobile = info->getMobile(); + const Mat4& transform = info->getTransformation(); + const Vec3& speed = mobile->getSpeed(); + const Vec3 change = {speed.x - moveAway->m_vec30.x, + speed.y - moveAway->m_vec30.y, + speed.z - moveAway->m_vec30.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveAway->m_vec30 = speed; + const Vec3 point = {transform.m[8] * 100.0f + transform.m[12], + 0.0f * 100.0f + transform.m[13], + transform.m[10] * 100.0f + transform.m[14]}; + ok = HeliControl::moveToPoint(bot, point, 25.0f, acceleration) != 0; + const float distance = moveAway->m_distance; + const Vec3 target = *moveAway->getFirstPoint(); + const float x = target.x - transform.m[12]; + const float z = target.z - transform.m[14]; + done = x * x + 0.0f + z * z > distance * distance; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.h new file mode 100644 index 000000000..8dea0a8e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.h @@ -0,0 +1,27 @@ +// EntryHeliMoveAwayFromObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVEAWAYFROMOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVEAWAYFROMOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveAwayFromObject - statement type 10. +class EntryHeliMoveAwayFromObject : public BAPEntry +{ +public: + EntryHeliMoveAwayFromObject(); + virtual ~EntryHeliMoveAwayFromObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVEAWAYFROMOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp new file mode 100644 index 000000000..d98730dd4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp @@ -0,0 +1,77 @@ +// EntryHeliMoveTo (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B6BB0 (__tcf_0 0x2B6C10, _GLOBAL__I 0x2B6C40): 's Init object only. +#include + +#include "EntryHeliMoveTo.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B6910 (C1; C2 0x2B68F0). +EntryHeliMoveTo::EntryHeliMoveTo() +{ +} + +// ELF 0x2B6950 (D1; D2 0x2B6930, D0 0x2B6970). +EntryHeliMoveTo::~EntryHeliMoveTo() +{ +} + +// ELF 0x2B6C60. +int EntryHeliMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B69B0. +bool EntryHeliMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3d* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Vec3 point = {0.0f, 0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + // shipped defect: missing equipment does not stop execution. + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + point = *moveTo->getFirstPoint(); + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 change = {speed.x - moveTo->m_vec3C.x, + speed.y - moveTo->m_vec3C.y, + speed.z - moveTo->m_vec3C.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveTo->m_vec3C = speed; + ok = HeliControl::moveToPoint(bot, point, moveTo->m_distance, acceleration) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.h new file mode 100644 index 000000000..66375d5c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.h @@ -0,0 +1,27 @@ +// EntryHeliMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveTo - statement type 7. +class EntryHeliMoveTo : public BAPEntry +{ +public: + EntryHeliMoveTo(); + virtual ~EntryHeliMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp new file mode 100644 index 000000000..71d81e1ac --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp @@ -0,0 +1,83 @@ +// EntryHeliMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B7260 (__tcf_0 0x2B72C0, _GLOBAL__I 0x2B72F0): 's Init object only. +#include + +#include "EntryHeliMoveToDirection.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dDirection.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B6C90 (C1; C2 0x2B6C70). +EntryHeliMoveToDirection::EntryHeliMoveToDirection() +{ +} + +// ELF 0x2B6CD0 (D1; D2 0x2B6CB0, D0 0x2B6CF0). +EntryHeliMoveToDirection::~EntryHeliMoveToDirection() +{ +} + +// ELF 0x2B7310. +int EntryHeliMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2B6D30. +bool EntryHeliMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dDirection* const moveTo = static_cast(script); + Mat4 transform = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + Mat4 transpose = transform; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + info->getMobile()->getTurnRadius(); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + transform = info->getTransformation(); + transpose.setTranspose(transform); + const Vec3 position = info->getPosition(); + (void)position; + info->getMobile()->getSpeedMagnitude(); + Vec3 point = moveTo->m_target; + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 change = {speed.x - moveTo->m_vector24.x, + speed.y - moveTo->m_vector24.y, + speed.z - moveTo->m_vector24.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveTo->m_vector24 = speed; + point.y = -99999.0f; + ok = HeliControl::moveToPoint(bot, point, moveTo->m_altitude, acceleration) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.h new file mode 100644 index 000000000..777b2619b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryHeliMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveToDirection - statement type 8. +class EntryHeliMoveToDirection : public BAPEntry +{ +public: + EntryHeliMoveToDirection(); + virtual ~EntryHeliMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp new file mode 100644 index 000000000..5916dc8cb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp @@ -0,0 +1,78 @@ +// EntryHeliMoveToObject (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2B7580 (__tcf_0 0x2B75E0, _GLOBAL__I 0x2B7610): 's Init object only. +#include + +#include "EntryHeliMoveToObject.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B7340 (C1; C2 0x2B7320). +EntryHeliMoveToObject::EntryHeliMoveToObject() +{ +} + +// ELF 0x2B7380 (D1; D2 0x2B7360, D0 0x2B73A0). +EntryHeliMoveToObject::~EntryHeliMoveToObject() +{ +} + +// ELF 0x2B7630. +int EntryHeliMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B73E0. +bool EntryHeliMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dObject* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement still drives the helicopter below. + } + else + done = false; + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 change = {speed.x - moveTo->m_vec34.x, + speed.y - moveTo->m_vec34.y, + speed.z - moveTo->m_vec34.z}; + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {change.x * inverse, change.y * inverse, change.z * inverse}; + moveTo->m_vec34 = speed; + const float distance = moveTo->m_distance; + const Vec3& point = *moveTo->getFirstPoint(); + ok = HeliControl::moveToPoint(bot, point, distance, acceleration) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.h new file mode 100644 index 000000000..bc1153fe9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.h @@ -0,0 +1,27 @@ +// EntryHeliMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliMoveToObject - statement type 9. +class EntryHeliMoveToObject : public BAPEntry +{ +public: + EntryHeliMoveToObject(); + virtual ~EntryHeliMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp new file mode 100644 index 000000000..c12fcf293 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp @@ -0,0 +1,60 @@ +// EntryHeliResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B7920 (__tcf_0 0x2B7980, _GLOBAL__I 0x2B79B0): 's Init object only. +#include + +#include "EntryHeliResetControls.h" + +#include "HeliControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryHeliResetControls::EntryHeliResetControls() +{ +} + +EntryHeliResetControls::~EntryHeliResetControls() +{ +} + +int EntryHeliResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B7700 (Ghidra). The bot's current equipment is looked up first and not used (only the +// virtual getCurrentEquipment call survives in the image). A single-input reset releases that one +// input; the group form resets through HeliControl::resetControls, ignores its answer, and sets +// `done` then `ok`. +bool EntryHeliResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + (void)equipment; + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + HeliControl::resetControls(bot, reset->m_resetMove, reset->m_resetLook, reset->m_resetTrigger); + done = true; + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.h new file mode 100644 index 000000000..0b3191097 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.h @@ -0,0 +1,28 @@ +// EntryHeliResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryHeliResetControls - statement type 14. +class EntryHeliResetControls : public BAPEntry +{ +public: + EntryHeliResetControls(); + virtual ~EntryHeliResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYHELIRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp new file mode 100644 index 000000000..bdcbc7a76 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp @@ -0,0 +1,103 @@ +// EntryInfanteryMoveTo (attested TU `EntryInfanteryMoveTo.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that executes a +// BAPAMoveTo for a soldier at full LOD. Package B; see docs/macos-ai-behaviour-plan.md. +// +// execute's two flags follow the BotScript convention: `ok` (the step ran) and `done` (the +// statement is finished; with ok == false it failed). + +// static init: ELF 0x2B7DC0 (__tcf_0 0x2B7E20, _GLOBAL__I 0x2B7E50): 's Init object only. +#include + +#include "EntryInfanteryMoveTo.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Vec3.h" +#include "../AIBot/SquadMember.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryMoveTo::EntryInfanteryMoveTo() +{ +} + +EntryInfanteryMoveTo::~EntryInfanteryMoveTo() +{ +} + +int EntryInfanteryMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2B7AA0 +bool EntryInfanteryMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + Vec2 dir; + dir.x = dir.y = 0.0f; + Vec2 unused; // [INFERRED] a zeroed local the image never reads (-0x48) + unused.x = unused.y = 0.0f; + Vec2 targetDir; + targetDir.x = targetDir.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile; + if (info == 0 || (mobile = info->getMobile()) == 0) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + vec3ToVec2XZ(info->getPosition(), position); + + if (bot->isFireAllowed() && moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool arrived; + ok = moveTo->update(dir, done, arrived, 0.0f) != 0; + if (ok) + { + if (arrived || done) + { + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + return true; + } + if (!moveTo->getTargetDir(bot, dir, targetDir, 0, false)) + { + infantry_detail::setSensingMoveDirection(bot->getSensingAgent(), targetDir); + removeZoom(bot); + const bool sprint = moveTo->getIsSprinting(); + infanteryControlThrottle(bot, bot->getInput(), + info->getControlInfo(), mobile->getMaxSpeed(), sprint); + if (info->getSoldierPose() == SPSwimming) + return true; + bot->requestSoldierPose(SPStanding, true); + return true; + } + } + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.h new file mode 100644 index 000000000..627339548 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.h @@ -0,0 +1,28 @@ +// EntryInfanteryMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryMoveTo - statement type 7. +class EntryInfanteryMoveTo : public BAPEntry +{ +public: + EntryInfanteryMoveTo(); + virtual ~EntryInfanteryMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp new file mode 100644 index 000000000..d01afa007 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp @@ -0,0 +1,36 @@ +// EntryInfanteryMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2B7F50 (__tcf_0 0x2B7FB0, _GLOBAL__I 0x2B7FE0): 's Init object only. +#include + +#include "EntryInfanteryMoveToDirection.h" + +#include "../Main/AIDllFrontier.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryMoveToDirection::EntryInfanteryMoveToDirection() +{ +} + +EntryInfanteryMoveToDirection::~EntryInfanteryMoveToDirection() +{ +} + +int EntryInfanteryMoveToDirection::getTargetId() +{ + return 8; +} + +// A retail stub - see the block above. , and all it does is succeed. +bool EntryInfanteryMoveToDirection::execute(BotScript *, Bot *, bool&, bool&) +{ + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.h new file mode 100644 index 000000000..a78f5829e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.h @@ -0,0 +1,28 @@ +// EntryInfanteryMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryMoveToDirection - statement type 8. +class EntryInfanteryMoveToDirection : public BAPEntry +{ +public: + EntryInfanteryMoveToDirection(); + virtual ~EntryInfanteryMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp new file mode 100644 index 000000000..5298337e8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp @@ -0,0 +1,129 @@ +// EntryInfanteryMoveToObject (attested TU `EntryInfanteryMoveToObject.cpp`, split out of +// BAPEntries.cpp by S0). Recovered from libaidll.so (Linux 1.5.3153, ia-32): the full-LOD soldier +// entry for BAPAMoveToObject (statement type 9). Package B; see docs/macos-ai-behaviour-plan.md. +// Flags as in EntryInfanteryMoveTo: `ok` (the step ran), `done` (finished; failed when !ok). + +// static init: ELF 0x2B8550 (__tcf_0 0x2B85B0, _GLOBAL__I 0x2B85E0): 's Init object only. +#include + +#include "EntryInfanteryMoveToObject.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryMoveToObject::EntryInfanteryMoveToObject() +{ +} + +EntryInfanteryMoveToObject::~EntryInfanteryMoveToObject() +{ +} + +int EntryInfanteryMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2B80D0 +bool EntryInfanteryMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + BotMain* botMain = static_cast(bot); + Vec2 dir; + dir.x = dir.y = 0.0f; + Vec2 unused; // [INFERRED] a zeroed local the image never reads (-0x48) + unused.x = unused.y = 0.0f; + Vec2 targetDir; + targetDir.x = targetDir.y = 0.0f; + Vec2 position; + position.x = position.y = 0.0f; + + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* mobile; + if (info == 0 || (mobile = info->getMobile()) == 0) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + + if (informationManager->getInformation(static_cast(moveTo->getObject())) == 0) + { + done = true; + ok = false; + return true; + } + if (bot->isFireAllowed() && moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + + // BotMain +0x21C/+0x218/+0x220/+0x22C/+0x228, named as in AIBot/BotMain.h + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now - botMain->getTimeOfLastFailedStaticSkyAttack() < 1.5) + { + botMain->setTimeOfLastFailedStaticAttack(now); + } + else if (botMain->getBotWantsToSimulateArtillery()) + { + botMain->setTimeOfLastFailedStaticSkyAttack(now); + botMain->setBotWantsToSimulateArtillery(false); + } + + vec3ToVec2XZ(info->getPosition(), position); + bool arrived; + ok = moveTo->update(dir, done, arrived, 0.0f) != 0; + if (ok) + { + if (arrived || done) + { + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + return true; + } + Information* target = informationManager->getInformation(static_cast(moveTo->getObject())); + const bool movingAway = moveTo->getIsMovingAway(); + if (!moveTo->getTargetDir(bot, dir, targetDir, target, movingAway)) + { + infantry_detail::setSensingMoveDirection(bot->getSensingAgent(), targetDir); + removeZoom(bot); + const bool sprint = moveTo->getIsSprinting(); + infanteryControlThrottle(bot, bot->getInput(), + info->getControlInfo(), mobile->getMaxSpeed(), sprint); + if (info->getSoldierPose() != SPSwimming) + bot->requestSoldierPose(SPStanding, true); + if (moveTo->isStuck()) + { + // a stuck soldier gives up: IAIGameEffector +0x30 + static_cast(CommonSingletonServer::m_iaiGameEffector)->suicide(bot->getPlayer()); + } + return true; + } + } + ok = infanteryResetControls(bot, bot->getInput(), true, false, false); + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.h new file mode 100644 index 000000000..22337963a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.h @@ -0,0 +1,28 @@ +// EntryInfanteryMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryMoveToObject - statement type 9. +class EntryInfanteryMoveToObject : public BAPEntry +{ +public: + EntryInfanteryMoveToObject(); + virtual ~EntryInfanteryMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp new file mode 100644 index 000000000..d0c7fcfc3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp @@ -0,0 +1,57 @@ +// EntryInfanteryResetControls (attested TU `EntryInfanteryResetControls.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPAResetControls (statement type 14). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2B8900 (__tcf_0 0x2B8960, _GLOBAL__I 0x2B8990): 's Init object only. +#include + +#include "EntryInfanteryResetControls.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfanteryResetControls::EntryInfanteryResetControls() +{ +} + +EntryInfanteryResetControls::~EntryInfanteryResetControls() +{ +} + +int EntryInfanteryResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2B86D0. A single-input reset releases that one input (the image inlines setInput(index, +// 0.0f) with its "1 setInput out of range" diagnostic); the group form resets through +// infanteryResetControls. Always succeeds and finishes at once. +bool EntryInfanteryResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + } + else + { + // 0x2B88C0: movzbl +0x14 / +0x15 / +0x16 -> (move, look, trigger) + infanteryResetControls(bot, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger); + } + ok = true; + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.h new file mode 100644 index 000000000..1aa2ed6ab --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.h @@ -0,0 +1,28 @@ +// EntryInfanteryResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfanteryResetControls - statement type 14. +class EntryInfanteryResetControls : public BAPEntry +{ +public: + EntryInfanteryResetControls(); + virtual ~EntryInfanteryResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFANTERYRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp new file mode 100644 index 000000000..f39c6b0f4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp @@ -0,0 +1,41 @@ +// EntryInfoWrapper (attested TU `EntryInfoWrapper.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the entry for BAPInfoWrapper (statement type 15). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2B8AE0 (__tcf_0 0x2B8B40, _GLOBAL__I 0x2B8B70): 's Init object only. +#include + +#include "EntryInfoWrapper.h" + +#include "PlanInterpreter.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryInfoWrapper::EntryInfoWrapper() +{ +} + +EntryInfoWrapper::~EntryInfoWrapper() +{ +} + +int EntryInfoWrapper::getTargetId() +{ + return 15; +} + +// ELF 0x2B8A80. Runs the wrapped statement through the bot's plan interpreter (PlanInterpreter +8). +bool EntryInfoWrapper::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BotScript* inner = static_cast(script)->m_statement; // 0x2B8A98 +0x14 + return static_cast(bot)->getPlanInterpreter()->execute(inner, bot, ok, done); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.h new file mode 100644 index 000000000..d6c5f1dec --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.h @@ -0,0 +1,28 @@ +// EntryInfoWrapper: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFOWRAPPER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFOWRAPPER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryInfoWrapper - statement type 15. +class EntryInfoWrapper : public BAPEntry +{ +public: + EntryInfoWrapper(); + virtual ~EntryInfoWrapper(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYINFOWRAPPER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp new file mode 100644 index 000000000..c96b103ff --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp @@ -0,0 +1,147 @@ +// Key-driven turret aiming entry for BAPAAimAt. Attested TU: EntryKeyTurretAimAt.cpp. + +// static init: ELF 0x2B9580 (__tcf_0 0x2B95E0, _GLOBAL__I 0x2B9610): 's Init object only. +#include + +#include "EntryKeyTurretAimAt.h" + +#include "ControlFunctions.h" +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAAimAt.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2B8BC0 (C1; C2 0x2B8BA0). +EntryKeyTurretAimAt::EntryKeyTurretAimAt() +{ +} + +// ELF 0x2B8C00 (D1; D2 0x2B8BE0, D0 0x2B8C20). +EntryKeyTurretAimAt::~EntryKeyTurretAimAt() +{ +} + +// ELF 0x2B9630. +int EntryKeyTurretAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2B8C60. Drives mapped pitch and yaw inputs from the weapon-relative aim vector and +// their previous errors. The plain target-vector fallback is used without normalising it. +bool EntryKeyTurretAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt* const aim = static_cast(script); + Vec3 direction; + direction.x = direction.y = direction.z = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + if (aim->m_endCondition->evaluate(bot)) + { + done = true; + ok = true; + aim->m_lastYawError = 3.141592741f; + return true; + } + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + aim->m_lastYawError = 3.141592741f; + return true; + } + IPIArmament* const armament = info->getArmament(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + const Mat4& transformation = weapon->getAbsoluteTransformation(); + IPIMobile* mobile = info->getMobile(); + if (!mobile && !info->isPrimary()) + { + Information* const primary = informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + if (primary) + mobile = primary->getMobile(); + } + if (mobile) + ownSpeed = mobile->getSpeed(); + const Mat4& origin = weapon->getProjectileOrigin(); + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float velocity = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + if (!aim->getAimVec(origin, ownSpeed, direction, 0.5f, drag, velocity, gravity, indirect, bot)) + { + const Vec3& position = *reinterpret_cast(&transformation.m[12]); + if (!aim->getVectorToTarget(position, direction)) + { + done = true; + ok = false; + aim->m_lastYawError = 3.141592741f; + return true; + } + } + float pitchDot = direction.x * transformation.m[4] + direction.y * transformation.m[5] + + direction.z * transformation.m[6]; + if (pitchDot < -1.0f) + pitchDot = -1.0f; + else if (pitchDot > 1.0f) + pitchDot = 1.0f; + const float pitchError = acosf(pitchDot) - 1.570796371f; + float yawDot = direction.x * transformation.m[0] + direction.y * transformation.m[1] + + direction.z * transformation.m[2]; + if (yawDot < -1.0f) + yawDot = -1.0f; + else if (yawDot > 1.0f) + yawDot = 1.0f; + float yawError = acosf(yawDot) - 1.570796371f; + if (direction.x * transformation.m[8] + direction.y * transformation.m[9] + + direction.z * transformation.m[10] < 0.0f) + yawError = (yawError < 0.0f ? -3.141592741f : 3.141592741f) - yawError; + + IPIControlInfo* const controlInfo = info->getControlInfo(); + io::PlayerInput* const pitchInput = bot->getInput(); + const io::PlayerInputMap pitchMapping = controlInfo->getAimVerticalControl(); + float pitch = infantry_detail::inputValue(pitchInput, pitchMapping); + io::PlayerInput* const yawInput = bot->getInput(); + const io::PlayerInputMap yawMapping = controlInfo->getAimHorizontalControl(); + float yaw = infantry_detail::inputValue(yawInput, yawMapping); + const float pitchScale = controlInfo->getPitchScale(); + const float pitchLookAhead = controlInfo->getPitchLookAhead(); + const float pitchSensitivity = controlInfo->getPitchSensitivity(); + updateAngle(pitchError, pitchError - aim->m_pitchErrors[aim->m_pitchIndex], pitch, + pitchSensitivity, pitchLookAhead, pitchScale); + const float yawScale = controlInfo->getRollScale(); + const float yawLookAhead = controlInfo->getRollLookAhead(); + const float yawSensitivity = controlInfo->getRollSensitivity(); + updateAngle(yawError, yawError - aim->m_lastYawError, yaw, yawSensitivity, yawLookAhead, yawScale); + io::PlayerInput* const output = bot->getInput(); + const io::PlayerInputMap vertical = controlInfo->getAimVerticalControl(); + output->setInput(vertical, pitch); + const io::PlayerInputMap horizontal = controlInfo->getAimHorizontalControl(); + bot->getInput()->setInput(horizontal, yaw); + aim->m_pitchIndex = (aim->m_pitchIndex + 1) % 10; + aim->m_pitchErrors[aim->m_pitchIndex] = pitchError; + aim->m_lastYawError = yawError; + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.h new file mode 100644 index 000000000..179d075a6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.h @@ -0,0 +1,27 @@ +// Key-driven turret aiming entry for BAPAAimAt. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYKEYTURRETAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYKEYTURRETAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryKeyTurretAimAt - statement type 6. +class EntryKeyTurretAimAt : public BAPEntry +{ +public: + EntryKeyTurretAimAt(); + virtual ~EntryKeyTurretAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYKEYTURRETAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp new file mode 100644 index 000000000..bdf536f3e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp @@ -0,0 +1,144 @@ +// EntryMouseTurretAimAt (attested TU `EntryMouseTurretAimAt.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier mouse-aim entry for BAPAAimAt and its subclasses (statement type 6). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2B9D10 (__tcf_0 0x2B9D70, _GLOBAL__I 0x2B9DA0): 's Init object only. +#include + +#include "EntryMouseTurretAimAt.h" + +#include "InfanteryControl.h" +#include "MouseControl.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotSubObjects.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBotActionPlan/BAPAAimAt.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMouseTurretAimAt::EntryMouseTurretAimAt() +{ +} + +EntryMouseTurretAimAt::~EntryMouseTurretAimAt() +{ +} + +int EntryMouseTurretAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2B9700. Mouse-aims the soldier's active weapon with BAPAAimAt's ballistic aim vector +// (falling back to the plain vector to the target), with the target's angular speed as feed-forward +// and the average of the last ten pitch errors as the vertical bias. The end condition finishes it. +bool EntryMouseTurretAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt* aim = static_cast(script); + Vec3 dir; + dir.x = dir.y = dir.z = 0.0f; + Vec3 ownSpeed; + ownSpeed.x = ownSpeed.y = ownSpeed.z = 0.0f; + bot->getSensingAgent()->setOverride(true); + if (!aim->m_endCondition->evaluate(bot)) + { + done = false; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info != 0) + { + IPIControlInfo* controlInfo = info->getControlInfo(); + IPIArmament* armament = info->getArmament(); + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + const Mat4& weaponTransformation = weapon->getAbsoluteTransformation(); + IPIMobile* mobile = info->getMobile(); + if (mobile == 0 && !info->isPrimary()) + { + Information* primary = informationManager->getInformation(info->getPrimaryObject(bot->getSide())); + if (primary != 0) + mobile = primary->getMobile(); + } + if (mobile != 0) + ownSpeed = mobile->getSpeed(); + const Mat4& origin = weapon->getProjectileOrigin(); + Vec3 lastAim; + lastAim.x = lastAim.y = lastAim.z = 0.0f; + const bool haveLastAim = aim->getLastAimVec(lastAim) != 0; + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float exitVelocity = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + if (!aim->getAimVec(origin, ownSpeed, dir, 0.5f, drag, exitVelocity, gravity, indirect, bot)) + { + Vec3 from; + from.x = weaponTransformation.m[12]; + from.y = weaponTransformation.m[13]; + from.z = weaponTransformation.m[14]; + if (!aim->getVectorToTarget(from, dir)) // slot +0x28, 0x2B9985 test al + { + done = true; + ok = false; + aim->m_lastYawError = 3.14159274f; + return true; + } + infantry_detail::normaliseInline(dir); + } + Vec3 predicted; + predicted.x = predicted.y = predicted.z = 0.0f; + aim->getPredictedPosition(predicted); + // 0x2B9A5C: BotMain +0xB4; only while a correction shot is out (+6). + FireCorrectionData* correction = static_cast(bot)->getFireCorrection(); + if (correction->m_flag6) + { + correction->m_aimDirection = dir; // +0x20 + correction->m_predictedTarget = predicted; // +0x38 + } + + float yawSpeed = 0.0f; + float pitchSpeed = 0.0f; + if (haveLastAim) + { + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + yawSpeed = getSignedDiffAngleToDirXZ(lastAim, dir) / dt; + pitchSpeed = getSignedDiffAngleToDirYZ(lastAim, dir) / dt; + } + ok = true; + const float averagePitch = aim->getAveragePitchAngle(); + float pitchError; + float yawError; + mouseControlLookAtDirection(bot, dir, origin, pitchError, aim->m_pitchErrors[aim->m_pitchIndex], yawError, + aim->m_lastYawError, 0.0043633231f, controlInfo, bot->getInput(), + averagePitch, yawSpeed, pitchSpeed); + aim->m_pitchIndex = (aim->m_pitchIndex + 1) % 10; + aim->m_pitchErrors[aim->m_pitchIndex] = pitchError; + aim->m_lastYawError = yawError; + return true; + } + done = true; + ok = false; + } + else + { + done = true; + ok = true; + } + aim->m_lastYawError = 3.14159274f; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.h new file mode 100644 index 000000000..382a4d3e5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.h @@ -0,0 +1,28 @@ +// EntryMouseTurretAimAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMouseTurretAimAt - statement type 6. +class EntryMouseTurretAimAt : public BAPEntry +{ +public: + EntryMouseTurretAimAt(); + virtual ~EntryMouseTurretAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp new file mode 100644 index 000000000..3fa196ea1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp @@ -0,0 +1,97 @@ +// EntryMouseTurretLookAt (attested TU `EntryMouseTurretLookAt.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier mouse-look entry for BAPALook and its subclasses (statement type 23). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2BA240 (__tcf_0 0x2BA2A0, _GLOBAL__I 0x2BA2D0): 's Init object only. +#include + +#include "EntryMouseTurretLookAt.h" + +#include "MouseControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBotActionPlan/BAPALook.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" +#include "InfanteryControl.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMouseTurretLookAt::EntryMouseTurretLookAt() +{ +} + +EntryMouseTurretLookAt::~EntryMouseTurretLookAt() +{ +} + +int EntryMouseTurretLookAt::getTargetId() +{ + return 23; +} + +// BAPALook fields as this entry uses them (0x2B9E90): +0x18 (m_lookSpeed) is +// mouseControlLookAtDirection's allowed deviation, +0x1C (m_deviation) the last yaw error and +// +0x20 (m_lastControl) the last pitch error. + +// ELF 0x2B9E90. Mouse-look towards BAPALook's direction; the end condition finishes the look. +// A direction that is not available fails the statement softly (not done, yaw error reset to pi). +bool EntryMouseTurretLookAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPALook* look = static_cast(script); + bot->getSensingAgent()->setOverride(true); + if (!look->m_endCondition->evaluate(bot)) + { + done = false; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info != 0) + { + Vec3 dir = look->getLookDirection(ok); + infantry_detail::normaliseInline(dir); + if (!ok) + { + done = false; + look->m_deviation = 3.14159274f; + return true; + } + IPIControlInfo* controlInfo = info->getControlInfo(); + ok = true; + io::PlayerInput* input = bot->getInput(); + const float allowed = look->m_lookSpeed; + const float lastYaw = look->m_deviation; + const float lastPitch = look->m_lastControl; + const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); + float pitchError; + float yawError; + mouseControlLookAtDirection(bot, dir, camera, pitchError, lastPitch, yawError, lastYaw, allowed, + controlInfo, input, 0.0f, 0.0f, 0.0f); + look->m_deviation = yawError; + look->m_lastControl = pitchError; + const Mat4& after = *static_cast(bot->getPlayer()->getCameraTransformation()); + look->m_cameraForward.x = after.m[8]; + look->m_cameraForward.y = after.m[9]; + look->m_cameraForward.z = after.m[10]; + return true; + } + done = true; + ok = false; + } + else + { + done = true; + ok = true; + } + look->m_deviation = 3.14159274f; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.h new file mode 100644 index 000000000..fe8739158 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.h @@ -0,0 +1,28 @@ +// EntryMouseTurretLookAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETLOOKAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETLOOKAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMouseTurretLookAt - statement type 23. +class EntryMouseTurretLookAt : public BAPEntry +{ +public: + EntryMouseTurretLookAt(); + virtual ~EntryMouseTurretLookAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOUSETURRETLOOKAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp new file mode 100644 index 000000000..cca49cd54 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp @@ -0,0 +1,207 @@ +// Medium-LOD vehicle movement entry. Attested TU: EntryMoveToMedium.cpp. + +// static init: ELF 0x2BB1C0 (__tcf_0 0x2BB220, _GLOBAL__I 0x2BB250): 's Init object only. +#include + +#include "EntryMoveToMedium.h" + +#include "InfanteryControl.h" +#include "TankControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BA300. The output's y is cleared before the trigonometric calls; input may alias output. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BA3A0 (C1; C2 0x2BA380). +EntryMoveToMedium::EntryMoveToMedium() +{ +} + +// ELF 0x2BA3E0 (D1; D2 0x2BA3C0, D0 0x2BA400). +EntryMoveToMedium::~EntryMoveToMedium() +{ +} + +// ELF 0x2BB270. +int EntryMoveToMedium::getTargetId() +{ + return 7; +} + +// ELF 0x2BA440. Moves a vehicle without physics, limits its heading change by the turn radius, +// and aligns the resulting transform with the terrain normal. +bool EntryMoveToMedium::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectMobile* const mobile = object->getMobile(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + const Vec3 facing = info->getFaceing(); + const Vec3& velocity = mobile->getSpeed(); + TankControl::resetControls(bot, bot->getInput(), true, false, false, + velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z); + Vec3 position = object->getPosition(); + Vec2 position2; + vec3ToVec2XZ(position, position2); + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + return true; + Vec2 delta; + delta.x = point.x - position2.x; + delta.y = point.y - position2.y; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + const Mat4 previous = object->getTransformation(); + Vec2 forward2; + forward2.x = previous.m[8]; + forward2.y = previous.m[10]; + vehiclecontrol::normalizeVec2(forward2); + // The shipped angle calculation divides by distance even when it is zero. + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + const float scaledSpeed = speedFactor * previous.m[5] * 0.6f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + Vec3 forward; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + else + { + forward.x = delta.x; + forward.y = 0.0f; + forward.z = delta.y; + } + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + if (distance > 1e-05f) + { + const float invDistance = 1.0f / distance; + delta.x = delta.x * invDistance; + delta.y = invDistance * delta.y; + } + position.x = delta.x * dt * speed + position.x; + position.z = delta.y * dt * speed + position.z; + } + else if (!(distance > 0.5f)) + { + position.x = previous.m[8] * 0.5f + position.x; + position.z = 0.5f * previous.m[10] + position.z; + } + else + { + position.x = delta.x + position.x; + position.z = delta.y + position.z; + } + vehiclecontrol::normalizeVec3(forward); + const float currentHeight = info->getPosition().y; + float height; + Vec3 up; + up.x = up.y = up.z = 0.0f; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, height, up, slope); + if (!(currentHeight > height) || !(currentHeight - height > slope + slope)) + position.y = mobile->getLodHeight() + height; + else + position.y = currentHeight - slope; + Vec3 right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + Mat4 transformation = object->getTransformation(); + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.h new file mode 100644 index 000000000..d60a58b50 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.h @@ -0,0 +1,27 @@ +// Medium-LOD vehicle movement entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUM_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUM_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToMedium - statement type 7. +class EntryMoveToMedium : public BAPEntry +{ +public: + EntryMoveToMedium(); + virtual ~EntryMoveToMedium(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp new file mode 100644 index 000000000..9ce85325e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp @@ -0,0 +1,236 @@ +// Medium-LOD boat movement entry. Attested TU: EntryMoveToMediumBoat.cpp. + +// static init: ELF 0x2BC280 (__tcf_0 0x2BC2E0, _GLOBAL__I 0x2BC310): 's Init object only. +#include + +#include "EntryMoveToMediumBoat.h" + +#include "BoatControl.h" +#include "InfanteryControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BB280. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BB320 (C1; C2 0x2BB300). +EntryMoveToMediumBoat::EntryMoveToMediumBoat() +{ +} + +// ELF 0x2BB360 (D1; D2 0x2BB340, D0 0x2BB380). +EntryMoveToMediumBoat::~EntryMoveToMediumBoat() +{ +} + +// ELF 0x2BC330. +int EntryMoveToMediumBoat::getTargetId() +{ + return 7; +} + +// ELF 0x2BB3C0. Moves the boat without physics, retaining a running statement when both the +// current and proposed positions fail the pathfinding check. Grounded boats follow the terrain; +// floating boats use the water level and a world-up axis. +bool EntryMoveToMediumBoat::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + bool resetDone; + BoatControl::resetControls(bot, true, false, false, resetDone); + Vec3 position = object->getPosition(); + Vec2 position2; + vec3ToVec2XZ(position, position2); + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + return true; + Vec2 delta; + delta.x = point.x - position2.x; + delta.y = point.y - position2.y; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + if (distance <= 0.01f) + { + done = true; + return true; + } + object->releaseObjectFromSpawner(); + IAIObjectMobile* const mobile = object->getMobile(); + const Mat4 previous = object->getTransformation(); + Vec2 forward2; + forward2.x = previous.m[8]; + forward2.y = previous.m[10]; + vehiclecontrol::normalizeVec2(forward2); + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + const float scaledSpeed = speedFactor * previous.m[5] * 0.9f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + Vec3 forward; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + else + { + forward.x = delta.x; + forward.y = 0.0f; + forward.z = delta.y; + } + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + if (distance > 1e-05f) + { + const float invDistance = 1.0f / distance; + delta.x = delta.x * invDistance; + delta.y = invDistance * delta.y; + } + position.x = delta.x * dt * speed + position.x; + position.z = delta.y * dt * speed + position.z; + } + else if (!(distance > 0.5f)) + { + position.x = previous.m[8] * 0.5f + position.x; + position.z = 0.5f * previous.m[10] + position.z; + } + else + { + position.x = delta.x + position.x; + position.z = delta.y + position.z; + } + vehiclecontrol::normalizeVec3(forward); + const int equipmentType = info->getUnit()->getEquipmentType(); + if (static_cast(moveTo->usesPathfinding())) + { + const Vec3& currentPosition = info->getPosition(); + const int vehicle = mobile->getVehicleNumber(); + if (!IAIPathfinding::instance->isValidPosition(vehicle, equipmentType, currentPosition, true)) + { + const int candidateVehicle = mobile->getVehicleNumber(); + if (!IAIPathfinding::instance->isValidPosition(candidateVehicle, equipmentType, position, true)) + return true; + } + } + Vec3 up; + up.x = up.y = up.z = 0.0f; + unsigned char material; + const float height = terrain->getHeightAndNormal(position.x, position.z, up, material); + const float water = terrain->getWaterLevel(position.x, position.z); + const float lodHeight = mobile->getLodHeight(); + Vec3 right; + if (water - lodHeight > height) + { + position.y = mobile->getLodHeight() + water; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = infantry_detail::crossInline(up, forward); + } + else + { + LocalBoundingBox* const bounds = const_cast(physical->getLocalBoundingBox()); + position.y = 0.5f * bounds->getSize().y + height; + right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + } + Mat4 transformation = object->getTransformation(); + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.h new file mode 100644 index 000000000..fa88d6110 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.h @@ -0,0 +1,27 @@ +// Medium-LOD boat movement entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMBOAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMBOAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToMediumBoat - statement type 7. +class EntryMoveToMediumBoat : public BAPEntry +{ +public: + EntryMoveToMediumBoat(); + virtual ~EntryMoveToMediumBoat(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMBOAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp new file mode 100644 index 000000000..3b7872dad --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp @@ -0,0 +1,193 @@ +// EntryMoveToMediumSoldier (attested TU `EntryMoveToMediumSoldier.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the medium-LOD soldier entry for BAPAMoveTo (statement type 7). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2BCFF0 (__tcf_0 0x2BD050, _GLOBAL__I 0x2BD080): 's Init object only. +#include + +#include "EntryMoveToMediumSoldier.h" + +#include "InfanteryControl.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMoveToMediumSoldier::EntryMoveToMediumSoldier() +{ +} + +EntryMoveToMediumSoldier::~EntryMoveToMediumSoldier() +{ +} + +int EntryMoveToMediumSoldier::getTargetId() +{ + return 7; +} + +using infantry_detail::crossInline; +using infantry_detail::normaliseInline; + +// ELF 0x2BC400. Medium LOD: no inputs are simulated. Physics is switched off and the soldier's +// transformation is moved directly towards the BAPAMoveTo point at its top speed (halved +// crouching, quartered lying, 0 for any other pose), snapped to the ground (or let down by at most +// the slope step when it is above it) and oriented along the move; a lying soldier is aligned to +// the ground normal and lowered by 0.5. Close to the point (within one step) it jumps there, and +// within 0.5 m it moves half a metre along its current facing. +bool EntryMoveToMediumSoldier::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + Mat4 transformation; + for (int i = 0; i < 16; ++i) + transformation.m[i] = 0.0f; + Vec2 dir; + dir.x = dir.y = 0.0f; + Vec3 right; + right.x = right.y = right.z = 0.0f; + Vec3 forward; + forward.x = forward.y = forward.z = 0.0f; + Vec3 up; + up.x = up.y = up.z = 0.0f; + Vec2 goal; + goal.x = goal.y = 0.0f; + Vec3 position; + position.x = position.y = position.z = 0.0f; + Vec2 position2; + position2.x = position2.y = 0.0f; + + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info == 0) + { + done = true; + ok = false; + return true; + } + IAIObject* object = info->getAIObject(); + IAIObjectPhysical* physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + infanteryResetControls(bot, bot->getInput(), true, false, false); + position = object->getPosition(); + vec3ToVec2XZ(position, position2); + bool arrived; + ok = moveTo->update(goal, done, arrived, 0.0f) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + return true; + + Vec2 delta; + delta.x = goal.x - position2.x; + delta.y = goal.y - position2.y; + const float distance = std::sqrt(delta.y * delta.y + delta.x * delta.x); + dir = delta; + IAIObjectMobile* mobile = object->getMobile(); + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + float speed = mobile->getMaxSpeed(); + bot->requestSoldierPose(SPStanding, false); + const SoldierPose pose = info->getSoldierPose(); + if (pose == SPCrouching) + speed = speed * 0.5f; + else if (pose == SPLying) + speed = speed * 0.25f; + else if (pose != SPStanding) + speed = 0.0f; + transformation = object->getTransformation(); + + if (dt * speed <= distance) + { + if (1e-05f < distance) + { + dir.x = dir.x * (1.0f / distance); + dir.y = (1.0f / distance) * dir.y; + } + const float stepZ = dt * dir.y * speed; + const float stepX = dir.x * dt * speed; + position.x = stepX + position.x; + position.z = stepZ + position.z; + vec2ToVec3XZ(dir, forward); + } + else if (distance <= 0.5f) + { + position.x = transformation.m[8] * 0.5f + position.x; + position.z = transformation.m[10] * 0.5f + position.z; + forward.x = transformation.m[8]; + forward.y = transformation.m[9]; + forward.z = transformation.m[10]; + } + else + { + position.x = dir.x + position.x; + position.z = dir.y + position.z; + vec2ToVec3XZ(dir, forward); + } + normaliseInline(forward); + + const float currentHeight = info->getPosition().y; + float ground; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, ground, up, slope); + if (currentHeight <= ground || currentHeight - ground <= slope + slope) + position.y = mobile->getLodHeight() + ground; + else + position.y = currentHeight - slope; + + if (pose == SPLying) + { + position.y = position.y - 0.5f; + right = crossInline(up, forward); + normaliseInline(right); + forward = crossInline(right, up); + normaliseInline(forward); + } + else + { + // upright: up is the world y axis; the right vector stays unnormalised here (retail) + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = crossInline(up, forward); + } + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.h new file mode 100644 index 000000000..bffb745af --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.h @@ -0,0 +1,28 @@ +// EntryMoveToMediumSoldier: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMSOLDIER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMSOLDIER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToMediumSoldier - statement type 7. +class EntryMoveToMediumSoldier : public BAPEntry +{ +public: + EntryMoveToMediumSoldier(); + virtual ~EntryMoveToMediumSoldier(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOMEDIUMSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp new file mode 100644 index 000000000..6e8bcd9f8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp @@ -0,0 +1,201 @@ +// Medium-LOD vehicle movement towards an object. Attested TU: EntryMoveToObjectMedium.cpp. + +// static init: ELF 0x2BDED0 (__tcf_0 0x2BDF30, _GLOBAL__I 0x2BDF60): 's Init object only. +#include + +#include "EntryMoveToObjectMedium.h" + +#include "InfanteryControl.h" +#include "TankControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BD0B0. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BD150 (C1; C2 0x2BD130). +EntryMoveToObjectMedium::EntryMoveToObjectMedium() +{ +} + +// ELF 0x2BD190 (D1; D2 0x2BD170, D0 0x2BD1B0). +EntryMoveToObjectMedium::~EntryMoveToObjectMedium() +{ +} + +// ELF 0x2BDF80. +int EntryMoveToObjectMedium::getTargetId() +{ + return 9; +} + +// ELF 0x2BD1F0. A missing object finishes successfully. Arrival clears done, and movement +// follows the turn-limited heading until the remaining distance is shorter than a tick's step. +bool EntryMoveToObjectMedium::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectMobile* const mobile = object->getMobile(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(info->getSide()); + const Vec3 facing = info->getFaceing(); + const Vec3& velocity = mobile->getSpeed(); + TankControl::resetControls(bot, bot->getInput(), true, false, false, + velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z); + Information* const target = informationManager->getInformation(moveTo->getObject()); + if (!target || moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + { + done = false; + return true; + } + const float ownX = info->getPosition().x; + const float ownZ = info->getPosition().z; + const Vec3& ownPosition = info->getPosition(); + const Vec3& targetPosition = target->getPosition(); + (void)(targetPosition.z - ownPosition.z); + Vec2 delta; + delta.x = point.x - ownX; + delta.y = point.y - ownZ; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + if (distance <= 0.01f) + { + done = false; + return true; + } + Mat4 transformation = object->getTransformation(); + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + Vec2 forward2; + forward2.x = transformation.m[8]; + forward2.y = transformation.m[10]; + vehiclecontrol::normalizeVec2(forward2); + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + const float scaledSpeed = speedFactor * transformation.m[5] * 0.6f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + Vec3 position = object->getPosition(); + Vec3 forward; + forward.x = delta.x / distance; + forward.y = 0.0f; + forward.z = delta.y / distance; + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + float stepX = delta.x; + float stepZ = delta.y; + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + stepX = forward.x * dt * speed; + stepZ = forward.z * dt * speed; + } + position.x = stepX + position.x; + position.z = stepZ + position.z; + const float currentHeight = info->getPosition().y; + float height; + Vec3 up; + up.x = up.y = up.z = 0.0f; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, height, up, slope); + if (!(currentHeight > height) || !(currentHeight - height > slope + slope)) + position.y = mobile->getLodHeight() + height; + else + position.y = currentHeight - slope; + Vec3 right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.h new file mode 100644 index 000000000..850713390 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.h @@ -0,0 +1,27 @@ +// Medium-LOD vehicle movement towards an object. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUM_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUM_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToObjectMedium - statement type 9. +class EntryMoveToObjectMedium : public BAPEntry +{ +public: + EntryMoveToObjectMedium(); + virtual ~EntryMoveToObjectMedium(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp new file mode 100644 index 000000000..c898b5ae7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp @@ -0,0 +1,209 @@ +// Medium-LOD boat movement towards an object. Attested TU: EntryMoveToObjectMediumBoat.cpp. + +// static init: ELF 0x2BEE60 (__tcf_0 0x2BEEC0, _GLOBAL__I 0x2BEEF0): 's Init object only. +#include + +#include "EntryMoveToObjectMediumBoat.h" + +#include "InfanteryControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../../../../Math/Mat4.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF 0x2BDF90. +void rotate2d(const Vec3& input, Vec3& output, float angle) +{ + output.y = 0.0f; + const float cosine = cosf(angle); + const float sine = sinf(angle); + output.x = cosine * input.x - sine * input.z; + output.z = sine * input.x + cosine * input.z; +} + +} // namespace + +// ELF 0x2BE030 (C1; C2 0x2BE010). +EntryMoveToObjectMediumBoat::EntryMoveToObjectMediumBoat() +{ +} + +// ELF 0x2BE070 (D1; D2 0x2BE050, D0 0x2BE090). +EntryMoveToObjectMediumBoat::~EntryMoveToObjectMediumBoat() +{ +} + +// ELF 0x2BEF10. +int EntryMoveToObjectMediumBoat::getTargetId() +{ + return 9; +} + +// ELF 0x2BE0D0. A missing target finishes successfully; arrival keeps the statement active. +// The terrain basis uses the previous transform's forward axis, while movement uses the limited +// target heading. There is no zero-distance guard before the direction divisions. +bool EntryMoveToObjectMediumBoat::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObject* const object = info->getAIObject(); + IAIObjectMobile* const mobile = object->getMobile(); + IAIObjectPhysical* const physical = object->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + Information* const target = informationManager->getInformation(moveTo->getObject()); + if (!target || moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = static_cast(moveTo->update(point, done, arrived, 0.0f)) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + { + done = false; + return true; + } + const float ownX = info->getPosition().x; + const float ownZ = info->getPosition().z; + const Vec3& ownPosition = info->getPosition(); + const Vec3& targetPosition = target->getPosition(); + (void)(targetPosition.z - ownPosition.z); + Vec2 delta; + delta.x = point.x - ownX; + delta.y = point.y - ownZ; + const float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + Mat4 transformation = object->getTransformation(); + const double timeIncrease = static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease(); + Vec2 forward2; + forward2.x = transformation.m[8]; + forward2.y = transformation.m[10]; + vehiclecontrol::normalizeVec2(forward2); + const float inverse = 1.0f / distance; + const float targetX = inverse * delta.x; + const float targetZ = inverse * delta.y; + float rightDot = targetX * forward2.y - targetZ * forward2.x; + const float forwardDot = targetX * forward2.x + targetZ * forward2.y; + if (rightDot < -1.0f) + rightDot = -1.0f; + else if (rightDot > 1.0f) + rightDot = 1.0f; + float angle = acosf(rightDot) - 1.570796371f; + if (forwardDot < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = sign * 3.141592741f - angle; + } + Vec3 position = object->getPosition(); + Vec3 up; + up.x = up.y = up.z = 0.0f; + const float speedFactor = forwardDot < 0.2f ? 0.2f : forwardDot; + // shipped defect: speed uses the still-zero terrain normal's y before the terrain query. + const float scaledSpeed = speedFactor * up.y * 0.6f; + const float speed = mobile->getMaxSpeed() * scaledSpeed; + Vec3 forward; + forward.x = delta.x / distance; + forward.y = 0.0f; + forward.z = delta.y / distance; + const float dt = static_cast(timeIncrease); + const float step = dt * speed; + const float radius = mobile->getTurnRadius(); + const float limitedRadius = radius < 1.0f ? 1.0f : radius; + const float angularStep = step / limitedRadius; + const float limit = angularStep < 0.003926991f ? 0.003926991f : angularStep; + if (limit < 6.283185482f && std::fabs(angle) > limit) + { + Vec3 current; + current.x = forward2.x; + current.y = 0.0f; + current.z = forward2.y; + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + rotate2d(current, forward, sign * limit); + } + float stepX = delta.x; + float stepZ = delta.y; + if (!(static_cast(speed) * timeIncrease > static_cast(distance))) + { + stepX = forward.x * dt * speed; + stepZ = forward.z * dt * speed; + } + position.x = stepX + position.x; + position.z = stepZ + position.z; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + unsigned char material; + const float height = terrain->getHeightAndNormal(position.x, position.z, up, material); + const float water = terrain->getWaterLevel(position.x, position.z); + const float lodHeight = mobile->getLodHeight(); + Vec3 previousForward; + previousForward.x = transformation.m[8]; + previousForward.y = transformation.m[9]; + previousForward.z = transformation.m[10]; + Vec3 right; + if (water - lodHeight > height) + { + position.y = mobile->getLodHeight() + water; + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = infantry_detail::crossInline(up, previousForward); + vehiclecontrol::normalizeVec3(right); + } + else + { + LocalBoundingBox* const bounds = const_cast(physical->getLocalBoundingBox()); + position.y = 0.5f * bounds->getSize().y + height; + right = infantry_detail::crossInline(up, previousForward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + } + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.h new file mode 100644 index 000000000..8b6b62e2a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.h @@ -0,0 +1,27 @@ +// Medium-LOD boat movement towards an object. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMBOAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMBOAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToObjectMediumBoat - statement type 9. +class EntryMoveToObjectMediumBoat : public BAPEntry +{ +public: + EntryMoveToObjectMediumBoat(); + virtual ~EntryMoveToObjectMediumBoat(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMBOAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp new file mode 100644 index 000000000..0a9a3ad6b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp @@ -0,0 +1,189 @@ +// EntryMoveToObjectMediumSoldier (attested TU `EntryMoveToObjectMediumSoldier.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the medium-LOD soldier entry for BAPAMoveToObject (statement type 9). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2BFAF0 (__tcf_0 0x2BFB50, _GLOBAL__I 0x2BFB80): 's Init object only. +#include + +#include "EntryMoveToObjectMediumSoldier.h" + +#include "InfanteryControl.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryMoveToObjectMediumSoldier::EntryMoveToObjectMediumSoldier() +{ +} + +EntryMoveToObjectMediumSoldier::~EntryMoveToObjectMediumSoldier() +{ +} + +int EntryMoveToObjectMediumSoldier::getTargetId() +{ + return 9; +} + +using infantry_detail::crossInline; +using infantry_detail::normaliseInline; + +// ELF 0x2BEFE0. Medium LOD for BAPAMoveToObject: as EntryMoveToMediumSoldier, but it finishes when +// the target object is gone, reports "not done" (instead of returning the action's done flag) when +// the action has arrived, stands still within 1 cm of the point, never jumps along the facing, and +// normalises the right vector of an upright soldier too. +bool EntryMoveToObjectMediumSoldier::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo* moveTo = static_cast(script); + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info == 0) + { + done = true; + ok = false; + return true; + } + IAIObject* object = info->getAIObject(); + IAIObjectMobile* mobile = object->getMobile(); + IAIObjectPhysical* physical = info->getAIObject()->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(object->getSide()); + infanteryResetControls(bot, bot->getInput(), true, false, false); + Information* target = informationManager->getInformation(static_cast(moveTo->getObject())); + if (target == 0 || moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + Vec2 goal; + goal.x = 0.0f; + done = false; + goal.y = goal.x; + bool arrived; + ok = moveTo->update(goal, done, arrived, 0.0f) != 0; + if (!ok) + { + done = true; + return true; + } + if (done || arrived) + { + done = false; + return true; + } + + Vec2 own; + own.x = info->getPosition().x; + own.y = info->getPosition().z; + // retail: the target's position is read here and only its z difference is formed, unused + const Vec3 ownPosition = info->getPosition(); + const Vec3& targetPosition = target->getPosition(); + (void)(targetPosition.z - ownPosition.z); + Vec2 delta; + delta.x = goal.x - own.x; + delta.y = goal.y - own.y; + const float distance = std::sqrt(delta.y * delta.y + delta.x * delta.x); + if (distance <= 0.01f) + { + done = false; + return true; + } + + const Mat4& current = object->getTransformation(); + Mat4 transformation; + for (int i = 0; i < 16; ++i) + transformation.m[i] = 0.0f; + for (int i = 0; i < 8; ++i) + transformation.m[i] = current.m[i]; + transformation.m[11] = current.m[11]; + transformation.m[15] = current.m[15]; + + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + bot->requestSoldierPose(SPStanding, false); + float speed = mobile->getMaxSpeed(); + const SoldierPose pose = info->getSoldierPose(); + if (pose == SPCrouching) + speed = speed * 0.5f; + else if (pose == SPLying) + speed = speed * 0.25f; + else if (pose != SPStanding) + speed = 0.0f; + + const Vec3& objectPosition = object->getPosition(); + Vec3 position; + position.y = objectPosition.y; + Vec3 forward; + forward.z = delta.y / distance; + forward.x = delta.x / distance; + forward.y = 0.0f; + float stepZ = delta.y; + float stepX = delta.x; + if (dt * speed <= distance) + { + stepZ = dt * forward.z * speed; + stepX = forward.x * dt * speed; + } + position.x = objectPosition.x + stepX; + position.z = objectPosition.z + stepZ; + + Vec3 up; + up.x = up.y = up.z = 0.0f; + const float currentHeight = info->getPosition().y; + float ground; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, position, ground, up, slope); + if (currentHeight <= ground || currentHeight - ground <= slope + slope) + position.y = mobile->getLodHeight() + ground; + else + position.y = currentHeight - slope; + + Vec3 right; + if (pose == SPLying) + { + position.y = position.y - 0.5f; + right = crossInline(up, forward); + normaliseInline(right); + forward = crossInline(right, up); + normaliseInline(forward); + } + else + { + up.x = 0.0f; + up.y = 1.0f; + up.z = 0.0f; + right = crossInline(up, forward); + normaliseInline(right); + } + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + transformation.m[12] = position.x; + transformation.m[13] = position.y; + transformation.m[14] = position.z; + object->setTransformation(transformation, bot->getSide()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.h new file mode 100644 index 000000000..ff49fdb21 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.h @@ -0,0 +1,28 @@ +// EntryMoveToObjectMediumSoldier: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMSOLDIER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMSOLDIER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryMoveToObjectMediumSoldier - statement type 9. +class EntryMoveToObjectMediumSoldier : public BAPEntry +{ +public: + EntryMoveToObjectMediumSoldier(); + virtual ~EntryMoveToObjectMediumSoldier(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYMOVETOOBJECTMEDIUMSOLDIER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp new file mode 100644 index 000000000..aa6afbc80 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp @@ -0,0 +1,234 @@ +// EntryPlaneAimAt (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C0B00 (__tcf_0 0x2C0B60, _GLOBAL__I 0x2C0B90): 's Init object only. +#include + +#include "EntryPlaneAimAt.h" + +#include "PlaneControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAAimAtObject3d.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2BFBD0 (C1; C2 0x2BFBB0). +EntryPlaneAimAt::EntryPlaneAimAt() +{ +} + +// ELF 0x2BFC10 (D1; D2 0x2BFBF0, D0 0x2BFC30). +EntryPlaneAimAt::~EntryPlaneAimAt() +{ +} + +// ELF 0x2C0BB0. +int EntryPlaneAimAt::getTargetId() +{ + return 6; +} + +// ELF 0x2BFC70. +bool EntryPlaneAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAAimAt3d* const aim = static_cast(script); + ok = true; + done = false; + if (aim->m_condition->evaluate(bot)) + { + done = true; + return true; + } + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + IPIArmament* const armament = info->getArmament(); + WeaponInfo* const weapon = WeaponInfoManager::m_instance->getInformation( + armament->getWeapon(armament->getActiveWeapon())); + IPIMobile* const mobile = info->getMobile(); + if (aim->getAimAtType() != 1) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + Information* const target = informationManager->getInformation(static_cast(aim)->m_target); + if (!target) + { + done = true; + ok = false; + aim->m_floats1AC[0] = 3.1415927f; + return true; + } + Vec3 direction = {0.0f, 0.0f, 0.0f}; + Vec3 firingDirection = {0.0f, 0.0f, 0.0f}; + const Mat4& origin = weapon->getProjectileOrigin(); + const Mat4& targetTransform = target->getTransformation(); + float throttle = 1.0f; + float distance; + bool useForward = false; + if ((target->getObjectTypeFlags() & 0x10) != 0) + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + bool solved = aim->getAimVec(origin, mobile->getSpeed(), direction, 0.5f, drag, speed, gravity, indirect); + if (solved) + firingDirection = direction; + else + { + if (!aim->getVectorToTarget(info->getPosition(), direction)) + { + ok = false; + done = true; + return true; + } + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (length > 1.0f) + { + solved = true; + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + } + distance = std::sqrt(direction.x * direction.x + direction.z * direction.z); + useForward = !solved; + } + else + { + const bool indirect = weapon->getIndirect(); + const float gravity = weapon->getGravityModifier(); + const float speed = weapon->getExitVelocity(); + const float drag = weapon->getDrag(); + const bool solved = aim->getAimVec(origin, mobile->getSpeed(), direction, 0.75f, drag, speed, gravity, false); + throttle = 0.5f; + if (solved) + { + firingDirection = direction; + if (indirect) + { + const float x = origin.m[12] - targetTransform.m[12]; + const float y = origin.m[13] - targetTransform.m[13]; + const float z = origin.m[14] - targetTransform.m[14]; + distance = std::sqrt(x * x + y * y + z * z); + if (distance < 60.0f || distance > 300.0f) + { + direction.y = 0.0f; + if (std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z) > 1e-05f) + { + const float inverse = 1.0f / std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + } + } + else + distance = std::sqrt(direction.x * direction.x + direction.z * direction.z); + } + else + { + if (!aim->getVectorToTarget(info->getPosition(), direction)) + { + ok = false; + done = true; + return true; + } + direction.y = 20.0f + direction.y; + distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (distance > 1.0f) + { + const float inverse = 1.0f / distance; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + else + useForward = true; + } + } + if (useForward || -0.7f > direction.y) + { + direction = info->getFaceing(); + direction.y = 0.0f; + distance = 1.0f; + vehiclecontrol::normalizeVec3(direction); + } + const float dt = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getTimeIncrease()); + const Vec3& speed = mobile->getSpeed(); + const float inverse = 1.0f / dt; + const Vec3 acceleration = {(speed.x - aim->m_vecA8.x) * inverse, + (speed.y - aim->m_vecA8.y) * inverse, + (speed.z - aim->m_vecA8.z) * inverse}; + (void)acceleration; + aim->m_vecA8 = speed; + Mat4 inverseOrigin = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + inverseOrigin.setInverse(origin); + const Vec3 localDirection = { + direction.x * inverseOrigin.m[0] + direction.y * inverseOrigin.m[4] + direction.z * inverseOrigin.m[8], + direction.x * inverseOrigin.m[1] + direction.y * inverseOrigin.m[5] + direction.z * inverseOrigin.m[9], + direction.x * inverseOrigin.m[2] + direction.y * inverseOrigin.m[6] + direction.z * inverseOrigin.m[10]}; + const Mat4& transform = info->getTransformation(); + const Vec3 steeringDirection = { + localDirection.x * transform.m[0] + localDirection.y * transform.m[4] + localDirection.z * transform.m[8], + localDirection.x * transform.m[1] + localDirection.y * transform.m[5] + localDirection.z * transform.m[9], + localDirection.x * transform.m[2] + localDirection.y * transform.m[6] + localDirection.z * transform.m[10]}; + const auto clamp = [](float value) { + return -1.0f > value ? -1.0f : (value > 1.0f ? 1.0f : value); + }; + if (aim->isAimVecValid()) + { + const Mat4& weaponUp = weapon->getAbsoluteTransformation(); + float dot = firingDirection.x * weaponUp.m[4] + firingDirection.y * weaponUp.m[5] + firingDirection.z * weaponUp.m[6]; + const float pitch = std::acos(clamp(clamp(dot))) - 1.5707964f; + const Mat4& weaponRight = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponRight.m[0] + firingDirection.y * weaponRight.m[1] + firingDirection.z * weaponRight.m[2]; + float yaw = std::acos(clamp(clamp(dot))) - 1.5707964f; + const Mat4& weaponForward = weapon->getAbsoluteTransformation(); + dot = firingDirection.x * weaponForward.m[8] + firingDirection.y * weaponForward.m[9] + firingDirection.z * weaponForward.m[10]; + if (dot < 0.0f) + yaw = (yaw < 0.0f ? -3.1415927f : 3.1415927f) - yaw; + aim->m_floats1AC[1] = pitch; + aim->m_floats1AC[0] = yaw; + } + else + { + aim->m_floats1AC[1] = 3.1415927f; + aim->m_floats1AC[0] = 3.1415927f; + } + aim->m_vec24 = info->getFaceing(); + const Mat4& right = info->getTransformation(); + aim->m_vec30 = {right.m[0], right.m[1], right.m[2]}; + const Mat4& up = info->getTransformation(); + aim->m_vec3C = {up.m[4], up.m[5], up.m[6]}; + aim->m_floats1AC[3] = info->getPosition().y; + ok = PlaneControl::aimAtDirection(bot, info, steeringDirection, distance, throttle, aim->m_float1A4, + aim->m_vec24, aim->m_vec30, aim->m_vec3C, bot->getInput()); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.h new file mode 100644 index 000000000..7fd11a476 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.h @@ -0,0 +1,27 @@ +// EntryPlaneAimAt: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEAIMAT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEAIMAT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneAimAt - statement type 6. +class EntryPlaneAimAt : public BAPEntry +{ +public: + EntryPlaneAimAt(); + virtual ~EntryPlaneAimAt(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEAIMAT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp new file mode 100644 index 000000000..8b4857217 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp @@ -0,0 +1,73 @@ +// EntryPlaneMoveTo (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C0E80 (__tcf_0 0x2C0EE0, _GLOBAL__I 0x2C0F10): 's Init object only. +#include + +#include "EntryPlaneMoveTo.h" + +#include "PlaneControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3d.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C0BE0 (C1; C2 0x2C0BC0). +EntryPlaneMoveTo::EntryPlaneMoveTo() +{ +} + +// ELF 0x2C0C20 (D1; D2 0x2C0C00, D0 0x2C0C40). +EntryPlaneMoveTo::~EntryPlaneMoveTo() +{ +} + +// ELF 0x2C0F30. +int EntryPlaneMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2C0C80. +bool EntryPlaneMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3d* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Vec3 point = {0.0f, 0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement still drives the plane below. + } + else + done = false; + point = *moveTo->getFirstPoint(); + ok = PlaneControl::towardsPoint(bot, info, point, 1.0f, moveTo->m_forward, + moveTo->m_right, moveTo->m_up, moveTo->m_distance, bot->getInput()); + const Mat4& transform = info->getTransformation(); + moveTo->m_forward = {transform.m[8], transform.m[9], transform.m[10]}; + moveTo->m_up = {transform.m[4], transform.m[5], transform.m[6]}; + moveTo->m_right = {transform.m[0], transform.m[1], transform.m[2]}; + moveTo->m_int4C = transform.m[13]; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.h new file mode 100644 index 000000000..60807d35d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.h @@ -0,0 +1,27 @@ +// EntryPlaneMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneMoveTo - statement type 7. +class EntryPlaneMoveTo : public BAPEntry +{ +public: + EntryPlaneMoveTo(); + virtual ~EntryPlaneMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp new file mode 100644 index 000000000..24bebd6e5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp @@ -0,0 +1,226 @@ +// EntryPlaneMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C2950 (__tcf_0 0x2C29B0, _GLOBAL__I 0x2C29E0): 's Init object only. +#include + +#include "EntryPlaneMoveToDirection.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dDirection.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../Core/Debug.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C0F60 (C1; C2 0x2C0F40). +EntryPlaneMoveToDirection::EntryPlaneMoveToDirection() +{ +} + +// ELF 0x2C0FA0 (D1; D2 0x2C0F80, D0 0x2C0FC0). +EntryPlaneMoveToDirection::~EntryPlaneMoveToDirection() +{ +} + +// ELF 0x2C2A00. +int EntryPlaneMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2C1000. +bool EntryPlaneMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dDirection* const moveTo = static_cast(script); + Mat4 transform = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + Mat4 transpose = transform; + io::PlayerInput* const input = bot->getInput(); + float yawInput = (input->mappingFlags & 1ULL) ? input->inputs[0] : 0.0f; + float pitchInput = (input->mappingFlags & 2ULL) ? input->inputs[1] : 0.0f; + float rollInput = (input->mappingFlags & 4ULL) ? input->inputs[2] : 0.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement continues through the controls. + } + else + done = false; + transform = info->getTransformation(); + const Vec3 right = {transform.m[0], transform.m[1], transform.m[2]}; + const Vec3 up = {transform.m[4], transform.m[5], transform.m[6]}; + const Vec3 forward = {transform.m[8], transform.m[9], transform.m[10]}; + transpose.setTranspose(transform); + const Vec3 position = info->getPosition(); + info->getMobile()->getSpeedMagnitude(); + Vec3 point = moveTo->m_target; + const Vec3& speed = info->getMobile()->getSpeed(); + const Vec3 lookAhead = {speed.x * 10.0f, speed.y * 10.0f, speed.z * 10.0f}; + const float altitude = info->getAltitude(lookAhead); + moveTo->m_currentAltitude = altitude; + const float heightError = moveTo->m_altitude - altitude; + const float desiredHeight = heightError + position.y; + point.y = desiredHeight > point.y ? desiredHeight : point.y; + Vec2 position2, point2, forward2, targetDirection2, normal, targetNormal; + vec3ToVec2XZ(position, position2); + vec3ToVec2XZ(point, point2); + vec3ToVec2XZ(forward, forward2); + vec3ToVec2XZ(moveTo->m_direction, targetDirection2); + getNormal(forward2, normal); + vehiclecontrol::normalizeVec2(normal); + getNormal(targetDirection2, targetNormal); + vehiclecontrol::normalizeVec2(targetNormal); + const float radius = 80.0f; + const Vec2 targetCentre = {radius * targetNormal.x + point2.x, targetNormal.y * radius + point2.y}; + const Vec2 centreDifference = {targetCentre.x - (normal.x * radius + position2.x), + targetCentre.y - (normal.y * radius + position2.y)}; + const float centreDistance = std::sqrt(centreDifference.x * centreDifference.x + centreDifference.y * centreDifference.y); + const float pi = 3.1415927f; + const float halfPi = 1.5707964f; + const float twoPi = 6.2831855f; + // [INFERRED] inline comparison shapes. The cosine clamp maps unordered input to -1. + const auto clampUnit = [](float value) { + return -1.0f > value ? -1.0f : (value > 1.0f ? 1.0f : value); + }; + const auto clampCos = [](float value) { + const float upper = value > 1.0f ? 1.0f : value; + return upper > -1.0f ? upper : -1.0f; + }; + Vec3 direction; + float yawTarget; + // shipped defect: the height slope uses world-position magnitude, not target distance. + const auto perpendicular = [&]() { + return Vec3{normal.x, (point.y - position.y) / + std::sqrt(position.x * position.x + position.y * position.y + position.z * position.z), normal.y}; + }; + if (radius * 0.075f > centreDistance) + { + direction = perpendicular(); + moveTo->m_state = 2; + yawTarget = halfPi; + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp", 210, "") + << "We don't think that we are using this code..., check yaw angle."; + } + else + { + float theta = std::acos(clampUnit(clampUnit(std::fabs(centreDifference.y) / centreDistance))); + if (centreDifference.x < 0.0f) + theta = twoPi - theta; + float normalTheta = std::acos(clampUnit(clampUnit(normal.y))); + if (normal.x < 0.0f) + normalTheta = twoPi - normalTheta; + float difference = theta - normalTheta; + if (difference < 0.0f) + difference = -difference; + if (difference > pi) + difference = twoPi - difference; + else if (difference < 0.0f) + difference += twoPi; + if (moveTo->m_state == 1 || 0.18325958f > difference) + { + const float sine = std::sin(theta); + const Vec3 turnPoint = {targetCentre.x - sine * radius, point.y, + targetCentre.y - radius * std::cos(theta)}; + direction = {turnPoint.x - position.x, turnPoint.y - position.y, turnPoint.z - position.z}; + Vec2 direction2; + vec3ToVec2XZ(direction, direction2); + vehiclecontrol::normalizeVec2(direction2); + const float dot = normal.x * direction2.x + direction2.y * normal.y; + yawTarget = std::acos(clampCos(dot)) - halfPi; + vehiclecontrol::normalizeVec3(direction); + moveTo->m_state = 1; + } + else + { + direction = perpendicular(); + yawTarget = halfPi; + } + } + vehiclecontrol::normalizeVec3(direction); + float rollTarget = -(std::acos(clampCos(right.y)) - halfPi); + const float yawChange = std::acos(clampCos(right.x * moveTo->m_forward.x + right.y * moveTo->m_forward.y + right.z * moveTo->m_forward.z)) - halfPi; + const float rollChange = rollTarget + (std::acos(clampCos(right.y)) - halfPi); + const float pitchChange = std::acos(clampCos(up.x * moveTo->m_forward.x + up.y * moveTo->m_forward.y + up.z * moveTo->m_forward.z)) - halfPi; + const Vec3 localUp = {transpose.m[0] * 0.0f + transpose.m[4] + transpose.m[8] * 0.0f, + transpose.m[1] * 0.0f + transpose.m[5] + transpose.m[9] * 0.0f, + transpose.m[2] * 0.0f + transpose.m[6] + transpose.m[10] * 0.0f}; + const float currentPitch = std::asin(clampUnit(localUp.z)); + float pitchTarget; + const auto dot = [](const Vec3& a, const Vec3& b) { + return a.x * b.x + a.y * b.y + a.z * b.z; + }; + if (heightError > moveTo->m_altitude * 0.1f) + { + pitchTarget = -(0.43633232f - currentPitch); + yawTarget = 0.0f; + pitchTarget /= 1.0001f - std::sin(rollTarget); + } + else if (!(0.08726646f > std::fabs(yawTarget))) + { + if (!(0.21816616f > std::fabs(yawTarget))) + { + const float angle = std::atan(dot(direction, right)); + yawTarget = 0.0f; + pitchTarget = -halfPi; + const float upDot = dot(up, direction); + const float absoluteUpDot = upDot < 0.0f ? -upDot : upDot; + rollTarget = (angle / absoluteUpDot) * 0.9f + 0.1f * rollTarget; + } + else + { + const float angle = std::acos(clampCos(dot(direction, up))) - halfPi; + pitchTarget = -(0.43633232f - currentPitch) / (1.0001f - std::sin(rollTarget)); + pitchTarget = pitchTarget > angle ? pitchTarget : angle; + const float rightAngle = std::acos(clampCos(dot(direction, right))) - halfPi; + rollTarget = rightAngle * -0.1f + rollTarget * 0.9f; + } + } + else + { + const float absoluteZ = direction.z < 0.0f ? -direction.z : direction.z; + const float targetPitch = std::atan(direction.y / absoluteZ); + const float forwardAbsoluteZ = forward.z < 0.0f ? -forward.z : forward.z; + const float facingPitch = std::atan(forward.y / forwardAbsoluteZ); + const float pitchDifference = targetPitch - facingPitch; + const float pitchLimit = (1.0f - std::cos(std::fabs(rollTarget))) * 1.2f * halfPi + (0.43633232f - currentPitch); + pitchTarget = -(pitchLimit > pitchDifference ? pitchDifference : pitchLimit); + const float rollSign = rollTarget > 0.0f ? 1.0f : (rollTarget < 0.0f ? -1.0f : 0.0f); + rollTarget = rollSign * rollTarget * rollTarget; + const float yawSign = yawTarget > 0.0f ? 1.0f : (yawTarget < 0.0f ? -1.0f : 0.0f); + yawTarget = yawSign * yawTarget * yawTarget; + } + updateAngle(yawTarget, yawChange, yawInput, 1.0f, 1.0f, 1.5f); + updateAngle(pitchTarget, pitchChange, pitchInput, -1.0f, 1.0f, 1.5f); + updateAngle(rollTarget, rollChange, rollInput, -0.5f, 1.0f, 1.5f); + io::PlayerInput* output = bot->getInput(); + if (output->mappingFlags & 1ULL) + output->inputs[0] = yawInput; + bot->getInput()->setInput(static_cast(1), pitchInput); + bot->getInput()->setInput(static_cast(2), rollInput); + bot->getInput()->setInput(static_cast(3), 1.0f); + ok = true; + moveTo->m_forward = forward; + moveTo->m_up = up; + moveTo->m_right = right; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.h new file mode 100644 index 000000000..3d56ed559 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryPlaneMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneMoveToDirection - statement type 8. +class EntryPlaneMoveToDirection : public BAPEntry +{ +public: + EntryPlaneMoveToDirection(); + virtual ~EntryPlaneMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp new file mode 100644 index 000000000..8bb059c45 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp @@ -0,0 +1,112 @@ +// EntryPlaneMoveToObject (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C2F40 (__tcf_0 0x2C2FA0, _GLOBAL__I 0x2C2FD0): 's Init object only. +#include + +#include "EntryPlaneMoveToObject.h" + +#include "PlaneControl.h" +#include "ControlFunctions.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo3dObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C2A30 (C1; C2 0x2C2A10). +EntryPlaneMoveToObject::EntryPlaneMoveToObject() +{ +} + +// ELF 0x2C2A70 (D1; D2 0x2C2A50, D0 0x2C2A90). +EntryPlaneMoveToObject::~EntryPlaneMoveToObject() +{ +} + +// ELF 0x2C2FF0. +int EntryPlaneMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2C2AD0. +bool EntryPlaneMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveTo3dObject* const moveTo = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + // shipped defect: current equipment is dereferenced before any validity check. + const Vec3 position = info->getPosition(); + (void)position; + Information* const target = informationManager->getInformation(moveTo->m_object); + if (!target) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + // shipped defect: the completed statement still drives the plane below. + } + else + done = false; + const Mat4& transform = info->getTransformation(); + const float speed = info->getMobile()->getSpeedMagnitude(); + float throttle; + if ((target->getObjectTypeFlags() & 0x10) != 0) + { + io::PlayerInput* const input = bot->getInput(); + throttle = ((input->mappingFlags >> 3) & 1ULL) ? input->inputs[3] : 0.0f; + const Vec3& targetPosition = target->getPosition(); + const Vec3& currentPosition = info->getPosition(); + const float x = targetPosition.x - currentPosition.x; + const float y = targetPosition.y - currentPosition.y; + const float z = targetPosition.z - currentPosition.z; + const float distanceSquared = x * x + y * y + z * z; + IPIMobile* const targetMobile = target->getMobile(); + const float range = moveTo->m_float18; + float targetSpeed; + if (targetMobile) + targetSpeed = targetMobile->getSpeedMagnitude(); + else + targetSpeed = moveTo->m_maxArriveSpeed; + if (range * range >= distanceSquared) + updateLinear(targetSpeed, speed, moveTo->m_int40[0], throttle, -1.0f, 1.0f, 1.0f); + else if ((range + range) * (range + range) >= distanceSquared) + { + // shipped defect: the transition uses squared distance divided by range. + updateLinear((distanceSquared * targetSpeed) / range, speed, moveTo->m_int40[0], throttle, -1.0f, 1.0f, 1.0f); + } + else + throttle = 1.0f; + moveTo->m_int40[0] = speed; + } + else + throttle = 1.0f; + const float distance = moveTo->m_distance; + const Vec3 point = *moveTo->getFirstPoint(); + ok = PlaneControl::towardsPoint(bot, info, point, throttle, moveTo->m_right, + moveTo->m_forward, moveTo->m_up, distance, bot->getInput()); + moveTo->m_right = {transform.m[8], transform.m[9], transform.m[10]}; + moveTo->m_up = {transform.m[4], transform.m[5], transform.m[6]}; + moveTo->m_forward = {transform.m[0], transform.m[1], transform.m[2]}; + moveTo->m_int84 = transform.m[13]; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.h new file mode 100644 index 000000000..064729e97 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.h @@ -0,0 +1,27 @@ +// EntryPlaneMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneMoveToObject - statement type 9. +class EntryPlaneMoveToObject : public BAPEntry +{ +public: + EntryPlaneMoveToObject(); + virtual ~EntryPlaneMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp new file mode 100644 index 000000000..8aecf36e7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp @@ -0,0 +1,59 @@ +// EntryPlaneResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2C3330 (__tcf_0 0x2C3390, _GLOBAL__I 0x2C33C0): 's Init object only. +#include + +#include "EntryPlaneResetControls.h" + +#include "PlaneControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryPlaneResetControls::EntryPlaneResetControls() +{ +} + +EntryPlaneResetControls::~EntryPlaneResetControls() +{ +} + +int EntryPlaneResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2C30C0 (Ghidra). The bot's current equipment is looked up first (not null-tested). A +// single-input reset releases that one input; the group form resets through +// PlaneControl::resetControls with that information, ignores its answer, and sets `done` then `ok`. +bool EntryPlaneResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + PlaneControl::resetControls(bot, equipment, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger); + done = true; + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.h new file mode 100644 index 000000000..c7d45c572 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.h @@ -0,0 +1,28 @@ +// EntryPlaneResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANERESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANERESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryPlaneResetControls - statement type 14. +class EntryPlaneResetControls : public BAPEntry +{ +public: + EntryPlaneResetControls(); + virtual ~EntryPlaneResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANERESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp new file mode 100644 index 000000000..5d355e4c3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp @@ -0,0 +1,87 @@ +// Plane roll entry. Attested TU: EntryPlaneRoll.cpp. + +// static init: ELF 0x2C38B0 (__tcf_0 0x2C3910, _GLOBAL__I 0x2C3940): 's Init object only. +#include + +#include "EntryPlaneRoll.h" + +#include "PlaneControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPARoll3d.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C3410 (C1; C2 0x2C33F0). +EntryPlaneRoll::EntryPlaneRoll() +{ +} + +// ELF 0x2C3450 (D1; D2 0x2C3430, D0 0x2C3470). +EntryPlaneRoll::~EntryPlaneRoll() +{ +} + +// ELF 0x2C34B0 +bool EntryPlaneRoll::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPARoll3d* const roll = static_cast(script); + Mat4 unused = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + (void)unused; + if (roll->getBreakCondition()->evaluate(bot)) + { + done = true; + ok = true; + // shipped defect: satisfying the break condition does not stop the controls. + } + else + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + const Mat4& transform = info->getTransformation(); + const Vec3 position = info->getPosition(); + const Vec3 speed = info->getMobile()->getSpeed(); + // shipped defect: +0x2C, used as the minimum altitude, is not initialized by the constructor. + const float minimumAltitude = roll->m_float2C; + const Vec3 lookAhead = {speed.x * 10.0f, speed.y * 10.0f, speed.z * 10.0f}; + const float heightDifference = minimumAltitude - info->getAltitude(lookAhead); + IPIControlInfo* const controls = info->getControlInfo(); + bool wrapped = false; + // The second argument is the local [ebp-0xA4] (zeroed 0x2C354E, read 0x2C37BB, never written); + // PlaneControl::roll does not read it. + ok = PlaneControl::roll(roll->m_roll, 0.0f, bot->getInput(), transform, roll->m_previousY, + heightDifference > 0.0f, roll->m_flatFacing, roll->m_vector78, roll->m_vector6C, + roll->m_forward, roll->m_right, roll->m_up, controls, 1.0f, + roll->m_direction == 1, wrapped) != 0; + if (wrapped) + roll->m_roll += roll->m_direction == 1 ? -6.2831855f : 6.2831855f; + roll->m_forward = {transform.m[8], transform.m[9], transform.m[10]}; + roll->m_up = {transform.m[4], transform.m[5], transform.m[6]}; + roll->m_right = {transform.m[0], transform.m[1], transform.m[2]}; + roll->m_previousY = position.y; + return true; +} + +// ELF 0x2C3960 +int EntryPlaneRoll::getTargetId() +{ + return 25; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.h new file mode 100644 index 000000000..056eba72c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.h @@ -0,0 +1,31 @@ +// Plane roll action-plan entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEROLL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEROLL_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BD7A8 (4 words), package H-deferred. +class EntryPlaneRoll : public BAPEntry +{ +public: + EntryPlaneRoll(); // 0x2C3410 + virtual ~EntryPlaneRoll(); // 0x2C3450 + + virtual bool execute(BotScript*, Bot*, bool&, bool&); // 0x2C34B0, slot +0x08; from the base declaration + virtual int getTargetId(); // 0x2C3960, slot +0x0C; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYPLANEROLL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp new file mode 100644 index 000000000..18efb0463 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp @@ -0,0 +1,61 @@ +// EntrySense (attested TU `EntrySense.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the entry for BAPASense (statement type 20). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C3AE0 (__tcf_0 0x2C3B40, _GLOBAL__I 0x2C3B70): 's Init object only. +#include + +#include "EntrySense.h" + +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPASense.h" +#include "../AIBotActionPlan/BAPCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C3990 (C1; C2 0x2C3970) +EntrySense::EntrySense() +{ +} + +// ELF 0x2C39D0 (D1; D2 0x2C39B0, D0 0x2C39F0) +EntrySense::~EntrySense() +{ +} + +// ELF 0x2C3B90 +int EntrySense::getTargetId() +{ + return 20; +} + +// ELF 0x2C3A30. The condition at +0x18 ends the statement at once. Otherwise the statement keeps +// running until the condition at +0x14 holds; then the bot's inverse attention is reset to 0 and it +// finishes. +bool EntrySense::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPASense* sense = static_cast(script); + if (sense->m_secondCondition->evaluate(bot)) + { + ok = true; + done = true; + return true; + } + if (!sense->m_firstCondition->evaluate(bot)) + { + ok = true; + done = false; + return true; + } + static_cast(bot)->setInvAttention(0.0f); + ok = true; + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.h new file mode 100644 index 000000000..660e18957 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySense.h @@ -0,0 +1,27 @@ +// Runs the sensing statement until either owned condition completes it. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSENSE_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSENSE_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntrySense - statement type 20. +class EntrySense : public BAPEntry +{ +public: + EntrySense(); + virtual ~EntrySense(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSENSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp new file mode 100644 index 000000000..aaed669aa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp @@ -0,0 +1,65 @@ +// EntrySoldierPose (attested TU `EntrySoldierPose.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPASoldierPose (statement type 26). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C3E50 (__tcf_0 0x2C3EB0, _GLOBAL__I 0x2C3EE0): 's Init object only. +#include + +#include "EntrySoldierPose.h" + +#include "InfanteryControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPASoldierPose.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntrySoldierPose::EntrySoldierPose() +{ +} + +EntrySoldierPose::~EntrySoldierPose() +{ +} + +int EntrySoldierPose::getTargetId() +{ + return 26; +} + +// ELF 0x2C3C60. Wanted pose: the statement's normal pose, or standing while the bot presses +// throttle, yaw or sprint. Done when the soldier is in it; otherwise the pose is requested (not while +// swimming). Without the bot's own information the image returns false and leaves the flags alone. +bool EntrySoldierPose::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPASoldierPose* pose = static_cast(script); + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + if (info == 0) + return false; + SoldierPose wanted = static_cast(static_cast(pose)->getNormalPose()); + const io::PlayerInput* input = bot->getInput(); + if (infantry_detail::inputValue(input, io::PIThrottle) != 0.0f + || infantry_detail::inputValue(input, io::PIYaw) != 0.0f + || infantry_detail::inputValue(input, io::PISprint) != 0.0f) + wanted = SPStanding; + if (info->getSoldierPose() == wanted) + { + ok = true; + done = true; + return true; + } + const SoldierPose current = info->getSoldierPose(); + if (current != SPSwimming && current != wanted) + bot->requestSoldierPose(wanted, pose->getFlag()); + ok = true; + done = false; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.h new file mode 100644 index 000000000..bee00d118 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.h @@ -0,0 +1,28 @@ +// EntrySoldierPose: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSOLDIERPOSE_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSOLDIERPOSE_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntrySoldierPose - statement type 26. +class EntrySoldierPose : public BAPEntry +{ +public: + EntrySoldierPose(); + virtual ~EntrySoldierPose(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYSOLDIERPOSE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp new file mode 100644 index 000000000..a0786d5cb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp @@ -0,0 +1,175 @@ +// EntryTankMoveTo (attested TU `EntryTankMoveTo.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a tank +// along a BAPAMoveTo. execute's flags follow the BotScript convention: `ok` (the step ran) and +// `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2C4680 (__tcf_0 0x2C46E0, _GLOBAL__I 0x2C4710): the guard object only. + +#include "EntryTankMoveTo.h" + +#include "TankControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryTankMoveTo::EntryTankMoveTo() +{ +} + +EntryTankMoveTo::~EntryTankMoveTo() +{ +} + +int EntryTankMoveTo::getTargetId() +{ + return 7; +} + +// ELF 0x2C3FC0 (listing; Ghidra cross-check). The car entry's shape with the tank's tuning: no +// initial flag stores; the equipment's mobile/control/physical members are read before the +// equipment is null-tested (as shipped); physics is enabled also when already on while the static +// alwaysEnable is set; turn factor 1 - min(1, 2.5 * max(0, |largest angle diff| - 0.35)) * 0.7 +// above 3 m/s; the approach factor uses the SQUARED distance minus the smallest radius and 0.5 +// against fallOffDistanceSqr (196), at least 0.35; and TankControl gets the normalised direction. +bool EntryTankMoveTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static bool alwaysEnable; // .bss 0x4CE5B1 (false) + static float fallOffDistanceSqr = 196.0f; // .data 0x4BD8C4 + + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = info->getMobile(); // read before the null test (0x2C401E) + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!info || !mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (alwaysEnable || !object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + const double last = static_cast(bot)->getLastCheckMoveToFinishedTime(); // Bot +0x274 + done = false; + if (now - last > 1.0) + { + static_cast(bot)->setLastCheckMoveToFinishedTime(now); // +0x270 + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + } + + Vec2 target; + target.x = target.y = 0.0f; + bool arrived; + ok = moveTo->update(target, done, arrived, 0.0f) != 0; + if (!ok) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = target.x - position.x; + toTarget.y = target.y - position.y; + Vec2 direction = toTarget; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-05f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 3.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - 0.35f) + excess = std::fabs(largestAngle) - 0.35f; + float scaled = excess * 2.5f; + if (1.0f < excess * 2.5f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * 0.7f; + } + + float mode; + float angle; + float reference; + float limit; + ok = TankControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + const float maxSpeed = mobile->getMaxSpeed(); + Vec2 remaining; + remaining.x = target.x - position.x; + remaining.y = target.y - position.y; + const float remainingSqr = remaining.y * remaining.y + remaining.x * remaining.x; + float approachFactor = 1.0f; + const float gap = remainingSqr - physical->getSmallestRadius() - 0.5f; + if (gap < fallOffDistanceSqr) + { + approachFactor = gap / fallOffDistanceSqr; + if (approachFactor <= 0.35f) + approachFactor = 0.35f; + } + const float factor = (approachFactor < turnFactor) ? approachFactor : turnFactor; + ok = TankControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), direction, + factor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.h new file mode 100644 index 000000000..7414c9287 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.h @@ -0,0 +1,28 @@ +// EntryTankMoveTo: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETO_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankMoveTo - statement type 7. +class EntryTankMoveTo : public BAPEntry +{ +public: + EntryTankMoveTo(); + virtual ~EntryTankMoveTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp new file mode 100644 index 000000000..bbd0b6bdb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp @@ -0,0 +1,143 @@ +// EntryTankMoveToDirection (split out of BAPEntries.cpp by S0, bodies unchanged). + +// static init: ELF 0x2C5110 (__tcf_0 0x2C5170, _GLOBAL__I 0x2C51A0): 's Init object only. +#include + +#include "EntryTankMoveToDirection.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveToDirection.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C4760 (C1; C2 0x2C4740). +EntryTankMoveToDirection::EntryTankMoveToDirection() +{ +} + +// ELF 0x2C47A0 (D1; D2 0x2C4780, D0 0x2C47C0). +EntryTankMoveToDirection::~EntryTankMoveToDirection() +{ +} + +// ELF 0x2C51C0. +int EntryTankMoveToDirection::getTargetId() +{ + return 8; +} + +// ELF 0x2C4800. +bool EntryTankMoveToDirection::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAMoveToDirection* const moveTo = static_cast(script); + Vec2 position = {0.0f, 0.0f}; + Vec2 direction = {0.0f, 0.0f}; + Vec2 normal = {0.0f, 0.0f}; + Vec2 facing = {0.0f, 0.0f}; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(info->getSide()); + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + vec3ToVec2XZ(info->getPosition(), position); + const Vec3 face = info->getFaceing(); + vec3ToVec2XZ(face, facing); + getNormal(facing, normal); + vehiclecontrol::normalizeVec2(normal); + const float magnitude = info->getMobile()->getSpeedMagnitude(); + const Vec3 facing3 = info->getFaceing(); + const Vec3& speed = info->getMobile()->getSpeed(); + const float speedDot = speed.x * facing3.x + speed.y * facing3.y + speed.z * facing3.z; + const float sign = speedDot > 0.0f ? 1.0f : (speedDot < 0.0f ? -1.0f : 0.0f); + const float signedSpeed = sign * magnitude; + const auto clampCos = [](float value) { + const float upper = value > 1.0f ? 1.0f : value; + return upper > -1.0f ? upper : -1.0f; + }; + float targetAngle; + float targetSpeed; + if (moveTo->m_condition64->evaluate(bot)) + { + vec3ToVec2XZ(moveTo->m_direction, direction); + targetSpeed = 0.0f; + const float dot = direction.x * normal.x + direction.y * normal.y; + if (facing.x * direction.x + facing.y * direction.y > 0.0f) + targetAngle = std::acos(clampCos(dot)) - 1.5707964f; + else + { + const float clamped = clampCos(dot); + const float directionSign = clamped > 0.0f ? 1.0f : (clamped < 0.0f ? -1.0f : 0.0f); + targetAngle = directionSign * 1.5707964f; + } + } + else + { + Vec2 point = {0.0f, 0.0f}; + ok = moveTo->update(point, done) != 0; + if (!ok) + { + done = true; + return true; + } + direction = {point.x - position.x, point.y - position.y}; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y); + if (length > 1e-06f) + { + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + } + targetAngle = std::acos(clampCos(direction.x * normal.x + direction.y * normal.y)) - 1.5707964f; + const float angleSign = targetAngle > 0.0f ? 1.0f : (targetAngle < 0.0f ? -1.0f : 0.0f); + const float absoluteAngle = targetAngle < 0.0f ? -targetAngle : targetAngle; + const float facingDot = facing.x * direction.x + facing.y * direction.y; + vehiclecontrol::normalizeVec2(facing); + if (absoluteAngle > 0.87266463f || facingDot < 0.0f) + targetAngle = angleSign * 0.017453292f * 90.0f; + const float maximum = info->getMobile()->getMaxSpeed(); + targetSpeed = moveTo->m_maxSpeed > maximum ? maximum : moveTo->m_maxSpeed; + if (facingDot < 0.0f) + targetSpeed = 0.0f; + } + io::PlayerInput* const input = bot->getInput(); + float turnInput = (input->mappingFlags & 1ULL) ? input->inputs[0] : 0.0f; + float throttle = (input->mappingFlags & 8ULL) ? input->inputs[3] : 0.0f; + const float facingDot = facing.x * moveTo->m_state68.y + facing.y * moveTo->m_state68.z; + updateAngle(targetAngle, std::acos(clampCos(facingDot)), turnInput, 1.0f, 1.0f, 0.8f); + updateLinear(targetSpeed, signedSpeed, moveTo->m_state68.x, throttle, -0.9f, 1.0f, 1.0f); + moveTo->m_state68.y = facing.x; + moveTo->m_state68.z = facing.y; + moveTo->m_state68.x = signedSpeed; + io::PlayerInput* const output = bot->getInput(); + if (output->mappingFlags & 1ULL) + output->inputs[0] = turnInput; + bot->getInput()->setInput(static_cast(3), throttle); + ok = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.h new file mode 100644 index 000000000..6aa4b1d6b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.h @@ -0,0 +1,27 @@ +// EntryTankMoveToDirection: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETODIRECTION_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETODIRECTION_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankMoveToDirection - statement type 8. +class EntryTankMoveToDirection : public BAPEntry +{ +public: + EntryTankMoveToDirection(); + virtual ~EntryTankMoveToDirection(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETODIRECTION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp new file mode 100644 index 000000000..7507f813c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp @@ -0,0 +1,172 @@ +// EntryTankMoveToObject (attested TU `EntryTankMoveToObject.cpp`, split out of BAPEntries.cpp by S0). +// Recovered from libaidll.so (Linux 1.5.3153, ia-32): the interpreter entry that drives a tank +// to an object (a BAPAMoveTo with a target object). execute's flags follow the BotScript +// convention: `ok` (the step ran) and `done` (the statement is finished; with ok == false it failed). +// +// static init: ELF 0x2C5940 (__tcf_0 0x2C59A0, _GLOBAL__I 0x2C59D0): the guard object only. + +#include "EntryTankMoveToObject.h" + +#include "TankControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +EntryTankMoveToObject::EntryTankMoveToObject() +{ +} + +EntryTankMoveToObject::~EntryTankMoveToObject() +{ +} + +int EntryTankMoveToObject::getTargetId() +{ + return 9; +} + +// ELF 0x2C5290 (listing; Ghidra cross-check). EntryTankMoveTo's steering for a move to an object, +// with these differences: physics is enabled only when off (no alwaysEnable static); it fails +// (done, not ok) without the target's information; isFinished is asked on every call (no +// one-second throttle); update gets the target's radius (its physical part +0x2C, unchecked); the +// direction is normalised above 1e-06. Shipped quirks kept: the equipment's parts are read before +// its null test, the fall-off compares the SQUARED distance (static fallOffDistanceSqr 196). +bool EntryTankMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float fallOffDistanceSqr = 196.0f; // .data 0x4BD984 + + BAPAMoveTo* const moveTo = static_cast(script); + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = info->getMobile(); // read before the null test (0x2C52F6) + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!info || !mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + Information* const target = informationManager->getInformation(moveTo->getObject()); + if (!target) + { + done = true; + ok = false; + return true; + } + if (moveTo->isFinished(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + + Vec2 point; + point.x = point.y = 0.0f; + bool arrived; + ok = moveTo->update(point, done, arrived, target->getPhysical()->getRadius()) != 0; + if (!ok) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (arrived || done) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + return true; + } + + Vec2 position; + position.x = info->getPosition().x; + position.y = info->getPosition().z; + Vec2 forward; // read, never used + forward.x = info->getTransformation().m[8]; + forward.y = info->getTransformation().m[10]; + (void)forward; + Vec2 toTarget; + toTarget.x = point.x - position.x; + toTarget.y = point.y - position.y; + Vec2 direction = toTarget; + const float distance = std::sqrt(toTarget.x * toTarget.x + toTarget.y * toTarget.y); + if (distance > 1e-06f) + { + const float inverse = 1.0f / distance; + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + float turnFactor = 1.0f; + float largestAngle; + if (std::fabs(mobile->getSpeedMagnitude()) > 3.0f && moveTo->getLargestAngleDiff(largestAngle)) + { + float excess = 0.0f; + if (0.0f <= std::fabs(largestAngle) - 0.35f) + excess = std::fabs(largestAngle) - 0.35f; + float scaled = excess * 2.5f; + if (1.0f < excess * 2.5f) + scaled = 1.0f; + turnFactor = 1.0f - scaled * 0.7f; + } + + float mode; + float angle; + float reference; + float limit; + ok = TankControl::actionStatusDecision(bot, info, direction, distance, moveTo, mode, angle, reference, limit) != 0; + if (mode == 666.0f) + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + ok = TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z) != 0; + done = true; + return true; + } + if (!ok) + return true; + + const float maxSpeed = mobile->getMaxSpeed(); + Vec2 remaining; + remaining.x = point.x - position.x; + remaining.y = point.y - position.y; + const float remainingSqr = remaining.y * remaining.y + remaining.x * remaining.x; + float approachFactor = 1.0f; + const float gap = remainingSqr - physical->getSmallestRadius() - 0.5f; + if (gap < fallOffDistanceSqr) + { + approachFactor = gap / fallOffDistanceSqr; + if (approachFactor <= 0.35f) + approachFactor = 0.35f; + } + const float factor = (approachFactor < turnFactor) ? approachFactor : turnFactor; + ok = TankControl::controlTowardsDirection(info, controlInfo, mobile, physical, bot->getInput(), direction, + factor * maxSpeed, mode, angle, reference, limit) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.h new file mode 100644 index 000000000..1b34f398c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.h @@ -0,0 +1,28 @@ +// EntryTankMoveToObject: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETOOBJECT_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETOOBJECT_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankMoveToObject - statement type 9. +class EntryTankMoveToObject : public BAPEntry +{ +public: + EntryTankMoveToObject(); + virtual ~EntryTankMoveToObject(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKMOVETOOBJECT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp new file mode 100644 index 000000000..3e9e1aca8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp @@ -0,0 +1,64 @@ +// EntryTankResetControls (split out of BAPEntries.cpp by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +// static init: ELF 0x2C5D70 (__tcf_0 0x2C5DD0, _GLOBAL__I 0x2C5E00): 's Init object only. +#include + +#include "EntryTankResetControls.h" + +#include "TankControl.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPAResetControls.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/AIDllFrontier.h" +#include "../../../../IO/Input/PlayerInput.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryTankResetControls::EntryTankResetControls() +{ +} + +EntryTankResetControls::~EntryTankResetControls() +{ +} + +int EntryTankResetControls::getTargetId() +{ + return 14; +} + +// ELF 0x2C5AC0 (Ghidra, listing for the dot product). A single-input reset releases that one +// input (setInput inlined with its range diagnostic) and succeeds. The group form resets through +// TankControl::resetControls with the equipment's forward speed (mobile speed dot facing); the +// information lookup is not null-tested. Unlike the car entry, nothing is asked for twice. +// `ok` is that call's answer; `done` is always set. +bool EntryTankResetControls::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPAResetControls* const reset = static_cast(script); + if (reset->hasSingleInput()) + { + io::PlayerInput* const input = bot->getInput(); + input->setInput(static_cast(reset->getInput()), 0.0f); + ok = true; + done = true; + return true; + } + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + done = true; + const Vec3 facing = equipment->getFaceing(); // +0x40 + const Vec3& speed = mobile->getSpeed(); // +0x1C + const float forwardSpeed = speed.y * facing.y + speed.x * facing.x + speed.z * facing.z; + ok = TankControl::resetControls(bot, bot->getInput(), reset->m_resetMove, reset->m_resetLook, + reset->m_resetTrigger, forwardSpeed) != 0; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.h new file mode 100644 index 000000000..20277ffbb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.h @@ -0,0 +1,28 @@ +// EntryTankResetControls: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKRESETCONTROLS_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKRESETCONTROLS_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankResetControls - statement type 14. +class EntryTankResetControls : public BAPEntry +{ +public: + EntryTankResetControls(); + virtual ~EntryTankResetControls(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKRESETCONTROLS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp new file mode 100644 index 000000000..d1949143d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp @@ -0,0 +1,183 @@ +// Tank turning entry for BAPATurn. Attested TU: EntryTankTurnTo.cpp. + +// static init: ELF 0x2C6780 (__tcf_0 0x2C67E0, _GLOBAL__I 0x2C6810): 's Init object only. +#include + +#include "EntryTankTurnTo.h" + +#include "TankControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATurn.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C5E50 (C1; C2 0x2C5E30). +EntryTankTurnTo::EntryTankTurnTo() +{ +} + +// ELF 0x2C5E90 (D1; D2 0x2C5E70, D0 0x2C5EB0). +EntryTankTurnTo::~EntryTankTurnTo() +{ +} + +// ELF 0x2C6830. +int EntryTankTurnTo::getTargetId() +{ + return 24; +} + +// ELF 0x2C5EF0. The end condition finishes the statement; otherwise getDirection supplies ok, +// and the entry turns or brakes while keeping the statement active. +bool EntryTankTurnTo::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPATurn* const turn = static_cast(script); + Vec2 position; + position.x = position.y = 0.0f; + if (turn->m_endCondition->evaluate(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + if (!object->hasPhysicsEnabled()) + object->enablePhysics(info->getSide()); + IPIMobile* const mobile = info->getMobile(); + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physical = info->getPhysical(); + if (!mobile || !controlInfo || !physical) + { + done = true; + ok = false; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + const Vec3 target = turn->getDirection(ok); + if (!ok) + { + done = true; + return true; + } + Vec2 direction; + vec3ToVec2XZ(target, direction); + vehiclecontrol::normalizeVec2(direction); + const Mat4& forwardTransform = info->getTransformation(); + const Vec3& forward3 = *reinterpret_cast(&forwardTransform.m[8]); + Vec2 forward; + vec3ToVec2XZ(forward3, forward); + vehiclecontrol::normalizeVec2(forward); + Vec2 right; + vec3ToVec2XZ(vehiclecontrol::rightAxis(info->getTransformation()), right); + vehiclecontrol::normalizeVec2(right); + float dot = right.x * direction.x + right.y * direction.y; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + const float halfPi = 1.570796371f; + float angle = acosf(dot) - halfPi; + if (angle < -halfPi) + angle = -halfPi; + else if (angle > halfPi) + angle = halfPi; + if (forward.x * direction.x + forward.y * direction.y < 0.0f) + { + if (angle == 0.0f) + angle = 3.141592741f; + else + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = angle + sign * halfPi; + } + } + if (std::fabs(angle) > turn->m_turnSpeed) + TankControl::turnTowardsDirection(angle, turn->m_turnSpeed, true, info, mobile, + controlInfo, bot->getInput(), &ok); + else + { + const Vec3 facing = info->getFaceing(); + const Vec3& speed = mobile->getSpeed(); + TankControl::resetControls(bot, bot->getInput(), true, false, false, + speed.x * facing.x + speed.y * facing.y + speed.z * facing.z); + } + const Mat4& transformation = info->getTransformation(); + turn->m_vec28.x = transformation.m[8]; + turn->m_vec28.y = transformation.m[9]; + turn->m_vec28.z = transformation.m[10]; + turn->m_unwritten24 = mobile->getSpeedMagnitude(); + return true; +} + +// ELF 0x2C65E0. Returns the midpoint of the two lowest-scored relative box corners. +// Corners outside the facing half-plane receive -1 and remain eligible. +void EntryTankTurnTo::getCentreOfFacingSide(const Vec2& origin, const Vec2& minimum, + const Vec2& maximum, const Vec2& facing, Vec2& centre) +{ + Vec2 corners[4]; + corners[0] = minimum; + corners[1].x = minimum.x; + corners[1].y = maximum.y; + corners[2].x = maximum.x; + corners[2].y = minimum.y; + corners[3] = maximum; + const float dx = facing.x - origin.x; + const float dy = facing.y - origin.y; + float scores[4]; + for (int i = 0; i < 4; ++i) + { + corners[i].x = corners[i].x - origin.x; + corners[i].y = corners[i].y - origin.y; + if (dx * corners[i].x + dy * corners[i].y > 0.0f) + scores[i] = corners[i].x * corners[i].x + corners[i].y * corners[i].y; + else + scores[i] = -1.0f; + } + int first = 0; + int second = 1; + if (scores[0] > scores[1]) + { + first = 1; + second = 0; + } + for (int i = 2; i < 4; ++i) + { + if (scores[first] > scores[i]) + { + second = first; + first = i; + } + else if (scores[second] > scores[i]) + second = i; + } + centre = corners[first]; + centre.x = centre.x + corners[second].x; + centre.y = centre.y + corners[second].y; + centre.x = centre.x * 0.5f; + centre.y = centre.y * 0.5f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.h new file mode 100644 index 000000000..0241c3394 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.h @@ -0,0 +1,30 @@ +// Tank turning entry for BAPATurn. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKTURNTO_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKTURNTO_H + +#include "BAPEntry.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTankTurnTo - statement type 24. +class EntryTankTurnTo : public BAPEntry +{ +public: + EntryTankTurnTo(); + virtual ~EntryTankTurnTo(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); + // Returns a midpoint relative to the first argument, using the shipped corner scores. + void getCentreOfFacingSide(const Vec2&, const Vec2&, const Vec2&, const Vec2&, Vec2&); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTANKTURNTO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp new file mode 100644 index 000000000..a18f8b985 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp @@ -0,0 +1,226 @@ +// EntryTrigger (attested TU `EntryTrigger.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPATrigger (statement type 11). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C7270 (__tcf_0 0x2C72D0, _GLOBAL__I 0x2C7300): 's Init object only. +#include + +#include "EntryTrigger.h" + +#include "InfanteryControl.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryTrigger::EntryTrigger() +{ +} + +EntryTrigger::~EntryTrigger() +{ +} + +int EntryTrigger::getTargetId() +{ + return 11; +} + +namespace { + +inline Information* lookup(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +} // namespace + +// ELF 0x2C6900. Presses the statement's input once the start condition holds and releases it on the +// stop condition (or right away for a one-shot trigger: m_flag false finishes on the press). For +// weapon-select inputs it finishes as soon as that weapon is active. For PIFire/PIAltFire it first +// puts the soldier into the weapon's firing pose (crouching against a lying target closer than +// `range`) and tunes the weapon's bot skill: 1 for thrown or guided weapons, otherwise +// 1 - (1 - skill) * {0.5 direct fire, 0.8 explosive from a vehicle, 0.4 explosive on foot}, with +// direct fire at an occupied human vehicle left at the raw skill; the scale is 3 against an +// object flagged 0x10 by a secondary non-0x80 object (the image's flag tests on Information +4). +bool EntryTrigger::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + static float range = 1.0f; // ELF 0x4BDAA4 (.data), compared with a squared XZ distance + + BAPATrigger* trigger = static_cast(script); + BotMain* botMain = static_cast(bot); + int type = trigger->m_input; + Information* info = lookup(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + WeaponInfo* weapon = 0; + if (armament != 0 && armament->getActiveWeapon() != -1) + weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + + const io::PlayerInput* input = bot->getInput(); + bool moving = false; + if (infantry_detail::inputValue(input, io::PIThrottle) != 0.0f + || infantry_detail::inputValue(input, io::PIYaw) != 0.0f + || infantry_detail::inputValue(input, io::PISprint) != 0.0f) + moving = true; + bool isFire = false; + if (type == io::PIFire || type == io::PIAltFire) + isFire = true; + bool allowPress = true; + if (isFire && botMain->botInPoseTransition()) + allowPress = false; + + if (weapon != 0) + { + if (static_cast(type - io::PIWeaponSelect1) < 8) + { + if (weapon->getWeaponActivate() == type) + { + ok = true; + done = true; + return true; + } + if (trigger->m_started) + { + ok = true; + done = false; + return true; + } + } + else if (weapon->getWeaponZoom() == type) + { + if (moving) + return true; + } + else if (isFire) + { + if (!moving && weapon->getWeaponType() != 4) + { + SoldierPose pose = SPStanding; + if (info->getObjectTypeFlags() & 0x200000) + { + pose = weapon->getFiringPose(); + if (armament->getActiveWeapon() == 0 + || (bot->getFiringTarget() != static_cast(-1) && weapon->getWeaponType() == 3)) + { + Vec2 own; + own.x = own.y = 0.0f; + Vec2 other; + other.x = other.y = 0.0f; + vec3ToVec2XZ(info->getPosition(), own); + Information* target = lookup(bot->getFiringTarget()); + if (target != 0) + { + vec3ToVec2XZ(target->getPosition(), other); + const float dx = other.x - own.x; + const float dy = other.y - own.y; + if (dy * dy + dx * dx < range && target->getSoldierPose() == SPLying) + pose = SPCrouching; + } + } + } + const SoldierPose current = info->getSoldierPose(); + if (current != SPSwimming && current != pose) + bot->requestSoldierPose(pose, false); + } + + Information* target = lookup(bot->getFiringTarget()); + float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + bool humanVehicle = false; + if (target != 0 && target->getAIObject() != 0 + && IBotManager::instance->getBot(target->getAIObject()) == 0 + && target->getUnit() != 0 && target->getUnit()->isOccupied()) + humanVehicle = true; + if (weapon->getWeaponZoom() != io::PINone && bot->getSpawnKit() == 1) + weapon->getMaxRange(); // retail: the result is dropped + if (!weapon->getIsThrown()) + { + if (weapon->getExplosionRadius() == 0.0f) + { + if (!humanVehicle) + skill = 1.0f - (1.0f - skill) * 0.5f; + } + else if ((info->getObjectTypeFlags() & 0x200000) == 0) + { + skill = 1.0f - (1.0f - skill) * 0.8f; + } + else + { + skill = 1.0f - (1.0f - skill) * 0.4f; + } + } + else + { + skill = 1.0f; + } + if (weapon->getWeaponGuidanceType() != 0) + skill = 1.0f; + float scale = 1.0f; + bool apply = true; + if ((info->getObjectTypeFlags() & 0x10) == 0) + { + if (target == 0) + apply = false; + else if ((target->getObjectTypeFlags() & 0x10) != 0 && !info->isPrimary() + && (info->getObjectTypeFlags() & 0x80) == 0) + scale = 3.0f; + } + if (apply) + weapon->setBotSkill(skill, bot->getFiringTargetTime(), scale); + } + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now < trigger->m_endTime) + return true; + io::PlayerInput* writable = bot->getInput(); + if (trigger->m_stopCondition != 0 && trigger->m_stopCondition->evaluate(bot)) + { + // inlined setInput in the image + writable->setInput(static_cast(type), 0.0f); + trigger->m_started = false; + ok = true; + done = true; + return true; + } + if (!trigger->m_started || !trigger->m_flag) + { + if (allowPress && trigger->m_startCondition->evaluate(bot)) + { + writable->setInput(static_cast(trigger->m_input), 1.0f); + trigger->m_started = true; + ok = true; + done = !trigger->m_flag; + return true; + } + writable->setInput(static_cast(trigger->m_input), 0.0f); + trigger->m_started = false; + ok = true; + done = false; + return true; + } + writable->setInput(static_cast(trigger->m_input), 0.0f); + trigger->m_started = false; + ok = true; + done = true; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.h new file mode 100644 index 000000000..71b1fd4bd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.h @@ -0,0 +1,28 @@ +// EntryTrigger: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGER_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTrigger - statement type 11. +class EntryTrigger : public BAPEntry +{ +public: + EntryTrigger(); + virtual ~EntryTrigger(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp new file mode 100644 index 000000000..2ff5983b3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp @@ -0,0 +1,180 @@ +// EntryTriggerContinously (attested TU `EntryTriggerContinously.cpp`, split out of BAPEntries.cpp by S0). Recovered from +// libaidll.so (Linux 1.5.3153, ia-32): the soldier entry for BAPATriggerContinously (statement type 12). Package B; see docs/macos-ai-behaviour-plan.md. +// execute's flags follow the BotScript convention: `ok` (the step ran) and `done` (finished; with +// ok == false the statement failed). + +// static init: ELF 0x2C7CD0 (__tcf_0 0x2C7D30, _GLOBAL__I 0x2C7D60): 's Init object only. +#include + +#include "EntryTriggerContinously.h" + +#include "InfanteryControl.h" +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +EntryTriggerContinously::EntryTriggerContinously() +{ +} + +EntryTriggerContinously::~EntryTriggerContinously() +{ +} + +int EntryTriggerContinously::getTargetId() +{ + return 12; +} + +namespace { + +inline Information* lookup(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +} // namespace + +// ELF 0x2C73F0. Holds the statement's input while the start condition holds (or, once started, +// until the stop condition holds) and finishes on the abort condition. For PIFire/PIAltFire it puts +// the soldier into the weapon's firing pose (not for kit 4's weapon 5 on foot) and tunes the +// weapon's bot skill as EntryTrigger does, without the thrown-weapon case. Fails (ok false, done) +// for a fire input when the bot has weapons but no active one. +bool EntryTriggerContinously::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPATriggerContinously* trigger = static_cast(script); + BotMain* botMain = static_cast(bot); + Information* info = lookup(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + WeaponInfo* weapon = 0; + if (armament != 0 && armament->getActiveWeapon() != -1) + weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + + const int type = trigger->m_input; + bool isFire = false; + if (type == io::PIFire || type == io::PIAltFire) + isFire = true; + bool allowPress = true; + if (isFire) + { + allowPress = !botMain->botInPoseTransition(); + if (weapon == 0) + { + if (armament != 0) + { + ok = false; + done = true; + return true; + } + } + else + { + const io::PlayerInput* input = bot->getInput(); + if (infantry_detail::inputValue(input, io::PIThrottle) == 0.0f + && infantry_detail::inputValue(input, io::PIYaw) == 0.0f + && infantry_detail::inputValue(input, io::PISprint) == 0.0f + && !(bot->getSpawnKit() == 4 && (info->getObjectTypeFlags() & 0x200000) != 0 + && armament->getActiveWeapon() == 5)) + { + SoldierPose pose = SPStanding; + if (info->getObjectTypeFlags() & 0x200000) + pose = weapon->getFiringPose(); + const SoldierPose current = info->getSoldierPose(); + if (current != SPSwimming && current != pose) + bot->requestSoldierPose(pose, false); + } + + Information* target = lookup(bot->getFiringTarget()); + float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + bool humanVehicle = false; + if (target != 0 && target->getAIObject() != 0 + && IBotManager::instance->getBot(target->getAIObject()) == 0 + && target->getUnit() != 0 && target->getUnit()->isOccupied()) + humanVehicle = true; + weapon->getExplosionRadius(); // retail: called twice, the first result dropped + if (weapon->getExplosionRadius() == 0.0f) + { + if (!humanVehicle) + skill = 1.0f - (1.0f - skill) * 0.5f; + } + else if ((info->getObjectTypeFlags() & 0x200000) == 0) + { + skill = 1.0f - (1.0f - skill) * 0.8f; + } + else + { + skill = 1.0f - (1.0f - skill) * 0.4f; + } + if (weapon->getWeaponGuidanceType() != 0) + skill = 1.0f; + float scale = 1.0f; + bool apply = true; + if ((info->getObjectTypeFlags() & 0x10) == 0) + { + if (target == 0) + apply = false; + else if ((target->getObjectTypeFlags() & 0x10) != 0 && !info->isPrimary() + && (info->getObjectTypeFlags() & 0x80) == 0) + scale = 3.0f; + } + if (apply) + weapon->setBotSkill(skill, bot->getFiringTargetTime(), scale); + } + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now < trigger->m_endTime) + return true; + if (trigger->m_abortCondition != 0 && trigger->m_abortCondition->evaluate(bot)) + { + ok = true; + done = true; + return true; + } + io::PlayerInput* writable = bot->getInput(); + if (allowPress) + { + if (trigger->m_startCondition->evaluate(bot)) + { + // inlined setInput in the image + writable->setInput(static_cast(type), 1.0f); + trigger->m_started = true; + ok = true; + done = false; + return true; + } + if (trigger->m_stopCondition != 0 && trigger->m_started && !trigger->m_stopCondition->evaluate(bot)) + { + writable->setInput(static_cast(type), 1.0f); + ok = true; + done = false; + return true; + } + } + // inlined setInput in the image + writable->setInput(static_cast(type), 0.0f); + trigger->m_started = false; + ok = true; + done = false; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.h new file mode 100644 index 000000000..c59cb8478 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.h @@ -0,0 +1,28 @@ +// EntryTriggerContinously: action-plan entry (split out of BAPEntries.h by S0, bodies unchanged). +// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate execute. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGERCONTINOUSLY_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGERCONTINOUSLY_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { +namespace ai { + +// EntryTriggerContinously - statement type 12. +class EntryTriggerContinously : public BAPEntry +{ +public: + EntryTriggerContinously(); + virtual ~EntryTriggerContinously(); + + virtual bool execute(BotScript *, Bot *, bool&, bool&); + virtual int getTargetId(); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTRIGGERCONTINOUSLY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp new file mode 100644 index 000000000..1e88e17c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp @@ -0,0 +1,165 @@ +// Medium-LOD turning entry for BAPATurn. Attested TU: EntryTurnToMedium.cpp. + +// static init: ELF 0x2C89C0 (__tcf_0 0x2C8A20, _GLOBAL__I 0x2C8A50): 's Init object only. +#include + +#include "EntryTurnToMedium.h" + +#include "InfanteryControl.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBotActionPlan/BAPATurn.h" +#include "../AIBotActionPlan/BAPCondition.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2C7DB0 (C1; C2 0x2C7D90). +EntryTurnToMedium::EntryTurnToMedium() +{ +} + +// ELF 0x2C7DF0 (D1; D2 0x2C7DD0, D0 0x2C7E10). +EntryTurnToMedium::~EntryTurnToMedium() +{ +} + +// ELF 0x2C7E50. Turns the object without physics using a fixed angular step per tick, then +// aligns its axes to the terrain normal without moving its position. Only the condition ends it. +bool EntryTurnToMedium::execute(BotScript* script, Bot* bot, bool& ok, bool& done) +{ + BAPATurn* const turn = static_cast(script); + Vec2 position; + position.x = position.y = 0.0f; + if (turn->m_endCondition->evaluate(bot)) + { + done = true; + ok = true; + return true; + } + done = false; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + if (!info) + { + done = true; + ok = false; + return true; + } + IAIObjectPhysical* const physical = info->getAIObject()->getPhysical(); + if (physical->hasPhysicsEnabled()) + physical->disablePhysics(info->getSide()); + IPIMobile* const mobile = info->getMobile(); + IPIControlInfo* const controlInfo = info->getControlInfo(); + IPIPhysical* const physicalInfo = info->getPhysical(); + if (!mobile || !controlInfo || !physicalInfo) + { + done = true; + ok = false; + return true; + } + vec3ToVec2XZ(info->getPosition(), position); + const Vec3 target = turn->getDirection(ok); + if (!ok) + { + done = true; + return true; + } + Vec2 direction; + vec3ToVec2XZ(target, direction); + vehiclecontrol::normalizeVec2(direction); + const Mat4& forwardTransform = info->getTransformation(); + const Vec3& forward3 = *reinterpret_cast(&forwardTransform.m[8]); + Vec2 forward2; + vec3ToVec2XZ(forward3, forward2); + vehiclecontrol::normalizeVec2(forward2); + Vec2 right2; + vec3ToVec2XZ(vehiclecontrol::rightAxis(info->getTransformation()), right2); + vehiclecontrol::normalizeVec2(right2); + float dot = right2.x * direction.x + right2.y * direction.y; + if (dot < -1.0f) + dot = -1.0f; + else if (dot > 1.0f) + dot = 1.0f; + const float halfPi = 1.570796371f; + float angle = acosf(dot) - halfPi; + if (angle < -halfPi) + angle = -halfPi; + else if (angle > halfPi) + angle = halfPi; + if (forward2.x * direction.x + forward2.y * direction.y < 0.0f) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + angle = angle + sign * halfPi; + } + const float magnitude = std::fabs(angle); + if (magnitude > turn->m_turnSpeed) + { + IAIObject* const object = info->getAIObject(); + const Mat4& current = object->getTransformation(); + (void)info->getPosition(); + Vec3 forward; + const float step = 0.003926991f; + if (magnitude > step) + { + const float sign = angle > 0.0f ? 1.0f : (0.0f > angle ? -1.0f : 0.0f); + const Vec3& currentForward = *reinterpret_cast(¤t.m[8]); + rotateXZ(currentForward, forward, sign * step); + } + else + { + forward.x = direction.x; + forward.y = 0.0f; + forward.z = direction.y; + } + const Vec3& objectPosition = object->getPosition(); + float height; + Vec3 up; + up.x = up.y = up.z = 0.0f; + float slope; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getHeightAndNormalForObject(object, objectPosition, height, up, slope); + Vec3 right = infantry_detail::crossInline(up, forward); + vehiclecontrol::normalizeVec3(right); + forward = infantry_detail::crossInline(right, up); + vehiclecontrol::normalizeVec3(forward); + Mat4 transformation = current; + transformation.m[0] = right.x; + transformation.m[1] = right.y; + transformation.m[2] = right.z; + transformation.m[4] = up.x; + transformation.m[5] = up.y; + transformation.m[6] = up.z; + transformation.m[8] = forward.x; + transformation.m[9] = forward.y; + transformation.m[10] = forward.z; + object->setTransformation(transformation, bot->getSide()); + } + const Mat4& transformation = info->getTransformation(); + turn->m_vec28.x = transformation.m[8]; + turn->m_vec28.y = transformation.m[9]; + turn->m_vec28.z = transformation.m[10]; + turn->m_unwritten24 = mobile->getSpeedMagnitude(); + return true; +} + +// ELF 0x2C8A70 +int EntryTurnToMedium::getTargetId() +{ + return 24; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.h new file mode 100644 index 000000000..5231920ab --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.h @@ -0,0 +1,31 @@ +// Medium-LOD turning entry for BAPATurn. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTURNTOMEDIUM_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTURNTOMEDIUM_H + +#include "BAPEntry.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// ELF: vtable 0x4BDB68; fieldless BAPEntry subclass. +class EntryTurnToMedium : public BAPEntry +{ +public: + EntryTurnToMedium(); // 0x2C7DB0 + virtual ~EntryTurnToMedium(); // 0x2C7DF0 + + virtual bool execute(BotScript*, Bot*, bool&, bool&); // 0x2C7E50, slot +0x08; from the base declaration + virtual int getTargetId(); // 0x2C8A70, slot +0x0C; from the base declaration +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_ENTRYTURNTOMEDIUM_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp new file mode 100644 index 000000000..ef29057f1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp @@ -0,0 +1,578 @@ +// Helicopter attitude, height and obstacle-avoidance controls. + +// static init: ELF 0x2CB150 (__tcf_0 0x2CB1B0, _GLOBAL__I 0x2CB1E0): 's Init object only. +#include + +#include "HeliControl.h" + +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIStrategicMap/AerialHeightMap.h" +#include "VehicleControlInline.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [INFERRED] Names for inline scalar/vector operations in the control bodies. +float clampHeliInput(float value, float minimum, float maximum) +{ + if (value < minimum) + return minimum; + return value > maximum ? maximum : value; +} + +Vec3 rotateHeliVector(const Mat4& matrix, const Vec3& v) +{ + // The retail expansions (moveToPoint 0x2C9A30..0x2C9A7D, aimAtDirection 0x2CA8CD..0x2CA91C) add the + // x and y products before the z product in every component. + return Vec3{matrix.m[0] * v.x + matrix.m[4] * v.y + matrix.m[8] * v.z, + matrix.m[1] * v.x + matrix.m[5] * v.y + matrix.m[9] * v.z, + matrix.m[2] * v.x + matrix.m[6] * v.y + matrix.m[10] * v.z}; +} + +} // namespace + +bool avoidRight(Bot* bot, float& clearance); + +// ELF 0x2C8A80 +void HeliControl::quickyMoveForward(Bot* bot, float heightDifference, const Vec3& rotationalSpeed) +{ + static float maxHeightDiff = 10.0f; + static float wantedPitchAtMaxHeight = -0.45f; + static float wantedPitchAtMinHeight = -0.1f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + input->setInput(information->getControlInfo()->getDriveThrottleControl(), 1.0f); + const float factor = clampHeliInput(heightDifference / maxHeightDiff, -1.0f, 1.0f); + keepPitchAt(bot, wantedPitchAtMinHeight + (wantedPitchAtMaxHeight - wantedPitchAtMinHeight) * + (1.0f - (factor + 1.0f) * 0.5f), + 1.0f, 0.3f, rotationalSpeed, 0.0f); +} + +// ELF 0x2C8D00 +int HeliControl::gotoHeight(Bot* bot, float height, const Vec3& rotationalSpeed) +{ + static float maxHeightDiff = 5.0f; + static float wantedElevationAtMaxHeightDiff = 5.0f; + static float maxElevationDiff = 2.0f; + static float minThrottleInput = 0.0f; + static float maxAngle = 0.3f; + static float wantedRotationSpeedAtMaxAngle = 0.5f; + static float maxRotationSpeedDiff = 0.4f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + if (!bot->isAirBorn() && information->getAltitude() > 5.0f) + bot->event_airborn(); + const Mat4& transformation = information->getTransformation(); + IPIMobile* mobile = information->getMobile(); + IPIControlInfo* controls = information->getControlInfo(); + const float elevation = clampHeliInput((height - transformation.m[13]) / maxHeightDiff, + -1.0f, 1.0f) * wantedElevationAtMaxHeightDiff; + const Vec3& speed = mobile->getSpeed(); + float throttle = clampHeliInput(clampHeliInput((elevation - speed.y) / maxElevationDiff, + -1.0f, 1.0f) + minThrottleInput, 0.0f, 1.0f); + if (elevation > 0.0f && speed.y < 0.0f && transformation.m[5] > 0.0f) + throttle = 1.0f; + input->setInput(controls->getDriveThrottleControl(), throttle); + float difference = (clampHeliInput(transformation.m[9] / maxAngle, -1.0f, 1.0f) * + wantedRotationSpeedAtMaxAngle - rotationalSpeed.x) / maxRotationSpeedDiff; + float value = difference * difference; + if (value > 1.0f) + value = 1.0f; + if (difference < 0.0f) + value = -value; + input->setInput(controls->getDrivePitchControl(), value); + difference = (-clampHeliInput(transformation.m[1] / maxAngle, -1.0f, 1.0f) * + wantedRotationSpeedAtMaxAngle - rotationalSpeed.z) / maxRotationSpeedDiff; + value = difference * difference; + if (value > 1.0f) + value = 1.0f; + if (difference > 0.0f) + value = -value; + input->setInput(controls->getDriveRollControl(), value); + input->setInput(controls->getDriveTurnControl(), 0.0f); + return 1; +} + +// ELF 0x2C9060 +void HeliControl::strafeTo(Bot* bot, const Vec3& target, const Vec3& rotationalSpeed) +{ + static float maxDist = 20.0f; + static float maxValue = 0.25f; + static float maxInput = 0.15f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + const Mat4& transformation = information->getTransformation(); + const Vec3 delta = {target.x - transformation.m[12], target.y - transformation.m[13], + target.z - transformation.m[14]}; + const float side = delta.x * transformation.m[0] + delta.y * transformation.m[1] + + delta.z * transformation.m[2]; + const float forward = delta.x * transformation.m[8] + delta.y * transformation.m[9] + + delta.z * transformation.m[10]; + keepRollAt(bot, -clampHeliInput(side / maxDist, -1.0f, 1.0f) * maxValue, + maxInput, 0.2f, rotationalSpeed); + keepPitchAt(bot, -clampHeliInput(forward / maxDist, -1.0f, 1.0f) * maxValue, + maxInput, 0.2f, rotationalSpeed, 0.0f); +} + +// ELF 0x2C9220 +void HeliControl::keepRollAt(Bot* bot, float dot, float maxInput, float maxSpeed, + const Vec3& rotationalSpeed) +{ + keepDotAt(bot, 2, dot, maxInput, maxSpeed, rotationalSpeed, 0.0f); +} + +// ELF 0x2C9280 +void HeliControl::keepPitchAt(Bot* bot, float dot, float maxInput, float maxSpeed, + const Vec3& rotationalSpeed, float feedForward) +{ + keepDotAt(bot, 0, dot, maxInput, maxSpeed, rotationalSpeed, feedForward); +} + +// ELF 0x2C92D0 +void HeliControl::keepDotAt(Bot* bot, int axis, float dot, float maxInput, float maxSpeed, + const Vec3& rotationalSpeed, float feedForward) +{ + static float maxDiff = 0.02f; + static float maxAngleSpeedDiff = 0.1f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + IPIControlInfo* controls = information->getControlInfo(); + const Mat4& transformation = information->getTransformation(); + const float currentDot = axis == 0 ? transformation.m[9] : transformation.m[1]; + const float speed = axis == 0 ? rotationalSpeed.x : rotationalSpeed.z; + float wantedSpeed = clampHeliInput((dot - currentDot) / maxDiff, -1.0f, 1.0f); + if (axis == 0) + wantedSpeed = -wantedSpeed; + float value = clampHeliInput(((wantedSpeed * maxSpeed - feedForward) - speed) / + maxAngleSpeedDiff, -1.0f, 1.0f) * maxInput; + if (axis == 2) + input->setInput(controls->getDriveRollControl(), -value); + else + input->setInput(controls->getDrivePitchControl(), value); +} + +// ELF 0x2C9450 +void HeliControl::limitSpeedTo(Bot* bot, float speed, float limit, float maxRotationSpeed, + const Vec3& rotationalSpeed) +{ + static float minPitch = 0.0f; + static float additional = 0.3f; + static float maxInput = 1.0f; + static float maxPitch = 0.5f; + if (limit > std::fabs(speed)) + return; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + information->getTransformation(); + float factor = (std::fabs(speed) - limit) / 5.0f; + float sign = speed > 0.0f ? 1.0f : (speed < 0.0f ? -1.0f : 0.0f); + if (factor > 1.0f) + factor = 1.0f; + keepPitchAt(bot, factor * factor * (limit == 0.0f ? maxPitch : additional) * sign + minPitch, + maxInput, maxRotationSpeed, rotationalSpeed, 0.0f); +} + +// ELF 0x2C95D0 +float HeliControl::keepHeight(Bot* bot, float clearance, float minimumHeight, + const Vec3& rotationalSpeed) +{ + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& speed = information->getMobile()->getSpeed(); + const Mat4& transformation = information->getTransformation(); + (void)std::sqrt(speed.x * speed.x + speed.y * speed.y + speed.z * speed.z); + float highest = -999999.0f; + for (int i = 0; i < 5; ++i) + { + const float time = static_cast(i); + const Vec3 position = {speed.x * time + transformation.m[12], + speed.y * time + transformation.m[13], + speed.z * time + transformation.m[14]}; + const float height = AerialHeightMap::m_instance->getGroundHeight(position); + if (height > highest) + highest = height; + } + float height = clearance + highest; + if (!(height > minimumHeight)) + height = minimumHeight; + gotoHeight(bot, height, rotationalSpeed); + return height - transformation.m[13]; +} + +// ELF 0x2C9760 +int HeliControl::moveToPoint(Bot* bot, const Vec3& point, float height, const Vec3& acceleration) +{ + static float minAltitudeDiff = 5.0f; + static float maxAltitudeDiff = 15.0f; + static float maxDistanceForStrafe = 20.0f; + static float minDist = 5.0f; + static float speedAtMax = 5.0f; + static float speedAtMin = 3.0f; + static float maxSpeed = 35.0f; + static float altitudeFactorTweak = 0.9f; + static float maxSpeedDiff = 10.0f; + static float maxAcceleration = 15.0f; + static float maxAccelerationDiff = 6.0f; + static float maxDiff = 0.2f; + static float maxInput = 1.0f; + Information* const info = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* const input = bot->getInput(); + if (!info) + return false; + IPIMobile* const mobile = info->getMobile(); + const Vec3& speed = mobile->getSpeed(); + const Mat4& transform = info->getTransformation(); + IPIControlInfo* const controls = info->getControlInfo(); + const Vec3& position = info->getPosition(); + Vec3 direction = {point.x - position.x, 0.0f, point.z - position.z}; + const float distance = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (distance < 0.001f) + direction = {0.0f, 0.0f, 1.0f}; + else + { + const float inverse = 1.0f / distance; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + const float altitude = AerialHeightMap::m_instance->getAltitude(info->getPosition()); + Mat4 inverseTransform = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + inverseTransform.setInverse(transform); + Vec3 facing = info->getFaceing(); + facing.y = 0.0f; + vehiclecontrol::normalizeVec3(facing); + const float forwardAcceleration = facing.x * acceleration.x + facing.y * acceleration.y + facing.z * acceleration.z; + const float forwardSpeed = facing.x * speed.x + facing.y * speed.y + facing.z * speed.z; + const Vec3& rotation = mobile->getRotationalSpeed(); + const Vec3 localRotation = { + rotation.x * inverseTransform.m[0] + rotation.y * inverseTransform.m[4] + rotation.z * inverseTransform.m[8], + rotation.x * inverseTransform.m[1] + rotation.y * inverseTransform.m[5] + rotation.z * inverseTransform.m[9], + rotation.x * inverseTransform.m[2] + rotation.y * inverseTransform.m[6] + rotation.z * inverseTransform.m[10]}; + float groundHeight; + if (avoidCrash(bot, localRotation, groundHeight)) + return true; + const float clearanceHeight = height + groundHeight; + const float desiredHeight = clearanceHeight > point.y ? clearanceHeight : point.y; + gotoHeight(bot, desiredHeight, localRotation); + const float heightDifference = desiredHeight - transform.m[13]; + float altitudeFactor = 0.0f; + if (!(minAltitudeDiff > heightDifference)) + { + altitudeFactor = (heightDifference - minAltitudeDiff) / (maxAltitudeDiff - minAltitudeDiff); + if (altitudeFactor > 1.0f) + altitudeFactor = 1.0f; + } + if (maxDistanceForStrafe > distance && altitudeFactor < 0.1f) + { + float desiredSpeed = speedAtMin; + if (!(minDist > distance)) + desiredSpeed = ((distance - minDist) / (maxDistanceForStrafe - minDist)) * (speedAtMax - speedAtMin) + speedAtMin; + if (std::fabs(forwardSpeed) > desiredSpeed) + limitSpeedTo(bot, forwardSpeed, desiredSpeed, 0.3f, localRotation); + else + strafeTo(bot, point, localRotation); + return true; + } + float turn = 0.0f; + if (altitude > 5.0f) + turn = turnTowardsDirection(bot, direction, localRotation); + if (turn > 45.0f) + { + limitSpeedTo(bot, forwardSpeed, 5.0f, 0.3f, localRotation); + return true; + } + if (!(altitude > 5.0f)) + return true; + // [INFERRED] inline clamp expansion; unordered values pass through. + const auto clamp = [](float value, float low, float high) { + return low > value ? low : (value > high ? high : value); + }; + const float distanceFactor = distance / 50.0f < 1.0f ? distance / 50.0f : 1.0f; + const float desiredSpeed = distanceFactor * ((1.0f - altitudeFactor * altitudeFactorTweak) * maxSpeed); + const float speedFactor = clamp((desiredSpeed - forwardSpeed) / maxSpeedDiff, -1.0f, 1.0f); + const float accelerationFactor = clamp((speedFactor * maxAcceleration - forwardAcceleration) / maxAccelerationDiff, -0.1f, 1.0f); + const float pitchDifference = clamp(accelerationFactor * -0.4f - transform.m[9], -1.0f, 1.0f); + const float pitchFactor = clamp(pitchDifference / maxDiff, -1.0f, 1.0f); + const float damping = clamp(4.0f * localRotation.x, -1.2f, 1.2f); + const float pitchInput = clamp(pitchFactor * -maxInput - damping, -maxInput, maxInput); + input->setInput(controls->getDrivePitchControl(), pitchInput); + return true; +} + +// ELF 0x2C9F30 +bool HeliControl::avoidCrash(Bot* bot, const Vec3& rotationalSpeed, float& ground) +{ + static float tiltLimit = 0.2f; + static float safetyConstant = 0.08f; + static bool testAvoidCrash = false; + static float minDiffToTryToTurn = -10.0f; + static float roll = -0.2f; + static float maxInput = 0.5f; + static float maxRotSpeed = 0.5f; + static float maxDiff = 10.0f; + static float minValue = 0.1f; + static float addition = 0.3f; + static float speedLimit = 3.0f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + IPIMobile* mobile = information->getMobile(); + const Mat4& transformation = information->getTransformation(); + const Vec3& speed = mobile->getSpeed(); + IPIControlInfo* controls = information->getControlInfo(); + ground = -99999.0f; + const bool tilted = std::fabs(transformation.m[1]) > tiltLimit || + std::fabs(transformation.m[9]) > 0.6f; + const Vec3 facing = information->getFaceing(); + float forwardSpeed = facing.x * speed.x + facing.y * speed.y + facing.z * speed.z; + if (!(forwardSpeed > 4.0f)) + forwardSpeed = 4.0f; + float lowest = 999999.0f; + if (!tilted) + { + const Vec3 currentFacing = information->getFaceing(); + Vec3 direction = {currentFacing.x * forwardSpeed, currentFacing.y * forwardSpeed, + currentFacing.z * forwardSpeed}; + if (forwardSpeed > 0.00001f) + { + const float inverse = 1.0f / forwardSpeed; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + int count = static_cast((forwardSpeed * safetyConstant * forwardSpeed) / 15.0f) + 2; + if (count < 6) + count = 5; + for (int i = 0; i < count; ++i) + { + const float sample = static_cast(i); + const Vec3 position = {(direction.x * sample) * 15.0f + transformation.m[12], + (direction.y * sample) * 15.0f + transformation.m[13], + (direction.z * sample) * 15.0f + transformation.m[14]}; + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + if (position.y - altitude > ground) + ground = position.y - altitude; + if (lowest > altitude) + lowest = altitude; + } + if (!(lowest < 5.0f && forwardSpeed > 4.0f) && !testAvoidCrash) + return false; + } + if (!(lowest < minDiffToTryToTurn) || tilted) + keepRollAt(bot, 0.0f, 1.0f, 0.5f, rotationalSpeed); + else + { + input->setInput(static_cast(0), 0.5f); + float sideClearance; + const bool right = avoidRight(bot, sideClearance); + keepRollAt(bot, right ? roll : -roll, maxInput, maxRotSpeed, rotationalSpeed); + if (sideClearance > -10.0f) + { + const float forward = speed.x * transformation.m[8] + speed.y * transformation.m[9] + + speed.z * transformation.m[10]; + limitSpeedTo(bot, forward, 5.0f, 0.3f, rotationalSpeed); + input->setInput(controls->getDriveThrottleControl(), 1.0f); + return true; + } + } + const float forward = speed.x * transformation.m[8] + speed.y * transformation.m[9] + + speed.z * transformation.m[10]; + float factor = 0.0f; + if (forward > 0.1f) + { + factor = std::fabs(forward) / maxDiff; + if (factor > 1.0f) + factor = 1.0f; + } + limitSpeedTo(bot, forward, speedLimit, factor * addition + minValue, rotationalSpeed); + if (transformation.m[9] > 0.0f) + input->setInput(controls->getDriveThrottleControl(), 1.0f); + return true; +} + +// ELF 0x2CA4B0 +bool avoidRight(Bot* bot, float& clearance) +{ + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + const Mat4& transformation = information->getTransformation(); + const Vec3 firstFacing = information->getFaceing(); + const Vec3 first = {firstFacing.x * 0.7f, firstFacing.y * 0.7f, firstFacing.z * 0.7f}; + const Mat4& firstTransformation = information->getTransformation(); + const Vec3 right = {0.1f * firstTransformation.m[0] + first.x, + 0.1f * firstTransformation.m[1] + first.y, + 0.1f * firstTransformation.m[2] + first.z}; + const Vec3 secondFacing = information->getFaceing(); + const Vec3 second = {secondFacing.x * 0.7f, secondFacing.y * 0.7f, secondFacing.z * 0.7f}; + const Mat4& secondTransformation = information->getTransformation(); + const Vec3 left = {second.x - 0.1f * secondTransformation.m[0], + second.y - 0.1f * secondTransformation.m[1], + second.z - 0.1f * secondTransformation.m[2]}; + // shipped defect: positive clearances cannot raise either minimum above its initial zero. + float minimumRight = 0.0f; + float minimumLeft = 0.0f; + float sumRight = 0.0f; + float sumLeft = 0.0f; + for (int i = 0; i < 12; ++i) + { + const float sample = static_cast(i); + const Vec3 position = {(right.x * sample) * 22.0f + transformation.m[12], + (right.y * sample) * 22.0f + transformation.m[13], + (right.z * sample) * 22.0f + transformation.m[14]}; + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + sumRight += altitude; + if (minimumRight > altitude) + minimumRight = altitude; + } + for (int i = 0; i < 12; ++i) + { + const float sample = static_cast(i); + const Vec3 position = {(left.x * sample) * 22.0f + transformation.m[12], + (left.y * sample) * 22.0f + transformation.m[13], + (left.z * sample) * 22.0f + transformation.m[14]}; + const float altitude = AerialHeightMap::m_instance->getAltitude(position); + sumLeft += altitude; + if (minimumLeft > altitude) + minimumLeft = altitude; + } + clearance = sumRight > sumLeft ? minimumRight : minimumLeft; + return sumRight > sumLeft; +} + +// ELF 0x2CA7D0 +int HeliControl::aimAtDirection(Bot* bot, const Vec3& direction, float, float clearance, + const Vec3& acceleration, float feedForward) +{ + static float minDot = -0.6f; + static float maxDot = 0.35f; + static float maxAngleSpeed = 0.2f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + io::PlayerInput* input = bot->getInput(); + if (!information) + return 0; + IPIMobile* mobile = information->getMobile(); + const Mat4& transformation = information->getTransformation(); + Mat4 inverse = Mat4::getIdentity(); + inverse.setInverse(transformation); + const Vec3 rotationalSpeed = rotateHeliVector(inverse, mobile->getRotationalSpeed()); + float ground; + if (!avoidCrash(bot, rotationalSpeed, ground)) + { + gotoHeight(bot, ground + 10.0f, rotationalSpeed); + if (!(direction.y > minDot) || !(maxDot > direction.y)) + { + Vec3 forward = {transformation.m[8], 0.0f, transformation.m[10]}; + vehiclecontrol::normalizeVec3(forward); + const Vec3 target = {forward.x * 150.0f + transformation.m[12], + forward.y * 150.0f + transformation.m[13], + forward.z * 150.0f + transformation.m[14]}; + moveToPoint(bot, target, clearance, acceleration); + } + else + { + const float turn = turnTowardsDirection(bot, direction, rotationalSpeed); + if (turn < 10.0f && std::fabs(rotationalSpeed.y) < 0.1f) + keepPitchAt(bot, direction.y, 1.0f, maxAngleSpeed, rotationalSpeed, feedForward); + } + } + else + { + IPIControlInfo* controls = information->getControlInfo(); + if (transformation.m[9] > -0.15f && mobile->getSpeedMagnitude() > 2.0f) + input->setInput(controls->getDriveThrottleControl(), 1.0f); + } + return 1; +} + +// ELF 0x2CAC20 +float HeliControl::turnTowardsDirection(Bot* bot, const Vec3& direction, const Vec3& rotationalSpeed) +{ + static bool dontTurn = false; + static float maxAngleVelocity = 1.0f; + static float maxAngleVelocityDiff = 0.1f; + static float maxInput = 1.0f; + Information* information = informationManager->getInformation(bot->getCurrentEquipment()); + IPIControlInfo* controls = information->getControlInfo(); + io::PlayerInput* input = bot->getInput(); + if (dontTurn) + return 0.0f; + const Mat4& transformation = information->getTransformation(); + float z, x, yaw; + getRotationZXY(transformation, z, x, yaw); + if (yaw < 0.0f) + yaw += 360.0f; + Mat4 look = Mat4::getIdentity(); + const Vec3 up = {0.0f, 1.0f, 0.0f}; + const Vec3 target = {direction.x + transformation.m[12], direction.y + transformation.m[13], + direction.z + transformation.m[14]}; + const Vec3& position = *reinterpret_cast(&transformation.m[12]); + calcLookAtMatrix(look, position, target, up); + float targetZ, targetX, targetYaw; + getRotationZXY(look, targetZ, targetX, targetYaw); + if (targetYaw < 0.0f) + targetYaw += 360.0f; + float difference = targetYaw - yaw; + if (difference < -180.0f) + difference += 360.0f; + else if (difference > 180.0f) + difference -= 360.0f; + const float wantedSpeed = -clampHeliInput(difference / 30.0f, -1.0f, 1.0f) * maxAngleVelocity; + const float value = clampHeliInput((wantedSpeed - rotationalSpeed.y) / maxAngleVelocityDiff, + -1.0f, 1.0f); + const io::PlayerInputMap turnControl = controls->getDriveTurnControl(); + input->setInput(turnControl, value * maxInput); + return std::fabs(difference); +} + +// ELF 0x2CAF00 (Ghidra). Moving releases inputs 0, 2, 1 and 3; look 4 and 5; trigger 8, 31, +// 23..28, 14..16, 38, 37, 10, 32 and 47. Returns 1. +int HeliControl::resetControls(Bot* bot, bool move, bool look, bool trigger) +{ + io::PlayerInput* const input = bot->getInput(); + if (move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + input->setInput(static_cast(3), 0.0f); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + input->setInput(static_cast(23), 0.0f); + input->setInput(static_cast(24), 0.0f); + input->setInput(static_cast(25), 0.0f); + input->setInput(static_cast(26), 0.0f); + input->setInput(static_cast(27), 0.0f); + input->setInput(static_cast(28), 0.0f); + input->setInput(static_cast(14), 0.0f); + input->setInput(static_cast(15), 0.0f); + input->setInput(static_cast(16), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + input->setInput(static_cast(47), 0.0f); + } + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.h new file mode 100644 index 000000000..26e25e3e5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.h @@ -0,0 +1,38 @@ +// Helicopter controls. Rotational-speed arguments use the vehicle's local axes; movement and +// acceleration arguments use world coordinates. Most helpers require valid current equipment. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_HELICONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_HELICONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace HeliControl +{ + void quickyMoveForward(Bot*, float, const Vec3&); // 0x2C8A80; [INFERRED] ELF void + int gotoHeight(Bot*, float, const Vec3&); // 0x2C8D00; [INFERRED] ELF int + void strafeTo(Bot*, const Vec3&, const Vec3&); // 0x2C9060; [INFERRED] ELF void + void keepRollAt(Bot*, float, float, float, const Vec3&); // 0x2C9220; [INFERRED] ELF void + void keepPitchAt(Bot*, float, float, float, const Vec3&, float); // 0x2C9280; [INFERRED] ELF void + void keepDotAt(Bot*, int, float, float, float, const Vec3&, float); // 0x2C92D0; [INFERRED] ELF void + void limitSpeedTo(Bot*, float, float, float, const Vec3&); // 0x2C9450; [INFERRED] ELF void + float keepHeight(Bot*, float, float, const Vec3&); // 0x2C95D0; [INFERRED] ELF float + int moveToPoint(Bot*, const Vec3&, float, const Vec3&); // 0x2C9760; [INFERRED] ELF int + bool avoidCrash(Bot*, const Vec3&, float&); // 0x2C9F30; [INFERRED] ELF int, callers {'bool': 2} + int aimAtDirection(Bot*, const Vec3&, float, float, const Vec3&, float); // 0x2CA7D0; [INFERRED] ELF int + float turnTowardsDirection(Bot*, const Vec3&, const Vec3&); // 0x2CAC20; [INFERRED] ELF float + int resetControls(Bot*, bool, bool, bool); // 0x2CAF00; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_HELICONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp new file mode 100644 index 000000000..bb46b7009 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp @@ -0,0 +1,495 @@ +// InfanteryControl (attested TU `AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp`, the path of +// infanteryPose's Debug). Recovered from libaidll.so (Linux 1.5.3153, ia-32); every body carries its +// ELF address. Read in Intel syntax (no x87 operand swap) and checked against the Ghidra +// decompilation. Parameter and local names are [INFERRED]. +// +// Input writes: the image calls Input::setInput(index, float) out of line at +// most sites and inlines it at a few (removeZoom's release); both are the same function here. + +// static init: ELF 0x2CCE30 (__tcf_0 0x2CCE90, _GLOBAL__I 0x2CCEC0): 's Init object only. +#include + +#include "../AIBot/SensingAgent.h" +#include "InfanteryControl.h" + +#include +#include +#include + +#include "../Main/AIDllFrontier.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../../../../Core/Debug.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace infantry_detail { + +float inputValue(const io::PlayerInput* input, io::PlayerInputMap index) +{ + const int i = static_cast(index); + if (i > 63) + return 0.0f; + if (!((input->mappingFlags >> (static_cast(i) & 0x3F)) & 1ULL)) + return 0.0f; + return input->inputs[i]; +} + +// [CHOSEN, not recovered] the image writes SensingAgent +0x50 (the move direction) and stores 0.0 +// at +0x7C (a double) inline (EntryInfanteryMoveTo 0x2B7CF7 `fstpl 0x7c(%eax)`, 0x2B7CFA/0x2B7CFD). +// The +0x7C store is SensingAgent::setOverrideTime (ai-bot). +void setSensingMoveDirection(SensingAgent* agent, const Vec2& direction) +{ + agent->setOverrideTime(0.0); + agent->setMoveDirection(direction); +} + +void normaliseInline(Vec3& v) +{ + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (!(1.1920929e-07f <= std::fabs(lengthSqr - 1.0f))) + return; + if (!(1.1920929e-07f <= std::fabs(lengthSqr))) + { + v.x = v.y = v.z = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; +} + +Vec3 crossInline(const Vec3& a, const Vec3& b) +{ + Vec3 r; + r.x = a.y * b.z - a.z * b.y; + r.y = a.z * b.x - b.z * a.x; + r.z = b.y * a.x - b.x * a.y; + return r; +} + +} // namespace infantry_detail + +namespace { + +using infantry_detail::inputValue; + +inline Information* lookupInformation(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +// The inline zero test the image applies to trace results (|c - 0| <= FLT_EPSILON for x, y, z). +inline bool isZeroVec(const Vec3& v) +{ + const float eps = 1.1920929e-07f; + return std::fabs(v.x - 0.0f) <= eps && std::fabs(v.y - 0.0f) <= eps && std::fabs(v.z - 0.0f) <= eps; +} + +inline float distance(const Vec3& a, const Vec3& b) +{ + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +} // namespace + +// ELF 0x2CB200 +void removeZoom(Bot* bot) +{ + Information* info = lookupInformation(bot->getCurrentEquipment()); + IPIArmament* armament = info->getArmament(); + if (armament == 0) + return; + // [INFERRED] the image queries the active weapon twice and drops the first result. + const unsigned int unusedWeapon = armament->getWeapon(armament->getActiveWeapon()); + (void)unusedWeapon; + WeaponInfo* weapon = WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (weapon == 0) + return; + if (weapon->getWeaponZoom() == io::PINone) + return; + + if (!weapon->isZoomed()) + { + bot->getInput()->setInput(static_cast(weapon->getWeaponZoom()), 0.0f); + return; + } + io::PlayerInput* input = bot->getInput(); + if (inputValue(input, static_cast(weapon->getWeaponZoom())) != 0.0f) + { + // the zoom key is held: release it (inlined setInput in the image, ELF 0x2CB3xx) + input->setInput(static_cast(weapon->getWeaponZoom()), 0.0f); + return; + } + // press it once to leave zoom + bot->getInput()->setInput(static_cast(weapon->getWeaponZoom()), 1.0f); +} + +// ELF 0x2CB550 +void infanteryControlThrottle(Bot* bot, io::PlayerInput* input, IPIControlInfo*, float maxSpeed, bool sprint) +{ + if (static_cast(bot)->getBotIsSimulatingArtillery()) // BotMain +0x234 + { + bot->getBotNavigation()->clearProgress(); + bot->requestSoldierPose(SPCrouching, true); + return; + } + const float squadSpeed = bot->getSquadMember()->getMaxSpeed(); // 0x2CB5D1 + if (sprint) + { + float throttle; + if (maxSpeed <= 0.0f) + throttle = (maxSpeed < 0.0f) ? -1.0f : 0.0f; + else + throttle = 1.0f; + input->setInput(io::PIThrottle, throttle); + input->setInput(io::PISprint, 1.0f); + } + else + { + input->setInput(io::PIThrottle, squadSpeed / maxSpeed); + input->setInput(io::PISprint, 0.0f); + } +} + +// ELF 0x2CB660 +bool infanteryResetControls(Bot* bot, io::PlayerInput* input, bool movement, bool look, bool weapons) +{ + if (movement) + { + input->setInput(io::PIAction, 0.0f); + input->setInput(io::PISprint, 0.0f); + input->setInput(io::PIYaw, 0.0f); + input->setInput(io::PIRoll, 0.0f); + input->setInput(io::PIPitch, 0.0f); + input->setInput(io::PIThrottle, 0.0f); + input->setInput(io::PIMouseLookX, 0.0f); + input->setInput(io::PIMouseLookY, 0.0f); + } + if (look) + { + // level the view: look down by the forward vector's height (transformation row 2, y) + Information* info = lookupInformation(bot->getCurrentEquipment()); + const Mat4& transformation = info->getTransformation(); + input->setInput(io::PIMouseLookX, 0.0f); + input->setInput(io::PIMouseLookY, -transformation.m[9]); + } + if (weapons) + { + input->setInput(io::PIFire, 0.0f); + input->setInput(io::PIAltFire, 0.0f); + input->setInput(io::PIWeaponSelect1, 0.0f); + input->setInput(io::PIWeaponSelect2, 0.0f); + input->setInput(io::PIWeaponSelect3, 0.0f); + input->setInput(io::PIWeaponSelect4, 0.0f); + input->setInput(io::PIWeaponSelect5, 0.0f); + input->setInput(io::PIWeaponSelect6, 0.0f); + input->setInput(io::PIWeaponSelect7, 0.0f); + input->setInput(io::PIWeaponSelect8, 0.0f); + input->setInput(io::PIPositionSelect1, 0.0f); + input->setInput(io::PIPositionSelect2, 0.0f); + input->setInput(io::PIPositionSelect3, 0.0f); + input->setInput(io::PIPositionSelect4, 0.0f); + input->setInput(io::PIPositionSelect5, 0.0f); + input->setInput(io::PIPositionSelect6, 0.0f); + input->setInput(io::PIPositionSelect7, 0.0f); + input->setInput(io::PIPositionSelect8, 0.0f); + input->setInput(io::PIUse, 0.0f); + input->setInput(io::PIReload, 0.0f); + input->setInput(io::PIFlareFire, 0.0f); + } + return true; +} + +// ELF 0x2CB9B0. PICrouch and PILie are toggles: the table presses the one that leads from the +// current to the wanted pose (and nothing when they are equal). +int infanteryPose(io::PlayerInput* input, SoldierPose current, SoldierPose wanted) +{ + int line; + switch (current) + { + case SPCrouching: + if (wanted == SPCrouching) + goto none; + if (wanted == SPStanding) + goto crouch; + if (wanted == SPLying) + goto lie; + line = 263; + break; + case SPStanding: + if (wanted == SPCrouching) + goto crouch; + if (wanted == SPStanding) + goto none; + if (wanted == SPLying) + goto lie; + line = 243; + break; + case SPLying: + if (wanted == SPCrouching) + goto crouch; + if (wanted == SPStanding) + goto lie; + if (wanted == SPLying) + goto none; + line = 283; + break; + default: + line = 288; + break; + } + Debug(DebugTypeError, "AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp", line, "") + << "Internal error, unknown pose."; + return 0; + +none: + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 0.0f); + return 1; +crouch: + input->setInput(io::PICrouch, 1.0f); + input->setInput(io::PILie, 0.0f); + return 1; +lie: + input->setInput(io::PICrouch, 0.0f); + input->setInput(io::PILie, 1.0f); + return 1; +} + +// ELF 0x2CBC90 +bool needsUpdate(const Vec2& point, unsigned int handle, float radius) +{ + Information* info = lookupInformation(handle); + if (info == 0) + return false; + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + vec3ToVec2XZ(info->getPosition(), position); + const float distSqr = (point.y - position.y) * (point.y - position.y) + + (point.x - position.x) * (point.x - position.x); + return distSqr < radius * radius || (radius + 1.5f) * (radius + 1.5f) < distSqr; +} + +// ELF 0x2CBD70. Picks the nearest obstacle in front of the bot on the way to `target` (from the +// navigation's obstacle list: physical objects that are mobile or flagged 0x2000000, within 2 m of +// the bot's height and inside their radius + 1 of the path) and returns in `avoidPos` a point beside +// it: the obstacle position moved along the path normal by at most its radius, to the side where a +// pathfinding trace (15 m each way from the obstacle) has room. The obstacle's handle, position, +// radius and "damaged" state (flag 0x2000000 or health under the bail value) are returned through +// the other references; repair and change targets are never treated as damaged. +// Returns false in every normal case (also when there is no obstacle); true only when the obstacle +// stands on no valid pathfinding position (a retail quirk the callers rely on). +bool updateInfantryMoveToPosWithObstacles(Bot* bot, const Vec2& target, const Vec3&, unsigned int targetHandle, + Vec2& avoidPos, unsigned int& obstacleHandle, float& avoidOffset, + Vec2& obstaclePos, float& obstacleRadius, bool& obstacleDamaged, + Information* ignored, bool includeIgnored) +{ + Information* botInfo = lookupInformation(bot->getCurrentEquipment()); + BotNavigation* navigation = bot->getBotNavigation(); + float bestAlong = 99999.0f; + Vec2 closest; + closest.x = 0.0f; + closest.y = 0.0f; + const Vec3& botPos3 = botInfo->getPosition(); + Vec2 botPos; + botPos.x = 0.0f; + botPos.y = 0.0f; + vec3ToVec2XZ(botPos3, botPos); + Vec2 dir; + dir.x = target.x - botPos.x; + dir.y = target.y - botPos.y; + const float length = std::sqrt(dir.y * dir.y + dir.x * dir.x); + if (length < 0.0001f) + return false; + dir.x = dir.x * (1.0f / length); + dir.y = (1.0f / length) * dir.y; + Vec2 normal; + normal.x = 0.0f; + normal.y = 0.0f; + getNormal(dir, normal); + + IPIMobile* bestMobile = 0; + Information* targetInfo = lookupInformation(targetHandle); + Vec3 bestPos3; + bestPos3.x = 0.0f; + bestPos3.y = 0.0f; + bestPos3.z = 0.0f; + if (targetInfo != 0 && !targetInfo->isPrimary()) + targetInfo->getPrimaryObject(bot->getSide()); // retail: the result is dropped + avoidOffset = 0.0f; + + unsigned int changeTarget = bot->getChangeTarget(); + Information* changeInfo = lookupInformation(changeTarget); + if (changeInfo != 0 && !changeInfo->isPrimary()) + changeTarget = changeInfo->getPrimaryObject(bot->getSide()); + unsigned int repairTarget = bot->getRepairTarget(); + Information* repairInfo = lookupInformation(repairTarget); + if (repairInfo != 0 && !repairInfo->isPrimary()) + repairTarget = repairInfo->getPrimaryObject(bot->getSide()); + + const std::vector& obstacles = navigation->getObstacles(); // 0x2CBE2E: BotNavigation +0x58 + for (unsigned int i = 0; i < obstacles.size(); ++i) + { + Information* info = lookupInformation(obstacles[i]); + if (info == botInfo) + continue; + if (!(info != ignored || includeIgnored) || info == 0) + continue; + IPIPhysical* physical = info->getPhysical(); + if (physical == 0 || (info->getObjectTypeFlags() & 0x200000) != 0) + continue; + IPIMobile* mobile = info->getMobile(); + if (mobile == 0 && (info->getObjectTypeFlags() & 0x2000000) == 0) + continue; + + bool isTarget = false; + if (obstacles[i] == repairTarget || obstacles[i] == changeTarget) + isTarget = true; + const float health = physical->getHealth(); + bool damaged = false; + if ((info->getObjectTypeFlags() & 0x2000000) != 0 || health < IBotManager::instance->getVehicleBailValue()) + damaged = true; + float radius; + if (!damaged || isTarget) + { + radius = physical->getSmallestRadius(); + } + else + { + const float smallest = physical->getSmallestRadius(); + float grown = physical->getSmallestRadius() + 4.0f; + if (10.0f < grown) + grown = 10.0f; + if (grown <= smallest) + grown = smallest; + radius = grown * 1.3f; + } + + if (!(std::fabs(info->getPosition().y - botPos3.y) <= 2.0f)) + continue; + Vec2 pos; + pos.x = 0.0f; + pos.y = 0.0f; + vec3ToVec2XZ(info->getPosition(), pos); + const float rx = pos.x - botPos.x; + const float ry = pos.y - botPos.y; + const float distSqr = rx * rx + ry * ry; + const float along = rx * dir.x + ry * dir.y; + if (!(distSqr <= (radius + 1.0f) * (radius + 1.0f))) + continue; + if (!(0.1f <= along / std::sqrt(distSqr))) + continue; + if (radius + 1.0f <= std::fabs(rx * normal.x + ry * normal.y)) + continue; + if (bestAlong <= along) + continue; + closest = pos; + obstacleRadius = radius; + bestPos3 = info->getPosition(); + obstacleHandle = obstacles[i]; + obstaclePos = pos; + obstacleDamaged = damaged; + bestMobile = mobile; + bestAlong = along; + } + if (99999.0f <= bestAlong) + return false; + + const int vehicleNumber = botInfo->getMobile()->getVehicleNumber(); + bot->getBotNavigation(); // retail: called and dropped + const int equipmentType = botInfo->getUnit()->getEquipmentType(); + Vec3 hitBack; + hitBack.x = hitBack.y = hitBack.z = 0.0f; + Vec3 hitFront; + hitFront.x = hitFront.y = hitFront.z = 0.0f; + Vec3 normal3; + normal3.x = normal3.y = normal3.z = 0.0f; + vec2ToVec3XZ(normal, normal3); + IAIPathfinding* pathfinding = IAIPathfinding::instance; + unsigned int polygon; // trace output, unused + float frontDist; + if (bestMobile == 0) + { + if (!pathfinding->isValidPosition(vehicleNumber, equipmentType, bestPos3, true)) + return true; + Vec3 to; + to.x = normal3.x * 15.0f + bestPos3.x; + to.y = normal3.y * 15.0f + bestPos3.y; + to.z = normal3.z * 15.0f + bestPos3.z; + pathfinding->trace(vehicleNumber, bestPos3, to, hitFront, polygon, equipmentType, -1, 0.0f, 0, 0); + frontDist = isZeroVec(hitFront) ? 0.0f : distance(hitFront, bestPos3); + to.x = bestPos3.x - normal3.x * 15.0f; + to.y = bestPos3.y - normal3.y * 15.0f; + to.z = bestPos3.z - normal3.z * 15.0f; + pathfinding->trace(vehicleNumber, bestPos3, to, hitBack, polygon, equipmentType, -1, 0.0f, 0, 0); + } + else + { + const IPIMobile::ValidPos& valid = bestMobile->getLastValidPosition(vehicleNumber); + Vec3 to; + to.x = normal3.x * 15.0f + valid.position.x; + to.y = normal3.y * 15.0f + valid.position.y; + to.z = normal3.z * 15.0f + valid.position.z; + pathfinding->trace(valid.polygon, valid.quadTree, vehicleNumber, valid.position, to, hitFront, polygon, + equipmentType, -1, 0.0f, 0, 0); + // retail: measured from the obstacle's position, not from the valid position traced from + frontDist = isZeroVec(hitFront) ? 0.0f : distance(hitFront, bestPos3); + to.x = valid.position.x - normal3.x * 15.0f; + to.y = valid.position.y - normal3.y * 15.0f; + to.z = valid.position.z - normal3.z * 15.0f; + pathfinding->trace(valid.polygon, valid.quadTree, vehicleNumber, valid.position, to, hitBack, polygon, + equipmentType, -1, 0.0f, 0, 0); + } + const float backDist = isZeroVec(hitBack) ? 0.0f : distance(hitBack, bestPos3); + + avoidPos = closest; + bool goBack; + float room = frontDist; + float radius; + if ((closest.y - botPos.y) * normal.y + (closest.x - botPos.x) * normal.x <= 0.0f) + { + radius = obstacleRadius; + goBack = !(radius + 1.0f < frontDist || backDist < frontDist); + } + else + { + radius = obstacleRadius; + goBack = !(backDist <= radius + 1.0f && backDist <= frontDist); + } + if (goBack) + room = backDist; + float offset = radius; + if (room < offset) + offset = room; + const float signedOffset = goBack ? -offset : offset; + avoidPos.x = normal.x * signedOffset + avoidPos.x; + avoidPos.y = signedOffset * normal.y + avoidPos.y; + avoidOffset = offset; + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.h new file mode 100644 index 000000000..718bc01f6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.h @@ -0,0 +1,67 @@ +// InfanteryControl: the soldier input helpers of the infantry plan-interpreter entries +// (attested TU `AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp`). Package B +// (docs/macos-ai-behaviour-plan.md). Signatures from the mangled ELF names; return types checked +// against the bodies and their callers. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_INFANTERYCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_INFANTERYCONTROL_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" +#include "../../../../IO/Input/Input.h" + +namespace dice { +namespace hfe { +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class BAPAMoveTo; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; +class SensingAgent; + +// Presses or releases the zoom input so that the bot's active weapon leaves zoom. +void removeZoom(Bot*); // 0x2CB200 +// Throttle (and sprint) for a soldier whose own top speed is maxSpeed; `sprint` comes from +// BAPAMoveTo::getIsSprinting. +void infanteryControlThrottle(Bot*, io::PlayerInput*, IPIControlInfo*, float maxSpeed, bool sprint); // 0x2CB550 +// Releases the movement inputs (`movement`), levels the look (`look`) and releases the fire, +// weapon-select and use inputs (`weapons`). Always true; the callers store it into their ok flag. +bool infanteryResetControls(Bot*, io::PlayerInput*, bool movement, bool look, bool weapons); // 0x2CB660 +// Presses PICrouch / PILie to go from `current` to `wanted`. 0 only after an unknown pose (an +// Error Debug, which aborts). +int infanteryPose(io::PlayerInput*, SoldierPose current, SoldierPose wanted); // 0x2CB9B0 +// True when the object `handle` left the ring [radius, radius + 1.5] around `point`. +bool needsUpdate(const Vec2& point, unsigned int handle, float radius); // 0x2CBC90 +bool updateInfantryMoveToPosWithObstacles(Bot*, const Vec2&, const Vec3&, unsigned int, Vec2&, unsigned int&, float&, Vec2&, float&, bool&, Information*, bool); // 0x2CBD70 + +namespace infantry_detail { + +// [INFERRED] The image expands an inline input reader at every site (`[input+0x100/0x104]`, +// shrd, `test 1`, then `fld [input+4*i]`): the value when the input is mapped, else 0. Indices +// above 63 read 0 (`cmp idx,0x3f; jg`). The Input template in IO/ has no such member, so the +// reader lives here. +float inputValue(const io::PlayerInput* input, io::PlayerInputMap index); + +// [INFERRED] The inline Vec3 normalise the entries expand: unchanged when |v|^2 is within +// FLT_EPSILON of 1, zeroed when |v|^2 is within FLT_EPSILON of 0, else scaled by 1/|v|. +void normaliseInline(Vec3& v); +// a x b, component order as the image computes it +Vec3 crossInline(const Vec3& a, const Vec3& b); + +// [CHOSEN, not recovered] Bridge to the SensingAgent move direction: the move entries store the +// direction inline at SensingAgent +0x50 (Vec2) and zero the double at +0x7C (both private in +// AIBot/SensingAgent.h). Stops by name until ai-bot adds the writer. +void setSensingMoveDirection(SensingAgent* agent, const Vec2& direction); + +} // namespace infantry_detail + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_INFANTERYCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp new file mode 100644 index 000000000..d8ffa4a7d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp @@ -0,0 +1,195 @@ +// MouseControl (attested TU `AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp`, FILE symbol and +// static initialiser beside 0x2CCEE0). Recovered from libaidll.so (Linux 1.5.3153, ia-32), read in +// Intel syntax and checked against the Ghidra decompilation. Parameter names are [INFERRED]. + +// static init: ELF 0x2CDA50 (__tcf_0 0x2CDAB0, _GLOBAL__I 0x2CDAE0): 's Init object only. +#include + +#include "MouseControl.h" + +#include + +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "InfanteryControl.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Vec3.h" +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inline clamp (`fld -1; fucomi; ... fcmov`); NaN gives -1. The image clamps the +// direction cosines twice, which is the same value. +inline float clampUnit(float v) +{ + if (!(-1.0f <= v)) + return -1.0f; + if (1.0f < v) + return 1.0f; + return v; +} + +inline float signOf(float v) +{ + if (v <= 0.0f) + return (v < 0.0f) ? -1.0f : 0.0f; + return 1.0f; +} + +// sign of the target speed: NaN counts as positive here (`fld 1; ... p <= 0`), as in the image +inline float speedSign(float v) +{ + if (v <= 0.0f) + return (v < 0.0f) ? -1.0f : 0.0f; + return 1.0f; +} + +} // namespace + +// ELF 0x2CCEE0. Drives the mouse-look inputs so that the camera `camera` turns towards the unit +// direction `dir`. The pitch and yaw errors (radians, from the camera's up and right rows) are +// returned through pitchError/yawError; the previous frame's errors give the derivative term, and +// the target's own angular speeds (targetYawSpeed, targetPitchSpeed) add a feed-forward term that is +// halved when the target moves the same way as the error. With useAllowedDeviation (never set in +// this build) errors below allowedDeviation give no input. The vertical output is damped by bot +// skill; both are kept above minInput and inside the per-axis limits, which grow with bot skill. +// Soldiers (object flag 0x200000) look at full speed vertically and, while idle without a firing +// target, use a softer horizontal gain (newP) and limit (1.5). +void mouseControlLookAtDirection(Bot* bot, const Vec3& dir, const Mat4& camera, float& pitchError, float lastPitchError, + float& yawError, float lastYawError, float allowedDeviation, + IPIControlInfo* controlInfo, io::PlayerInput* input, + float pitchBias, float targetYawSpeed, float targetPitchSpeed) +{ + // function-local tuning statics (.data, never written in this build) + static float maxYInputNew = 2.0f; // ELF 0x4BDD14 + static float tweak = 0.05f; // ELF 0x4BDD18 + static float minInput = 0.01f; // ELF 0x4BDD1C + static bool useAllowedDeviation = false; // ELF 0x4CE5E5 (.bss) + + const float x = dir.x; + const float y = dir.y; + const float z = dir.z; + const float upCos = clampUnit(camera.m[6] * z + camera.m[5] * y + camera.m[4] * x); + const float rightCos = clampUnit(camera.m[2] * z + camera.m[1] * y + camera.m[0] * x); + const float forwardCos = clampUnit(z * camera.m[10] + camera.m[8] * x + y * camera.m[9]); + + pitchError = -(std::acos(clampUnit(upCos)) - 1.57079637f); + const float rightAngle = std::acos(clampUnit(rightCos)); + yawError = rightAngle; + if (forwardCos < 0.0f) + { + if (rightCos < 0.0f) + yawError = 4.71238899f - rightAngle; + else + yawError = -(rightAngle + 1.57079637f); + } + else + { + yawError = rightAngle - 1.57079637f; + } + + const float proportional = controlInfo->getProportionalConstant(); + float horizontalP = proportional; + const float derivative = controlInfo->getDerivativeConstant(); + const float angleSpeed = controlInfo->getAngleSpeedConstant(); + + float maxY = 4.0f; + float maxX; + Information* info = informationManager->getInformation(bot->getCurrentEquipment()); + const float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + if (info == 0 || (info->getObjectTypeFlags() & 0x200000) == 0) + { + static float maxXInputNew = 1.0f; // ELF 0x4BDD10 + maxY = (4.0f - maxYInputNew) * skill + maxYInputNew; + maxX = (4.0f - maxXInputNew) * skill + maxXInputNew; + } + else if (bot->getFiringTarget() == static_cast(-1) + && infantry_detail::inputValue(input, io::PIThrottle) == 0.0f + && infantry_detail::inputValue(input, io::PISprint) == 0.0f + && infantry_detail::inputValue(input, io::PIYaw) == 0.0f) + { + static float newP = -3.0f; // ELF 0x4BDD04 + static float maxXInputNew = 1.5f; // ELF 0x4BDD08 + horizontalP = newP; + maxX = maxXInputNew; + } + else if (infantry_detail::inputValue(input, io::PISprint) != 0.0f) + { + maxX = maxY; + } + else + { + static float maxXInputNew = 1.0f; // ELF 0x4BDD0C + maxX = (4.0f - maxXInputNew) * skill + maxXInputNew; + } + + // vertical + float feedForward = angleSpeed * targetPitchSpeed; + if (signOf(pitchError) == speedSign(targetPitchSpeed)) + feedForward = feedForward * 0.5f; + float bias = 0.0f; + if (pitchBias < -0.0001f) + { + const float t = pitchBias / -tweak; + bias = 0.75f; + if (t < 0.75f) + bias = t; + } + float vertical = proportional * pitchError + (pitchError - lastPitchError) * derivative + feedForward + bias; + if (!useAllowedDeviation || allowedDeviation <= std::fabs(pitchError)) + { + if (4.0f < std::fabs(vertical)) + vertical = 4.0f * signOf(vertical); + } + else + { + vertical = 0.0f; + } + vertical = vertical * (1.0f - skill * 0.5f) * 0.5f; + if (std::fabs(vertical) < minInput && vertical != 0.0f) + vertical = signOf(vertical) * minInput; + float verticalInput = -maxY; + if (-maxY <= vertical) + { + if (maxY < vertical) + vertical = maxY; + verticalInput = vertical; + } + // inlined setInput in the image (range diagnostic, then the mapped-bit store) + input->setInput(controlInfo->getLookVerticalControl(), verticalInput); + + // horizontal + float yawFeedForward = angleSpeed * targetYawSpeed; + if (signOf(yawError) == speedSign(targetYawSpeed)) + yawFeedForward = yawFeedForward * 0.5f; + const float horizontalRaw = horizontalP * yawError + (yawError - lastYawError) * derivative + yawFeedForward; + float horizontal = 0.0f; + if (!useAllowedDeviation || allowedDeviation <= std::fabs(yawError)) + { + horizontal = horizontalRaw; + if (4.0f < std::fabs(horizontalRaw)) + horizontal = signOf(horizontalRaw) * 4.0f; + } + if (std::fabs(horizontal) < minInput && horizontal != 0.0f) + horizontal = signOf(horizontal) * minInput; + float horizontalInput = -maxX; + if (-maxX <= horizontal) + { + horizontalInput = horizontal; + if (maxX < horizontal) + horizontalInput = maxX; + } + input->setInput(controlInfo->getLookHorizontalControl(), horizontalInput); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.h new file mode 100644 index 000000000..16a9fa74f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.h @@ -0,0 +1,32 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_MOUSECONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_MOUSECONTROL_H + +#include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class BAPAMoveTo; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +void mouseControlLookAtDirection(Bot*, const Vec3&, const Mat4&, float&, float, float&, float, float, IPIControlInfo*, io::PlayerInput*, float, float, float); // 0x2CCEE0; [INFERRED] ELF void + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_MOUSECONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlanInterpreter.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlanInterpreter.h new file mode 100644 index 000000000..18246b2aa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlanInterpreter.h @@ -0,0 +1,35 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_PLANINTERPRETER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_PLANINTERPRETER_H + + +namespace dice { +namespace hfe { + +namespace ai { + +class Bot; +class BotScript; + +// Interpreter interface. Vtable 0x4BCA60: D1, D0, execute (pure). Inline in the image. +// ELF: vtable 0x4BCA60 (3 words), package S0-skeleton. +// [UNRESOLVED] data members: the owning package names them from the constructors. +class PlanInterpreter +{ +public: + virtual ~PlanInterpreter() {} // weak in the image (inline) + + virtual bool execute(BotScript*, Bot*, bool& ok, bool& finished) = 0; // no body, slot +0x08; from the base declaration +}; + + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_PLANINTERPRETER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp new file mode 100644 index 000000000..d73672e0c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp @@ -0,0 +1,451 @@ +// Fixed-wing flight and attitude controls, recovered from libaidll.so. + +// static init: ELF 0x2D0700 (__tcf_0 0x2D0760, _GLOBAL__I 0x2D0790): 's Init object only. +#include + +#include "PlaneControl.h" + +#include "ControlFunctions.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIStrategicMap/AerialHeightMap.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { +// [CHOSEN, not recovered] Local packaging of the inline vector/scalar operations in +// ELF 0x2CDB00, 0x2CE3C0, 0x2CE6D0 and 0x2CF9F0. +float clampPlane(float value, float minimum, float maximum) +{ + return value < minimum ? minimum : (value > maximum ? maximum : value); +} + +float planeSign(float value) +{ + return value > 0.0f ? 1.0f : (value < 0.0f ? -1.0f : 0.0f); +} + +float dotPlane(const Vec3& a, const Vec3& b) +{ + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +Vec3 crossPlane(const Vec3& a, const Vec3& b) +{ + return Vec3{a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; +} + +Vec3 rotatePlane(const Mat4& matrix, const Vec3& value) +{ + return Vec3{matrix.m[0] * value.x + matrix.m[4] * value.y + matrix.m[8] * value.z, + matrix.m[1] * value.x + matrix.m[5] * value.y + matrix.m[9] * value.z, + matrix.m[2] * value.x + matrix.m[6] * value.y + matrix.m[10] * value.z}; +} + +Mat4 planeIdentity() +{ + Mat4 matrix = {}; + matrix.m[0] = matrix.m[5] = matrix.m[10] = matrix.m[15] = 1.0f; + return matrix; +} + +float planeMappedInput(io::PlayerInput* input, io::PlayerInputMap control) +{ + const int index = static_cast(control); + if (index < 64 && ((input->mappingFlags >> (static_cast(index) & 63)) & 1ULL)) + return input->inputs[index]; + return 0.0f; +} + +float planeImpulse(float value) +{ + if (value < 0.0f && value > -0.15f) + return -0.15f; + if (value > 0.0f && value < 0.15f) + return 0.15f; + return value; +} + +float planeLogResponse(float value) +{ + return value < 0.0f ? -std::log10(1.0f - value * 9.0f) : std::log10(1.0f + value * 9.0f); +} +} + +// ELF 0x2CDB00 +bool PlaneControl::towardsPoint(Bot* bot, Information* equipment, Vec3 target, float, + const Vec3& previousForward, const Vec3& previousRight, + const Vec3& previousUp, float clearance, io::PlayerInput* input) +{ + IPIMobile* mobile = equipment->getMobile(); + IPIControlInfo* controls = equipment->getControlInfo(); + const Vec3 position = equipment->getPosition(); + const Vec3 velocity = mobile->getSpeed(); + Vec3 direction = {0.0f, 0.0f, 0.0f}; + const Mat4& transformation = equipment->getTransformation(); + const float dx = transformation.m[12] - target.x; + const float dz = transformation.m[14] - target.z; + const float horizontalDistanceSq = dx * dx + dz * dz; + if (horizontalDistanceSq < 10000.0f) + { + const float ground = AerialHeightMap::m_instance->getGroundHeight(target) + clearance; + const float floor = ground > transformation.m[13] ? ground : transformation.m[13]; + const float raised = (target.y - floor) * horizontalDistanceSq * 0.0001f + floor; + if (raised > target.y) + target.y = raised; + } + Vec3 prediction = velocity; + const float speed = mobile->getSpeedMagnitude(); + if (speed > 0.00001f) + { + const float inverse = 1.0f / speed; + prediction.x *= inverse; + prediction.y *= inverse; + prediction.z *= inverse; + } + prediction.x *= 100.0f; + prediction.y *= 100.0f; + prediction.z *= 100.0f; + const bool takingOff = !bot->isAirBorn(); + if (takingOff && equipment->getAltitude() > 50.0f && speed / mobile->getMaxSpeed() > 0.5f) + bot->event_airborn(); + float altitude = equipment->getAltitude(prediction); + if (prediction.y < -50.0f) + { + Vec3 horizontal = {velocity.x, 0.0f, velocity.z}; + vehiclecontrol::normalizeVec3(horizontal); + horizontal.x *= 100.0f; + horizontal.y *= 100.0f; + horizontal.z *= 100.0f; + const float horizontalAltitude = equipment->getAltitude(horizontal); + if (!(horizontalAltitude > altitude)) // 0x2CDDEA..0x2CDDF4: unordered keeps the sample + altitude = horizontalAltitude; + } + if (takingOff) + { + target = static_cast(bot)->getTakeOffPosition(); + const Vec3& zero = Vec3::getZero(); + if (std::fabs(target.x - zero.x) <= 1.1920929e-07f + && std::fabs(target.y - zero.y) <= 1.1920929e-07f + && std::fabs(target.z - zero.z) <= 1.1920929e-07f) + { + Vec3 forward = equipment->getFaceing(); + forward.y = 0.0f; + vehiclecontrol::normalizeVec3(forward); + target = Vec3{forward.x * 500.0f + position.x, + forward.y * 500.0f + position.y + 200.0f, + forward.z * 500.0f + position.z}; + static_cast(bot)->setTakeOffPosition(target); + } + } + direction = Vec3{target.x - position.x, target.y - position.y, target.z - position.z}; + const float distance = std::sqrt(dotPlane(direction, direction)); + if (distance > 0.0001f) + { + const float inverse = 1.0f / distance; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + } + else + { + const Mat4& current = equipment->getTransformation(); + direction = Vec3{current.m[8], current.m[9], current.m[10]}; + } + const float heightError = clearance - altitude; + IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + if (!takingOff && terrain->isInsideCombatArea(bot->getPlayer())) + { + bool reverse = direction.y < -0.7f; + if (!reverse && horizontalDistanceSq < 250000.0f) + { + const Mat4& current = equipment->getTransformation(); + reverse = direction.x * current.m[8] + current.m[9] * direction.y + + direction.z * current.m[10] < 0.5f; + } + if (reverse) + { direction.x = -direction.x; direction.z = -direction.z; } + } + return towardsDirection(direction, distance, input, transformation, heightError, clearance, + false, previousForward, previousRight, previousUp, mobile, controls, + 1.0f, speed, false); +} + +// ELF 0x2CE3C0 +bool PlaneControl::aimAtDirection(Bot* bot, Information* equipment, const Vec3& wanted, + float distance, float throttle, float clearance, + const Vec3& previousForward, const Vec3& previousRight, + const Vec3& previousUp, io::PlayerInput* input) +{ + IPIMobile* mobile = equipment->getMobile(); + if (!mobile) + return false; + const Mat4& transformation = equipment->getTransformation(); + const Vec3& velocity = mobile->getSpeed(); + const float speed = std::sqrt(dotPlane(velocity, velocity)); + float lowest = 999999.0f; + for (int i = 0; i < 5; ++i) + { + const float step = static_cast(i); + const Vec3 sample = {step * velocity.x * 0.25f + transformation.m[12], + velocity.y * step * 0.25f + transformation.m[13], + velocity.z * step * 0.25f + transformation.m[14]}; + const float aboveGround = sample.y - AerialHeightMap::m_instance->getGroundHeight(sample); + if (lowest > aboveGround) + lowest = aboveGround; + } + const float heightError = (clearance - lowest) + (clearance - lowest); + IPIControlInfo* controls = equipment->getControlInfo(); + const bool takingOff = !bot->isAirBorn(); + Vec3 direction = wanted; + if (takingOff) + { + direction.y = 0.3333f; + if (equipment->getAltitude() > 50.0f && speed / mobile->getMaxSpeed() > 0.5f) + bot->event_airborn(); + } + const Mat4& current = equipment->getTransformation(); + return towardsDirection(direction, distance, input, current, heightError, clearance, takingOff, + previousForward, previousRight, previousUp, mobile, controls, + throttle, speed, true); +} + +// ELF 0x2CE6D0 +bool PlaneControl::towardsDirection(const Vec3& wanted, float, io::PlayerInput* input, + const Mat4& transformation, float heightError, float clearance, + bool takingOff, const Vec3&, const Vec3&, const Vec3&, + IPIMobile* mobile, IPIControlInfo* controls, float throttle, + float speed, bool aiming) +{ + static bool useAngle = true; // ELF .data 0x4BDD44; only read at 0x2CF088. + const Vec3 up = {transformation.m[4], transformation.m[5], transformation.m[6]}; + const Vec3 right = {transformation.m[0], transformation.m[1], transformation.m[2]}; + const Vec3 forward = {transformation.m[8], transformation.m[9], transformation.m[10]}; + Vec3 direction = wanted; + vehiclecontrol::normalizeVec3(direction); + const Vec3 worldUp = {0.0f, 1.0f, 0.0f}; + Vec3 levelRight = crossPlane(worldUp, forward); + vehiclecontrol::normalizeVec3(levelRight); + const Vec3 levelUp = crossPlane(forward, levelRight); + const bool behind = dotPlane(forward, direction) < 0.0f; + Mat4 inverse = planeIdentity(); + inverse.setInverse(transformation); + const Vec3 rotation = rotatePlane(inverse, mobile->getRotationalSpeed()); + const float upright = dotPlane(up, levelUp); + float bank = dotPlane(right, levelUp); + const float ratio = heightError / (clearance - 10.0f); + const float altitudeFactor = clampPlane(planeSign(ratio) * ratio * ratio, 0.0f, 1.0f); + const float blend = 1.0f - altitudeFactor; + float pitch = altitudeFactor + altitudeFactor; + const float speedFraction = clampPlane(speed / 43.0f, 0.0f, 1.0f); + const float exponential = std::exp(clampPlane((1.0f - speedFraction) * 2.302585125f, -10.0f, 10.0f)); + const float climb = ((exponential - 1.0f) / 9.0f) * -0.833f + 0.333f; + const float maxClimb = controls->getMaxClimbAngle(); + const float climbLimit = clampPlane(climb, -1.0f, maxClimb); + float pitchLimit = 1.0f; + if (levelUp.y > 0.0f) + { + if (forward.y > 0.0f) + pitchLimit = climbLimit < 0.0f ? (1.0f - levelUp.y) * climbLimit : climbLimit * levelUp.y; + else + pitchLimit = climbLimit / levelUp.y; + } + if (!(throttle > pitch)) + throttle = pitch; + const float wantedPitch = dotPlane(levelUp, direction); + if (!(wantedPitch > pitchLimit)) + pitchLimit = wantedPitch; + pitch += pitchLimit * blend; + float yaw = 0.0f; + if (!takingOff) + { + const float wantedYaw = dotPlane(levelRight, direction); + yaw = behind ? planeSign(wantedYaw) : wantedYaw; + } + if (aiming && pitch < 0.0f && dotPlane(forward, direction) > 0.9f && yaw < 0.1f) + pitch = -clampPlane(std::log10(1.0f - pitch * 18.0f), 0.3f, 1.0f); + if (climbLimit < forward.y) + { + const float limited = -std::log10(1.0f + (forward.y - climbLimit) * 9.0f); + if (limited < pitch) + pitch = limited; + } + pitch = clampPlane(pitch + clampPlane(rotation.x, -1.0f, 1.0f), -1.0f, 1.0f); + yaw = clampPlane(yaw - clampPlane(rotation.y, -1.0f, 1.0f) * 0.1f, -1.0f, 1.0f); + const float maxRoll = controls->getMaxRollAngle(); + const float pitchInput = -(dotPlane(up, levelRight) * yaw + upright * pitch) * 4.0f; + const float pitchBank = dotPlane(right, levelUp) * pitch; + const float yawInput = pitchBank + pitchBank + dotPlane(right, levelRight) * yaw; + if (upright < 0.0f) + bank = planeSign(bank) * 2.0f - bank; + const float angle = std::asin(clampPlane(yaw, -1.0f, 1.0f)); + const float wantedBank = useAngle ? angle * 3.0f : yaw + yaw; + // 0x2CF0F8 then 0x2CF14B: bank + clamped wanted bank first, then the half rotation added. + const float rollInput = clampPlane(rotation.z, -1.0f, 1.0f) * 0.5f + + (bank + clampPlane(wantedBank, -maxRoll, maxRoll)); + const float roll = planeImpulse(clampPlane(planeLogResponse(clampPlane(rollInput, -1.0f, 1.0f)), -1.0f, 1.0f)); + const float turn = planeImpulse(clampPlane(planeLogResponse(clampPlane(yawInput, -1.0f, 1.0f)), -1.0f, 1.0f)); + const float pitchOutput = clampPlane(clampPlane(pitchInput, -1.0f, 1.0f), -1.0f, 1.0f); + const float throttleOutput = clampPlane(throttle, 0.0f, 1.0f); + input->setInput(controls->getDriveThrottleControl(), throttleOutput); + input->setInput(controls->getDrivePitchControl(), pitchOutput); + input->setInput(controls->getDriveRollControl(), roll); + input->setInput(controls->getDriveTurnControl(), turn); + return true; +} + +// ELF 0x2CF9F0 +int PlaneControl::roll(float wantedRoll, float, io::PlayerInput* input, const Mat4& transformation, + float, bool takingOff, const Vec3& referenceForward, + const Vec3& referenceRight, const Vec3& referenceUp, const Vec3&, + const Vec3& previousRight, const Vec3& previousUp, + IPIControlInfo* controls, float throttle, bool left, bool& wrapped) +{ + Mat4 transpose = planeIdentity(); + float turnInput = planeMappedInput(input, controls->getDriveTurnControl()); + float pitchInput = planeMappedInput(input, controls->getDrivePitchControl()); + float rollInput = planeMappedInput(input, controls->getDriveRollControl()); + const Vec3 up = {transformation.m[4], transformation.m[5], transformation.m[6]}; + const Vec3 right = {transformation.m[0], transformation.m[1], transformation.m[2]}; + transpose.setTranspose(transformation); + const float halfPi = 1.570796371f; + const float pi = 3.141592741f; + const float twoPi = 6.283185482f; + const float firstPitch = std::acos(clampPlane(clampPlane(dotPlane(up, referenceForward), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + // The second pitch sample uses the same current up vector, as shipped. + const float secondPitch = std::acos(clampPlane(clampPlane(dotPlane(up, referenceForward), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + const Vec3 worldUp = {0.0f, 1.0f, 0.0f}; + const Vec3 localUp = rotatePlane(transpose, worldUp); + const float elevation = std::asin(clampPlane(localUp.z, -1.0f, 1.0f)); + float pitchDemand; + float pitchChange = 0.0f; + float yawDemand = 0.0f; + float yawChange = 0.0f; + float rollDemand; + float rollChange = 0.0f; + if (takingOff) + { + throttle = 1.0f; + const float maxClimb = controls->getMaxClimbAngle(); + float climb = (maxClimb - elevation) / (1.00001f - std::fabs(right.y)); + if (climb > halfPi) + climb = halfPi; + pitchDemand = -climb; + float angle = std::acos(clampPlane(clampPlane(right.y, -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + if (up.y < 0.0f) + angle = planeSign(angle) * pi - angle; + // 0x2D02FC/0x2D032C store the angle as the roll change, 0x2D0345 its negation as the demand. + rollChange = angle; + rollDemand = -angle; + // The take-off arm leaves the caller's wrapped flag untouched. + } + else + { + pitchDemand = firstPitch * up.y; + pitchChange = pitchDemand - previousUp.y * secondPitch; + yawDemand = (1.0f - up.y) * firstPitch; + yawChange = yawDemand - (1.0f - previousUp.y) * secondPitch; + float angle = std::acos(clampPlane(clampPlane(dotPlane(right, referenceUp), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + if (dotPlane(referenceRight, right) < 0.0f) + angle = twoPi - angle; + float previous = std::acos(clampPlane(clampPlane(dotPlane(previousRight, referenceUp), -1.0f, 1.0f), -1.0f, 1.0f)) - halfPi; + if (dotPlane(referenceRight, previousRight) < 0.0f) + previous = twoPi - previous; + rollChange = angle - previous; + rollDemand = angle - wantedRoll; + if (left ? rollChange < -pi : rollChange > pi) + { + rollChange = left ? twoPi + rollChange : twoPi - rollChange; + wrapped = true; + } + else + wrapped = false; + } + const float pitchScale = controls->getPitchScale(); + const float pitchLookAhead = controls->getPitchLookAhead(); + const float pitchSensitivity = controls->getPitchSensitivity(); + updateAngle(pitchDemand, pitchChange, pitchInput, pitchSensitivity, pitchLookAhead, pitchScale); + const float rollScale = controls->getRollScale(); + const float rollLookAhead = controls->getRollLookAhead(); + const float rollSensitivity = controls->getRollSensitivity(); + updateAngle(rollDemand, rollChange, rollInput, rollSensitivity, rollLookAhead, rollScale); + if (takingOff) + turnInput = 0.0f; + else + { + const float yawScale = controls->getYawScale(); + const float yawLookAhead = controls->getYawLookAhead(); + const float yawSensitivity = controls->getYawSensitivity(); + updateAngle(yawDemand, yawChange, turnInput, yawSensitivity, yawLookAhead, yawScale); + } + input->setInput(controls->getDriveThrottleControl(), throttle); + input->setInput(controls->getDrivePitchControl(), pitchInput); + input->setInput(controls->getDriveRollControl(), rollInput); + input->setInput(controls->getDriveTurnControl(), turnInput); + return 1; +} + +// ELF 0x2D03E0 (listing; Ghidra cross-check). On the ground (BotMain +0x1A4 isAirBorn false) and +// slower than 0.1 (IPIMobile +0x24, asked before `move` is tested), moving releases inputs 0, 2, +// 1 and 3. Look releases 4 and 5; trigger 8, 31, 14..30, 38, 37, 10, 32 and 47. The information +// is not null-tested. Returns 1. +int PlaneControl::resetControls(Bot* bot, Information* equipment, io::PlayerInput* input, bool move, bool look, bool trigger) +{ + IPIMobile* const mobile = equipment->getMobile(); // +0x38 + if (!bot->isAirBorn() && mobile->getSpeedMagnitude() < 0.1f && move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + input->setInput(static_cast(3), 0.0f); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + input->setInput(static_cast(14), 0.0f); + input->setInput(static_cast(15), 0.0f); + input->setInput(static_cast(16), 0.0f); + input->setInput(static_cast(17), 0.0f); + input->setInput(static_cast(18), 0.0f); + input->setInput(static_cast(19), 0.0f); + input->setInput(static_cast(20), 0.0f); + input->setInput(static_cast(21), 0.0f); + input->setInput(static_cast(22), 0.0f); + input->setInput(static_cast(23), 0.0f); + input->setInput(static_cast(24), 0.0f); + input->setInput(static_cast(25), 0.0f); + input->setInput(static_cast(26), 0.0f); + input->setInput(static_cast(27), 0.0f); + input->setInput(static_cast(28), 0.0f); + input->setInput(static_cast(29), 0.0f); + input->setInput(static_cast(30), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + input->setInput(static_cast(47), 0.0f); + } + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.h new file mode 100644 index 000000000..320c514d0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.h @@ -0,0 +1,34 @@ +// Fixed-wing flight and attitude controls. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_PLANECONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_PLANECONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +struct Mat4; +namespace io { class PlayerInput; } +namespace ai { + +class Bot; +class IPIControlInfo; +class IPIMobile; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace PlaneControl +{ + bool towardsPoint(Bot*, Information*, Vec3, float, const Vec3&, const Vec3&, const Vec3&, float, io::PlayerInput*); // 0x2CDB00; [INFERRED] ELF bool + bool aimAtDirection(Bot*, Information*, const Vec3&, float, float, float, const Vec3&, const Vec3&, const Vec3&, io::PlayerInput*); // 0x2CE3C0; [INFERRED] ELF bool + bool towardsDirection(const Vec3&, float, io::PlayerInput*, const Mat4&, float, float, bool, const Vec3&, const Vec3&, const Vec3&, IPIMobile*, IPIControlInfo*, float, float, bool); // 0x2CE6D0; [INFERRED] ELF int, callers {'bool': 1} + int roll(float, float, io::PlayerInput*, const Mat4&, float, bool, const Vec3&, const Vec3&, const Vec3&, const Vec3&, const Vec3&, const Vec3&, IPIControlInfo*, float, bool, bool&); // 0x2CF9F0; [INFERRED] ELF int + int resetControls(Bot*, Information*, io::PlayerInput*, bool, bool, bool); // 0x2D03E0; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_PLANECONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp new file mode 100644 index 000000000..09d691024 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp @@ -0,0 +1,307 @@ +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x1CAC00..0x1CD520. [INFERRED] placement beside +// BAPDebugger in AIPlanInterpreter (no __FILE__ string). + +// static init: ELF 0x1CD160 (__tcf_0 0x1CD1C0, _GLOBAL__I 0x1CD1F0): 's Init object only. +#include + +#include "PrettyPrinter.h" + +#include +#include + +#include "../AIBotActionPlan/BAPATrigger.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPCombinerSerial.h" +#include "../AIBotActionPlan/BAPFlowCIf.h" +#include "../AIBotActionPlan/BAPFlowCWhile.h" +#include "../AIBotActionPlan/BAPInfoWrapper.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIBotActionPlan/BAPTypes.h" +#include "../Main/AIDllFrontier.h" +#include "../Main/AIStreamOperators.h" // operator<<(ostream&, BAPStatementType) + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x1CAC40 (C1), 0x1CAC00 (C2). +PrettyPrinter::PrettyPrinter(BAPStatement* statement, Bot* bot) + : m_statement(statement) + , m_bot(bot) + , m_root(0) +{ + update(); +} + +// ELF 0x1CACB0 (D1), 0x1CAC80 (D2). +PrettyPrinter::~PrettyPrinter() +{ + destroyPrettyTree(m_root); +} + +// ELF 0x1CACE0. The old tree is freed first, but m_root keeps pointing at it until the new root +// is stored. +void PrettyPrinter::update() +{ + destroyPrettyTree(m_root); + m_root = new Node; + m_root->m_statement = m_statement; + m_root->m_depth = 0; + m_root->m_specialInfo = PrettyActive; + prettyPrintScriptNode(m_root); +} + +// ELF 0x1CAD90. Children first, then the node. +void PrettyPrinter::destroyPrettyTree(Node* node) +{ + if (!node) + return; + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + destroyPrettyTree(*child); + delete node; +} + +// ELF 0x1CAE60. The node's text starts from the statement type's name; combiners, IF, WHILE and +// the info wrapper add one child node per sub-statement (depth + 1), and IF and WHILE add marker +// nodes at the node's own depth. A child is on the active path only where the node is: every +// child of a parallel combiner, the current child of a serial one, the IF branch last taken, the +// WHILE body and the wrapped statement. The parallel combiner's finished flags are fetched and +// not used (shipped). +void PrettyPrinter::prettyPrintScriptNode(Node* node) +{ + if (!node || !node->m_statement) + return; + + std::stringstream typeStream; + typeStream << node->m_statement->getId(); + + switch (node->m_statement->getId()) + { + case BAPSTParallel: + { + BAPCombinerParallel* const parallel = static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str(); + if (parallel->m_debugId != -1) + text << "(" << parallel->m_debugId << ")"; + node->m_text = text.str(); + + parallel->getIsFinished(); + for (std::list::iterator it = parallel->m_statements.begin(); + it != parallel->m_statements.end(); ++it) + { + Node* child = new Node; + child->m_statement = *it; + child->m_depth = node->m_depth + 1; + if (node->m_specialInfo == PrettyActive) + child->m_specialInfo = PrettyActive; + else + child->m_specialInfo = PrettyNormal; + prettyPrintScriptNode(child); + node->m_children.push_back(child); + node->m_separators.push_back(std::string("---")); + } + break; + } + + case BAPSTSerial: + { + BAPCombinerSerial* const serial = static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str(); + if (serial->m_debugId != -1) + text << "(" << serial->m_debugId << ")"; + node->m_text = text.str(); + + const std::list::iterator current = serial->m_current; + for (std::list::iterator it = serial->m_statements.begin(); + it != serial->m_statements.end(); ++it) + { + Node* child = new Node; + child->m_statement = *it; + child->m_depth = node->m_depth + 1; + if (it == current && node->m_specialInfo == PrettyActive) + child->m_specialInfo = PrettyActive; + else + child->m_specialInfo = PrettyNormal; + prettyPrintScriptNode(child); + node->m_children.push_back(child); + node->m_separators.push_back(std::string("---")); + } + break; + } + + case BAPSTIf: + { + BAPFlowCIf* const flow = static_cast(node->m_statement); + node->m_text = "IF"; + BAPStatement* const trueStatement = flow->getTrueStatement(); + BAPStatement* const active = flow->getActiveStatementDebug(); + + Node* trueNode = new Node; + trueNode->m_statement = trueStatement; + trueNode->m_depth = node->m_depth + 1; + trueNode->m_specialInfo = PrettyNormal; + if (node->m_specialInfo == PrettyActive && trueStatement == active) + trueNode->m_specialInfo = PrettyActive; + prettyPrintScriptNode(trueNode); + node->m_children.push_back(trueNode); + + BAPStatement* const falseStatement = flow->getFalseStatement(); + if (falseStatement) + { + Node* falseNode = new Node; + falseNode->m_statement = falseStatement; + falseNode->m_depth = node->m_depth + 1; + falseNode->m_specialInfo = PrettyNormal; + if (node->m_specialInfo == PrettyActive && falseStatement == active) + falseNode->m_specialInfo = PrettyActive; + + // the ELSE line goes in before the branch is printed + Node* elseNode = new Node; + elseNode->m_text = "ELSE"; + elseNode->m_depth = node->m_depth; + elseNode->m_specialInfo = PrettyNormal; + node->m_children.push_back(elseNode); + + prettyPrintScriptNode(falseNode); + node->m_children.push_back(falseNode); + } + + Node* endNode = new Node; + endNode->m_text = "ENDIF"; + endNode->m_depth = node->m_depth; + endNode->m_specialInfo = PrettyNormal; + node->m_children.push_back(endNode); + break; + } + + case BAPSTWhile: + { + BAPFlowCWhile* const flow = static_cast(node->m_statement); + node->m_text = typeStream.str(); + + Node* loopNode = new Node; + loopNode->m_statement = flow->getLoopStatement(); + loopNode->m_depth = node->m_depth + 1; + loopNode->m_specialInfo = node->m_specialInfo; + prettyPrintScriptNode(loopNode); + node->m_children.push_back(loopNode); + + Node* endNode = new Node; + endNode->m_text = "ENDWHILE"; + endNode->m_depth = node->m_depth; + endNode->m_specialInfo = PrettyNormal; + node->m_children.push_back(endNode); + break; + } + + case BAPSTTrigger: + { + BAPATrigger* const trigger = static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str() << " "; + if (trigger->m_started) + text << "Trig "; + else + text << "NoTr "; + node->m_text = text.str(); + break; + } + + case BAPSTTriggerContinously: + { + BAPATriggerContinously* const trigger = + static_cast(node->m_statement); + std::stringstream text; + text << typeStream.str() << " "; + if (trigger->m_started) + text << "Trig "; + else + text << "NoTr "; + node->m_text = text.str(); + break; + } + + case BAPSTInfoWrapper: + { + BAPInfoWrapper* const wrapper = static_cast(node->m_statement); + node->m_text = typeStream.str(); + + Node* child = new Node; + child->m_statement = wrapper->m_statement; + child->m_depth = node->m_depth + 1; + child->m_specialInfo = node->m_specialInfo; + prettyPrintScriptNode(child); + node->m_children.push_back(child); + break; + } + + default: + node->m_text = typeStream.str(); + break; + } +} + +// ELF 0x1CCC00. +void PrettyPrinter::getLineStrings(std::list& lines) const +{ + getLinesRecursive(lines, m_root); +} + +// ELF 0x1CCC40. Each child's lines are collected in a list of their own and spliced on. +void PrettyPrinter::getLinesRecursive(std::list& lines, Node* node) const +{ + lines.insert(lines.end(), node->m_text); + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + { + std::list childLines; + getLinesRecursive(childLines, *child); + lines.splice(lines.end(), childLines); + } +} + +// ELF 0x1CCE60. +void PrettyPrinter::getLineDepths(std::list& depths) const +{ + getDepthsRecursive(depths, m_root); +} + +// ELF 0x1CCEA0. +void PrettyPrinter::getDepthsRecursive(std::list& depths, Node* node) const +{ + depths.insert(depths.end(), node->m_depth); + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + { + std::list childDepths; + getDepthsRecursive(childDepths, *child); + depths.splice(depths.end(), childDepths); + } +} + +// ELF 0x1CCFE0. +void PrettyPrinter::getLineSpecialInfos(std::list& infos) const +{ + getSpecialInfosRecursive(infos, m_root); +} + +// ELF 0x1CD020. +void PrettyPrinter::getSpecialInfosRecursive(std::list& infos, Node* node) const +{ + infos.insert(infos.end(), node->m_specialInfo); + for (std::list::iterator child = node->m_children.begin(); + child != node->m_children.end(); ++child) + { + std::list childInfos; + getSpecialInfosRecursive(childInfos, *child); + infos.splice(infos.end(), childInfos); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.h new file mode 100644 index 000000000..d6505f687 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.h @@ -0,0 +1,73 @@ +// Builds a printable tree of a bot action plan: one node per statement plus IF/ELSE/ENDIF and +// ENDWHILE marker lines, each with its indentation depth and whether it lies on the active path. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x1CAC00..0x1CD520; the TU's static-init symbol +// names PrettyPrinter's constructor. Nothing else in the DLL refers to the class. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_PRETTYPRINTER_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_PRETTYPRINTER_H + +#include +#include + +namespace dice { +namespace hfe { + +namespace ai { + +class BAPStatement; +class Bot; + +// Per-line marker handed out by getLineSpecialInfos: 1 for lines on the plan's active path (the +// root, the running child of a serial combiner, the chosen IF branch), else 0. Four bytes. +// [INFERRED] an enum (the mangled name does not tell enum from class) and the enumerator names. +enum PrettySpecialInfo +{ + PrettyNormal = 0, + PrettyActive = 1 +}; + +// 12 bytes: the plan, the bot (stored, never read) and the tree's root. +class PrettyPrinter +{ +public: + // 24 bytes. The implicit constructor leaves the statement, depth and marker unset; the + // ELSE/ENDIF/ENDWHILE marker nodes never get a statement. + struct Node + { + /* +0x00 */ BAPStatement* m_statement; + /* +0x04 */ std::string m_text; + /* +0x08 */ int m_depth; + /* +0x0C */ PrettySpecialInfo m_specialInfo; + /* +0x10 */ std::list m_children; + /* +0x14 */ std::list m_separators; // "---" per combiner child; never read + }; + + // Builds the tree at once (update). + PrettyPrinter(BAPStatement* statement, Bot* bot); // ELF 0x1CAC40 (C1), 0x1CAC00 (C2) + ~PrettyPrinter(); // ELF 0x1CACB0 (D1), 0x1CAC80 (D2) + + // Rebuilds the tree from the plan's current state. + void update(); + void destroyPrettyTree(Node* node); + // Fills `node` (text and children) from its statement; nothing for a null node or statement. + void prettyPrintScriptNode(Node* node); + + // The tree in pre-order, one entry per line, appended to the caller's list. + void getLineStrings(std::list& lines) const; + void getLinesRecursive(std::list& lines, Node* node) const; + void getLineDepths(std::list& depths) const; + void getDepthsRecursive(std::list& depths, Node* node) const; + void getLineSpecialInfos(std::list& infos) const; + void getSpecialInfosRecursive(std::list& infos, Node* node) const; + +private: + /* +0x00 */ BAPStatement* m_statement; + /* +0x04 */ Bot* m_bot; + /* +0x08 */ Node* m_root; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_PRETTYPRINTER_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp new file mode 100644 index 000000000..ab36dbb0f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp @@ -0,0 +1,869 @@ +// Tank steering for the plan interpreter (libaidll.so TankControl TU). Every body is recovered. +// static init: the guard object only (ELF 0x2D4AF0, __tcf_0 0x2D4B50, _GLOBAL__I 0x2D4B80). + +#include "TankControl.h" + +#include "CommonControls.h" +#include "VehicleControlInline.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotNavigation.h" +#include "../AIBotActionPlan/BAPAMoveTo.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/IBotManager.h" +#include "../../../../Math/LocalBoundingBox.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../IO/Input/PlayerInput.h" +#include "../../../../Math/Mat4.h" +#include +#include "../../../../Math/Vec3.h" + +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +using namespace vehiclecontrol; + +namespace { + +// The TU's tweak values (.data 0x4BDD84..0x4BDDB8). Only the last three are read (by +// turnTowardsDirection); tweak_maxSpeed 20, tweak_minSpeed 2, tweak_stopAndTurn_maxSpeed 2, +// tweak_speedScale 2, tweak_speedCompensationFallOff 30, tweak_speedCompensationScale 1, +// tweak_maxSpeedCompensation 10, tweak_rotationalSpeedScale 1, +// tweak_rotationalSpeedCompensationFallOff 30, tweak_rotationalSpeedCompensationScale 1 and +// tweak_maxRotationalSpeedCompensation 10 have no reader in the image. +float tweak_velocityLimitModifier = 0.3f; // .data 0x4BDDB0 +float tweak_lowThrottle = 0.5f; // .data 0x4BDDB4 +float tweak_highThrottle = 1.0f; // .data 0x4BDDB8 + +// min(1, |signedSpeed|): the pass statuses' steering scale (0x2D3C39). +inline float passTurn(float signedSpeed) +{ + float magnitude = std::fabs(signedSpeed); + if (magnitude > 1.0f) + magnitude = 1.0f; + return magnitude; +} + +} // namespace + +// ELF 0x2D07B0 (Ghidra; listing for the statics and the inlined setInput). The car version with a +// speed-scaled turn: angle' = min(1, |v| / maxSpeed)^2 * angle, and 0 below minVelocity (the +// statics, 2 and 1). Driving: turn input clamp(3 * angle', -1, 1); target speed = speed * mode, +// capped at `limit` (no slope reduction); throttle = clamp(target / 15 + sign(r) * r^2, -1, 1) with +// r = min(1, (target - |v| * reference) / 3), and below 1.5 m/s a non-zero throttle becomes its sign. +// Turning on the spot: the turn input (only while mapped) is sign(angle') * min(1, |3 * (|angle'| +// [- pi])|); the throttle input gets `mode`. `direction` and the physical part are not read. +// Returns 1. +int TankControl::controlTowardsDirection(Information* info, IPIControlInfo* controlInfo, IPIMobile* mobile, + IPIPhysical*, io::PlayerInput* input, const Vec2&, float speed, float mode, + float angle, float reference, float limit) +{ + static float minVelocity = 1.0f; // .data 0x4BDDBC + static float maxSpeed = 2.0f; // .data 0x4BDDC0 + + const Mat4& transformation = info->getTransformation(); + Vec2 forward; + forward.x = forward.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[8]), forward); + Vec2 right; // read, never used + right.x = right.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[0]), right); + Vec2 position; // read, never used + position.x = position.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&transformation.m[12]), position); + Vec2 velocity; + velocity.x = velocity.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), velocity); + const float velocityLength = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); + Vec2 heading; // computed, never used + if (velocityLength == 0.0f) + { + heading = forward; + } + else + { + const float inverse = 1.0f / velocityLength; + heading.x = velocity.x * inverse; + heading.y = inverse * velocity.y; + } + (void)heading; + if (mode != 0.0f && reference != mode && velocityLength > 1.0f) + angle = -angle; + float speedRatio = std::fabs(velocityLength) / maxSpeed; + if (std::fabs(velocityLength) < minVelocity) + angle = 0.0f; + if (speedRatio > 1.0f) + speedRatio = 1.0f; + const float scaledAngle = speedRatio * speedRatio * angle; + float sign = 1.0f; + if (scaledAngle <= 0.0f) + sign = (0.0f <= scaledAngle) ? 0.0f : -1.0f; + if (speed != 0.0f) + { + IAIObjectPhysical* const object = info->getAIObject()->getPhysical(); + object->enablePhysics(1); + object->enablePhysics(2); + } + + float throttle; + if (mode != 0.0f) + { + const float turnAngle = scaledAngle * 3.0f; + float turn = -1.0f; + if (-1.0f <= turnAngle) + turn = (1.0f < turnAngle) ? 1.0f : turnAngle; + input->setInput(controlInfo->getDriveTurnControl(), turn); + speed = speed * mode; + if (std::fabs(speed) > limit) + { + float speedSign = 0.0f; + if (speed <= 0.0f) + { + if (speed < 0.0f) + speedSign = -1.0f; + } + else + { + speedSign = 1.0f; + } + speed = speedSign * limit; + } + float response = (speed - velocityLength * reference) / 3.0f; + if (response > 1.0f) + response = 1.0f; + float responseSign = 1.0f; + if (response <= 0.0f) + responseSign = (0.0f <= response) ? 0.0f : -1.0f; + const float combined = speed / 15.0f + responseSign * response * response; + throttle = -1.0f; + if (-1.0f <= combined) + throttle = (combined <= 1.0f) ? combined : 1.0f; + if (throttle != 0.0f && !(1.5f <= std::fabs(velocityLength))) + { + float throttleSign = 1.0f; + if (throttle <= 0.0f) + throttleSign = (throttle < 0.0f) ? -1.0f : 0.0f; + throttle = throttleSign; + } + } + else + { + float turnAngle = std::fabs(scaledAngle); + if (mode == -1.0f) + turnAngle = turnAngle - 3.1415927f; + float turn = std::fabs(turnAngle * 3.0f); + if (turn > 1.0f) + turn = 1.0f; + input->setInput(controlInfo->getDriveTurnControl(), sign * turn); + throttle = mode; + } + input->setInput(controlInfo->getDriveThrottleControl(), throttle); + return 1; +} + +// ELF 0x2D0E30 (listing; Ghidra cross-check). Turns a tank on the spot towards `angle`: +// turn input -sign(angle) * (forward ? 1 : -1); the rotational speed about y is driven to +// min(1, (|angle| + 0.05) / maxOffsetAngle) times that and rotationTweak in steps of 0.05; the +// throttle is (forward ? 1 : -1) times tweak_lowThrottle while the ground speed is above +// min(1, angle^2 * tweak_velocityLimitModifier), else tweak_highThrottle. `unused` and `done` are +// not read; the normalised ground velocity is computed and dropped. +void TankControl::turnTowardsDirection(float angle, float, bool forward, Information* info, IPIMobile* mobile, + IPIControlInfo* controlInfo, io::PlayerInput* input, bool*) +{ + static float rotationTweak = 2.0f; // .data 0x4BDDC4 + static float maxOffsetAngle = 0.6f; // .data 0x4BDDC8 + + Vec2 velocity; + velocity.x = velocity.y = 0.0f; + vec3ToVec2XZ(mobile->getSpeed(), velocity); + const float velocityLength = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); + const float inverse = 1.0f / velocityLength; + Vec2 heading; // computed, never used + heading.x = velocity.x * inverse; + heading.y = velocity.y * inverse; + (void)heading; + const float direction = forward ? 1.0f : -1.0f; + float sign = 1.0f; + if (!(angle > 0.0f)) + sign = (0.0f > angle) ? -1.0f : 0.0f; + float velocityLimit = angle * angle * tweak_velocityLimitModifier; + if (velocityLimit > 1.0f) + velocityLimit = 1.0f; + const float turn = -sign * direction; + input->setInput(controlInfo->getDriveTurnControl(), turn); + float offset = (std::fabs(angle) + 0.05f) / maxOffsetAngle; + if (offset > 1.0f) + offset = 1.0f; + info->getAIObject()->striveForRotationalSpeed(1, offset * turn * rotationTweak, 0.05f); + if (velocityLength > velocityLimit) + input->setInput(controlInfo->getDriveThrottleControl(), direction * tweak_lowThrottle); + else + input->setInput(controlInfo->getDriveThrottleControl(), direction * tweak_highThrottle); +} + +// ELF 0x2D1010 (Ghidra). The car's reset with the tank's own maxThrottle static (also 0.7): +// moving releases inputs 0, 2 and 1 and brakes the throttle (input 3) against `forwardSpeed` +// (clamped to +-maxThrottle, negated; released within 0.05 of zero, else the sign times at least +// 0.4). Look releases 4 and 5; trigger releases 8, 31, 14..30, 38, 37, 10 and 32. Returns 1. +int TankControl::resetControls(Bot*, io::PlayerInput* input, bool move, bool look, bool trigger, float forwardSpeed) +{ + static float maxThrottle = 0.7f; + if (move) + { + input->setInput(static_cast(0), 0.0f); + input->setInput(static_cast(2), 0.0f); + input->setInput(static_cast(1), 0.0f); + float clamped; + if (-maxThrottle > forwardSpeed) + clamped = -maxThrottle; + else + clamped = (forwardSpeed > maxThrottle) ? maxThrottle : forwardSpeed; + const float brake = -clamped; + float throttle = 0.0f; + if (std::fabs(brake) > 0.05f) + { + const float sign = (brake > 0.0f) ? 1.0f : ((0.0f > brake) ? -1.0f : 0.0f); + const float magnitude = std::fabs(brake); + throttle = sign * ((magnitude > 0.4f) ? magnitude : 0.4f); + } + input->setInput(static_cast(3), throttle); + } + if (look) + { + input->setInput(static_cast(4), 0.0f); + input->setInput(static_cast(5), 0.0f); + } + if (trigger) + { + input->setInput(static_cast(8), 0.0f); + input->setInput(static_cast(31), 0.0f); + for (int i = 14; i <= 30; ++i) + input->setInput(static_cast(i), 0.0f); + input->setInput(static_cast(38), 0.0f); + input->setInput(static_cast(37), 0.0f); + input->setInput(static_cast(10), 0.0f); + input->setInput(static_cast(32), 0.0f); + } + return 1; +} + +// ELF 0x2D1390 (listing, diffed against CarControl::actionStatusDecision 0x2AB970 instruction by +// instruction; Ghidra cross-check). The tank's move-to state machine, the car's with these changes: +// the near-goal distance is 5 radii (car 10), checkCollisions looks ahead 0.5 s (car 0.25 s), the +// speed limit is maxSpeed - (1 - ratio) * maxSpeed / 2 (no 5 m/s band), the pass statuses 4/5/13/14 +// steer +-0.2 * min(1, |signed speed|) (car +-2) and also leave when touching an obstacle more than +// 0.8 ahead, status 11 returns to 0 above 0.9 without the front-space test, and status 12 turns +// towards the side with more room. Outputs and shipped quirks as in the car version. +int TankControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& direction, float speed, + BAPAMoveTo* moveTo, float& mode, float& angle, float& speedSign, + float& speedLimit) +{ + static float spaceTweak = 1.3f; // .data 0x4BDDD0 + + IPIMobile* const mobile = info->getMobile(); + IPIPhysical* const physical = info->getPhysical(); + if (mobile == 0 || physical == 0) + return 0; + BotMain* const botMain = static_cast(bot); // slots 0x238.. are declared on BotMain only + const float radius = physical->getRadius(); + Vec2 desired = direction; + const Vec3& position3 = info->getPosition(); + Vec2 position; + position.x = position.y = 0.0f; + Vec2 forward; + forward.x = forward.y = 0.0f; + Vec2 normal; + normal.x = normal.y = 0.0f; + vec3ToVec2XZ(position3, position); + vec3ToVec2XZ(info->getFaceing(), forward); + normalizeVec2(forward); + getNormal(forward, normal); + Vec2 goal; + goal.x = goal.y = 0.0f; + vec3ToVec2XZ(moveTo->getCoordinate(), goal); + float goalDistance = moveTo->getTargetDistance(); + if (goalDistance == 0.0f) + { + Vec2 toGoal; + toGoal.x = position.x - goal.x; + toGoal.y = position.y - goal.y; + goalDistance = std::sqrt(toGoal.x * toGoal.x + toGoal.y * toGoal.y); + } + const float nearDistance = radius * 5.0f; + const float dot = desired.x * forward.x + desired.y * forward.y; + angle = getSignedDiffAngleToDirWithNormal(forward, normal, desired); + const bool angleNegative = 0.0f > angle; + const float speedMagnitude = mobile->getSpeedMagnitude(); + const Vec3& velocity = mobile->getSpeed(); + const Vec3 facing = info->getFaceing(); + if (velocity.x * facing.x + velocity.y * facing.y + velocity.z * facing.z >= 0.0f) + speedSign = 1.0f; + else + speedSign = -1.0f; + bool slowDownStop; + const float signedSpeed = speedMagnitude * speedSign; + const float slowDown = CommonControls::checkSlowDown(bot, info, velocity, signedSpeed, position3, slowDownStop); + Vec3 forward3; + forward3.x = forward3.y = forward3.z = 0.0f; + vec2ToVec3XZ(forward, forward3); + mode = 1.0f; + + // 0x2ABCE4: the eight space traces. + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + mobile->getVehicleNumber(); // result discarded + BotNavigation* const navigation = bot->getBotNavigation(); + const float traceLength = radius + 10.0f; + Vec3 hit; + hit.x = hit.y = hit.z = 0.0f; + const IPIMobile::ValidPos& lastValid = mobile->getLastValidPosition(pathfinding->getTraceMapIndex()); + const int equipmentType = info->getUnit()->getEquipmentType(); + Vec3 right; + right.x = normal.x; + right.y = 0.0f; + right.z = normal.y; + int status = botMain->getMoveToStatus(); + const bool reversing = status > 7; + float back = 0.0f; + float front = 0.0f; + LocalBoundingBox* const box = const_cast(physical->getLocalBoundingBox()); + const Vec3& size = box->getSize(); + const float width = size.x; + const float length = size.z; + const Vec3 origin = lastValid.position; + const Vec3 ahead = forward3; + Vec3 frontLeft; + frontLeft.x = length * forward3.x - right.x * width; + frontLeft.y = length * forward3.y - right.y * width; + frontLeft.z = length * forward3.z - right.z * width; + normalizeVec3(frontLeft); + Vec3 frontRight; + frontRight.x = length * ahead.x + right.x * width; + frontRight.y = ahead.y * length + right.y * width; + frontRight.z = length * ahead.z + right.z * width; + normalizeVec3(frontRight); + unsigned int polygon; + unsigned char traceStatus; + float frontUnused; // -0x2CC: updateSpaceWithObstacles' front output, never initialised or read + + Vec3 target = alongFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + front = distanceVec3(hit, origin); + const float firstFront = front; + target = alongFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > firstFront) ? firstFront : d; + } + target = alongFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + front = (d > front) ? front : d; + } + target = backFrom(origin, ahead, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, 0); + if (!isZeroVec3(hit)) + back = distanceVec3(hit, origin); + CommonControls::updateSpaceWithObstacles(bot, origin, ahead, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontLeft, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontLeft, frontUnused, back, 0xFFFFFFFFu); + target = backFrom(origin, frontRight, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + if (traceStatus != 4 && !isZeroVec3(hit)) + { + const float d = distanceVec3(hit, origin); + back = (d > back) ? back : d; + } + CommonControls::updateSpaceWithObstacles(bot, origin, frontRight, frontUnused, back, 0xFFFFFFFFu); + target = alongFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float rightSpace = traceLength; + if (traceStatus != 4) + rightSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + target = backFrom(origin, right, traceLength); + pathfinding->trace(navigation, true, target, hit, polygon, equipmentType, -1, 0.0f, 6, &traceStatus); + float leftSpace = traceLength; + if (traceStatus != 4) + leftSpace = isZeroVec3(hit) ? 0.0f : distanceVec3(hit, origin); + + // 0x2AD236: the obstacle ahead. + const float spaceRadius = radius * spaceTweak; + unsigned int obstacle = 0xFFFFFFFFu; + unsigned int collided = botMain->getCollidedObject(); + int avoidSide = botMain->getAvoidSide(); + Vec2 desiredVelocity; + desiredVelocity.x = speed * direction.x; + desiredVelocity.y = speed * direction.y; + float dotForward; + float angleToObstacle; + bool outOfOurWay; + bool passing; + bool collidedSeen; + float avoidAngle; + float tangentAngle; + bool touching; + bool collision = CommonControls::checkCollisions(bot, info, physical, forward, dotForward, angleToObstacle, + outOfOurWay, desiredVelocity, desired, speed, passing, obstacle, + collided, collidedSeen, avoidAngle, tangentAngle, speedSign, + touching, static_cast(avoidSide), false); + if (collided != 0xFFFFFFFFu && !collidedSeen) + collision = false; + if (collision) + { + Information* const obstacleInfo = lookupInformation(obstacle); + const float limitSqr = botMain->getIgnoreObstacles() ? 2.5f * 2.5f : 1.0f; + if (obstacle == collided && obstacle != 0xFFFFFFFFu) + { + // 0x2AEB27: drop the collision once the collided object has moved away. + const Vec3& last = botMain->getCollidedObjectPosition(); + const Vec3& now = obstacleInfo->getPosition(); + Vec3 moved; + moved.x = now.x - last.x; + moved.y = now.y - last.y; + moved.z = now.z - last.z; + if (moved.x * moved.x + moved.y * moved.y + moved.z * moved.z > limitSqr) + collision = false; + } + else + { + botMain->setCollidedObjectPosition(obstacleInfo->getPosition()); + } + } + if (!collision) + { + botMain->setCollidedObject(0xFFFFFFFFu); + obstacle = 0xFFFFFFFFu; + collided = 0xFFFFFFFFu; + } + bool tooClose = false; + if (collision) + { + botMain->setCollidedObject(obstacle); + collided = obstacle; + if (avoidSide == 0) + { + // 0x2AD494: choose the side with more room around the collided vehicle. + Information* const other = lookupInformation(collided); + IPIMobile* const otherMobile = other->getMobile(); + IPIPhysical* const otherPhysical = other->getPhysical(); + if (otherMobile == 0) + { + avoidSide = 1; + } + else + { + const float clearance = radius + otherPhysical->getSmallestRadius() * 0.5f; + const float reach = clearance + 0.5f; + const int vehicleNumber = mobile->getVehicleNumber(); + const IPIMobile::ValidPos& otherValid = otherMobile->getLastValidPosition(vehicleNumber); + if (otherValid.polygon == 0xFFFFFFFFu || otherValid.quadTree == 0xFFFFFFFFu) + { + avoidSide = 1; + } + else + { + Vec3 hitRight; + hitRight.x = hitRight.y = hitRight.z = 0.0f; + Vec3 hitLeft; + hitLeft.x = hitLeft.y = hitLeft.z = 0.0f; + unsigned int sidePolygon; + Vec3 sideTarget = alongFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + sideTarget, hitRight, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomRight = isZeroVec3(hitRight) ? 0.0f : distanceVec3(hitRight, otherValid.position); + sideTarget = backFrom(otherValid.position, rightAxis(info->getTransformation()), reach); + pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + sideTarget, hitLeft, sidePolygon, equipmentType, -1, 0.0f, 0, 0); + float roomLeft = isZeroVec3(hitLeft) ? 0.0f : distanceVec3(hitLeft, otherValid.position); + bool firstSide = roomRight < roomLeft; // before the obstacles shorten them + CommonControls::updateSpaceWithObstacles(bot, otherValid.position, + rightAxis(info->getTransformation()), roomRight, + roomLeft, collided); + const float smaller = (roomLeft < roomRight) ? roomLeft : roomRight; + const float larger = (roomRight > roomLeft) ? roomRight : roomLeft; + tooClose = clearance > larger; + if (smaller > clearance) + { + // 0x2AEA3E: room on both sides - the side the other vehicle lies on across the desired line. + Vec2 sideNormal; + sideNormal.x = sideNormal.y = 0.0f; + getNormal(desired, sideNormal); + Vec2 toOther; + toOther.x = otherValid.position.x - position.x; + toOther.y = otherValid.position.z - position.y; + firstSide = toOther.x * sideNormal.x + toOther.y * sideNormal.y > 0.0f; + } + else if (!(clearance * 0.7f > larger)) + { + firstSide = roomRight < roomLeft; + } + avoidSide = 2; + if (firstSide) + avoidSide = 1; + } + } + if (botMain->setAvoidSide(avoidSide) && !botMain->getIgnoreObstacles()) + { + status = 0; + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + } + } + else + { + botMain->setAvoidSide(0); + } + + // 0x2ADA40: arrived next to the collided object's goal? + bool hasCollided = collided != 0xFFFFFFFFu; + bot->setUnresolvedCollisionObject(collided); + if (hasCollided) + { + Information* const other = lookupInformation(collided); + if (other == 0) + { + hasCollided = false; + collided = 0xFFFFFFFFu; + } + else + { + Vec2 otherPosition; + otherPosition.x = otherPosition.y = 0.0f; + vec3ToVec2XZ(*reinterpret_cast(&other->getTransformation().m[12]), otherPosition); + const float otherRadius = other->getPhysical()->getRadius(); + Vec2 goalOffset; + goalOffset.x = goal.x - otherPosition.x; + goalOffset.y = goal.y - otherPosition.y; + if (otherRadius * otherRadius > goalOffset.x * goalOffset.x + goalOffset.y * goalOffset.y) + { + Vec2 toOther; + toOther.x = otherPosition.x - position.x; + toOther.y = otherPosition.y - position.y; + const float distanceSqr = toOther.x * toOther.x + toOther.y * toOther.y; + const float reach = other->getPhysical()->getRadius() + radius + 3.0f; + if (reach * reach > distanceSqr) + { + mode = 666.0f; + angle = 0.0f; + return 1; + } + } + } + } + else + { + avoidSide = 0; + botMain->setAvoidSide(0); + } + + // 0x2ADB2D: room flags and the speed limit. + bool wideSpace = false; + const bool obstacleAngleNegative = 0.0f > angleToObstacle; + if (leftSpace + rightSpace > radius * 2.7f && front + back > radius * 2.7f) + wideSpace = true; + bool veryWideSpace = false; + if (leftSpace + rightSpace > radius * 3.0f && front + back > radius * 3.0f) + veryWideSpace = true; + const float frontRatio = (front - spaceRadius) / (traceLength - spaceRadius); + const float backRatio = (back - spaceRadius) / (traceLength - spaceRadius); + bool stuck = false; + if (front == 0.0f && back == 0.0f) + { + stuck = true; + status = !(dot > 0.0f) ? 8 : 0; + } + const float maxSpeed = mobile->getMaxSpeed(); + const float minSpeed = maxSpeed * 0.5f; + if (!reversing) + speedLimit = maxSpeed - (1.0f - frontRatio) * (maxSpeed - minSpeed); + else + speedLimit = maxSpeed - (1.0f - backRatio) * (maxSpeed - minSpeed); + if (tooClose) + speedLimit = (7.0f > speedLimit) ? speedLimit : 7.0f; + if (!hasCollided) + { + botMain->setIgnoreObstacles(false); + botMain->setAvoidSide(0); + } + bool ignoring = botMain->getIgnoreObstacles(); + if (ignoring) + { + if (hasCollided) + { + // 0x2ADD1E: keep ignoring while we push the collided object, unless it has a human driver. + Information* const other = lookupInformation(collided); + IAIObjectPhysical* const otherObject = other->getAIObject()->getPhysical(); + otherObject->enablePhysics(1); + otherObject->enablePhysics(2); + if (botMain->getSlowDownToTarget() == collided) + ignoring = true; + if (other->getAIObject() != 0 && IBotManager::instance->getBot(other->getAIObject()) == 0 + && other->getUnit() != 0 && other->getUnit()->isOccupied()) + ignoring = false; + } + if (ignoring && (static_cast(status - 4) <= 2u || status == 13 || status == 14)) + { + status = 0; + botMain->setMoveToStatus(0); + } + } + + // 0x2ADE10 + switch (status) + { + case 0: + if (stuck) + { + mode = 1.0f; + speedLimit = maxSpeed * 0.5f; + break; + } + if (!(0.0f > dot) && !(spaceRadius > front)) + { + if (collision && !ignoring) + botMain->setMoveToStatus(6); + else + mode = 1.0f; + break; + } + if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(8); + break; + } + if (0.0f > dot && !wideSpace) + { + botMain->setMoveToStatus(12); + break; + } + botMain->setMoveToStatus(angleNegative ? 9 : 11); + break; + case 2: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(11); + break; + } + if (angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(9); + break; + } + mode = 1.0f; + angle = std::fabs(angle); + break; + case 3: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f) + { + botMain->setMoveToStatus(0); + break; + } + if (spaceRadius > front || (dotForward > 0.5f && hasCollided && !outOfOurWay && !ignoring)) + { + botMain->setMoveToStatus(9); + break; + } + if (!angleNegative && wideSpace && 0.0f > dot && back > spaceRadius) + { + botMain->setMoveToStatus(11); + break; + } + mode = 1.0f; + angle = -std::fabs(angle); + break; + case 4: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || (touching && dotForward > 0.8f)) + botMain->setMoveToStatus(13); + else + { + mode = 1.0f; + angle = passTurn(signedSpeed) * -0.2f; + } + break; + case 5: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > front || (touching && dotForward > 0.8f)) + botMain->setMoveToStatus(14); + else + { + mode = 1.0f; + angle = passTurn(signedSpeed) * 0.2f; + } + break; + case 6: + if (!hasCollided || (passing && 0.3f > dotForward)) + { + botMain->setMoveToStatus(0.0f > angle ? 3 : 2); + break; + } + if (touching && !outOfOurWay && dotForward > 0.0f) + { + botMain->setMoveToStatus(avoidSide == 2 ? 14 : 13); + break; + } + if (front >= spaceRadius) + { + angle = avoidAngle; + break; + } + if (avoidSide == 2) + { + if (botMain->setAvoidSide(1) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(13); + } + } + else + { + if (botMain->setAvoidSide(2) && !botMain->getIgnoreObstacles()) + { + botMain->setMoveToStatus(0); + botMain->setIgnoreObstacles(true); + } + else + { + botMain->setMoveToStatus(14); + } + } + break; + case 8: + if (stuck) + { + mode = -1.0f; + angle = -angle; + reverseAngle(angle); + break; + } + if (dot > -0.5f || goalDistance > nearDistance + 5.0f || spaceRadius > back) + { + botMain->setMoveToStatus(0); + mode = 1.0f; + break; + } + if (-0.6f > dotForward && hasCollided) + { + botMain->setMoveToStatus(obstacleAngleNegative ? 3 : 2); + break; + } + mode = -1.0f; + reverseAngle(angle); + break; + case 9: + if (!angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 2 : 11); + break; + } + if (dot > 0.9f && front > spaceRadius) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(3); + else + { + mode = -1.0f; + angle = std::fabs(angle); + } + break; + case 11: + if (angleNegative) + { + botMain->setMoveToStatus(dot > 0.0f ? 3 : 9); + break; + } + if (dot > 0.9f) + botMain->setMoveToStatus(0); + else if (spaceRadius > back) + botMain->setMoveToStatus(2); + else + { + mode = -1.0f; + angle = -std::fabs(angle); + } + break; + case 12: + if (dot > 0.0f) + botMain->setMoveToStatus(0); + else if (nearDistance >= goalDistance && -0.6f > dot && back > spaceRadius) + botMain->setMoveToStatus(8); + else if (veryWideSpace) + botMain->setMoveToStatus(rightSpace > leftSpace ? 9 : 11); + else + { + mode = -1.0f; + reverseAngle(angle); + } + break; + case 13: + if (!hasCollided || (outOfOurWay && !obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(4); + mode = -1.0f; + angle = passTurn(signedSpeed) * 0.2f; + break; + case 14: + if (!hasCollided || (outOfOurWay && obstacleAngleNegative)) + botMain->setMoveToStatus(6); + else if (spaceRadius > back) + botMain->setMoveToStatus(5); + mode = -1.0f; + angle = passTurn(signedSpeed) * -0.2f; + break; + default: + break; + } + // 0x2ADE60 + if (speedLimit > slowDown) + speedLimit = slowDown; + if (slowDownStop) + angle = -2.0f; + return 1; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.h new file mode 100644 index 000000000..678b732af --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.h @@ -0,0 +1,38 @@ +// [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) +// compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; +// the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). +// [RETIRE-WHEN: ai-behaviour-] the package recovers and validates every body in this file. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_TANKCONTROL_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_TANKCONTROL_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { + +namespace io { class PlayerInput; } +namespace ai { + +class BAPAMoveTo; +class Bot; +class IPIControlInfo; +class IPIMobile; +class IPIPhysical; +class Information; + +// [INFERRED] a namespace: no vtable, no constructor, and the first argument is never `this`. +namespace TankControl +{ + int controlTowardsDirection(Information*, IPIControlInfo*, IPIMobile*, IPIPhysical*, io::PlayerInput*, const Vec2&, float, float, float, float, float); // 0x2D07B0; [INFERRED] ELF int + void turnTowardsDirection(float, float, bool, Information*, IPIMobile*, IPIControlInfo*, io::PlayerInput*, bool*); // 0x2D0E30; [INFERRED] ELF void + int resetControls(Bot*, io::PlayerInput*, bool, bool, bool, float); // 0x2D1010; [INFERRED] ELF int + int actionStatusDecision(Bot*, Information*, const Vec2&, float, BAPAMoveTo*, float&, float&, float&, float&); // 0x2D1390; [INFERRED] ELF int +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_TANKCONTROL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h new file mode 100644 index 000000000..c639917c0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h @@ -0,0 +1,121 @@ +// [CHOSEN, not recovered] header-only helpers for the vehicle controls (CarControl, TankControl). +// libaidll.so has no symbol for any of them: each is the inline expansion the actionStatusDecision +// bodies spell out in place (ELF 0x2AB970 / 0x2D1390), written once here. No build-list entry. + +#ifndef AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H +#define AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H + +#include "../AIKnowledge/InformationManager.h" +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { +namespace vehiclecontrol { + +inline Information* lookupInformation(unsigned int handle) +{ + return informationManager->getInformation(handle); +} + +// The engine's inline Vec2 normalise: kept within FLT_EPSILON of unit length, zeroed below +// FLT_EPSILON^2, else scaled by 1/sqrt (0x2ABA6F). +inline void normalizeVec2(Vec2& v) +{ + const float lengthSqr = v.x * v.x + v.y * v.y; + if (std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSqr) < 1.4210855e-14f) + { + v.x = 0.0f; + v.y = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + v.x = v.x * inverse; + v.y = inverse * v.y; +} + +// The Vec3 variant: zeroed below FLT_EPSILON (0x2ABEDC). +inline void normalizeVec3(Vec3& v) +{ + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSqr) < 1.1920929e-07f) + { + v.x = v.y = v.z = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + v.x = v.x * inverse; + v.y = v.y * inverse; + v.z = inverse * v.z; +} + +// The zero test the bodies apply to trace hits: |c - 0| <= FLT_EPSILON for x, y and z (NaN is +// not zero). +inline bool isZeroVec3(const Vec3& v) +{ + const float epsilon = 1.1920929e-07f; + return std::fabs(v.x - 0.0f) <= epsilon && std::fabs(v.y - 0.0f) <= epsilon && std::fabs(v.z - 0.0f) <= epsilon; +} + +// |a - b| +inline float distanceVec3(const Vec3& a, const Vec3& b) +{ + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); +} + +// origin + direction * length +inline Vec3 alongFrom(const Vec3& origin, const Vec3& direction, float length) +{ + Vec3 v; + v.x = length * direction.x + origin.x; + v.y = length * direction.y + origin.y; + v.z = length * direction.z + origin.z; + return v; +} + +// origin - direction * length +inline Vec3 backFrom(const Vec3& origin, const Vec3& direction, float length) +{ + Vec3 v; + v.x = origin.x - length * direction.x; + v.y = origin.y - length * direction.y; + v.z = origin.z - length * direction.z; + return v; +} + +// The first row of a transformation, passed where the bodies hand the Mat4 itself to a +// `const Vec3&` parameter. +inline const Vec3& rightAxis(const Mat4& transformation) +{ + return *reinterpret_cast(&transformation.m[0]); +} + +// Folds a steering angle beyond +-pi/2 back to the reverse direction: sign(a) * (pi - |a|), with +// sign 0 for 0 and NaN (0x2AE3E1). +inline void reverseAngle(float& angle) +{ + const float magnitude = std::fabs(angle); + if (!(magnitude > 1.5707964f)) + return; + float sign = 1.0f; + if (!(angle > 0.0f)) + sign = (0.0f > angle) ? -1.0f : 0.0f; + angle = sign * (3.1415927f - magnitude); +} + +} // namespace vehiclecontrol +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp index 380de49c3..f90f5fef5 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp @@ -1,12 +1,20 @@ // Strategic simulation and supporting statistics. -// [FRONTIER] Remaining strategic phases and object-query paths stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate the remaining strategic operations. +// [RETIRE-WHEN: aidll-02-skeleton] chooseStrategy's body is recovered; remove this note after +// the coordinator validates strategy loading and selection at runtime. #include "SAI.h" +#include +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x330020, +// __tcf_0 0x330080, _GLOBAL__I 0x3300B0). The image has four more such triads for the TUs this file +// merges [INFERRED]: CommanderInterface (0x323420 / 0x323480 / 0x3234B0), ISAI and +// EnemyStatistics (0x323A40 / 0x323AA0 / 0x323AD0), SAIBotDCB (0x331F30 / 0x331F90 / 0x331FC0) +// and SAIBotSCB (0x332200 / 0x332260 / 0x332290). +#include +#include +#include #include -#include "../Main/AIDllFrontier.h" #include "../Main/AISettingsInterfaces.h" // IAISettings::getMaxNBots #include "../Main/BotBehaviourManager.h" // getBehaviourId, by name #include "../Main/CommonSingletonServer.h" @@ -20,13 +28,25 @@ #include "../AIBot/BotMain.h" #include "../AIBot/BotSquad.h" #include "../AIBot/SquadManager.h" +#include "../AIBot/SquadCoordinator.h" +#include "../AIBot/SquadMember.h" // setHavePath +#include "../AIBot/WaypointList.h" // updateBotPositions: +5 / getId +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../Main/AIRandom.h" #include "../AIStrategicEntity/AIStrategicObject.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" #include "../AIStrategicMap/BotSpawner.h" +#include "Strategy.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../Main/IBotManager.h" +#include "../Main/StrategyManager.h" #include "../AIUtils/checkPointer.h" #include "../../../AIInterface/BFKnowledge/BFCommander.h" // request-denial callbacks #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame counters #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::setSpawnGroup +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" // IAIGameEffector::respawnBot #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../../../../Core/Debug.h" // update's shipped invalid-state diagnostic @@ -34,6 +54,31 @@ namespace dice { namespace hfe { namespace ai { +namespace { + +// ELF: std::list<(anonymous)::SquareInfo> nodes carry 8 bytes, {int +0, float +4}; list::sort +// (0x330C40, merge 0x3317F0) orders ascending by the float. Member names [INFERRED]. +struct SquareInfo +{ + int m_index; // strategic-object index (+0xF0 of the object) + float m_value; + bool operator<(const SquareInfo& other) const { return m_value < other.m_value; } +}; + +// ELF heap helpers 0x330FE0 / 0x3311F0: the object with the smallest assigned part of its wanted +// strength is on top. The side is the comparator's only state. +struct sobOrdering +{ + explicit sobOrdering(int side) : m_side(side) {} + bool operator()(const AIStrategicObject* a, const AIStrategicObject* b) const + { + return a->getAssignedPartOfWantedStrength(m_side) > b->getAssignedPartOfWantedStrength(m_side); + } + int m_side; +}; + +} // namespace + // The concrete callback names and signatures are ELF-attested. Their source-file placement here // is [INFERRED]; only SAI.cpp is attested for this part of the strategic subsystem. class SAIBotDCB : public IBotDeathCallBack @@ -186,34 +231,55 @@ CommanderInterface::~CommanderInterface() } -void CommanderInterface::giveAttackOrder(const Vec3&, SquadCoordinator*) +// ELF IBFCommander 0x10: (position, squad id + 1, side + 1, no target); side is read first. +void CommanderInterface::giveAttackOrder(const Vec3& position, SquadCoordinator* squad) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveAttackOrder (SquadCoordinator)"); + const int side = squad->getSide() + 1; + const int id = squad->getSquadId() + 1; + static_cast(CommonSingletonServer::m_iBFCommander)->giveAttackOrder(position, id, side, 0); } -void CommanderInterface::giveMoveOrder(const Vec3&, SquadCoordinator*) +// ELF IBFCommander 0x14: (position, squad id + 1, side + 1, no target); side is read first. +void CommanderInterface::giveMoveOrder(const Vec3& position, SquadCoordinator* squad) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveMoveOrder (SquadCoordinator)"); + const int side = squad->getSide() + 1; + const int id = squad->getSquadId() + 1; + static_cast(CommonSingletonServer::m_iBFCommander)->giveMoveOrder(position, id, side, 0); } -void CommanderInterface::giveDefendOrder(const Vec3&, SquadCoordinator*) +// ELF IBFCommander 0x18: (position, squad id + 1, side + 1, no target); side is read first. +void CommanderInterface::giveDefendOrder(const Vec3& position, SquadCoordinator* squad) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveDefendOrder (SquadCoordinator)"); + const int side = squad->getSide() + 1; + const int id = squad->getSquadId() + 1; + static_cast(CommonSingletonServer::m_iBFCommander)->giveDefendOrder(position, id, side, 0); } -void CommanderInterface::giveAttackOrder(const Vec3&, Bot*) +// ELF IBFCommander 0x10: (position, the bot squad's id +4, the bot's side, no target) - no +1 +// here, unlike the squad overloads; the squad is read first. +void CommanderInterface::giveAttackOrder(const Vec3& position, Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveAttackOrder (Bot)"); + BotSquad* const squad = bot->getBotSquad(); + const int side = bot->getSide(); + static_cast(CommonSingletonServer::m_iBFCommander)->giveAttackOrder(position, squad->getSquadId(), side, 0); } -void CommanderInterface::giveMoveOrder(const Vec3&, Bot*) +// ELF IBFCommander 0x14: (position, the bot squad's id +4, the bot's side, no target) - no +1 +// here, unlike the squad overloads; the squad is read first. +void CommanderInterface::giveMoveOrder(const Vec3& position, Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveMoveOrder (Bot)"); + BotSquad* const squad = bot->getBotSquad(); + const int side = bot->getSide(); + static_cast(CommonSingletonServer::m_iBFCommander)->giveMoveOrder(position, squad->getSquadId(), side, 0); } -void CommanderInterface::giveDefendOrder(const Vec3&, Bot*) +// ELF IBFCommander 0x18: (position, the bot squad's id +4, the bot's side, no target) - no +1 +// here, unlike the squad overloads; the squad is read first. +void CommanderInterface::giveDefendOrder(const Vec3& position, Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::CommanderInterface::giveDefendOrder (Bot)"); + BotSquad* const squad = bot->getBotSquad(); + const int side = bot->getSide(); + static_cast(CommonSingletonServer::m_iBFCommander)->giveDefendOrder(position, squad->getSquadId(), side, 0); } @@ -226,6 +292,7 @@ ISAI::~ISAI() // the unwind path the // constructor's possible throw needs is the other hundred bytes. +// ELF 0x3239B0. SAI* ISAI::create(int side, int gridWidth, int gridHeight, Vec2 min, Vec2 max) { return new SAI(side, gridWidth, gridHeight, min, max); @@ -255,7 +322,8 @@ void SAI::clearStates(float* a, float* b) b[43] = 1.0f; } -// Creates strategic state for side. Grid dimensions and bounds are retained in the signature but unused. +// ELF 0x323AF0 (C2; C1 0x3249A0). Creates strategic state for side. Grid dimensions and bounds are +// retained in the signature but unused. +0xE0 is not constructed (no store in either body). SAI::SAI(int side, int, int, Vec2, Vec2) : m_flagAC(true) , m_behaviourIdle(0) @@ -264,14 +332,13 @@ SAI::SAI(int side, int, int, Vec2, Vec2) , m_behaviourFire(0) , m_intD8(0) , m_intDC(0) - , m_intE0(0) // The strategy cursor starts at `m_strategies.end`, which on a freshly built empty vector is // the null `finish` pointer. The binary copies the vector's finish word into it. , m_activeStrategy(0) , m_enemyStats(0) , m_friendlyStats(0) , m_int18C(19) - , m_float190(-992.0f) + , m_float190(-1000.0f) , m_side(side) , m_sideMask(1 << side) // the other side'S BIT, and the expression only has two answers - this is a two-sided game. @@ -340,13 +407,26 @@ SAI::SAI(int side, int, int, Vec2, Vec2) m_botInfo[i] = 0; } -// [FRONTIER] Strategy and distribution operations remain incomplete. -// [FRONTIER] Destruction stops until ordered teardown is implemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when its corresponding behavior is recovered. +// ELF 0x3257A0 (D2; D1 0x325E70, D0 0x326540; from BF2AI::clear): deletes the commander interface +// (+0x1F8), the two EnemyStatistics (+0x124/+0x128), delete[]s the four state rows (+0x1E4..+0x1F0), +// each tested for null; every container member then goes in reverse declaration order. The +// BotInfo pointers in m_botInfo are not deleted (no BotInfo destructor call in the body). SAI::~SAI() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::~SAI"); + if (m_commander) + delete m_commander; + if (m_enemyStats) + delete m_enemyStats; + if (m_friendlyStats) + delete m_friendlyStats; + if (m_stateA) + delete[] m_stateA; + if (m_stateB) + delete[] m_stateB; + if (m_stateC) + delete[] m_stateC; + if (m_stateD) + delete[] m_stateD; } @@ -360,9 +440,17 @@ void SAI::setMapYDimension(int) } -void SAI::addStrategy(Strategy*) +// ELF 0x326C10: appends {0, 0, 0, 1, strategy} and points the active strategy at the first one. +void SAI::addStrategy(Strategy* strategy) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::addStrategy"); + StrategyContainer container; + container.m_f00 = 0.0f; + container.m_f04 = 0.0f; + container.m_startTime = 0.0f; + container.m_i0C = 1; + container.m_strategy = strategy; + m_strategies.push_back(container); + m_activeStrategy = &m_strategies[0]; } // One resumable pass, with a budget check after each @@ -553,19 +641,83 @@ void SAI::addBot(Bot* bot) bot->setSpawnCallBack(checkPointer(new SAIBotSCB(bot, this))); } -void SAI::setBotIsDead(int) +// ELF 0x328D10: handleDeadBot(botId). +void SAI::setBotIsDead(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setBotIsDead"); + handleDeadBot(botId); +} + +// ELF 0x328DB0: a known bot leaves the strategic bookkeeping (BotInfo::remove); its assigned +// object (m_int04, read before the removal) and spawn kit (+0x104) are recorded in the dead-bot +// map (+0x5C, insert_unique), its player's spawn group is reset to 0 (IAIPlayer +0x38), and the +// record is marked dead. +void SAI::handleDeadBot(int botId) +{ + BotInfo* const info = m_botInfo[botId]; + if (!info) + return; + const int kit = info->m_bot->getSpawnKit(); + const int object = m_botInfo[botId]->m_int04; + m_botInfo[botId]->remove(this); + m_map5C.insert(std::make_pair(botId, std::make_pair(object, kit))); + m_botInfo[botId]->m_bot->getPlayer()->setSpawnGroup(0); + m_botInfo[botId]->setAsDead(this); } -void SAI::setBotIsAlive(int) +// ELF 0x328AE0: a known, living bot is placed at the closest strategic object to its current +// equipment's position (getClosestObject(pos, equipment type, vehicle number or -1, side)) and +// leaves the dead-bot map; the map is searched linearly (`cmpl %ecx,0x10(%edx)`) and the first +// match erased. The first spawn after a reset (+0xAC) resets the bridges. +void SAI::setBotIsAlive(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setBotIsAlive"); + if (!m_botInfo[botId]) + return; + if (m_flagAC) + { + AIStrategicObjectManager::getInstance()->resetBridges(); + m_flagAC = false; + } + if (m_botInfo[botId]->m_bot->isDead()) + return; + Information* const information = + informationManager->getInformation(m_botInfo[botId]->m_bot->getCurrentEquipment()); + if (!information || !information->getUnit()) + return; + int vehicle = -1; + if (information->getMobile()) + vehicle = information->getMobile()->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + const Vec3& position = information->getPosition(); + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(position, equipment, vehicle, m_side); + m_botInfo[botId]->respawn(object, this); + for (std::map >::iterator it = m_map5C.begin(); it != m_map5C.end(); ++it) + { + if (it->first == botId) + { + m_map5C.erase(it); + break; + } + } } -void SAI::removeBot(Bot*) +// ELF 0x329300: a dead bot only leaves the dead-bot map (linear key search, first match), a +// living one leaves the bookkeeping (BotInfo::remove); then its record is deleted. +void SAI::removeBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::removeBot"); + const int id = bot->getBotId(); + if (!m_botInfo[id]) + return; + std::map >::iterator it = m_map5C.begin(); + for (; it != m_map5C.end(); ++it) + if (it->first == id) + break; + if (it != m_map5C.end()) + m_map5C.erase(it); + else + m_botInfo[id]->remove(this); + delete m_botInfo[id]; + m_botInfo[id] = 0; } // Both test the requested bit; x86 masks shift count. @@ -580,29 +732,79 @@ bool SAI::isFriend(int side) const return (static_cast(m_sideMask) & (1u << (side & 31))) != 0; } +// ELF 0x329450 / 0x329460 / 0x329470 / 0x329480: `lea 0x12C/0x144/0x15C/0x174(this)`; the +// index argument is ignored. The "types" rows hold the float counts the SAI accumulates +// (`+= 1.0f`), so they are returned as float* (the shared declaration said int*). float* SAI::getEnemyStrengths(int) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getEnemyStrengths"); + return const_cast(m_enemyStrengths); } -int* SAI::getEnemyTypes(int) const +float* SAI::getEnemyTypes(int) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getEnemyTypes"); + return const_cast(m_enemyCounts); } float* SAI::getFriendlyStrengths(int) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getFriendlyStrengths"); + return const_cast(m_friendlyStrengths); +} + +float* SAI::getFriendlyTypes(int) const +{ + return const_cast(m_friendlyCounts); } -int* SAI::getFriendlyTypes(int) const +// ELF 0x32D5F0: the bot's squad member (by player id, IBotManager::getBot +0x14) forgets its +// path, then handleChangingBot. +void SAI::setBotHasChangedEquipment(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getFriendlyTypes"); + Bot* const bot = IBotManager::instance->getBot(botId); + SquadMember* const member = SquadManager::m_instance->getSquadMember(bot->getPlayerId(), m_side); + if (member) + member->setHavePath(false); + handleChangingBot(botId); } -void SAI::setBotHasChangedEquipment(int) +// ELF 0x328FE0: a bot that is not in the free set gives up its assignment - an assigned object +// (m_int04) is left through removeAssigned(release) + free(false), else a current object +// (m_int0C) through free(true). Its last ordered square becomes -1, and when its current +// equipment's closest strategic object differs from the current one it moves there (occupy). +void SAI::handleChangingBot(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setBotHasChangedEquipment"); + if (!m_botInfo[botId]) + return; + if (m_set44.find(botId) == m_set44.end()) + { + BotInfo* const info = m_botInfo[botId]; + if (info->m_int04 != -1) + { + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getStrategicObject(info->m_int04); + m_botInfo[botId]->removeAssigned(object, true, this); + m_botInfo[botId]->free(false, this); + } + else if (info->m_int0C != -1) + { + info->free(true, this); + } + } + m_botInfo[botId]->setLastOrderedSquare(-1); + Information* const information = + informationManager->getInformation(m_botInfo[botId]->m_bot->getCurrentEquipment()); + if (!information || !information->getUnit()) + return; + IPIMobile* const mobile = information->getMobile(); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + int vehicle = -1; + if (mobile) + vehicle = mobile->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + AIStrategicObject* const closest = + manager->getClosestObject(information->getPosition(), equipment, vehicle, m_side); + if (closest->getIndex() == m_botInfo[botId]->m_int0C) + return; + m_botInfo[botId]->occupy(manager->getStrategicObject(m_botInfo[botId]->m_int0C), closest, this); } // find, update the second member of the existing pair, or do nothing. @@ -622,9 +824,20 @@ const std::map >& SAI::getDeadBots() const return m_map5C; } -void SAI::setPlayerIsCommander(bool) +// ELF 0x326CC0: a player giving up the commander seat (true -> false) unassigns the side's +// squads and restarts the commander timers: +0x68/+0x70/+0x78 = now + 60, +0x80 = now + 10. +void SAI::setPlayerIsCommander(bool isCommander) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::setPlayerIsCommander"); + if (!isCommander && m_flag1D1) + { + SquadManager::m_instance->unAssignSquads(m_side); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_time68 = now + 60.0f; + m_time70 = now + 60.0f; + m_time78 = now + 60.0f; + m_time80 = now + 10.0f; + } + m_flag1D1 = isCommander; } // byte getter at +0x1D1 / +0x221. @@ -633,24 +846,126 @@ bool SAI::isPlayerCommander() return m_flag1D1; } -bool SAI::playerRequestsArtillery(int, Vec3) +// ELF 0x327420. Ignored while a player commands the side. Without artillery (IBFCommander +0x38 +// gameHasArtillery, +0x3C anyArtilleryPiecesLeft) an "unavailable" answer (type 2) is queued; with +// the artillery timer (+0x68) running a denial (type 1). Otherwise the timer re-arms 60 s ahead, the +// engine commander fires (+0x24, the request's x/z) and the squads are warned. +// [CHOSEN, not recovered] the shipped body never materialises a return value (eax is whatever the +// last call left); the courier passes it on and the engine ignores it. This build answers false. +bool SAI::playerRequestsArtillery(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsArtillery"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + IBFCommander* const commander = static_cast(CommonSingletonServer::m_iBFCommander); + if (commander->gameHasArtillery(m_side) && commander->anyArtilleryPiecesLeft(m_side)) + { + if (now > m_time68) + { + m_time68 = now + 60.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + commander->fireArtillery(m_side, playerId, xz); + SquadManager::m_instance->incomingArtillery(position, m_side); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 1; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 2; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } -bool SAI::playerRequestsUav(int, Vec3) +// ELF 0x327720. Ignored while a player commands the side; the UAV timer (+0x80) re-arms 30 s +// ahead and the engine commander sends it (+0x28), otherwise a denial (type 3) is queued. +// [CHOSEN, not recovered] no shipped return value; see playerRequestsArtillery. +bool SAI::playerRequestsUav(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsUav"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_time80) + { + m_time80 = now + 30.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + static_cast(CommonSingletonServer::m_iBFCommander)->sendUav(m_side, playerId, xz); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 3; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } -bool SAI::playerRequestsSupply(int, Vec3) +// ELF 0x3278C0. As the UAV request with the supply timer (+0x70, 60 s), dropSupply (+0x2C) and +// denial type 0. [CHOSEN, not recovered] no shipped return value; see playerRequestsArtillery. +bool SAI::playerRequestsSupply(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsSupply"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_time70) + { + m_time70 = now + 60.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + static_cast(CommonSingletonServer::m_iBFCommander)->dropSupply(m_side, playerId, xz); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 0; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } -bool SAI::playerRequestsVehicleDrop(int, Vec3) +// ELF 0x327A60. As the UAV request with the vehicle-drop timer (+0x78, 60 s), dropVehicle (+0x30) +// and denial type 4. [CHOSEN, not recovered] no shipped return value; see playerRequestsArtillery. +bool SAI::playerRequestsVehicleDrop(int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::playerRequestsVehicleDrop"); + if (m_flag1D1) + return false; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (now > m_time78) + { + m_time78 = now + 60.0f; + Vec2 xz; + xz.x = position.x; + xz.y = position.z; + static_cast(CommonSingletonServer::m_iBFCommander)->dropVehicle(m_side, playerId, xz); + } + else + { + DenyRequest* const request = new DenyRequest(); + request->m_type = 4; + request->m_deadline = now + 2.0f + static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * 3.0f; + request->m_playerId = playerId; + m_denyRequests.push_back(request); + } + return false; } void SAI::updateRequestDenyTimers() @@ -707,91 +1022,349 @@ void SAI::updateRequestDenyTimers() } } +// ELF 0x326D60. The AI commander fires artillery when the player is not the commander, the game +// has more than one bot slot, the side has artillery pieces left and both timers (+0x68, +0x88) +// have expired. +0x88 is re-armed 10 s ahead first. A base under hostile takeover (virtual +0x6C) +// is shelled at a random point unless friendlies are within the safe distance or the 1-in-10 roll +// prefers camping humans; otherwise camping humans are the target. Firing re-arms +0x68 60 s +// ahead, asks the engine commander (+0x24 fireArtillery(side, -1, xz)) and warns the squads. +// [CHOSEN, not recovered] the roll is compared in double; the ELF compares the x87 product. void SAI::checkCommanderUseArtillery() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::checkCommanderUseArtillery"); + bool singleSlot = false; + if (CommonSingletonServer::m_iaiSettings) + singleSlot = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots() - 1 <= 0; + if (m_flag1D1 || singleSlot) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + IBFCommander* const commander = static_cast(CommonSingletonServer::m_iBFCommander); + if (!commander->gameHasArtillery(m_side) || !commander->anyArtilleryPiecesLeft(m_side)) + return; + if (!(now > m_time68) || !(now > m_time88)) + return; + m_time88 = now + 10.0f; + SquadManager* const squads = SquadManager::m_instance; + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + AIStrategicObject* base = 0; + if (hostileTakeoveInProgress(base, position)) + { + const double roll = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f; + if (roll > 0.1f) + { + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec3 target; + target.x = position.x; + target.y = terrain->getTerrainAltitude(position.x, position.y); + target.z = position.y; + const float safe = squads->getArtillerySafeDistance(); + if (!squads->friendliesCloseTo(target, safe, m_side)) + { + m_time68 = now + 60.0f; + commander->fireArtillery(m_side, -1, position); + squads->incomingArtillery(target, m_side); + return; + } + } + } + if (!squads->haveCampingHumans(m_side, position)) + return; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec3 target; + target.x = position.x; + target.y = terrain->getTerrainAltitude(position.x, position.y); + target.z = position.y; + m_time68 = now + 60.0f; + commander->fireArtillery(m_side, -1, position); + squads->incomingArtillery(target, m_side); +} + +// ELF 0x327210. The first strategic object that is a control point (hasObjectTypeFlag(16)), +// being taken over by the enemy of this side and with a takeover counter below 0.75 is returned +// in base; position becomes a uniform random point of the box around its position (slot 3), +// mirrored at the area centre (+0x110): centre + 2 (position - centre) u, x then y. +bool SAI::hostileTakeoveInProgress(AIStrategicObject*& base, Vec2& position) +{ + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + if (!object || !object->hasObjectTypeFlag(static_cast(16))) + continue; + if (!object->isEnemyTakingOverBase(m_side)) + continue; + if (!(0.75f > object->getControlPointTakeOverCounter())) + continue; + base = object; + const Vec2 centre = static_cast(object)->m_centre; + const Vec2 corner = object->getPosition(m_side); + const double u = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f; + position.x = static_cast(centre.x + (static_cast(corner.x) - centre.x) * 2.0 * u); + const double v = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f; + position.y = static_cast(centre.y + (static_cast(corner.y) - centre.y) * 2.0 * v); + return true; + } + return false; +} + +// ELF 0x3270A0: the closest object (getClosestObject(pos, side)) must be an owned control point +// (slot 19, type 16). Its control point (area +0x13C) gives centre and radius through IAIGame +// (+0x28); a positive maxRadius above that radius replaces it (`fcmovbe`). Inside means a squared +// 3-D distance below the squared radius and an active point; then object is the closest one. +bool SAI::isPosInsideOwnedControlPoint(AIStrategicObject*& object, Vec3 position, float maxRadius) +{ + bool inside = false; + AIStrategicObject* const closest = AIStrategicObjectManager::getInstance()->getClosestObject(position, m_side); + if (!closest->hasObjectTypeFlag(AIStrategicObject::ControlPoint) || closest->getStatus(m_side) != StatusMap::Owned) + return inside; + float radius = 0.0f; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + bool active; + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo( + static_cast(closest)->m_controlPointId, centre, radius, active); + if (maxRadius > 0.0f) + radius = maxRadius <= radius ? radius : maxRadius; + radius = radius * radius; + const float dx = centre.x - position.x; + const float dy = centre.y - position.y; + const float dz = centre.z - position.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (active && radius > distance) + { + inside = true; + object = closest; + } + return inside; +} + +// ELF 0x328590: any strategic object (not only control points) the side owns. +bool SAI::haveAnyOwnedCps(int side) +{ + bool owned = false; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (*it && (*it)->getStatus(side) == StatusMap::Owned) + { + owned = true; + break; + } + } + return owned; +} + +// ELF 0x3285F0: an owned object whose control point (area +0x13C, -1 for none) the game reports +// as active. The position and radius outputs are zeroed once, before the loop. +bool SAI::haveAnyOwnedAndTakeableCps(int side) +{ + bool found = false; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + float radius = 0.0f; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + if (!object || object->getStatus(side) != StatusMap::Owned) + continue; + bool active = false; + const unsigned int cp = static_cast(object)->m_controlPointId; + if (cp != static_cast(-1)) + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo(cp, position, radius, active); + if (active) + { + found = true; + break; + } + } + return found; +} + +// ELF 0x3286C0: false as soon as an active control point is not owned by the side. +bool SAI::ownAllTakeableCps(int side) +{ + bool all = true; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + float radius = 0.0f; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + if (!object || object->getStatus(side) == StatusMap::Owned) + continue; + bool active = false; + const unsigned int cp = static_cast(object)->m_controlPointId; + if (cp != static_cast(-1)) + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo(cp, position, radius, active); + if (active) + { + all = false; + break; + } + } + return all; } -bool SAI::hostileTakeoveInProgress(AIStrategicObject*&, Vec2&) +// preserve unAssignSquads' full integer return. +// The caller's full-EAX additions establish the count contract; the body remains stopped. +// ELF 0x32D680: the object's index (+0xF0) and the side go to SquadManager::unAssignSquads. +int SAI::releaseSquadsFromObject(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::hostileTakeoveInProgress"); + AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return SquadManager::m_instance->unAssignSquads(target->getIndex(), side); } -bool SAI::isPosInsideOwnedControlPoint(AIStrategicObject*&, Vec3, float) +// ELF 0x32D6D0: the unit leaves the object's assigned set and SAI's occupied set, then +// m_botInfo[*it]->free(false) runs - with the iterator removeAssigned has already advanced, so +// the image frees the *next* assigned unit (`movl (%esi),%eax` reloads it after the call). +// [CHOSEN, not recovered] When the released unit was the last one, the image reads the old +// libstdc++ header node's stale value as a bot index; here that second call is skipped. +// The side argument is unused; the image answers 1. +bool SAI::releaseUnitFromObject(int object, std::set::iterator& it, int) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::isPosInsideOwnedControlPoint"); + AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + m_botInfo[*it]->removeAssigned(target, it, true, this); + if (it != target->getAssignedUnits(m_side).end()) + m_botInfo[*it]->free(false, this); + return true; } -bool SAI::haveAnyOwnedCps(int) +// ELF 0x329250: erase the bot from the set at +0xF0; answers whether it was there. +bool SAI::foundDeadBot(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::haveAnyOwnedCps"); + std::set::iterator it = m_setF0.find(botId); + if (it == m_setF0.end()) + return false; + m_setF0.erase(it); + return true; } -bool SAI::haveAnyOwnedAndTakeableCps(int) +// ELF 0x32D770: membership in the set at +0xB0. +bool SAI::hasChangedEquipment(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::haveAnyOwnedAndTakeableCps"); + return m_setB0.find(botId) != m_setB0.end(); } -bool SAI::ownAllTakeableCps(int) +// ELF 0x32D7D0: erase from the set at +0xB0 when present. +void SAI::equipmentChangedFinished(int botId) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::ownAllTakeableCps"); + std::set::iterator it = m_setB0.find(botId); + if (it != m_setB0.end()) + m_setB0.erase(it); } -// preserve unAssignSquads' full integer return. -// The caller's full-EAX additions establish the count contract; the body remains stopped. -int SAI::releaseSquadsFromObject(int, int) +// ELF 0x32D870: answers the bot's current object index (m_int0C, read first). +int SAI::assignBot(std::set::iterator& it, int object, int botId, bool attacker) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::releaseSquadsFromObject"); + const int current = m_botInfo[botId]->m_int0C; + AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + m_botInfo[botId]->assignToObject(it, target, attacker, this); + return current; } -void SAI::releaseUnitFromObject(int, std::map::iterator&, int) +// ELF 0x32E830: the byte at +0x1CF. +bool SAI::strategicObjectsHasChanged() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::releaseUnitFromObject"); + return m_flag1CF; } -void SAI::foundDeadBot(int) +// ELF 0x32E840: the id is appended to the teleporter list (+0x110). +void SAI::registerTeleporter(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::foundDeadBot"); + m_list110.push_back(id); } -bool SAI::hasChangedEquipment(int) +// ELF 0x32E380: the container's first two floats (last distribution score, latest score); zero for +// an index past the end. +Vec2 SAI::getStrategyHeat(unsigned int index) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::hasChangedEquipment"); + Vec2 heat; + heat.x = 0.0f; + heat.y = 0.0f; + if (index < m_strategies.size()) + { + heat.x = m_strategies[index].m_f00; + heat.y = m_strategies[index].m_f04; + } + return heat; } -void SAI::equipmentChangedFinished(int) +// ELF 0x32E420: one " " line per container that has a strategy. +std::string SAI::listStrategies() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::equipmentChangedFinished"); + std::ostringstream out; + for (unsigned int i = 0; i < m_strategies.size(); ++i) + { + if (m_strategies[i].m_strategy) + out << i << " " << m_strategies[i].m_strategy->getName() << std::endl; + } + return out.str(); } -void SAI::assignBot(std::map::iterator&, int, int, bool) +// ELF 0x32EA90: the active container's strategy, unguarded. +Strategy* SAI::getActiveStrategy() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::assignBot"); + return m_activeStrategy->m_strategy; } -bool SAI::strategicObjectsHasChanged() +// ELF 0x32EAB0: the active container's three floats (zero, with no active container) and its +// strategy. The strategy is read even when the cursor is at end(), as shipped. +Strategy* SAI::getActiveStrategy(float& a, float& b, float& c) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::strategicObjectsHasChanged"); + if (m_activeStrategy != m_strategies.data() + m_strategies.size()) + { + a = m_activeStrategy->m_f00; + b = m_activeStrategy->m_f04; + c = m_activeStrategy->m_startTime; + } + else + { + a = 0.0f; + b = 0.0f; + c = 0.0f; + } + return m_activeStrategy->m_strategy; } -void SAI::registerTeleporter(int) +// ELF 0x32E2D0: membership in the free set (+0x44). +bool SAI::isBotFree(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::registerTeleporter"); + return m_set44.find(botId) != m_set44.end(); } -float SAI::getStrategyHeat(unsigned int) +// ELF 0x32E320: membership in the occupied set (+0xFC). +bool SAI::isBotAssigned(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getStrategyHeat"); + return m_setFC.find(botId) != m_setFC.end(); } -void SAI::listStrategies() +// ELF 0x32CEE0: empty. +void SAI::updateMap(double) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::listStrategies"); } -int SAI::getActiveStrategy() +// ELF 0x329490: one 1.0f modifier per behaviour (IAISettings +0xC getNumberOfBehaviours); the +// caller owns the array. +float* SAI::createUnitMods() const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getActiveStrategy"); + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfBehaviours(); + float* const mods = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + mods[i] = 1.0f; + return mods; } // insert (point,1), increment only on duplicate. @@ -804,24 +1377,34 @@ void SAI::addSpawnToPoint(int point) ++inserted.first->second; } -int SAI::getSpawnsToPoint(int) const +// ELF 0x32EF90: the spawn count of the point (map +0x1D8), 0 when unknown. +int SAI::getSpawnsToPoint(int point) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getSpawnsToPoint"); + std::map::const_iterator it = m_map1D8.find(point); + if (it == m_map1D8.end()) + return 0; + return it->second; } -Vec3 SAI::getBotCurrentPos(int) const +// ELF 0x32E240 / 0x32E270 / 0x32E2A0: the bot's current object (m_int0C), ordered object +// (m_int04) and last ordered square (m_int08) - indices, not positions (eax, no sret). An unknown +// bot answers -22, -44 and -1 (`movl $0xffffffea/$0xffffffd4/$0xffffffff,%edx`). +int SAI::getBotCurrentPos(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getBotCurrentPos"); + const BotInfo* const info = m_botInfo[botId]; + return info ? info->m_int0C : -22; } -Vec3 SAI::getBotOrderedPos(int) const +int SAI::getBotOrderedPos(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getBotOrderedPos"); + const BotInfo* const info = m_botInfo[botId]; + return info ? info->m_int04 : -44; } -Vec3 SAI::getBotLastOrderedPos(int) const +int SAI::getBotLastOrderedPos(int botId) const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getBotLastOrderedPos"); + const BotInfo* const info = m_botInfo[botId]; + return info ? info->m_int08 : -1; } // Accumulate into the previous totals, then decay; no initial clear. @@ -1119,22 +1702,93 @@ void SAI::clearSpawnsToPoints() it->second = 0; } -// Remaining direct SAI::update dependencies. Paired callers and helper return paths establish -// these signatures; the strategic work behind them remains unrecovered. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// BotInfo::remove: / , paired callers discard -// the result and neither body materializes a return. Assigned/free/present-unit removal is absent. -void SAI::BotInfo::remove(SAI*) +void SAI::BotInfo::remove(SAI* sai) +{ + const int id = m_bot->getBotId(); + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + AIStrategicObject* const assigned = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int04); + if (assigned) + { + removeAssigned(assigned, true, sai); + current->removeAsPresentUnit(id, sai->m_side); + } + else if (current) + { + if (sai->m_setFC.find(id) != sai->m_setFC.end()) + free(true, sai); + current->removeAsPresentUnit(id, sai->m_side); + } + std::set::iterator it = sai->m_set44.find(id); + if (it != sai->m_set44.end()) + sai->m_set44.erase(it); +} + +void SAI::BotInfo::removeAssigned(AIStrategicObject* object, bool release, SAI* sai) +{ + std::set::iterator it = object->getAssignedUnits(sai->m_side).find(m_bot->getBotId()); + removeAssigned(object, it, release, sai); +} + +void SAI::BotInfo::occupy(AIStrategicObject* from, AIStrategicObject* to, SAI* sai) +{ + std::set::iterator it = from->getPresentUnits(sai->m_side).find(m_bot->getBotId()); + occupy(it, from, to, sai); +} + +void SAI::BotInfo::assignToObject(std::set::iterator& it, AIStrategicObject* object, bool attacker, SAI* sai) +{ + m_int04 = object->getIndex(); + m_int08 = object->getIndex(); + m_double14 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + if (attacker) + current->unregisterAvailableAttacker(it, sai->m_side); + else + current->unregisterAvailableDefender(it, sai->m_side); + object->getAssignedUnits(sai->m_side).insert(m_bot->getBotId()); +} + +void SAI::BotInfo::assignToObject(AIStrategicObject* object, bool attacker, SAI* sai) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::BotInfo::remove"); + std::set::iterator it = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C)-> + getAvailableBots(attacker, sai->m_side).find(m_bot->getBotId()); + assignToObject(it, object, attacker, sai); } -// Void is inferred from complete -// bodies and their callers. The spawn-group selector and dead-bot/respawn chain remain absent. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -void SAI::handleTeleportingBot(int) +void SAI::BotInfo::assign(bool attacker, SAI* sai) { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::handleTeleportingBot"); + std::set::iterator it = sai->m_set44.find(m_bot->getBotId()); + assign(it, attacker, sai); +} + +void SAI::BotInfo::setAsDead(SAI*) +{ + m_int04 = -1; + m_int08 = -1; + m_int0C = -1; + m_float10 = 0.0f; +} + +void SAI::BotInfo::setAsFree(SAI* sai) +{ + sai->m_set44.insert(m_bot->getBotId()); +} + +// ELF 0x328EF0: with a suitable spawn group the bot enters its transition phase (+0x180), +// is handled as dead, gets the group and is respawned through the game effector (+0x1C). +void SAI::handleTeleportingBot(int botId) +{ + if (!m_botInfo[botId]) + return; + AIStrategicObject* object; + const int group = BotSpawner::findSuitableSpawnGroup(m_side, object, m_botInfo[botId]->m_bot); + if (!group) + return; + m_botInfo[botId]->m_bot->setIsInTransitionPhase(true); + handleDeadBot(botId); + m_botInfo[botId]->m_bot->getPlayer()->setSpawnGroup(group); + static_cast(CommonSingletonServer::m_iaiGameEffector) + ->respawnBot(m_botInfo[botId]->m_bot->getPlayer()); } bool SAI::updateStrategicObjects() @@ -1185,45 +1839,808 @@ bool SAI::updateStrategicObjects() return true; } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x329A10. A strategy forced for this side (StrategyManager::getForcedStrategy) is scored +// once (result discarded) and activated. Otherwise every strategy is re-scored into m_f04 +// (clamped at 0) against the latest friendly/enemy state arrays; when a score moved by 17% or +// more against the last distribution's m_f00 (ratio <= 0.83 or >= 1.2), or when the active +// strategy has outlived m_f20 * (2 - 2 * 0.5^m_i0C) seconds (then m_i0C counts up), the scores +// are copied to m_f00 and a strategy is drawn at random, weighted by its positive score. +// shipped defect: an empty strategy list still dereferences the end() active-strategy cursor. void SAI::chooseStrategy() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::chooseStrategy"); + float total = 0.0f; + bool changed = false; + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + Strategy* const forced = StrategyManager::getInstance()->getForcedStrategy(m_side); + if (forced) + { + forced->calculatePrerequisite(m_int1F4 ? m_stateB : m_stateA, m_int1F4 ? m_stateD : m_stateC, + m_activeStrategy->m_strategy, m_side); + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + if (it->m_strategy == forced) + changeStrategy(it); + return; + } + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + { + it->m_f04 = it->m_strategy->calculatePrerequisite( + m_int1F4 ? m_stateB : m_stateA, m_int1F4 ? m_stateD : m_stateC, + m_activeStrategy->m_strategy, m_side); + if (total > it->m_f04) // total is still 0 here + it->m_f04 = total; + float ratio; + if (it->m_f04 != 0.0f) + ratio = it->m_f00 / it->m_f04; + else + ratio = it->m_f00 == 0.0f ? 1.0f : 0.0f; + if (ratio <= 0.83 || ratio >= 1.2) + changed = true; + } + if (!changed) + { + const float limit = m_activeStrategy->m_strategy->m_f20; + const float p = powf(0.5f, static_cast(m_activeStrategy->m_i0C)); + const float d = 0.5f - p; + const double threshold = ((d + d) + 1.0f) * limit; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(now - m_activeStrategy->m_startTime >= threshold)) + return; + ++m_activeStrategy->m_i0C; + } + + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + { + it->m_f00 = it->m_f04; + total += it->m_f04 > 0.0f ? it->m_f04 : 0.0f; + } + float pick = static_cast(AIRandom::m_instance->next()) * 2.3283064365386963e-10f * total; + std::vector::iterator it = m_strategies.begin(); + for (; it != m_strategies.end(); ++it) + { + pick -= it->m_f00 > 0.0f ? it->m_f00 : 0.0f; + if (0.0 >= pick) + break; + } + if (it == m_strategies.end()) + --it; + changeStrategy(it); } +// ELF 0x329610. Activating another strategy releases every object's assigned resources and +// frees all its available attackers and defenders; the new strategy's clock restarts. +void SAI::changeStrategy(std::vector::iterator& it) +{ + if (m_activeStrategy == &*it) + return; + m_activeStrategy = &*it; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + std::set::iterator unit; + for (std::vector::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + (*object)->releaseAssignedResources(m_side); + std::set& attackers = (*object)->getAvailableAttackers(m_side); + for (unit = attackers.begin(); unit != attackers.end();) + m_botInfo[*unit]->free(*object, true, unit, this); + std::set& defenders = (*object)->getAvailableDefenders(m_side); + for (unit = defenders.begin(); unit != defenders.end();) + m_botInfo[*unit]->free(*object, false, unit, this); + } + StrategyContainer* const active = m_activeStrategy; + active->m_i0C = 1; + active->m_startTime = static_cast(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +// ELF 0x32FDF0. The occupied-set erase uses find() unchecked, as shipped. +void SAI::BotInfo::free(AIStrategicObject* object, bool attacker, std::set::iterator& it, SAI* sai) +{ + const int id = m_bot->getBotId(); + if (attacker) + object->unregisterAvailableAttacker(it, sai->m_side); + else + object->unregisterAvailableDefender(it, sai->m_side); + sai->m_setFC.erase(sai->m_setFC.find(id)); + sai->m_set44.insert(m_bot->getBotId()); +} + +// ELF 0x3299A0: every strategic object (no null check) applies the active strategy's +// modifiers; the returned temperature is discarded. void SAI::modifyStrategicObjectsTemperatures() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::modifyStrategicObjectsTemperatures"); + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + (*it)->updateTemperature(m_activeStrategy->m_strategy, m_side); } +// ELF 0x32F290. The occupied-set find result is unused in the image. +void SAI::BotInfo::occupy(std::set::iterator& it, AIStrategicObject* from, AIStrategicObject* to, SAI* sai) +{ + const int id = m_bot->getBotId(); + to->setAsPresentUnit(id, sai->m_side); + bool moved = false; + if (from->unregisterAvailableAttacker(id, sai->m_side)) + { + to->registerAvailableAttacker(id, sai->m_side); + moved = true; + } + else if (from->unregisterAvailableDefender(id, sai->m_side)) + { + to->registerAvailableDefender(id, sai->m_side); + moved = true; + } + if (moved) + sai->m_setFC.find(id); + from->removeAsPresentUnit(it, sai->m_side); + m_int0C = to->getIndex(); +} + +// ELF 0x32D910. Per strategic area (getType 0): a present bot whose equipment fits a neighbour +// (+0x128 objects: allowed vehicle group, not expelled, an area, not a landing-zone user) with a +// stronger gravity at the bot's position moves there. Then the area's assigned units and its +// available attackers and defenders are retained (slot 28) when they have reached a MoveTo +// waypoint, sense at most one object, are present and their last order is older than 20 s on +// foot or 35 s in a vehicle. void SAI::updateBotPositions() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::updateBotPositions"); + std::set::iterator unit; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + IBotManager* const bots = IBotManager::instance; + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + for (std::vector::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + std::set& present = (*object)->getPresentUnits(m_side); + if ((*object)->getType() != 0) + continue; + const std::vector& neighbours = + static_cast(*object)->m_neighbouringObjects; + for (unit = present.begin(); unit != present.end();) + { + Bot* const bot = bots->getBotFromId(*unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information || !information->getUnit()) + { + ++unit; + continue; + } + const int equipment = information->getUnit()->getEquipmentType(); + const int group = settings->getVehicleGroup(equipment); + AIStrategicObject* best = *object; + float bestGravity = best->gravity(information->getPosition(), m_side); + for (std::vector::const_iterator n = neighbours.begin(); n != neighbours.end(); ++n) + { + if (!(*n)->isAllowedVehicleGroup(group)) + continue; + if ((*n)->isExpelledUnit(equipment) || (*n)->getType() != 0 + || static_cast(*n)->isLandingZoneUser(equipment)) + continue; + const float gravity = (*n)->gravity(information->getPosition(), m_side); + if (gravity > bestGravity) + { + bestGravity = gravity; + best = *n; + } + } + if (best == *object) + ++unit; + else + m_botInfo[*unit]->occupy(unit, *object, best, this); + } + + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + std::set* const groups[3] = { + &(*object)->getAssignedUnits(m_side), + &(*object)->getAvailableAttackers(m_side), + &(*object)->getAvailableDefenders(m_side) }; + for (int g = 0; g < 3; ++g) + { + for (std::set::iterator it = groups[g]->begin(); it != groups[g]->end(); ++it) + { + Bot* const bot = bots->getBotFromId(*it); + const unsigned int equipment = bot->getCurrentEquipment(); + const float wait = equipment != bot->getPlayer()->getSoldier()->getInformation(m_side) ? 35.0f : 20.0f; + // 0x32DC8C..0x32DF66: a reached (+5) MoveTo list (getId +0x10 == 1), the last order + // (BotInfo +0x14) older than `wait` (`fsubl 0x14; fucompi; jbe`), at most one sensed + // object (map node count `cmpl $0x1,0x4(%eax); ja`) and still present: retain the + // bot (slot 28, (side, unit, this)) and stamp the order time. + WaypointList* const waypoints = bot->getWaypoints(); + if (!waypoints->m_flag5 || waypoints->getId() != 1) + continue; + if (!(now - m_botInfo[*it]->m_double14 > wait)) + continue; + if (bot->getSensedObjects().size() > 1) + continue; + if (!(*object)->isPresentUnit(*it, m_side)) + continue; + (*object)->retainBot(m_side, *it, this); + m_botInfo[*it]->m_double14 = now; + } + } + } +} + +void SAI::BotInfo::free(bool release, SAI* sai) +{ + const int id = m_bot->getBotId(); + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + if (release) + { + if (!object->unregisterAvailableAttacker(id, sai->m_side)) + object->unregisterAvailableDefender(id, sai->m_side); + sai->m_setFC.erase(sai->m_setFC.find(id)); + } + sai->m_set44.insert(m_bot->getBotId()); +} + +namespace { + +// The unit of a bot's current equipment, or null (the inlined handle lookup of the image). +IPIUnit* currentUnit(unsigned int botId) +{ + Bot* const bot = IBotManager::instance->getBotFromId(botId); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + return information ? information->getUnit() : 0; } +// The mean of a unit's strategic strengths, summed in a float. +float meanStrength(IPIUnit* unit) +{ + float sum = 0.0f; + for (int i = 0; i < unit->getNStrategicStrengths(); ++i) + sum += unit->getStrategicStrengths()[i]; + sum /= static_cast(unit->getNStrategicStrengths()); + return sum; +} + +} // namespace + +// ELF 0x329E60. Recounts the side's attack (+0xD8, first strength), defence (+0xDC, second +// strength) and idle (+0xE0, mean strength of present units, less the attackers' and +// defenders' mean strengths at the end) resources over all strategic objects. With +0x1CD / +// +0x1CC set, the available attackers / defenders are freed instead (+0x1CE marks it). void SAI::updateDistribution() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::updateDistribution"); + const std::vector& objects = + AIStrategicObjectManager::getInstance()->getStrategicObjects(); + float attackSum = 0.0f; + float defenceSum = 0.0f; + m_flag1CE = false; + m_intD8 = 0; + m_intDC = 0; + m_intE0 = 0; + for (std::vector::const_iterator object = objects.begin(); object != objects.end(); ++object) + { + if (m_flag1CD) + { + while ((*object)->getAvailableAttackers(m_side).size()) + { + m_botInfo[*(*object)->getAvailableAttackers(m_side).begin()]->free(true, this); + m_flag1CE = true; + } + } + else + { + for (std::set::iterator it = (*object)->getAvailableAttackers(m_side).begin(); + it != (*object)->getAvailableAttackers(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (!unit) + continue; + m_intD8 += static_cast(unit->getStrategicStrengths()[0]); + attackSum += meanStrength(unit); + } + } + if (m_flag1CC) + { + while ((*object)->getAvailableDefenders(m_side).size()) + { + m_botInfo[*(*object)->getAvailableDefenders(m_side).begin()]->free(true, this); + m_flag1CE = true; + } + } + else + { + for (std::set::iterator it = (*object)->getAvailableDefenders(m_side).begin(); + it != (*object)->getAvailableDefenders(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (!unit) + continue; + m_intDC += static_cast(unit->getStrategicStrengths()[1]); + defenceSum += meanStrength(unit); + } + } + for (std::set::iterator it = (*object)->getPresentUnits(m_side).begin(); + it != (*object)->getPresentUnits(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (unit) + m_intE0 += static_cast(meanStrength(unit)); + } + for (std::set::iterator it = (*object)->getAssignedUnits(m_side).begin(); + it != (*object)->getAssignedUnits(m_side).end(); ++it) + { + IPIUnit* const unit = currentUnit(*it); + if (!unit) + continue; + if ((*object)->isAttack(m_side)) + { + m_intD8 += static_cast(unit->getStrategicStrengths()[0]); + attackSum += meanStrength(unit); + } + else + { + m_intDC += static_cast(unit->getStrategicStrengths()[1]); + defenceSum += meanStrength(unit); + } + } + } + defenceSum = defenceSum + attackSum; + m_intE0 -= static_cast(defenceSum); +} + +void SAI::BotInfo::respawn(AIStrategicObject* object, SAI* sai) +{ + m_int0C = object->getIndex(); + object->setAsPresentUnit(m_bot->getBotId(), sai->m_side); + sai->m_setFC.find(m_bot->getBotId()); // result unused in the image + sai->m_set44.insert(m_bot->getBotId()); } +void SAI::BotInfo::assign(std::set::iterator& it, bool attacker, SAI* sai) +{ + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + if (attacker) + object->registerAvailableAttacker(m_bot->getBotId(), sai->m_side); + else + object->registerAvailableDefender(m_bot->getBotId(), sai->m_side); + sai->m_set44.erase(it++); + sai->m_setFC.insert(m_bot->getBotId()); +} + +void SAI::BotInfo::removeAssigned(AIStrategicObject* object, std::set::iterator& it, bool release, SAI* sai) +{ + object->getAssignedUnits(sai->m_side).erase(it++); + if (release) + { + sai->m_setFC.erase(sai->m_setFC.find(m_bot->getBotId())); + } + else + { + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + if (current->isAttack(sai->m_side)) + current->registerAvailableAttacker(m_bot->getBotId(), sai->m_side); + else + current->registerAvailableDefender(m_bot->getBotId(), sai->m_side); + } + m_int04 = -1; + m_double14 = 0.0; +} + +int SAI::BotInfo::setLastOrderedSquare(int square) +{ + m_double14 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_int08 = square; + return square; +} + +// ELF 0x32A690. Every free bot (+0x44) is placed at its strategic object (or, after a respawn, +// the closest fitting one), re-ordered there when its last ordered square differs, and assigned +// as attacker or defender: by the strategy's aggression share against the current attack share +// (all attack without friendly areas, all defence when nothing is neutral or hostile). Then +// +0x1CD / +0x1CC ask the next updateDistribution to free attackers / defenders when their +// share exceeds 1.2 times the wanted one. The unused bool[getMaxNBots] and the two +// list > locals are kept as shipped. void SAI::distributeResources() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeResources"); + std::list > unusedA; + std::list > unusedB; + bool lastWasDefence = true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + const int slots = settings->getMaxNBots(); + bool* const flags = checkPointer(new bool[slots]); + for (int i = 0; i < slots; ++i) + flags[i] = false; + + const float* const friendly = m_int1F4 ? m_stateB : m_stateA; + float attackShare; + float defenceShare; + if (friendly[StrategyCondition::NumberOfFriendlyAreas] == 0.0f) + { + attackShare = 1.0f; + defenceShare = 0.0f; + } + else if (friendly[StrategyCondition::NumberOfNeutralAreas] == 0.0f + && friendly[StrategyCondition::NumberOfHostileAreas] == 0.0f) + { + attackShare = 0.0f; + defenceShare = 1.0f; + } + else + { + attackShare = m_activeStrategy->m_strategy->getAggression(); + defenceShare = 1.0f - m_activeStrategy->m_strategy->getAggression(); + } + + for (std::set::iterator it = m_set44.begin(); it != m_set44.end();) + { + BotInfo* const info = m_botInfo[*it]; + if (!info) + { + ++it; + continue; + } + Information* const information = informationManager->getInformation(info->m_bot->getCurrentEquipment()); + if (!information) + { + ++it; + continue; + } + AIStrategicObject* object = manager->getStrategicObject(info->m_int0C); + if (!object) + { + if (!information->getUnit()) + { + ++it; + continue; + } + int vehicle = -1; + if (information->getMobile()) + vehicle = information->getMobile()->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + object = manager->getClosestObject(information->getPosition(), equipment, vehicle, m_side); + if (!object) + { + ++it; + continue; + } + m_botInfo[*it]->respawn(object, this); + } + else + { + object->setAsPresentUnit(*it, m_side); + } + if (object->getIndex() != m_botInfo[*it]->m_int08) + { + object->retainBot(m_side, *it, this); + m_botInfo[*it]->setLastOrderedSquare(object->getIndex()); + } + IPIUnit* const unit = information->getUnit(); // not null-checked on this path + const int attack = m_intD8; + const int defence = m_intDC; + bool toAttack; + if (attack + defence == 0) + toAttack = attackShare >= 0.5f; + else if (0.0f >= attackShare) + toAttack = false; + else if (0.0f >= defenceShare) + toAttack = true; + else + toAttack = attackShare >= static_cast(attack) / static_cast(attack + defence); + if (toAttack) + m_intD8 = static_cast(unit->getStrategicStrengths()[0]) + attack; + else + m_intDC = static_cast(unit->getStrategicStrengths()[1]) + defence; + m_intE0 -= static_cast(meanStrength(unit)); + lastWasDefence = !toAttack; + m_botInfo[*it]->assign(it, toAttack, this); + } + + const float total = static_cast(m_intD8 + m_intDC + m_intE0); + if (total == 0.0f) + { + m_flag1CD = false; + m_flag1CC = false; + } + else + { + if (static_cast(m_intD8) / total > attackShare * 1.2f && !lastWasDefence) + { + m_flag1CD = true; + m_flag1CE = true; + } + else + { + m_flag1CD = false; + } + if (static_cast(m_intDC) / total > 1.2f * defenceShare && lastWasDefence) + { + m_flag1CC = true; + m_flag1CE = true; + } + else + { + m_flag1CC = false; + } + } + delete[] flags; } +// ELF 0x32AE70: per category (or over all objects when there are none), unless the active +// strategy runs no defences. void SAI::distributeDefence() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeDefence"); + if (!m_activeStrategy->m_strategy->getNumberOfDefences()) + return; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + if (!manager->getNumberOfCategories()) + { + categoryDistributeDefence(manager->getStrategicObjects()); + return; + } + for (int category = 0; category < manager->getNumberOfCategories(); ++category) + categoryDistributeDefence(manager->getStrategicObjectsOfCategory(category)); +} + +// ELF 0x32AF10. Objects needing defence (need > 0.1) are ranked by need, highest first; objects +// with no need that are not attacked release their resources. Beyond twice the strategy's +// defence count, entries below 90% of the need at that rank are dropped (releasing their +// resources unless attacked). With +0x1CC set (and +0x1CE clear) and nothing released yet, the +// lowest-need defence releases resources instead. Otherwise up to getNumberOfDefences() areas +// are set to defend and fed one squad at a time, the least supplied first (sobOrdering). +void SAI::categoryDistributeDefence(const std::vector& objects) +{ + std::list squares; + int released = 0; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!*it) + continue; + SquareInfo square; + square.m_index = -1; + square.m_value = (*it)->calculateDefenseNeed(m_side); + if (square.m_value > 0.1f) + { + square.m_index = (*it)->getIndex(); + squares.push_back(square); + } + else if (0.0f >= square.m_value && !(*it)->isAttack(m_side)) + { + released += (*it)->releaseAssignedResources(m_side); + } + } + squares.sort(); + squares.reverse(); + if (squares.empty()) + return; + + float threshold = 0.0f; + unsigned int rank = 0; + std::list::iterator it = squares.begin(); + for (; it != squares.end(); ++it) + { + ++rank; + const unsigned int keep = m_activeStrategy->m_strategy->getNumberOfDefences() * 2; + if (rank == keep) + threshold = it->m_value; + else if (rank > keep && threshold * 0.9f > it->m_value) + break; + } + while (it != squares.end()) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object && !object->isAttack(m_side)) + released += object->releaseAssignedResources(m_side); + it = squares.erase(it); + } + if (squares.empty()) + return; + + if (m_flag1CC && !m_flag1CE && !released) + { + squares.reverse(); + for (it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object || object->isAttack(m_side)) + continue; + released += object->releaseAssignedResources(m_side); + if (released > 0) + return; + } + return; + } + + unsigned int count = 0; + std::priority_queue, sobOrdering> queue((sobOrdering(m_side))); + for (it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object) + continue; + object->setAttack(false, m_side); + queue.push(object); + ++count; + if (!(m_activeStrategy->m_strategy->getNumberOfDefences() > count)) + break; + } + while (!queue.empty()) + { + AIStrategicObject* const object = queue.top(); + queue.pop(); + if (object->collectAdditionalSquadResources(1, m_side, this)) + queue.push(object); + } } +// ELF 0x32B9B0: per category (or over all objects when there are none), unless the active +// strategy runs no attacks. void SAI::distributeAttack() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeAttack"); + if (!m_activeStrategy->m_strategy->getNumberOfAttacks()) + return; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + if (!manager->getNumberOfCategories()) + { + categoryDistributeAttack(manager->getStrategicObjects()); + return; + } + for (int category = 0; category < manager->getNumberOfCategories(); ++category) + categoryDistributeAttack(manager->getStrategicObjectsOfCategory(category)); +} + +// ELF 0x32BA50. Areas worth attacking (value > 0.001) are ranked, highest first. The first +// getNumberOfAttacks() set the threshold; up to twice that many are kept while they reach 80% of +// it, the rest are dropped, releasing their resources when attacked. With +0x1CD set (and +0x1CE +// clear) and nothing released, the lowest entry is dropped as well and attacked areas release +// resources instead, until something was released. Otherwise already attacked areas are chosen +// first (up to numberOfAttacks + 1 entries, as shipped), filled up from the top of the ranking, +// set to attack, collect their squads (slot 23) and are then fed one more squad at a time, the +// least supplied first. The isAttack call for non-positive values is discarded, as shipped. +void SAI::categoryDistributeAttack(const std::vector& objects) +{ + std::list squares; + std::list chosen; + int released = 0; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!*it) + continue; + SquareInfo square; + square.m_index = -1; + square.m_value = (*it)->calculateAttackValue(m_side); + if (square.m_value > 0.001f) + { + square.m_index = (*it)->getIndex(); + squares.push_back(square); + } + else if (0.0f >= square.m_value) + { + (*it)->isAttack(m_side); + } + } + squares.sort(); + squares.reverse(); + if (squares.empty()) + return; + + float threshold = 0.0f; + unsigned int rank = 0; + std::list::iterator it = squares.begin(); + while (it != squares.end()) + { + ++rank; + if (rank <= m_activeStrategy->m_strategy->getNumberOfAttacks()) + threshold = it->m_value; + else if (rank > m_activeStrategy->m_strategy->getNumberOfAttacks() * 2 + || threshold * 0.8f > it->m_value) + break; + ++it; + } + while (it != squares.end()) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object && object->isAttack(m_side)) + released += object->releaseAssignedResources(m_side); + it = squares.erase(it); + } + const bool shed = m_flag1CD && !m_flag1CE && !released; + if (shed) + { + it = squares.end(); + --it; + while (it != squares.end()) + it = squares.erase(it); + } + if (squares.empty()) + return; + if (shed) + { + for (it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object || !object->isAttack(m_side)) + continue; + released += object->releaseAssignedResources(m_side); + if (released > 0) + return; + } + return; + } + + it = squares.begin(); + while (it != squares.end() && !(chosen.size() > m_activeStrategy->m_strategy->getNumberOfAttacks())) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object && object->isAttack(m_side)) + { + chosen.push_back(*it); + it = squares.erase(it); + } + else + { + ++it; + } + } + it = squares.begin(); + while (!(chosen.size() > m_activeStrategy->m_strategy->getNumberOfAttacks()) && it != squares.end()) + { + chosen.push_back(*it); + ++it; + } + for (it = chosen.begin(); it != chosen.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object) + continue; + object->setAttack(true, m_side); + object->collectSquadResources(m_side, this); + } + std::priority_queue, sobOrdering> queue((sobOrdering(m_side))); + for (it = chosen.begin(); it != chosen.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (object) + queue.push(object); + } + while (!queue.empty()) + { + AIStrategicObject* const object = queue.top(); + queue.pop(); + if (object->collectAdditionalSquadResources(1, m_side, this)) + queue.push(object); + } } +// ELF 0x32B6E0: per category, or over all objects when there are none. void SAI::distributeWithNoAreas() { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::distributeWithNoAreas"); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + if (!manager->getNumberOfCategories()) + { + categoryDistributeWithNoAreas(manager->getStrategicObjects()); + return; + } + for (int category = 0; category < manager->getNumberOfCategories(); ++category) + categoryDistributeWithNoAreas(manager->getStrategicObjectsOfCategory(category)); +} + +// ELF 0x32B770. Every non-null object becomes a SquareInfo {index, 1.0f} (in object order, not +// sorted here); each one that still resolves is set to attack unless the side owns it, then +// collects two additional squads (slot 24 with (2, side, this)). The second list is unused. +void SAI::categoryDistributeWithNoAreas(const std::vector& objects) +{ + std::list squares; + std::list unused; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!*it) + continue; + SquareInfo square; + square.m_value = 1.0f; + square.m_index = (*it)->getIndex(); + squares.push_back(square); + } + for (std::list::iterator it = squares.begin(); it != squares.end(); ++it) + { + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); + if (!object) + continue; + object->setAttack(object->getStatus(m_side) != StatusMap::Owned, m_side); + object->collectAdditionalSquadResources(2, m_side, this); + } } // Recovered empty helper: , (frame prologue/epilogue and return only). @@ -1253,9 +2670,51 @@ void SampleHelper::clear(float* strength, int* count) } } +// ELF 0x331B80 (weak, inline in the header): the owned commander interface at +0x1F8. CommanderInterface* SAI::getCommanderInterface() const { - BF2_AI_FRONTIER("dice::hfe::ai::SAI::getCommanderInterface"); + return m_commander; +} + +// ELF 0x32E8A0: per-round state back to its constructed values (the strategy containers' first +// two floats, the four six-bucket rows, the flags, the resumable update state 19 with the -1000.0 +// timestamp, +0xD8/+0xDC), the deny requests freed, the four timers restarted from the game time +// (+0x68/+0x70/+0x78 now + 60, +0x80 now + 10, +0x88 zero), the squad manager reset, +0xAC set. +bool SAI::reset() +{ + for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) + { + it->m_f04 = 0.0f; + it->m_f00 = 0.0f; + } + for (int i = 0; i <= 5; ++i) + { + m_enemyStrengths[i] = 0.0f; + m_enemyCounts[i] = 0.0f; + m_friendlyStrengths[i] = 0.0f; + m_friendlyCounts[i] = 0.0f; + } + m_flag1C0 = false; + m_flag1C1 = false; + m_flag1CE = true; + m_float190 = -1000.0f; + m_int18C = 19; + m_intD8 = 0; + m_intDC = 0; + for (std::list::iterator it = m_denyRequests.begin(); it != m_denyRequests.end();) + { + ::operator delete(*it); + it = m_denyRequests.erase(it); + } + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_time80 = now + 10.0f; + m_time68 = now + 60.0f; + m_time70 = now + 60.0f; + m_time78 = now + 60.0f; + m_time88 = 0.0f; + SquadManager::m_instance->reset(); + m_flagAC = true; + return true; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h index d6b15e48f..93b1e5a12 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "../../../../Math/Vec3.h" // Vec2 and Vec3 are typedefs in here - never forward-declare @@ -27,12 +28,14 @@ class Strategy; // count that divides by five, so `sizeof(StrategyContainer) == 20`; the destructor also runs // `__destroy_aux` over the range, which is what proves the vector holds these by value rather than // by pointer. updateStates subtracts the float at +8 from game time. -// Its name is [INFERRED]; the other sixteen bytes remain [UNRESOLVED]. +// Its name is [INFERRED]. SAI::addStrategy (ELF 0x326C10) builds {0, 0, 0, 1, strategy}. struct StrategyContainer { - unsigned char m_unresolved00[8]; - float m_startTime; // +8, [INFERRED] name - unsigned char m_unresolved0C[8]; + float m_f00; // +0x00, [UNRESOLVED] role; SAI::reset zeroes it + float m_f04; // +0x04, [UNRESOLVED] role; SAI::reset zeroes it + float m_startTime; // +0x08, [INFERRED] name + int m_i0C; // +0x0C, = 1 [UNRESOLVED] + Strategy* m_strategy; // +0x10, borrowed; owned by the StrategyManager }; // Running weighted averages over a fixed number of strength categories. @@ -99,9 +102,9 @@ class ISAI virtual bool isEnemy(int side) const = 0; // +10 virtual bool isFriend(int side) const = 0; // +11 virtual float* getEnemyStrengths(int index) const = 0; // +12 - virtual int* getEnemyTypes(int index) const = 0; // +13 + virtual float* getEnemyTypes(int index) const = 0; // +13 (float counts) virtual float* getFriendlyStrengths(int index) const = 0; // +14 - virtual int* getFriendlyTypes(int index) const = 0; // +15 + virtual float* getFriendlyTypes(int index) const = 0; // +15 (float counts) virtual void setBotHasChangedEquipment(int botId) = 0; // +16 virtual void setNewBotKit(int botId, int kit) = 0; // +17 // Borrowed map address: ELF +0x48 / PE +0x44; caller copies map>. @@ -127,21 +130,23 @@ class ISAI virtual bool ownAllTakeableCps(int side) = 0; // +31 // Full released-squad count: ELF callers add EAX; PE +0x7C forwards that count. virtual int releaseSquadsFromObject(int a, int b) = 0; // +32 - virtual void releaseUnitFromObject(int a, std::map::iterator& it, int b) = 0; // +33 - virtual void foundDeadBot(int botId) = 0; // +34 + virtual bool releaseUnitFromObject(int object, std::set::iterator& it, int side) = 0; // +33 + virtual bool foundDeadBot(int botId) = 0; // +34 virtual bool hasChangedEquipment(int botId) = 0; // +35 virtual void equipmentChangedFinished(int botId) = 0; // +36 - virtual void assignBot(std::map::iterator& it, int a, int b, bool c) = 0; // +37 + virtual int assignBot(std::set::iterator& it, int object, int botId, bool attacker) = 0; // +37 virtual bool strategicObjectsHasChanged() = 0; // +38 virtual void registerTeleporter(int id) = 0; // +39 - virtual float getStrategyHeat(unsigned int index) = 0; // +40 - virtual void listStrategies() = 0; // +41 - virtual int getActiveStrategy() = 0; // +42 + // ELF 0x32E380 returns the eight-byte {m_f00, m_f04} pair through the hidden result pointer; + // the Vec2 spelling is [INFERRED]. + virtual Vec2 getStrategyHeat(unsigned int index) = 0; // +40 + virtual std::string listStrategies() = 0; // +41, by value + virtual Strategy* getActiveStrategy() = 0; // +42 virtual void addSpawnToPoint(int point) = 0; // +43 virtual int getSpawnsToPoint(int point) const = 0; // +44 - virtual Vec3 getBotCurrentPos(int botId) const = 0; // +45 - virtual Vec3 getBotOrderedPos(int botId) const = 0; // +46 - virtual Vec3 getBotLastOrderedPos(int botId) const = 0; // +47 + virtual int getBotCurrentPos(int botId) const = 0; // +45 + virtual int getBotOrderedPos(int botId) const = 0; // +46 + virtual int getBotLastOrderedPos(int botId) const = 0; // +47 virtual CommanderInterface* getCommanderInterface() const = 0; // +48 // the factory is static and it is the only way in. : `operator new(0x1FC)` then the @@ -159,7 +164,47 @@ class SAI : public ISAI struct BotInfo { explicit BotInfo(Bot* bot); - void remove(SAI* sai); // named removal frontier + // ELF 0x32F3D0: leave the assigned object (removeAssigned with release) and the current + // object's present set - or, unassigned, the occupied set through free(true) - and the + // free set (+0x44). + void remove(SAI* sai); + // ELF 0x32F5B0: removeAssigned through object->getAssignedUnits(side).find(id) (no end + // check in the image). + void removeAssigned(AIStrategicObject* object, bool release, SAI* sai); + // ELF 0x32FF30: m_int04/m_int08/m_int0C = -1, m_float10 = 0.0f. + void setAsDead(SAI* sai); + // ELF 0x32FF70: the id enters the free set (+0x44). + void setAsFree(SAI* sai); + // ELF 0x32FDF0: unregister the bot from the object's attacker/defender set (advancing + // it), move its id from SAI's occupied set (+0xFC) to the free set (+0x44). + void free(AIStrategicObject* object, bool attacker, std::set::iterator& it, SAI* sai); + // ELF 0x32FC80: with release, unregister from the current object (m_int0C) and leave the + // occupied set; the id always enters the free set (+0x44). + void free(bool release, SAI* sai); + // ELF 0x32F0E0: the bot respawned at an object: present there, id into the free set. + void respawn(AIStrategicObject* object, SAI* sai); + // ELF 0x32FB10: register as attacker/defender of the current object; the id moves from + // the free set (erasing under the iterator) to the occupied set. + void assign(std::set::iterator& it, bool attacker, SAI* sai); + int setLastOrderedSquare(int square); // ELF 0x32FFD0; stamps m_double14 + // ELF 0x32F660: leave the object's assigned set (erasing under the iterator); with + // release also SAI's occupied set (+0xFC), otherwise become an available attacker or + // defender of the current object (m_int0C). Clears m_int04 and m_double14. + void removeAssigned(AIStrategicObject* object, std::set::iterator& it, bool release, SAI* sai); + // ELF 0x32F290: the bot moves from one object's present set (advancing it) to another's, + // keeping its attacker/defender role there; m_int0C becomes the new object's index. + void occupy(std::set::iterator& it, AIStrategicObject* from, AIStrategicObject* to, SAI* sai); + // ELF 0x32F1F0: the iterator overload with from->getPresentUnits(side).find(id). + void occupy(AIStrategicObject* from, AIStrategicObject* to, SAI* sai); + // ELF 0x32F950: ordered to the object (m_int04 = m_int08 = its index, m_double14 = now); + // leaves the current object's attackers/defenders under the iterator and joins the + // object's assigned set. + void assignToObject(std::set::iterator& it, AIStrategicObject* object, bool attacker, SAI* sai); + // ELF 0x32F860: the iterator overload with the current object's available attackers or + // defenders (getAvailableBots(attacker, side)).find(id). + void assignToObject(AIStrategicObject* object, bool attacker, SAI* sai); + // ELF 0x32FA60: the iterator overload with SAI's free set (+0x44).find(id). + void assign(bool attacker, SAI* sai); /* +0x00 */ Bot* m_bot; /* +0x04 */ int m_int04; // = -1 @@ -183,6 +228,8 @@ class SAI : public ISAI SAI(int side, int gridWidth, int gridHeight, Vec2 min, Vec2 max); virtual ~SAI(); + bool reset(); // ELF 0x32E8A0, non-virtual; answers true + // the 49 interface slots. Unwritten bodies stop at named frontiers. virtual void addStrategy(Strategy* strategy); virtual void update(double budget); @@ -195,9 +242,9 @@ class SAI : public ISAI virtual bool isEnemy(int side) const; virtual bool isFriend(int side) const; virtual float* getEnemyStrengths(int index) const; - virtual int* getEnemyTypes(int index) const; + virtual float* getEnemyTypes(int index) const; virtual float* getFriendlyStrengths(int index) const; - virtual int* getFriendlyTypes(int index) const; + virtual float* getFriendlyTypes(int index) const; virtual void setBotHasChangedEquipment(int botId); virtual void setNewBotKit(int botId, int kit); virtual const std::map >& getDeadBots() const; @@ -216,21 +263,21 @@ class SAI : public ISAI virtual bool haveAnyOwnedAndTakeableCps(int side); virtual bool ownAllTakeableCps(int side); virtual int releaseSquadsFromObject(int a, int b); // frontier - virtual void releaseUnitFromObject(int a, std::map::iterator& it, int b); - virtual void foundDeadBot(int botId); + virtual bool releaseUnitFromObject(int object, std::set::iterator& it, int side); // ELF 0x32D6D0 + virtual bool foundDeadBot(int botId); // ELF 0x329250 virtual bool hasChangedEquipment(int botId); virtual void equipmentChangedFinished(int botId); - virtual void assignBot(std::map::iterator& it, int a, int b, bool c); + virtual int assignBot(std::set::iterator& it, int object, int botId, bool attacker); // ELF 0x32D870 virtual bool strategicObjectsHasChanged(); virtual void registerTeleporter(int id); - virtual float getStrategyHeat(unsigned int index); - virtual void listStrategies(); - virtual int getActiveStrategy(); + virtual Vec2 getStrategyHeat(unsigned int index); + virtual std::string listStrategies(); + virtual Strategy* getActiveStrategy(); virtual void addSpawnToPoint(int point); virtual int getSpawnsToPoint(int point) const; - virtual Vec3 getBotCurrentPos(int botId) const; - virtual Vec3 getBotOrderedPos(int botId) const; - virtual Vec3 getBotLastOrderedPos(int botId) const; + virtual int getBotCurrentPos(int botId) const; + virtual int getBotOrderedPos(int botId) const; + virtual int getBotLastOrderedPos(int botId) const; virtual CommanderInterface* getCommanderInterface() const; // non-virtual. The vtable does not carry these. @@ -244,6 +291,7 @@ class SAI : public ISAI void handleTeleportingBot(int botId); // named frontier bool updateStrategicObjects(); void chooseStrategy(); + void changeStrategy(std::vector::iterator& it); // ELF 0x329610 void modifyStrategicObjectsTemperatures(); void updateBotPositions(); void updateDistribution(); @@ -251,9 +299,21 @@ class SAI : public ISAI void distributeDefence(); void distributeAttack(); void distributeWithNoAreas(); + void categoryDistributeWithNoAreas(const std::vector& objects); // ELF 0x32B770 + void categoryDistributeAttack(const std::vector& objects); // ELF 0x32BA50 + void categoryDistributeDefence(const std::vector& objects); // ELF 0x32AF10 void distributeArtillery(); // genuinely empty, PE update elides it + void updateMap(double budget); // ELF 0x32CEE0, empty + float* createUnitMods() const; // ELF 0x329490 + bool isBotFree(int botId) const; // ELF 0x32E2D0 + bool isBotAssigned(int botId) const; // ELF 0x32E320 + Strategy* getActiveStrategy(float& a, float& b, float& c); // ELF 0x32EAB0 private: + // ELF 0x328DB0 (setBotIsDead's body, a direct call). + void handleDeadBot(int botId); + // ELF 0x328FE0 (setBotHasChangedEquipment's tail, a direct call). + void handleChangingBot(int botId); /* +0x000 */ // vptr - ISAI // forty bytes no constructor store and no destructor call ever touches. [UNRESOLVED]; kept // opaque so every offset below stays where the binary puts it. @@ -289,13 +349,13 @@ class SAI : public ISAI /* +0x0D8 */ int m_intD8; // [UNRESOLVED] - the ctor zeroes it /* +0x0DC */ int m_intDC; // [UNRESOLVED] - the ctor zeroes it - /* +0x0E0 */ int m_intE0; // [UNRESOLVED] + /* +0x0E0 */ int m_intE0; // [UNRESOLVED]; not constructed, updateDistribution zeroes it /* +0x0E4 */ std::map > m_mapE4; // a map of maps - node 32 /* +0x0F0 */ std::set m_setF0; /* +0x0FC */ std::set m_setFC; /* +0x108 */ std::list m_list108; // 4-byte element; type [UNRESOLVED] /* +0x10C */ std::list m_list10C; // 4-byte element; type [UNRESOLVED] - /* +0x110 */ std::list m_list110; // 4-byte element; type [UNRESOLVED] + /* +0x110 */ std::list m_list110; // teleporter ids (registerTeleporter) // by value, not by pointer - the destructor runs `__destroy_aux` over the // range, and the deallocation size divides by five, so `sizeof(StrategyContainer) == 20`. @@ -312,7 +372,7 @@ class SAI : public ISAI /* +0x174 */ float m_friendlyCounts[6]; /* +0x18C */ int m_int18C; // = 19; resumable strategic update state - /* +0x190 */ float m_float190; // = -992.0f; last-update timestamp used by state 4 + /* +0x190 */ float m_float190; // = -1000.0f; last-update timestamp used by state 4 /* +0x194 */ int m_side; // the constructor's first argument /* +0x198 */ int m_sideMask; // = 1 << side /* +0x19C */ int m_enemyMask; // = (side == 1) ? 4 : 2 - the other side's bit diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp new file mode 100644 index 000000000..7a9a58a3a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.cpp @@ -0,0 +1,57 @@ +// Area condition. Evidence: libaidll.so (ia-32) 0x3322B0..0x332770. + +#include "SCArea.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x3326E0, +// __tcf_0 0x332740, _GLOBAL__I 0x332770). +#include + +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCArea::SCArea(const std::string& name, const std::string& areaName, int object, + StatusMap::Status status) + : StrategyCondition(name, 0.0f, static_cast(9), Friendly, Crisp, + static_cast(44)), + m_object(object), + m_areaName(areaName), + m_status(status) +{ +} + +SCArea::~SCArea() +{ +} + +// ELF 0x3325B0: 1 when the object is an area (getType 0) whose status for this side is the +// wanted one, -1 otherwise. The object is not null-checked. +float SCArea::compare(float*, float*, int side) const +{ + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getStrategicObject(m_object); + if (object->getType() != 0) + return -1.0f; + return object->getStatus(side) == m_status ? 1.0f : -1.0f; +} + +// ELF 0x332630: resolves the area by name through the manager's active-area cursor. +int SCArea::updateArea() +{ + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + manager->setActive(m_areaName); + AIStrategicArea* const area = manager->getActiveArea(); + if (area) + m_object = area->getIndex(); + else + m_object = -1; + return m_object; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h new file mode 100644 index 000000000..89ce621fe --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCArea.h @@ -0,0 +1,35 @@ +// Condition on the status of one strategic area for the asking side. +// Evidence: libaidll.so (ia-32) 0x3322B0..0x332870, vtable 0x4BF458. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCAREA_H +#define AI_AIDLL_AI_AISTRATEGIC_SCAREA_H + +#include "StatusMap.h" +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCArea : public StrategyCondition +{ +public: + // ELF 0x3322B0: base (name, 0.0f, Compare 9, Friendly, Crisp, Conditional 44) - both + // out of range, so the base comparisons are never used. + SCArea(const std::string& name, const std::string& areaName, int object, + StatusMap::Status status); + virtual ~SCArea(); + virtual int getType() const { return 3; } // ELF 0x332870 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; + int updateArea(); // ELF 0x332630 + + /* +0x24 */ int m_object; // strategic-object index, -1 when unresolved + /* +0x28 */ std::string m_areaName; + /* +0x2C */ StatusMap::Status m_status; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCAREA_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.cpp new file mode 100644 index 000000000..b73fbfc35 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.cpp @@ -0,0 +1,34 @@ +// Constant condition. Evidence: libaidll.so (ia-32) 0x332880..0x332B10. + +#include "SCConstant.h" + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCConstant::SCConstant(const std::string& name, CompareType compareType, Compare compare, + ConditionSide side, Conditional conditional, float constant, float target) + : StrategyCondition(name, target, compare, side, compareType, conditional), + m_constant(constant) +{ +} + +SCConstant::~SCConstant() +{ +} + +// ELF 0x332A90: Friendly reads the friendly array, every other side the enemy array. The +// debug query's branch is empty in the shipped image; only the call remains. +float SCConstant::compare(float* friendly, float* enemy, int) const +{ + float* const values = m_side == Friendly ? friendly : enemy; + const float result = internalCompare(values[m_conditional], m_constant); + StrategyManager::getInstance()->isDebugEnabled(); + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h new file mode 100644 index 000000000..2df096f1a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCConstant.h @@ -0,0 +1,31 @@ +// Condition comparing one state value of the friendly or the enemy side with a constant. +// Evidence: libaidll.so (ia-32) 0x332880..0x332B10, vtable 0x4BF4A0. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCCONSTANT_H +#define AI_AIDLL_AI_AISTRATEGIC_SCCONSTANT_H + +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCConstant : public StrategyCondition +{ +public: + // ELF 0x332880: the base gets (name, target, compare, side, compareType, conditional); the + // first float is the constant operand at +0x24. + SCConstant(const std::string& name, CompareType compareType, Compare compare, + ConditionSide side, Conditional conditional, float constant, float target); + virtual ~SCConstant(); + virtual int getType() const { return Constant; } // ELF 0x332B10 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; + + /* +0x24 */ float m_constant; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCCONSTANT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp new file mode 100644 index 000000000..985151d37 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp @@ -0,0 +1,52 @@ +// Heterogeneous condition. Evidence: libaidll.so (ia-32) 0x332B20..0x332DD0. + +#include "SCHeterogeneous.h" + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCHeterogeneous::SCHeterogeneous(const std::string& name, CompareType compareType, + Compare compare, ConditionSide side, Conditional first, + Conditional second, float target) + : StrategyCondition(name, target, compare, side, compareType, first), + m_secondConditional(second) +{ +} + +SCHeterogeneous::~SCHeterogeneous() +{ +} + +// ELF 0x332D30. An unknown side answers 0 without comparing. +float SCHeterogeneous::compare(float* friendly, float* enemy, int) const +{ + float* a; + float* b; + switch (m_side) + { + case Friendly: + a = friendly; + b = friendly; + break; + case Enemy: + a = enemy; + b = enemy; + break; + case Both: + a = friendly; + b = enemy; + break; + default: + return 0.0f; + } + const float result = internalCompare(a[m_conditional], b[m_secondConditional]); + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h new file mode 100644 index 000000000..e4c7dec2d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHeterogeneous.h @@ -0,0 +1,30 @@ +// Condition comparing two different state values (of one side, or friendly against enemy). +// Evidence: libaidll.so (ia-32) 0x332B20..0x332DD0, vtable 0x4BF4C8. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCHETEROGENEOUS_H +#define AI_AIDLL_AI_AISTRATEGIC_SCHETEROGENEOUS_H + +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCHeterogeneous : public StrategyCondition +{ +public: + // ELF 0x332B20: the first conditional goes to the base, the second to +0x24. + SCHeterogeneous(const std::string& name, CompareType compareType, Compare compare, + ConditionSide side, Conditional first, Conditional second, float target); + virtual ~SCHeterogeneous(); + virtual int getType() const { return Heterogeneous; } // ELF 0x332DD0 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; + + /* +0x24 */ Conditional m_secondConditional; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCHETEROGENEOUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp new file mode 100644 index 000000000..8b34b1984 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp @@ -0,0 +1,50 @@ +// Homogeneous condition. Evidence: libaidll.so (ia-32) 0x332DE0..0x333090. + +#include "SCHomogeneous.h" + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +SCHomogeneous::SCHomogeneous(const std::string& name, CompareType compareType, Compare compare, + Conditional conditional, float target) + : StrategyCondition(name, target, compare, Both, compareType, conditional) +{ +} + +SCHomogeneous::~SCHomogeneous() +{ +} + +// ELF 0x332FF0. An unknown side answers 0 without comparing. +float SCHomogeneous::compare(float* friendly, float* enemy, int) const +{ + float* a; + float* b; + switch (m_side) + { + case Friendly: + a = friendly; + b = friendly; + break; + case Enemy: + a = enemy; + b = enemy; + break; + case Both: + a = friendly; + b = enemy; + break; + default: + return 0.0f; + } + const float result = internalCompare(a[m_conditional], b[m_conditional]); + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + return result; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.h new file mode 100644 index 000000000..60151cb2f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SCHomogeneous.h @@ -0,0 +1,28 @@ +// Condition comparing the same state value of two sides (friendly/friendly, enemy/enemy or +// friendly/enemy). Evidence: libaidll.so (ia-32) 0x332DE0..0x333090, vtable 0x4BF4F0. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_SCHOMOGENEOUS_H +#define AI_AIDLL_AI_AISTRATEGIC_SCHOMOGENEOUS_H + +#include "StrategyCondition.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SCHomogeneous : public StrategyCondition +{ +public: + // ELF 0x332DE0: the side is always Both. + SCHomogeneous(const std::string& name, CompareType compareType, Compare compare, + Conditional conditional, float target); + virtual ~SCHomogeneous(); + virtual int getType() const { return Homogeneous; } // ELF 0x333090 (weak) + virtual float compare(float* friendly, float* enemy, int side) const; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_SCHOMOGENEOUS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h index 03543d555..39e820866 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StatusMap.h @@ -1,11 +1,13 @@ -// Strategic status values used by scripts. Unknown input maps to Unknown. -// Writing an out-of-range value also produces Unknown, so such values do not round-trip. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// A row-major grid of strategic statuses, and the status values used by scripts. Unknown input +// maps to Unknown; writing an out-of-range value also produces Unknown, so such values do not +// round-trip. Evidence: libaidll.so (ia-32) 0x366000..0x3663E8 (AIStrategicMap/StatusMap.cpp); +// sizeof 12, the same shape as ScalarMap. Member names [INFERRED]. [INFERRED] header placement. #ifndef AI_AIDLL_AI_AISTRATEGIC_STATUSMAP_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGIC_STATUSMAP_H +#include + namespace dice { namespace hfe { namespace ai { @@ -21,6 +23,17 @@ class StatusMap Neutral = 2, Unknown = 3 }; + + // Allocates width * height uninitialised statuses (checkPointer reports a failed allocation). + StatusMap(int width, int height); + ~StatusMap(); + + // Appends the index of every Owned square, row by row. + void getOwnedSquares(std::vector& squares) const; + + /* +0x0 */ int m_width; + /* +0x4 */ int m_height; + /* +0x8 */ Status* m_statuses; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp new file mode 100644 index 000000000..c14838ce9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.cpp @@ -0,0 +1,274 @@ +// Strategy. Evidence: libaidll.so (ia-32) 0x3330A0..0x333DC0. + +#include "Strategy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x333DD0, +// __tcf_0 0x333E30, _GLOBAL__I 0x333E60). +#include + +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3330A0. The counts and +0x2C are left as allocated. The specific-modifier vector is +// resized to 0 (with fill 0.0f) after the object modifiers are reset. +Strategy::Strategy(const std::string& name) + : m_treeModifiers(new TemperatureTreeModifiers()), + m_aggression(0.5f), + m_abortLevel(0.0f), + m_prerequisiteWeight(1.0f), + m_f20(1e9f), + m_prerequisite(0), + m_abortCondition(0), + m_name(name) +{ + clearAllStrategicObjectsModifiers(); + m_specificModifiers.resize(0, 0.0f); +} + +// ELF 0x333460: only the tree modifiers are owned (operator delete, no destructor call); +// prerequisite and abort condition belong to the StrategyManager. +Strategy::~Strategy() +{ + delete m_treeModifiers; +} + +TemperatureTreeModifiers* Strategy::getTemperatureTreeModifiers() const +{ + return m_treeModifiers; +} + +void Strategy::setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers) +{ + m_treeModifiers = modifiers; +} + +float Strategy::getAggression() const +{ + return m_aggression; +} + +void Strategy::setAggression(float aggression) +{ + m_aggression = aggression; +} + +unsigned int Strategy::getNumberOfAttacks() const +{ + return m_attacks; +} + +void Strategy::setNumberOfAttacks(unsigned int count) +{ + m_attacks = count; +} + +unsigned int Strategy::getNumberOfAttackConsiderations() const +{ + return m_attackConsiderations; +} + +void Strategy::setNumberOfAttackConsiderations(unsigned int count) +{ + m_attackConsiderations = count; +} + +unsigned int Strategy::getNumberOfDefences() const +{ + return m_defences; +} + +void Strategy::setNumberOfDefences(unsigned int count) +{ + m_defences = count; +} + +unsigned int Strategy::getNumberOfDefenceConsiderations() const +{ + return m_defenceConsiderations; +} + +void Strategy::setNumberOfDefenceConsiderations(unsigned int count) +{ + m_defenceConsiderations = count; +} + +void Strategy::setPrerequisite(StrategyPrerequisite* prerequisite) +{ + m_prerequisite = prerequisite; +} + +void Strategy::setAbortCondition(StrategyPrerequisite* condition) +{ + m_abortCondition = condition; +} + +// ELF 0x3337C0: 0 when a required predecessor list exists and does not contain previous, or +// when previous is prohibited; otherwise the weighted prerequisite score. The prerequisite is +// not null-checked. +float Strategy::calculatePrerequisite(float* friendly, float* enemy, Strategy* previous, int side) +{ + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + if (!m_requiredPreceding.empty() && m_requiredPreceding.find(previous) == m_requiredPreceding.end()) + return 0.0f; + if (!m_prohibitedPreceding.empty() && m_prohibitedPreceding.find(previous) != m_prohibitedPreceding.end()) + return 0.0f; + return m_prerequisite->evaluate(friendly, enemy, previous == this, side) * m_prerequisiteWeight; +} + +// ELF 0x333890: the abort level minus the abort condition's score (fsubrs +0x18). +float Strategy::calculateAbortCondition(float* friendly, float* enemy, Strategy* previous, int side) +{ + return m_abortLevel - m_abortCondition->evaluate(friendly, enemy, previous == this, side); +} + +float Strategy::setAbortLevel(float level) +{ + return m_abortLevel = level; +} + +float Strategy::getAbortLevel() const +{ + return m_abortLevel; +} + +float Strategy::setPrerequisiteWeight(float weight) +{ + return m_prerequisiteWeight = weight; +} + +float Strategy::getPrerequisiteWeight() const +{ + return m_prerequisiteWeight; +} + +// ELF 0x333930: nodes above 40 are ignored (unsigned compare). +void Strategy::setTreeModifier(TemperatureTreeNode node, float value) +{ + if (static_cast(node) <= 40) + m_treeModifiers->m_nodeModifiers[node] = value; +} + +float Strategy::getTreeModifier(TemperatureTreeNode node) const +{ + return m_treeModifiers->m_nodeModifiers[node]; +} + +// ELF 0x333960. Types outside 0..5 are ignored; the image still carries a type-6 arm that +// sets all six types, unreachable behind the range check, kept as shipped. +void Strategy::setTreeModifier(TemperatureTreeNode node, CombatStrengthType type, float value) +{ + if (static_cast(node) > 40 || type < 0 || type > 5) + return; + if (type == 6) + { + for (int i = 0; i <= 5; ++i) + m_treeModifiers->m_combatStrengthModifiers[node][i] = value; + return; + } + m_treeModifiers->m_combatStrengthModifiers[node][type] = value; +} + +float Strategy::getTreeModifier(TemperatureTreeNode node, CombatStrengthType type) const +{ + return m_treeModifiers->m_combatStrengthModifiers[node][type]; +} + +// ELF 0x3339F0: the same body and the same array as the three-argument setTreeModifier. +void Strategy::setTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type, float value) +{ + if (static_cast(node) > 40 || type < 0 || type > 5) + return; + if (type == 6) + { + for (int i = 0; i <= 5; ++i) + m_treeModifiers->m_combatStrengthModifiers[node][i] = value; + return; + } + m_treeModifiers->m_combatStrengthModifiers[node][type] = value; +} + +float Strategy::getTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type) const +{ + return m_treeModifiers->m_combatStrengthModifiers[node][type]; +} + +bool Strategy::addRequiredPrecedingStrategy(Strategy* strategy) +{ + if (!strategy) + return false; + return m_requiredPreceding.insert(strategy).second; +} + +bool Strategy::addProhibitedPrecedingStrategy(Strategy* strategy) +{ + if (!strategy) + return false; + return m_prohibitedPreceding.insert(strategy).second; +} + +void Strategy::setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value) +{ + for (int status = 0; status < 3; ++status) + m_objectModifiers[status][type] = value; +} + +// ELF 0x333B70: the mean over the three statuses, summed from 0.0f. +float Strategy::getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type) const +{ + float sum = 0.0f; + for (int status = 0; status < 3; ++status) + sum += m_objectModifiers[status][type]; + return sum / 3.0f; +} + +void Strategy::setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value, StatusMap::Status status) +{ + m_objectModifiers[status][type] = value; +} + +float Strategy::getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, StatusMap::Status status) const +{ + return m_objectModifiers[status][type]; +} + +// ELF 0x333C20: negative indices are ignored; the vector grows with 1.0f to cover the index. +void Strategy::setSpecificStrategicObjectModifier(int object, float value) +{ + if (object < 0) + return; + if (object >= static_cast(m_specificModifiers.size())) + m_specificModifiers.resize(object + 1, 1.0f); + m_specificModifiers[object] = value; +} + +float Strategy::getSpecificStrategicObjectModifier(int object) const +{ + if (object >= 0 && object < static_cast(m_specificModifiers.size())) + return m_specificModifiers[object]; + return 1.0f; +} + +const float* Strategy::getStrategicObjectsModifiers(StatusMap::Status status) const +{ + return m_objectModifiers[status]; +} + +// ELF 0x333D70. +void Strategy::clearAllStrategicObjectsModifiers() +{ + for (int type = 0; type <= 26; ++type) + for (int status = 0; status < 3; ++status) + m_objectModifiers[status][type] = 1.0f; +} + +const std::string& Strategy::getName() const +{ + return m_name; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h new file mode 100644 index 000000000..4f2a1a22e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/Strategy.h @@ -0,0 +1,96 @@ +// A strategy of the strategic AI: the number of attacks/defences it runs, its aggression, the +// prerequisite and abort conditions that score it, which strategies may precede it, and the +// temperature and strategic-object modifiers it applies while active. The StrategyManager +// (Main) builds strategies from the ai/Strategies.ai scripts and owns them; SAI borrows them. +// Evidence: libaidll.so (ia-32) Strategy.cpp 0x3330A0..0x333DC0. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_STRATEGY_H +#define AI_AIDLL_AI_AISTRATEGIC_STRATEGY_H + +#include +#include +#include + +#include "StatusMap.h" +#include "StrategyCondition.h" +#include "StrategyPrerequisite.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicMap/TemperatureTreeModifiers.h" + +namespace dice { +namespace hfe { +namespace ai { + +enum TemperatureTreeNode : int; // index 0..40 (setTreeModifier checks > 0x28) +enum CombatStrengthType : int; // 0..5 per tree node + +class Strategy +{ +public: + explicit Strategy(const std::string& name); // ELF 0x3332E0 (complete) / 0x3330A0 + ~Strategy(); // ELF 0x333460 / 0x3335A0 + + TemperatureTreeModifiers* getTemperatureTreeModifiers() const; + void setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers); + float getAggression() const; + void setAggression(float aggression); + unsigned int getNumberOfAttacks() const; + void setNumberOfAttacks(unsigned int count); + unsigned int getNumberOfAttackConsiderations() const; + void setNumberOfAttackConsiderations(unsigned int count); + unsigned int getNumberOfDefences() const; + void setNumberOfDefences(unsigned int count); + unsigned int getNumberOfDefenceConsiderations() const; + void setNumberOfDefenceConsiderations(unsigned int count); + void setPrerequisite(StrategyPrerequisite* prerequisite); + void setAbortCondition(StrategyPrerequisite* condition); + float calculatePrerequisite(float* friendly, float* enemy, Strategy* previous, int side); + float calculateAbortCondition(float* friendly, float* enemy, Strategy* previous, int side); + float setAbortLevel(float level); // fsts: the value stays in st0 + float getAbortLevel() const; + float setPrerequisiteWeight(float weight); // fsts: the value stays in st0 + float getPrerequisiteWeight() const; + + void setTreeModifier(TemperatureTreeNode node, float value); + float getTreeModifier(TemperatureTreeNode node) const; + void setTreeModifier(TemperatureTreeNode node, CombatStrengthType type, float value); + float getTreeModifier(TemperatureTreeNode node, CombatStrengthType type) const; + void setTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type, float value); + float getTreeModifierCombatStrength(TemperatureTreeNode node, CombatStrengthType type) const; + bool addRequiredPrecedingStrategy(Strategy* strategy); // null -> false + bool addProhibitedPrecedingStrategy(Strategy* strategy); // null -> false + void setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value); // all three statuses + float getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type) const; // mean of the three + void setStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, float value, StatusMap::Status status); + float getStrategicObjectsModifier(AIStrategicObject::StrategicObjectType type, StatusMap::Status status) const; + void setSpecificStrategicObjectModifier(int object, float value); + float getSpecificStrategicObjectModifier(int object) const; // 1.0f outside the vector + const float* getStrategicObjectsModifiers(StatusMap::Status status) const; + void clearAllStrategicObjectsModifiers(); // 3 x 27 floats to 1.0f + const std::string& getName() const; + + // ELF layout (sizeof 0x1A8 on ia-32). Names [INFERRED] from the accessors. + /* +0x000 */ TemperatureTreeModifiers* m_treeModifiers; // owned, new'ed by the constructor + /* +0x004 */ float m_aggression; // 0.5f + /* +0x008 */ unsigned int m_attacks; // not written by the constructor + /* +0x00C */ unsigned int m_defences; + /* +0x010 */ unsigned int m_attackConsiderations; + /* +0x014 */ unsigned int m_defenceConsiderations; + /* +0x018 */ float m_abortLevel; // 0.0f + /* +0x01C */ float m_prerequisiteWeight; // 1.0f + /* +0x020 */ float m_f20; // 1e9f [UNRESOLVED] no reader in Strategy.cpp + /* +0x024 */ StrategyPrerequisite* m_prerequisite; // 0; borrowed + /* +0x028 */ StrategyPrerequisite* m_abortCondition; // 0; borrowed + /* +0x02C */ int m_i2C; // not written by the constructor [UNRESOLVED] + /* +0x030 */ std::set m_requiredPreceding; + /* +0x03C */ std::set m_prohibitedPreceding; + /* +0x048 */ float m_objectModifiers[3][27]; // [status][object type], stride 0x6C + /* +0x18C */ std::vector m_specificModifiers; // per strategic-object index + /* +0x198 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_STRATEGY_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp new file mode 100644 index 000000000..0afe5ba1f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp @@ -0,0 +1,158 @@ +// Strategy condition base: the crisp and fuzzy comparisons shared by all condition kinds. +// Evidence: libaidll.so (ia-32) 0x334150..0x334570. + +#include "StrategyCondition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x334580, +// __tcf_0 0x3345E0, _GLOBAL__I 0x334610). +#include + +#include + +namespace dice { +namespace hfe { +namespace ai { + +StrategyCondition::StrategyCondition(const std::string& name, float target, Compare compare, + ConditionSide side, CompareType compareType, + Conditional conditional) + : m_isAbortCondition(false), + m_targetValue(target), + m_compare(compare), + m_compareType(compareType), + m_side(side), + m_conditional(conditional), + m_strength(Required), + m_name(name) +{ +} + +float StrategyCondition::setTargetValue(float value) +{ + return m_targetValue = value; +} + +float StrategyCondition::getTargetValue() const +{ + return m_targetValue; +} + +void StrategyCondition::setConditionStrength(ConditionStrength strength) +{ + m_strength = strength; +} + +StrategyCondition::ConditionStrength StrategyCondition::getConditionStrength() const +{ + return m_strength; +} + +// ELF 0x334270. FuzzySqr keeps the sign of the fuzzy distance and squares its magnitude. +float StrategyCondition::internalCompare(float a, float b) const +{ + switch (m_compareType) + { + case Crisp: + return internalCompareCrisp(a, b); + case Fuzzy: + return internalCompareFuzzy(a, b); + case FuzzySqr: + { + const float r = internalCompareFuzzy(a, b); + const float sign = r > 0.0f ? 1.0f : (r < 0.0f ? -1.0f : 0.0f); + return sign * (r * r); + } + default: + return 0.0f; + } +} + +// ELF 0x334320: 1 when the relation to the target holds, -1 otherwise. A zero divisor answers +// -1, except QuotientGreater, which answers 1. +float StrategyCondition::internalCompareCrisp(float a, float b) const +{ + float x; + switch (m_compare) + { + case Equal: + case Difference: + x = a - b; + return x == m_targetValue ? 1.0f : -1.0f; + case EqualGreater: + case DifferenceGreater: + x = a - b; + return x < m_targetValue ? -1.0f : 1.0f; + case EqualSmaller: + case DifferenceSmaller: + x = a - b; + return m_targetValue < x ? -1.0f : 1.0f; + case Quotient: + if (b == 0.0f) + return -1.0f; + x = a / b; + return x == m_targetValue ? 1.0f : -1.0f; + case QuotientGreater: + if (b == 0.0f) + return 1.0f; + x = a / b; + return x < m_targetValue ? -1.0f : 1.0f; + case QuotientSmaller: + if (b == 0.0f) + return -1.0f; + x = a / b; + return m_targetValue < x ? -1.0f : 1.0f; + default: + return 0.0f; + } +} + +// ELF 0x334440: the signed distance to the target (negated absolute distance for the Equal +// kinds). A zero divisor answers -1000, except QuotientGreater, which answers 1000. +float StrategyCondition::internalCompareFuzzy(float a, float b) const +{ + switch (m_compare) + { + case Equal: + case Difference: + return -std::fabs(a - b - m_targetValue); + case EqualGreater: + case DifferenceGreater: + return a - b - m_targetValue; + case EqualSmaller: + case DifferenceSmaller: + return -(a - b - m_targetValue); + case Quotient: + if (b == 0.0f) + return -1000.0f; + return -std::fabs(a / b - m_targetValue); + case QuotientGreater: + if (b == 0.0f) + return 1000.0f; + return a / b - m_targetValue; + case QuotientSmaller: + if (b == 0.0f) + return -1000.0f; + return -(a / b - m_targetValue); + default: + return 0.0f; + } +} + +bool StrategyCondition::setIsAbortCondition(bool abort) +{ + return m_isAbortCondition = abort; +} + +bool StrategyCondition::getIsAbortCondition() const +{ + return m_isAbortCondition; +} + +bool StrategyCondition::isAbortCondition() const +{ + return m_isAbortCondition; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.h new file mode 100644 index 000000000..5cbbe3611 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyCondition.h @@ -0,0 +1,116 @@ +// One condition of a strategy prerequisite: compares a value of the 44-entry strategic state +// arrays (SAI::updateStates) with a target and answers a score in [-1, 1] (crisp) or a distance +// (fuzzy). Subclasses choose the operands: SCConstant, SCHomogeneous, SCHeterogeneous, SCArea. +// Evidence: libaidll.so (ia-32) 0x332790..0x333090 and 0x334150..0x334570; vtable 0x4BF470 +// {D1, D0, getType, compare = __cxa_pure_virtual}. Enumerator names are the strings the +// shipped stream operators print (0x3C5D20..0x3C6D30); member names are [INFERRED]. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_STRATEGYCONDITION_H +#define AI_AIDLL_AI_AISTRATEGIC_STRATEGYCONDITION_H + +#include + +namespace dice { +namespace hfe { +namespace ai { + +class StrategyCondition +{ +public: + // getType: SCConstant 0, SCHomogeneous 1, SCHeterogeneous 2, SCArea 3, the base 4. The + // printer names only 0..2. + // Fixed int representation also admits the parser's unnamed fallback value 4. + enum ConditionType : int + { + Constant = 0, + Homogeneous = 1, + Heterogeneous = 2 + }; + + enum ConditionStrength + { + Required = 0, + RequiredPositive = 1, + RequiredNegative = 2, + Advisory = 3, + AdvisoryPositive = 4, + AdvisoryNegative = 5 + }; + + enum CompareType + { + Crisp = 0, + Fuzzy = 1, + FuzzySqr = 2 + }; + + enum ConditionSide + { + Friendly = 0, + Enemy = 1, + Both = 2 + }; + + // Equal* compare the difference a - b, Quotient* the quotient a / b, Difference* repeat the + // Equal* arms (internalCompareCrisp/Fuzzy jump tables 0x4A2A00 / 0x4A2A24). + enum Compare + { + Equal = 0, + EqualGreater = 1, + EqualSmaller = 2, + Quotient = 3, + QuotientGreater = 4, + QuotientSmaller = 5, + Difference = 6, + DifferenceGreater = 7, + DifferenceSmaller = 8 + }; + + // Index into the 44-float state arrays. Spelled as the printer spells it ("Infantery"). + enum Conditional + { + Carrier = 0, BattleShip = 1, LCVP = 2, Naval = 3, Bomber = 4, Fighter = 5, AntiAir = 6, + Air = 7, Infantery = 8, Artillery = 9, AntiTank = 10, HeavyAttack = 11, FastAttack = 12, + Ticket = 13, ControlPoint = 14, Time = 15, StartTime = 16, Attacks = 17, Defences = 18, + NumberOfFriendlyAreas = 19, NumberOfNeutralAreas = 20, NumberOfHostileAreas = 21, + Flank = 22, Base = 23, Close = 24, Centre = 25, Remote = 26, Route = 27, Bridge = 28, + North = 29, West = 30, South = 31, East = 32, FrontFlank = 33, FrontBase = 34, + FrontClose = 35, FrontCentre = 36, FrontRemote = 37, FrontNeutral = 38, Front = 39, + Safe = 40, EnemyObject = 41, UnReachable = 42, UnitConstant = 43 + }; + + // ELF 0x334150: vptr, abort flag false, strength 0 (Required), name copied last. + StrategyCondition(const std::string& name, float target, Compare compare, ConditionSide side, + CompareType compareType, Conditional conditional); + virtual ~StrategyCondition() {} // ELF 0x332790 (weak) + virtual int getType() const { return 4; } // ELF 0x332860 (weak) + virtual float compare(float* friendly, float* enemy, int side) const = 0; + + float setTargetValue(float value); // ELF 0x334230; fsts leaves the value in st0 + float getTargetValue() const; + void setConditionStrength(ConditionStrength strength); + ConditionStrength getConditionStrength() const; + bool setIsAbortCondition(bool abort); // ELF 0x334540; answers the stored flag + bool getIsAbortCondition() const; + bool isAbortCondition() const; + + float internalCompare(float a, float b) const; + float internalCompareCrisp(float a, float b) const; + float internalCompareFuzzy(float a, float b) const; + + /* +0x00 */ // vptr + /* +0x04 */ bool m_isAbortCondition; + /* +0x08 */ float m_targetValue; + /* +0x0C */ Compare m_compare; + /* +0x10 */ CompareType m_compareType; + /* +0x14 */ ConditionSide m_side; + /* +0x18 */ Conditional m_conditional; + /* +0x1C */ ConditionStrength m_strength; + /* +0x20 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_STRATEGYCONDITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp new file mode 100644 index 000000000..0b0eeeacc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp @@ -0,0 +1,84 @@ +// Strategy prerequisite. Evidence: libaidll.so (ia-32) 0x334630..0x334AA0. + +#include "StrategyPrerequisite.h" + +#include "StrategyCondition.h" +#include "../Main/StrategyManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x334630: the list is cleared again after the name is copied. +StrategyPrerequisite::StrategyPrerequisite(const std::string& name) + : m_name(name) +{ + m_conditions.clear(); +} + +StrategyPrerequisite::~StrategyPrerequisite() +{ +} + +// ELF 0x334880: null conditions are ignored. +void StrategyPrerequisite::addCondition(StrategyCondition* condition, float weight) +{ + if (condition) + m_conditions.push_back(std::make_pair(condition, weight)); +} + +// ELF 0x3348E0: the image counts the list (size(), not empty()). +StrategyCondition* StrategyPrerequisite::popFirstCondition() +{ + if (m_conditions.size() == 0) + return 0; + StrategyCondition* const condition = m_conditions.begin()->first; + m_conditions.erase(m_conditions.begin()); + return condition; +} + +// ELF 0x334960: the sum of weighted condition scores. A Required(Positive) condition scoring +// below zero, or a RequiredNegative one above zero, makes the whole prerequisite 0 at once; +// the Advisory kinds clamp their contribution instead. +float StrategyPrerequisite::evaluate(float* friendly, float* enemy, bool isActive, int side) +{ + float sum = 0.0f; + for (std::list >::iterator it = m_conditions.begin(); + it != m_conditions.end(); ++it) + { + if (!isActive && it->first->isAbortCondition()) + continue; + float value = it->first->compare(friendly, enemy, side) * it->second; + switch (it->first->getConditionStrength()) + { + case StrategyCondition::Required: + case StrategyCondition::RequiredPositive: + if (0.0f > value) + return 0.0f; + break; + case StrategyCondition::RequiredNegative: + if (value > 0.0f) + return 0.0f; + break; + case StrategyCondition::Advisory: + break; + case StrategyCondition::AdvisoryPositive: + if (0.0f > value) + value = 0.0f; + break; + case StrategyCondition::AdvisoryNegative: + if (value > 0.0f) + value = 0.0f; + break; + default: + break; + } + sum += value; + } + StrategyManager::getInstance()->isDebugEnabled(); // empty debug branch in the image + return sum; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.h new file mode 100644 index 000000000..f9badfb94 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.h @@ -0,0 +1,38 @@ +// A weighted list of strategy conditions; Strategy uses one as its prerequisite and one as its +// abort condition. Evidence: libaidll.so (ia-32) 0x334630..0x334AA0. Conditions are borrowed +// (the destructor frees only the list nodes); the StrategyManager owns them. + +#ifndef AI_AIDLL_AI_AISTRATEGIC_STRATEGYPREREQUISITE_H +#define AI_AIDLL_AI_AISTRATEGIC_STRATEGYPREREQUISITE_H + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +class StrategyCondition; + +class StrategyPrerequisite +{ +public: + explicit StrategyPrerequisite(const std::string& name); + ~StrategyPrerequisite(); + + void addCondition(StrategyCondition* condition, float weight); + StrategyCondition* popFirstCondition(); + // isActive: the strategy being scored is the current one (Strategy passes previous == this); + // only then do abort conditions count. + float evaluate(float* friendly, float* enemy, bool isActive, int side); + + /* +0x00 */ std::list > m_conditions; + /* +0x04 */ std::string m_name; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGIC_STRATEGYPREREQUISITE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp new file mode 100644 index 000000000..6d3988dee --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp @@ -0,0 +1,242 @@ +// AI landing zones. Evidence: libaidll.so (ia-32) 0x334BB0..0x335480. + +#include "AILandingZone.h" + +#include +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3353D0, __tcf_0 0x335430, _GLOBAL__I 0x335460). +#include + +#include "../Main/AIRandom.h" +#include "../Main/IAIPathfinding.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// The image's inline uniform draw: lo + next() * 2^-32 * (hi - lo), unrounded until the store. +float randomBetween(float lo, float hi) +{ + const float range = hi - lo; + return lo + AIRandom::m_instance->next() * 2.3283064e-10f * range; +} + +} // namespace + +// ELF 0x334BB0 (C2; C1 0x334C40). +AILandingZone::AILandingZone(const std::string& name, int id, const Vec2& minCorner, + const Vec2& maxCorner, float height, + LandingZoneDirection beachDirection) + : m_minCorner(minCorner) + , m_maxCorner(maxCorner) + , m_beachDirection(beachDirection) + , m_name(name) + , m_id(id) + , m_height(height) +{ + if (m_minCorner.x > m_maxCorner.x) + { + const float x = m_minCorner.x; + m_minCorner.x = m_maxCorner.x; + m_maxCorner.x = x; + } + if (m_minCorner.y > m_maxCorner.y) + { + const float y = m_minCorner.y; + m_minCorner.y = m_maxCorner.y; + m_maxCorner.y = y; + } +} + +// ELF 0x334CD0 (D2; D1 0x334D20): the name is the only member with a destructor. +AILandingZone::~AILandingZone() +{ +} + +// ELF 0x334D70. The approach comes from the side opposite the beach; the modulo keeps the shipped +// sign test on the sum, not on the remainder. The pathfinder singleton is read once. +bool AILandingZone::getApproachPosition(int map, int type, Vec3& position, float distance) const +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + int attempts = 0; + const int opposite = m_beachDirection + 2; + const LandingZoneDirection side = + static_cast(opposite < 0 ? opposite % 4 + 4 : opposite % 4); + getRandomPosOnSide(side, map, position, distance); + do + { + if (pathfinding->isValidPosition(map, type, position, true)) + return true; + ++attempts; + getRandomPosOnSide(side, map, position, distance); + } while (attempts < 20); + return false; +} + +// ELF 0x334E60. +bool AILandingZone::getBeachPosition(int map, Vec3& position) const +{ + getRandomPosOnSide(m_beachDirection, map, position, 0.0f); + return true; +} + +// ELF 0x334EB0. +LandingZoneDirection AILandingZone::getBeachDirection() const +{ + return m_beachDirection; +} + +// ELF 0x334EC0. +void AILandingZone::setBeachDirection(LandingZoneDirection direction) +{ + m_beachDirection = direction; +} + +// ELF 0x334ED0. +bool AILandingZone::isInZone(const Vec2& position) const +{ + return insideCornerBox(position, m_minCorner, m_maxCorner); +} + +// ELF 0x334F10. +bool AILandingZone::isInZone(const Vec3& position) const +{ + Vec2 xz; + xz.x = 0.0f; + xz.y = 0.0f; + vec3ToVec2XZ(position, xz); + return isInZone(xz); +} + +// ELF 0x334F70. The direction from the centre is normalised inline as the image does elsewhere: +// left alone within FLT_EPSILON of unit length, zeroed below FLT_EPSILON squared, otherwise scaled +// by 1 / sqrt. Both tests are written so that NaN takes the scaling arm, as the shipped `ja` / +// `jbe` pair does. +float AILandingZone::getDistanceSqr(const Vec2& position) const +{ + if (isInZone(position)) + return 0.0f; + + Vec2 centre; + centre.x = 0.0f; + centre.y = 0.0f; + Vec2 direction; + direction.x = 0.0f; + direction.y = 0.0f; + Vec2 exit; + exit.x = 0.0f; + exit.y = 0.0f; + getBoxCentre(m_minCorner, centre, m_maxCorner); + direction.x = position.x - centre.x; + direction.y = position.y - centre.y; + const float lengthSq = direction.x * direction.x + direction.y * direction.y; + if (!(1.1920929e-07f > std::fabs(lengthSq - 1.0f))) + { + if (!(1.4210855e-14f > std::fabs(lengthSq))) + { + const float inverse = 1.0f / std::sqrt(lengthSq); + direction.x = direction.x * inverse; + direction.y = inverse * direction.y; + } + else + { + direction.x = 0.0f; + direction.y = 0.0f; + } + } + hfe::getIntersection(m_minCorner, m_maxCorner, direction, centre, exit); + const float dx = position.x - exit.x; + const float dy = position.y - exit.y; + return dx * dx + dy * dy; +} + +// ELF 0x335120. +float AILandingZone::getDistanceSqr(const Vec3& position) const +{ + Vec2 xz; + xz.x = 0.0f; + xz.y = 0.0f; + vec3ToVec2XZ(position, xz); + return getDistanceSqr(xz); +} + +// ELF 0x335170. +const std::string& AILandingZone::getName() const +{ + return m_name; +} + +// ELF 0x335180. +int AILandingZone::getId() const +{ + return m_id; +} + +// ELF 0x335190. +const Vec2& AILandingZone::getMinCorner() const +{ + return m_minCorner; +} + +// ELF 0x3351A0. +const Vec2& AILandingZone::getMaxCorner() const +{ + return m_maxCorner; +} + +// ELF 0x3351B0. +void AILandingZone::setMinCorner(const Vec2& corner) +{ + m_minCorner = corner; +} + +// ELF 0x3351D0. +void AILandingZone::setMaxCorner(const Vec2& corner) +{ + m_maxCorner = corner; +} + +// ELF 0x3351F0. Both ranges are taken before the first draw; x is drawn before z. +void AILandingZone::getRandomPosOnSide(LandingZoneDirection side, int, Vec3& position, + float distance) const +{ + float fromX; + float toX; + float fromZ; + float toZ; + switch (side) + { + case LZXMin: + fromX = toX = m_minCorner.x + distance; + fromZ = m_minCorner.y; + toZ = m_maxCorner.y; + break; + case LZZMin: + fromX = m_minCorner.x; + toX = m_maxCorner.x; + fromZ = toZ = m_minCorner.y + distance; + break; + case LZXMax: + fromX = toX = m_maxCorner.x - distance; + fromZ = m_minCorner.y; + toZ = m_maxCorner.y; + break; + case LZZMax: + fromX = m_minCorner.x; + toX = m_maxCorner.x; + fromZ = toZ = m_maxCorner.y - distance; + break; + default: + fromX = toX = fromZ = toZ = 0.0f; + break; + } + position.x = randomBetween(fromX, toX); + position.y = m_height; + position.z = randomBetween(fromZ, toZ); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.h new file mode 100644 index 000000000..bdc195f4a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZone.h @@ -0,0 +1,81 @@ +// A rectangular landing zone on the XZ plane with a beach side, used by the amphibious waypoints. +// Not polymorphic: the image has no vtable and no deleting destructor for it. sizeof is 32 (0x20) +// in the ia-32 image with its libstdc++ string; the native size differs. +// Placement in AIStrategicEntity is [INFERRED]: the TU sits in the image between +// StrategyPrerequisite and AIStrategicArea. +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONE_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONE_H + +#include + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// The side of the zone a beach landing comes from. Names and values from the image's stream +// operators (ELF 0x3C89A0 / 0x3C8A20), which also accept them without the "LZ" prefix. +enum LandingZoneDirection : int +{ + LZXMin = 0, + LZZMin = 1, + LZXMax = 2, + LZZMax = 3, + LZUndefined = 4 +}; + +class AILandingZone +{ +public: + // The corners are sorted per axis after the copy, so minCorner <= maxCorner. + AILandingZone(const std::string& name, int id, const Vec2& minCorner, const Vec2& maxCorner, + float height, LandingZoneDirection beachDirection); + ~AILandingZone(); + + // A random position on the side opposite the beach, `distance` inside the zone, that the + // pathfinder accepts (IAIPathfinding::isValidPosition(map, type, position, true)); up to 21 + // draws. False when none was accepted; `position` then holds the last draw. + bool getApproachPosition(int map, int type, Vec3& position, float distance) const; + // A random position on the beach side's edge. Always true. + bool getBeachPosition(int map, Vec3& position) const; + LandingZoneDirection getBeachDirection() const; + void setBeachDirection(LandingZoneDirection direction); + // Inclusive XZ box test. + bool isInZone(const Vec2& position) const; + bool isInZone(const Vec3& position) const; + // 0 inside the zone; otherwise the squared distance to where the ray from the centre towards + // `position` leaves the box. + float getDistanceSqr(const Vec2& position) const; + float getDistanceSqr(const Vec3& position) const; + const std::string& getName() const; + int getId() const; + const Vec2& getMinCorner() const; + const Vec2& getMaxCorner() const; + void setMinCorner(const Vec2& corner); + void setMaxCorner(const Vec2& corner); + // A uniformly random point on the line `distance` inside the given side, at the zone's height. + // An undefined side yields (0, height, 0); both random draws are still taken. `map` is unused. + void getRandomPosOnSide(LandingZoneDirection side, int map, Vec3& position, + float distance) const; + +private: + // AIStrategicArea::attachLandingZone / ::listLandingZones (ELF 0x33B580, 0x33B7A0) and + // AILandingZoneManager::activeZone / ::listZones read m_name at +0x14 directly instead of + // calling getName. [INFERRED] friendship. + friend class AIStrategicArea; + friend class AILandingZoneManager; // activeZone / listZones, same direct read + + /* +0x00 */ Vec2 m_minCorner; + /* +0x08 */ Vec2 m_maxCorner; + /* +0x10 */ LandingZoneDirection m_beachDirection; + /* +0x14 */ std::string m_name; + /* +0x18 */ int m_id; + /* +0x1C */ float m_height; // y of every position the zone hands out [INFERRED name] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp index 1a62116de..448b9fcf9 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp @@ -1,10 +1,15 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AILandingZoneManager operations. + +// static init: ELF 0x39AA80, __tcf_0 0x39AB10, _GLOBAL__I 0x39AB40: stream Init precedes the manager. +#include #include "AILandingZoneManager.h" -#include "../Main/AIDllFrontier.h" +#include + +#include "AILandingZone.h" +#include "../AIUtils/checkPointer.h" +#include "../AIUtils/DebugRendering/AIRenderUtil.h" // updateNumberOfLandingZones namespace dice { namespace hfe { @@ -12,16 +17,18 @@ namespace ai { AILandingZoneManager* AILandingZoneManager::m_instance = 0; -// Initializes an inactive landing-zone manager and explicitly resizes its new vector to zero. +// ELF 0x399980 (C1; C2 0x399B50). Initializes an inactive landing-zone manager and explicitly +// resizes its new vector to zero. AILandingZoneManager::AILandingZoneManager() - : m_unresolved1C(0) + : m_activeZone(0) , m_unresolved20(0) , m_activeZoneName("No valid zone is active") { m_zones.resize(0); } -// Constructs the landing-zone manager at DLL load. BF2AI::clear owns its later destruction. +// static init: ELF 0x39AA80 (with __tcf_0 0x39AB10 and _GLOBAL__I 0x39AB40): +// constructs the landing-zone manager at DLL load. BF2AI::clear owns its later destruction. namespace { struct AILandingZoneManagerInstaller @@ -36,17 +43,148 @@ AILandingZoneManagerInstaller g_aiLandingZoneManagerInstaller; } // namespace -// [FRONTIER] - the rest of the class. Addresses and sizes are in the header. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - +// ELF 0x399C50 (D1; D0 0x399D60): deletes every non-null zone (AILandingZone D1 + operator delete), +// then the name, the vector and the map go as members. m_instance is not cleared. AILandingZoneManager::~AILandingZoneManager() { - BF2_AI_FRONTIER("dice::hfe::ai::AILandingZoneManager::~AILandingZoneManager"); + for (std::vector::iterator zone = m_zones.begin(); zone != m_zones.end(); ++zone) + { + if (*zone) + delete *zone; + } +} + +// ELF 0x39A350: deletes the zones (as above), zeroes +0x20 and +0x1C, renames the active zone +// "No valid zone is active" and empties the zone vector (resize(0)); the name map is kept. +bool AILandingZoneManager::reset() +{ + for (std::vector::iterator zone = m_zones.begin(); zone != m_zones.end(); ++zone) + { + if (*zone) + delete *zone; + } + m_unresolved20 = 0; + m_activeZone = 0; + m_activeZoneName = "No valid zone is active"; + m_zones.resize(0, 0); + return true; +} + +// ELF 0x399E70. +const std::string& AILandingZoneManager::activeZone() +{ + return m_activeZone ? m_activeZone->m_name : m_activeZoneName; +} + +// ELF 0x399E90. +const std::string& AILandingZoneManager::activeZone(int index) +{ + if (index < static_cast(m_zones.size()) && index >= 0) + { + m_activeZone = m_zones[index]; + return m_activeZone->m_name; + } + m_activeZone = 0; + return m_activeZoneName; +} + +// ELF 0x399ED0. +const std::string& AILandingZoneManager::activeZone(const std::string& name) +{ + std::map::iterator it = m_zonesByName.find(name); + if (it == m_zonesByName.end()) + { + m_activeZone = 0; + return m_activeZoneName; + } + m_activeZone = it->second; + return m_activeZone->m_name; +} + +// ELF 0x399F40. +AILandingZone* AILandingZoneManager::getActiveZone() +{ + return m_activeZone; +} + +// ELF 0x399F50. +AILandingZone* AILandingZoneManager::getAILandingZone(int index) +{ + if (index < static_cast(m_zones.size()) && index >= 0) + return m_zones[index]; + return 0; +} + +// ELF 0x399F80. +AILandingZone* AILandingZoneManager::getAILandingZone(const std::string& name) +{ + std::map::iterator it = m_zonesByName.find(name); + if (it == m_zonesByName.end()) + return 0; + return it->second; +} + +// ELF 0x399FE0. +int AILandingZoneManager::getNumberOfLandingZones() const +{ + return static_cast(m_zones.size()); +} + +// ELF 0x39A000. AIRenderUtil::m_instance is not null-checked. +AILandingZone* AILandingZoneManager::createLandingZone(const std::string& name, const Vec2& minCorner, + const Vec2& maxCorner, float height, + LandingZoneDirection beachDirection) +{ + const int id = static_cast(m_zones.size()); + AILandingZone* const zone = + checkPointer(new AILandingZone(name, id, minCorner, maxCorner, height, beachDirection)); + m_zones.resize(m_zones.size() + 1); + m_zones[id] = zone; + m_activeZone = zone; + m_zonesByName.insert(std::make_pair(name, zone)); + AIRenderUtil::m_instance->updateNumberOfLandingZones(); + return zone; +} + +// ELF 0x39A460. +bool AILandingZoneManager::isInsideLandingZone(const Vec3& position) const +{ + AILandingZone* zone; + return isInsideLandingZone(position, zone); +} + +// ELF 0x39A4A0: `zone` receives the zone, 0 when none contains the position. +bool AILandingZoneManager::isInsideLandingZone(const Vec3& position, AILandingZone*& zone) const +{ + for (std::vector::const_iterator it = m_zones.begin(); it != m_zones.end(); ++it) + { + if ((*it)->isInZone(position)) + { + zone = *it; + return true; + } + } + zone = 0; + return false; } -void AILandingZoneManager::reset() +// ELF 0x39A510. Null slots are skipped; the corners use the image's inlined x/y Vec2 output and +// the direction prints as an int. +std::string AILandingZoneManager::listZones() { - BF2_AI_FRONTIER("dice::hfe::ai::AILandingZoneManager::reset"); + std::stringstream stream; + for (std::vector::iterator it = m_zones.begin(); it != m_zones.end(); ++it) + { + AILandingZone* const zone = *it; + if (!zone) + continue; + const Vec2& minCorner = zone->getMinCorner(); + const Vec2& maxCorner = zone->getMaxCorner(); + stream << zone->m_name << " " << minCorner.x << '/' << minCorner.y << " " << maxCorner.x + << '/' << maxCorner.y << " " << static_cast(zone->getBeachDirection()) + << std::endl; + } + return stream.str(); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h index 9d4a74e4a..bb029d795 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h @@ -1,6 +1,5 @@ // Owns AI landing zones. Constructed when the DLL loads and destroyed by BF2AI::clear. // reset is its only virtual method; the destructor is nonvirtual. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H // [INFERRED] guard style @@ -10,6 +9,8 @@ #include #include +#include "../../../../Math/Vec3.h" + // Vec2 and Vec3 are Math aliases, so do not forward-declare them as classes in this namespace. namespace dice { namespace hfe { @@ -17,7 +18,7 @@ namespace ai { class AILandingZone; -// [UNRESOLVED] enumerators - one dword at `createLandingZone`'s last parameter. +// Defined, with its enumerators, in AILandingZone.h. enum LandingZoneDirection : int; // sizeof is 40 (0x28) in retail, from the `operator new(0x28)` in this file's static initialiser @@ -27,20 +28,36 @@ class AILandingZoneManager public: AILandingZoneManager(); - // not virtual - see the header block. , . - ~AILandingZoneManager(); // [FRONTIER] + // Not virtual. Deletes the zones. + ~AILandingZoneManager(); // ELF 0x399C50 (D1; D0 0x399D60) // The class's only virtual, and the only entry in its vtable. - virtual void reset(); // [FRONTIER] - - // - written inline because the shipped body is the vector size and nothing - // else. This is the method `AIRenderUtil`'s constructor calls. - int getNumberOfLandingZones() const - { - return static_cast(m_zones.size()); - } - - // [FRONTIER] Remaining landing-zone operations require implementation. + // ELF 0x39A350: deletes the zones and answers true (`mov $0x1,%eax`). + virtual bool reset(); + + // ELF 0x399E70 / 0x399E90 / 0x399ED0: the active zone's name, or "No valid zone is active" + // when there is none; the int and name forms first select the zone (0 when not found). + const std::string& activeZone(); + const std::string& activeZone(int index); + const std::string& activeZone(const std::string& name); + AILandingZone* getActiveZone(); // ELF 0x399F40 + + // ELF 0x399F50: 0 for an index out of range. + AILandingZone* getAILandingZone(int index); + // ELF 0x399F80: the zone registered under the name, 0 when there is none. + AILandingZone* getAILandingZone(const std::string& name); + // ELF 0x399FE0. This is the method `AIRenderUtil`'s constructor calls. + int getNumberOfLandingZones() const; + + // ELF 0x39A000: a new zone with the next id, registered by name and made active. + AILandingZone* createLandingZone(const std::string& name, const Vec2& minCorner, + const Vec2& maxCorner, float height, + LandingZoneDirection beachDirection); + // ELF 0x39A460 / 0x39A4A0: the first zone containing the position. + bool isInsideLandingZone(const Vec3& position) const; + bool isInsideLandingZone(const Vec3& position, AILandingZone*& zone) const; + // ELF 0x39A510: " " per zone. + std::string listZones(); // set by this file'S static initialiser, not by any `init`. See the header block. static AILandingZoneManager* m_instance; @@ -50,8 +67,9 @@ class AILandingZoneManager /* +0x04 */ std::map m_zonesByName; /* +0x10 */ std::vector m_zones; // what getNumberOfLandingZones measures - // [UNRESOLVED] Two words initialized to zero; their roles are not yet established. - /* +0x1C */ int m_unresolved1C; + // The active zone (activeZone / createLandingZone), 0 for none. + /* +0x1C */ AILandingZone* m_activeZone; + // [UNRESOLVED] Initialized to zero; no reader in this class. /* +0x20 */ int m_unresolved20; // constructed from A literal, and the literal is the class's whole personality: diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp index 1c78ed584..b779e3be9 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp @@ -1,8 +1,11 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIStrategicArea operations. - #include "AIStrategicArea.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x33F260, __tcf_0 0x33F2C0, _GLOBAL__I 0x33F2F0). +#include +#include #include // the two centre-to-corner distances +#include // listLandingZones #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" @@ -10,13 +13,28 @@ #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" #include "../AIBot/SquadManager.h" +#include "../AIBot/SquadCoordinator.h" #include "../AIBotBehaviour/CustomCurve.h" #include "../AIStrategic/SAI.h" +#include "../AIStrategic/Strategy.h" +#include "AIStrategicObjectManager.h" +#include "../AIBot/BotMain.h" +#include "../Main/IBotManager.h" +#include "../Main/AIMain.h" // IAIMain::m_instance->getSAI #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIBot/SquadMember.h" // isSameWaypointList +#include "../AIBot/WPMoveTo.h" +#include "../AIBot/WPAltitudeMoveTo.h" +#include "../Main/AIRandom.h" +#include "SAWayPoint.h" +#include "AILandingZone.h" +#include "AILandingZoneManager.h" +#include "../AIKnowledge/AIInformationGrid.h" #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame - the control-point queries #include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain::getTerrainAltitude #include "../../../../Math/Vec3.h" // vec3ToVec2XZ / vec2ToVec3XZ @@ -25,6 +43,86 @@ namespace dice { namespace hfe { namespace ai { +namespace { + +// libaidll.so: std::list<(anonymous namespace)::ObjectSearchInfo> in AIStrategicArea.cpp, node +// 0x14 = twelve payload bytes, written as {object, predecessor, cost} by getDistances. +// [INFERRED] field names. +struct ObjectSearchInfo +{ + ObjectSearchInfo(AIStrategicObject* o, AIStrategicObject* p, float c) + : object(o), previous(p), cost(c) {} + AIStrategicObject* object; + AIStrategicObject* previous; + float cost; +}; + +// ELF vtable 0x4BF5F0: this TU's own predicate (mangled under AIStrategicArea.cpp's anonymous +// namespace; BotSpawner.cpp has a separate class of the same name). One slot, no destructor. +// Layout: vptr, side (+4). +class FreeUnitPred : public IAIInformationGridPredicate +{ +public: + explicit FreeUnitPred(int side) : m_side(side) {} + + // ELF 0x340B90. A known mobile unit (not types 0x80 / 0x200000) passes when it or one of its + // secondary objects is unoccupied. Only the root record's type and mobility are checked. + bool includeInformation(Information* information) const + { + if (!information->getUnit() || !information->hasMobile()) + return false; + const unsigned int flags = information->getObjectTypeFlags(); + if ((flags & 0x80u) || (flags & 0x200000u)) + return false; + + int iterator = information->getFirstSecondaryObjectIterator(); + Information* current = information; + while (current) + { + if (!current->getUnit()->isOccupied()) + return true; + // The ELF captures the manager before the secondary-object call. + InformationManager* const manager = informationManager; + const unsigned int handle = information->getSecondaryObject(iterator, m_side); + current = manager->getInformation(handle); + } + return false; + } + + int m_side; +}; + +} // namespace + +// ELF 0x335480 (C2; C1 0x335850). An area with explicit bounds: control point id -1, no +// control-point phase, the corner stored before the shared tail runs. +AIStrategicArea::AIStrategicArea(const std::string& name, Vec2 topLeft, Vec2 centre, float height, + float radius) + : AIStrategicObject(radius, height) + , m_list268() + , m_centre(topLeft) + , m_mapData(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) + , m_neighbours() + , m_neighbouringObjects() + , m_name(name) + , m_objectTypeFlags(0) + , m_controlPointId(static_cast(-1)) + , m_landingZones() + , m_i340(0) + , m_showNeighbours(false) +{ + m_i400 = -1; + m_visible = true; + m_statusChanged = false; + m_v416.x = 0.0f; + m_v416.y = 0.0f; + m_v416.z = 0.0f; + m_fromControlPoint = false; + m_orderPosesInitialised = false; + internalConstructorCall(topLeft, centre); +} + +// ELF 0x335B70 (C2; C1 0x335E70). // Creates a control-point area with an unset-height sentinel and one record per pathfinding map. AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int controlPointId, float radius) @@ -39,30 +137,39 @@ AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int controlPo , m_controlPointId(controlPointId) , m_landingZones() , m_i340(0) - , m_b358(false) + , m_showNeighbours(false) { // The tail. Everything above this point lands before the three list members are constructed, so // it cannot be body code; everything here lands after them, so it cannot be an initialiser. m_i400 = -1; - m_b404 = true; + m_visible = true; m_statusChanged = false; - m_i416 = 0; - m_i420 = 0; - m_i424 = 0; + m_v416.x = 0.0f; + m_v416.y = 0.0f; + m_v416.z = 0.0f; m_fromControlPoint = true; // the phase selector - see the header m_orderPosesInitialised = false; } -// Eleven hundred bytes: the per-map array, four lists, the name, and whatever the twenty-eight -// unwritten slots own. Not reachable before shutdown - `AIStrategicObjectManager`'s destructor is -// the only caller and it already carries a guarded seam for its area delete loop. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x336F90 (D2; D1 0x337410, D0 0x337890; from AIStrategicObjectManager::reset/destructor): +// delete[] of the per-map data (+0x118), the two per-group flag arrays (+0x15C/+0x160) and the +// six per-group container arrays (+0x168..+0x17C, each element destroyed). The member lists, +// vectors and the name (+0x188 down to +0x10C) then go in reverse declaration order, then the base. AIStrategicArea::~AIStrategicArea() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::~AIStrategicArea"); + delete[] m_mapData; + delete[] m_flagsA; + delete[] m_flagsB; + delete[] m_listsA; + delete[] m_listsB; + delete[] m_mapsA; + delete[] m_mapsB; + delete[] m_mapsC; + delete[] m_mapsD; } // Returns type code zero. [UNRESOLVED] Its meaning is not established as a StrategicObjectType. +// ELF 0x340B70. int AIStrategicArea::getType() const { return 0; @@ -70,6 +177,7 @@ int AIStrategicArea::getType() const // - one load. The flag word an `.ai` script fills through // `aiStrategicArea.addObjectTypeFlag`. +// ELF 0x340B80. int AIStrategicArea::getObjectTypeFlags() const { return m_objectTypeFlags; @@ -77,12 +185,14 @@ int AIStrategicArea::getObjectTypeFlags() const // Returns twice the center-to-side-corner distance along X or Z. // Side indices are one-based and must be valid. +// ELF 0x33B540. float AIStrategicArea::getXExtent(int side) const { const float half = m_position[side - 1].x - m_centre.x; return half + half; } +// ELF 0x33B560. float AIStrategicArea::getZExtent(int side) const { const float half = m_position[side - 1].y - m_centre.y; @@ -92,6 +202,7 @@ float AIStrategicArea::getZExtent(int side) const // The query's own result and // its fourth (active) output are discarded; the local is seeded true only to be passed along. // Any assigned id answers true, whatever the engine wrote; the singleton is not null-checked. +// ELF 0x33A040. bool AIStrategicArea::getControlPointPosAndRadius(Vec3& position, float& radius) { bool active = true; @@ -103,6 +214,7 @@ bool AIStrategicArea::getControlPointPosAndRadius(Vec3& position, float& radius) } // Resolves control-point position, height, and ownership after world objects are available. +// ELF 0x337E20. void AIStrategicArea::postLoadInit() { if (m_fromControlPoint) @@ -169,8 +281,8 @@ void AIStrategicArea::postLoadInit() } } -// Initializes per-vehicle-group area arrays, with at least one element in each allocation. -// [FRONTIER] The destructor must release these arrays when its implementation is completed. +// ELF 0x336170. Initializes per-vehicle-group area arrays, with at least one element in each +// allocation (each new[] goes through checkPointer); the destructor releases them. void AIStrategicArea::internalConstructorCall(const Vec2& topLeft, const Vec2& centre) { // unused, and deliberately so - see the note above. @@ -198,8 +310,8 @@ void AIStrategicArea::internalConstructorCall(const Vec2& topLeft, const Vec2& c m_listsA = checkPointer(new std::list >[groups]); m_listsB = checkPointer(new std::list >[groups]); - m_mapsA = checkPointer(new std::map[groups]); - m_mapsB = checkPointer(new std::map[groups]); + m_mapsA = checkPointer(new std::map >[groups]); + m_mapsB = checkPointer(new std::map >[groups]); m_mapsC = checkPointer(new std::map[groups]); m_mapsD = checkPointer(new std::map[groups]); @@ -231,6 +343,7 @@ void AIStrategicArea::internalConstructorCall(const Vec2& topLeft, const Vec2& c } // Raises the stored area height to the terrain height when the terrain is higher. +// ELF 0x337D20. void AIStrategicArea::init() { const IAITerrain* const terrain = @@ -257,6 +370,7 @@ void AIStrategicArea::init() } // Resolves order positions to the navmesh and converts them to area-relative offsets once. +// ELF 0x336E80. void AIStrategicArea::initOrderPoses() { Vec3 areaPosition; @@ -289,6 +403,7 @@ void AIStrategicArea::initOrderPoses() // Returns the area position plus the selected map's delta; map -1 omits the delta. // The second parameter is unused; [UNRESOLVED] its original purpose is unknown. +// ELF 0x339830. Vec3 AIStrategicArea::getOrderPos(int map, int unused) const { (void)unused; @@ -310,22 +425,69 @@ Vec3 AIStrategicArea::getOrderPos(int map, int unused) const } // Tests a StrategicObjectType bit position in the object flags. +// ELF 0x33A0B0. bool AIStrategicArea::hasObjectTypeFlag(StrategicObjectType type) const { return ((m_objectTypeFlags >> type) & 1) != 0; } -// Remaining virtual work keeps named stops. Live strategic ticks now reach the recovered update; -// later dirty/assignment/lifetime behavior remains separately bounded. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -void AIStrategicArea::updateTemperature(const Strategy*, int) +// ELF 0x33BD30. +bool AIStrategicArea::isLandingZoneUser(int equipment) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::updateTemperature"); + return (m_i340 >> equipment) & 1; +} + +// ELF 0x33A0F0. Both temperature pairs of the side (+0xA0/+0xA8 + 4 * side, i.e. m_f164[side - 1] +// and m_f164[side + 1]) are scaled by the strategy's object modifiers for the area's status: one +// factor per object type flag the area has (types 0..20), then the status factor (Owned: Front +// when a hostile neighbour exists, else Safe; Hostile: Enemy; Neutral: Neutral), then the +// strategy's specific modifier for this object. Answers the scaled first temperature. +float AIStrategicArea::updateTemperature(const Strategy* strategy, int side) +{ + const float* const modifiers = strategy->getStrategicObjectsModifiers(getStatus(side)); + for (int type = 0; type <= 20; ++type) + { + if (hasObjectTypeFlag(static_cast(type))) + { + m_f164[side - 1] *= modifiers[type]; + m_f164[side + 1] *= modifiers[type]; + } + } + switch (getStatus(side)) + { + case StatusMap::Owned: + if (hasNeighbourWithStatus(StatusMap::Hostile, side)) + { + m_f164[side - 1] *= modifiers[Front]; + m_f164[side + 1] *= modifiers[Front]; + } + else + { + m_f164[side - 1] *= modifiers[Safe]; + m_f164[side + 1] *= modifiers[Safe]; + } + break; + case StatusMap::Hostile: + m_f164[side - 1] *= modifiers[Enemy]; + m_f164[side + 1] *= modifiers[Enemy]; + break; + case StatusMap::Neutral: + m_f164[side - 1] *= modifiers[NeutralType]; + m_f164[side + 1] *= modifiers[NeutralType]; + break; + default: + break; + } + m_f164[side - 1] *= strategy->getSpecificStrategicObjectModifier(m_index); + m_f164[side + 1] *= strategy->getSpecificStrategicObjectModifier(m_index); + AIStrategicObjectManager::getInstance(); // result unused in the image + return m_f164[side - 1]; } // Parameter types // are mangled; neither body materializes a return. Names of local aggregates are inferred. +// ELF 0x337FF0. void AIStrategicArea::update(int side, ISAI* sai, bool& changed) { IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); @@ -540,12 +702,17 @@ void AIStrategicArea::update(int side, ISAI* sai, bool& changed) #endif } -int AIStrategicArea::getChangedAttackDefence(int) +// ELF 0x337FC0: 1 when the last update changed the status and the side does not own the area. +int AIStrategicArea::getChangedAttackDefence(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::getChangedAttackDefence"); + int changed = 0; + if (m_statusChanged && getStatus(side) != StatusMap::Owned) + changed = 1; + return changed; } // Full pair : fresh game/id after the flag callback. +// ELF 0x3399D0. float AIStrategicArea::getControlPointTakeOverCounter() { if (hasObjectTypeFlag(ControlPoint)) @@ -554,32 +721,74 @@ float AIStrategicArea::getControlPointTakeOverCounter() return 1.0f; } -bool AIStrategicArea::isEnemyTakingOverBase(int) +// ELF 0x338BF0. +bool AIStrategicArea::isEnemyTakingOverBase(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isEnemyTakingOverBase"); + return m_enemyTakeover[side - 1]; } -int AIStrategicArea::calculateDefenseNeed(int) +// ELF 0x338C10 (slot 11 answers a float in st0). Only owned areas need defence: +// (2 - SCurve(need input)) * (enemy battle strength + temperature), times 1.5 with a hostile +// neighbour, else 1.25 with a neutral one. +float AIStrategicArea::calculateDefenseNeed(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::calculateDefenseNeed"); + if (getStatus(side) != StatusMap::Owned) + return 0.0f; + float need = (2.0f - SCurve::calculate(m_needCurveInput[side - 1])) + * (m_enemyBattleStrength[side - 1] + m_f164[side - 1]); + if (hasNeighbourWithStatus(StatusMap::Hostile, side)) + need = need * 1.5f; + else if (hasNeighbourWithStatus(StatusMap::Neutral, side)) + need = need * 1.25f; + return need; } -int AIStrategicArea::calculateAttackValue(int) +// ELF 0x338CE0 (float). A not-owned area next to an owned one is worth +// (1 + need input) * temperature, times 1.5 next to a neutral area or 1.25 otherwise (no +// factor next to a hostile one), scaled by 100 / distance of the closest squad to the area's +// first position when that lies in (1, 100000), else 0; minus the attack cost. +float AIStrategicArea::calculateAttackValue(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::calculateAttackValue"); + float value = 0.0f; + if (getStatus(side) != StatusMap::Owned && hasNeighbourWithStatus(StatusMap::Owned, side)) + { + value = 1.0f; + value = value + m_needCurveInput[side - 1]; + value = value * m_f164[side - 1]; + if (!hasNeighbourWithStatus(StatusMap::Hostile, side)) + value = (hasNeighbourWithStatus(StatusMap::Neutral, side) ? 1.5f : 1.25f) * value; + const float x = m_position[0].x; + Vec3 position; + position.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getTerrainAltitude(x, m_position[0].y); + position.z = m_position[0].y; + position.x = x; + const float distance = SquadManager::m_instance->getDistanceToClosestSquad(position, side); + if (distance > 1.0f && 100000.0f > distance) + value = 1.0f / distance * 100.0f * value; + else + value = 0.0f; + } + value = value - calculateAttackCost(side); + return value; } -int AIStrategicArea::calculateAttackCost(int) +// ELF 0x338E60 (float): the enemy's second battle strength (-1 with fewer than two buckets) +// times (1.5 - 0.5 * need input) * (1 + friendly ratio). +float AIStrategicArea::calculateAttackCost(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::calculateAttackCost"); + const EnemyStatistics* const statistics = m_statistics[side - 1]; + const float strength = statistics->m_size > 1 ? statistics->m_strength[1] : -1.0f; + return strength * (1.5f - 0.5f * m_needCurveInput[side - 1]) * (1.0f + m_friendlyRatio[side - 1]); } -bool AIStrategicArea::isNeighbour(AIStrategicObject*) const +// ELF 0x339130. +bool AIStrategicArea::isNeighbour(AIStrategicObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isNeighbour"); + return std::find(m_neighbours.begin(), m_neighbours.end(), object) != m_neighbours.end(); } // Native vector scan, captured end, no null/side guards; first matching status wins. +// ELF 0x339330. bool AIStrategicArea::hasNeighbourWithStatus(StatusMap::Status status, int side) const { const auto end = m_neighbours.end(); @@ -591,12 +800,15 @@ bool AIStrategicArea::hasNeighbourWithStatus(StatusMap::Status status, int side) return false; } -bool AIStrategicArea::isNeighbouringObject(AIStrategicObject*) const +// ELF 0x339370. +bool AIStrategicArea::isNeighbouringObject(AIStrategicObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isNeighbouringObject"); + return std::find(m_neighbouringObjects.begin(), m_neighbouringObjects.end(), object) + != m_neighbouringObjects.end(); } // Applies the same scan to the second neighbor vector. +// ELF 0x3394C0. bool AIStrategicArea::hasNeighbouringObjectWithStatus(StatusMap::Status status, int side) const { const auto end = m_neighbouringObjects.end(); @@ -608,38 +820,318 @@ bool AIStrategicArea::hasNeighbouringObjectWithStatus(StatusMap::Status status, return false; } -bool AIStrategicArea::hasObjectTypeFlags(int) const +// ELF 0x33A0D0: all of the given flags. +bool AIStrategicArea::hasObjectTypeFlags(int flags) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::hasObjectTypeFlags"); + return (m_objectTypeFlags & flags) == flags; } -int AIStrategicArea::getTacticalStatus(int) const +// ELF 0x33A970: the int at +316 + 4 * side, i.e. m_i320 / m_i324 for sides 1 / 2. +int AIStrategicArea::getTacticalStatus(int side) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::getTacticalStatus"); + return side == 1 ? m_i320 : (side == 2 ? m_i324 : static_cast(m_controlPointId)); } +// ELF 0x339A30: the game reports the area's control point as active. The radius output is +// left uninitialised, as shipped. bool AIStrategicArea::isAreaTakeable() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::isAreaTakeable"); + bool active = false; + const unsigned int cp = m_controlPointId; + if (cp != static_cast(-1)) + { + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + float radius; + static_cast(CommonSingletonServer::m_iaiGame)->getControlPointInfo(cp, position, radius, active); + } + return active; +} + +// ELF 0x33A380: answers whether the assigned squad strength covers the need (+0xE0 + 4 side vs +// +0xD8 + 4 side). Otherwise the closest available squads are ordered to the area (y = m_f148) +// like collectAdditionalSquadResources does, while the assigned strength stays at or below the +// need (`jle` back to the query), so an exact match still asks for one more squad. +bool AIStrategicArea::collectSquadResources(int side, ISAI* sai) +{ + if (m_assignedSquadStrength[side - 1] >= m_resourceNeed[side - 1]) + return true; + int strength = 0; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + vec2ToVec3XZ(getPosition(side), position); + SquadManager* const squads = SquadManager::m_instance; + position.y = m_f148; + validateDistances(side); + if (m_assignedSquadStrength[side - 1] > m_resourceNeed[side - 1]) + return true; + do + { + SquadCoordinator* const squad = + squads->getClosestAvailableSquad(this, position, side, m_attack[side - 1], strength); + if (!squad) + break; + const StatusMap::Status status = getStatus(side); + bool defend; + if (status != StatusMap::Owned) + defend = m_enemyTakeover[side - 1] && status == StatusMap::Neutral; + else + defend = true; + if (defend) + sai->getCommanderInterface()->giveDefendOrder(position, squad); + else + sai->getCommanderInterface()->giveAttackOrder(position, squad); + m_assignedSquadStrength[side - 1] += strength; + } while (m_assignedSquadStrength[side - 1] <= m_resourceNeed[side - 1]); + return m_assignedSquadStrength[side - 1] >= m_resourceNeed[side - 1]; +} + +// ELF 0x33A530: up to `amount` of the closest available squads get an attack order to the +// area's position (y = m_f148), or a defend order when the side owns it or it is neutral and +// being taken over; their strength adds to m_assignedSquadStrength. Answers the squad count. +int AIStrategicArea::collectAdditionalSquadResources(int amount, int side, ISAI* sai) +{ + int count = 0; + int strength = 0; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + vec2ToVec3XZ(getPosition(side), position); + SquadManager* const squads = SquadManager::m_instance; + position.y = m_f148; + validateDistances(side); + for (; count < amount; ++count) + { + SquadCoordinator* const squad = + squads->getClosestAvailableSquad(this, position, side, m_attack[side - 1], strength); + if (!squad) + break; + const StatusMap::Status status = getStatus(side); + bool defend; + if (status != StatusMap::Owned) + defend = m_enemyTakeover[side - 1] && status == StatusMap::Neutral; + else + defend = true; + if (defend) + sai->getCommanderInterface()->giveDefendOrder(position, squad); + else + sai->getCommanderInterface()->giveAttackOrder(position, squad); + m_assignedSquadStrength[side - 1] += strength; + } + return count; +} + +// ELF 0x33BD50. +void AIStrategicArea::validateDistances(int side) +{ + if (!m_distancesDirty[side - 1]) + return; + m_distances[side - 1].clear(); + const int groups = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfVehicleGroups(); + if (!groups) + { + validateDistances(side, 0); + insertUnitDistances(side, 0); + return; + } + for (int group = 0; group < groups; ++group) + { + validateDistances(side, group); + insertUnitDistances(side, group); + } } -int AIStrategicArea::collectSquadResources(int, ISAI*) +// ELF 0x33BE30: a dirty group (m_flagsA/B[group]) is rebuilt: its distance list and both maps +// are cleared, then getDistances refills them for the group's bit. +void AIStrategicArea::validateDistances(int side, int group) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::collectSquadResources"); + bool* const flags = side == 1 ? m_flagsA : m_flagsB; + if (!flags[group]) + return; + flags[group] = false; + std::list >* const lists = side == 1 ? m_listsA : m_listsB; + std::map >* const routes = side == 1 ? m_mapsA : m_mapsB; + std::map* const costs = side == 1 ? m_mapsC : m_mapsD; + lists[group].clear(); + routes[group].clear(); + costs[group].clear(); + getDistances(side, lists[group], routes[group], costs[group], 1 << group); } -int AIStrategicArea::collectAdditionalSquadResources(int, int, ISAI*) +// ELF 0x33AAC0: a breadth-ordered relaxation over the area graph from this area. Entries +// {object, predecessor, cost} are appended to a FIFO (std::list<(anonymous)::ObjectSearchInfo>, +// node 0x14); the front entry is expanded when it improves the object's best cost +// (`fucompi; jbe` = skip unless costs[object] > cost or no cost yet) and the object allows one of +// the groups in groupMask. Edge cost: the 2-D distance between the side's positions (slot 3), +// times 5.0f into a hostile area and 1.1f into a neutral one (rodata 0x49CDAC / 0x49DCA8). +// The object's route is its predecessor's route with the object pushed to the front. Finally +// every (cost, object) of costs is appended to distances, which is sorted. +void AIStrategicArea::getDistances(int side, std::list >& distances, + std::map >& routes, + std::map& costs, int groupMask) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::collectAdditionalSquadResources"); + std::list open; + std::list route; + route.clear(); // 0x33AB53, on the fresh list + if (!allowsSomeVehicleGroups(groupMask)) + return; + open.push_back(ObjectSearchInfo(this, this, 0.0f)); + routes.insert(std::make_pair(static_cast(this), route)); + std::list::iterator it = open.begin(); + while (!open.empty()) + { + std::map::iterator found = costs.find(it->object); + if ((found == costs.end() || found->second > it->cost) + && it->object->allowsSomeVehicleGroups(groupMask)) + { + // A copy of the area's neighbour vector (+0x11C), then one entry per neighbour. + std::vector neighbours = + static_cast(it->object)->m_neighbours; + for (std::vector::iterator n = neighbours.begin(); + n != neighbours.end(); ++n) + { + const Vec2& from = it->object->getPosition(side); + const Vec2& to = (*n)->getPosition(side); + Vec2 delta; + delta.x = to.x - from.x; + delta.y = to.y - from.y; + float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y); + const StatusMap::Status status = (*n)->getStatus(side); + if (status == StatusMap::Neutral) + distance *= 1.1f; + else if (status == StatusMap::Hostile) + distance *= 5.0f; + open.push_back(ObjectSearchInfo(*n, it->object, it->cost + distance)); + } + if (found == costs.end()) + costs.insert(std::make_pair(it->object, it->cost)); + else + found->second = it->cost; + std::map >::iterator previous = + routes.find(it->previous); + std::map >::iterator own = + routes.find(it->object); + if (own == routes.end()) + { + routes.insert(std::make_pair(it->object, previous->second)); + own = routes.find(it->object); + } + else + { + own->second = previous->second; + } + own->second.push_front(it->object); + } + it = open.erase(it); + } + for (std::map::iterator c = costs.begin(); c != costs.end(); ++c) + distances.push_back(std::make_pair(c->second, c->first)); + distances.sort(); } -int AIStrategicArea::releaseSurplus(int) +// ELF 0x33BF90: merges the group's sorted distance list into the side's AreaDistanceInfo list +// (sorted by distance). An entry of equal distance gains the group's bit (`orl %eax,0x8(%edx)`); +// otherwise a new {1 << group, area, distance} is inserted before the first larger entry, and +// whatever is left is appended. +void AIStrategicArea::insertUnitDistances(int side, int group) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::releaseSurplus"); + AreaDistanceInfo info; + std::list& merged = m_distances[side - 1]; + std::list >& distances = (side == 1 ? m_listsA : m_listsB)[group]; + std::list::iterator at = merged.begin(); + std::list >::iterator it = distances.begin(); + for (; it != distances.end(); ++it) + { + // [CHOSEN] The image compares before the end test, reading the libstdc++ list header's + // payload once at the end; the end test runs first here (same result, no sentinel read). + while (at != merged.end() && it->first > at->m_distance) + ++at; + if (at == merged.end()) + break; + if (at->m_distance == it->first) + { + at->m_vehicleGroups |= 1 << group; + } + else + { + info.m_vehicleGroups = 1 << group; + info.m_area = static_cast(it->second); + info.m_distance = it->first; + merged.insert(at, info); + } + } + for (; it != distances.end(); ++it) + { + info.m_vehicleGroups = 1 << group; + info.m_area = static_cast(it->second); + info.m_distance = it->first; + merged.push_back(info); + } +} + +// ELF 0x33A6A0: with more strength assigned than needed, one assigned unit (+0x38 + 12 side, +// m_set68) is released. Units whose bot is gone are erased on the way. The pick prefers units +// not present in the area and, among those, the lowest strategic strength for the area's role +// (getStrategicStrengths()[attack ? 0 : 1], truncated to int). It is released through the side's +// SAI (slot 33) only if (assigned - strength) / need (integer division, `idivl` - a zero need +// traps as in the image) is still at least 1.1f; the assigned strength drops by that strength. +// The pick iterator starts value-initialised (null, not end()), as in the image: with no +// candidate the 1e9 start strength makes the ratio negative, so nothing is released. +bool AIStrategicArea::releaseSurplus(int side) +{ + std::set::iterator best = std::set::iterator(); + if (m_resourceNeed[side - 1] > m_assignedSquadStrength[side - 1]) + return false; + bool bestIsPresent = true; + int bestStrength = 1000000000; + std::set& units = m_set68[side - 1]; + for (std::set::iterator it = units.begin(); it != units.end();) + { + Bot* const bot = IBotManager::instance->getBotFromId(*it); + if (!bot) + { + units.erase(it++); + continue; + } + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + IPIUnit* const unit = information ? information->getUnit() : 0; + if (unit) + { + const bool present = isPresentUnit(*it, side); + if (!present || bestIsPresent) + { + const float* const strengths = unit->getStrategicStrengths(); + const int role = !m_attack[side - 1]; + if (static_cast(bestStrength) > strengths[role] || (!present && bestIsPresent)) + { + bestStrength = static_cast(strengths[role]); + bestIsPresent = present; + best = it; + } + } + } + ++it; + } + if (best == units.end()) + return true; + const int remaining = m_assignedSquadStrength[side - 1] - bestStrength; + const int ratio = remaining / m_resourceNeed[side - 1]; + if (static_cast(ratio) >= 1.1f) + { + m_assignedSquadStrength[side - 1] = remaining; + IAIMain::m_instance->getSAI(side)->releaseUnitFromObject(m_index, best, side); + } + return true; } // Both delegations stay virtual; // MSVC groups the Vec2/Vec3 overload slots in the opposite order to the ELF. +// ELF 0x33A990. float AIStrategicArea::gravity(const Vec3& position, int side) { Vec2 flat; @@ -651,6 +1143,7 @@ float AIStrategicArea::gravity(const Vec3& position, int side) // The position is read directly // using side-1. x87 keeps the arithmetic wide until the float call argument. +// ELF 0x33A9F0. float AIStrategicArea::gravity(const Vec2& position, int side) { const double dx = static_cast(position.x) - m_position[side - 1].x; @@ -666,23 +1159,502 @@ float AIStrategicArea::gravity(const Vec2& position, int side) return gravity(static_cast(distance), side); } -bool AIStrategicArea::retainBot(int, int, ISAI*) +// ELF 0x33EFA0: true when the bot's current equipment is a known mobile unit; the +// present-set find and the local object list are unused in the image. +bool AIStrategicArea::retainBot(int side, int unit, ISAI*) +{ + m_set92[side - 1].find(unit); + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information || !information->getMobile() || !information->getUnit()) + return false; + std::list objects; + return true; +} + +// ELF 0x33F0B0: the side's distance flag (+0x157 + side) and every vehicle-group flag of that +// side (+0x158 + 4 * side: m_flagsA for side 1, m_flagsB for side 2) are set. With zero vehicle +// groups the first flag is still written. +void AIStrategicArea::setAsDirty(int side) +{ + m_distancesDirty[side - 1] = true; + const int groups = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfVehicleGroups(); + bool* const flags = side == 1 ? m_flagsA : m_flagsB; + if (!groups) + { + flags[0] = true; + return; + } + for (int i = 0; i < groups; ++i) + flags[i] = true; +} + +// ELF 0x33F180. +bool AIStrategicArea::isInside(const Vec2& point) const +{ + return insideCentreBox(point, m_centre, m_position[0]); +} + +// ELF 0x3396E0: `lea eax, [this + 0x84]`. +const Vec2& AIStrategicArea::getCenterPosition() const +{ + return m_position[0]; +} + +// ELF 0x33F130. +bool AIStrategicArea::isInside(const Vec3& point) const +{ + Vec2 flat; + flat.x = 0.0f; + flat.y = 0.0f; + vec3ToVec2XZ(point, flat); + return isInside(flat); +} + +// ELF 0x33EF80. +Vec3 AIStrategicArea::getBotWaypoint(Vec3, Vec3 to, const std::vector&, int) +{ + return to; +} + +// ELF 0x339AB0: a position for a unit ordered to this area's control point. An active point +// (IAIGame +0x28) keeps `from` when it is within 0.8 radius and valid on the map (IAIPathfinding +// +0x30 with the area's island for the map); an inactive one uses twice the area's centre-to- +// position extent instead. Otherwise up to twenty-one randomized candidates around the point's +// centre (height m_f148; 0.8/radius resp. 1.0/twice-extent) are tried, then the object's order +// position (slot 5) is the answer. +void AIStrategicArea::getControlpointPos(AIStrategicObject* object, int side, int map, int unit, + const Vec3& from, Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::retainBot"); + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + bool active = true; + int tries = 0; + float radius = 1.0f; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + game->getControlPointInfo(m_controlPointId, centre, radius, active); + float scale; + float spread; + if (active) + { + const float dx = centre.x - from.x; + const float dy = centre.y - from.y; + const float dz = centre.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (0.8f * radius > distance + && pathfinding->isValidPosition(map, unit, from, m_mapData[map].m_island, true)) + { + position = from; + return; + } + scale = 0.8f; + spread = radius; + } + else + { + const Vec2 corner = m_centre; + const Vec2& anchor = getPosition(side); + const float hx = anchor.x - corner.x; + const float hy = anchor.y - corner.y; + const float extent = std::sqrt(hx * hx + hy * hy); + const float twice = extent + extent; + const float dx = centre.x - from.x; + const float dy = centre.y - from.y; + const float dz = centre.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (twice > distance + && pathfinding->isValidPosition(map, unit, from, m_mapData[map].m_island, true)) + { + position = from; + return; + } + scale = 1.0f; + spread = twice; + } + position.x = centre.x; + position.y = m_f148; + position.z = centre.z; + object->randomizeControlpointPos(scale, spread, position); + for (; tries <= 19; ++tries) + { + if (pathfinding->isValidPosition(map, unit, position, m_mapData[map].m_island, true)) + return; + position.x = centre.x; + position.y = m_f148; + position.z = centre.z; + object->randomizeControlpointPos(scale, spread, position); + } + // (sret, object, map, side): `movl 0x14(%ebp)` (map) before `0x10(%ebp)` (side) at 0x339CC8. + position = object->getOrderPos(map, side); +} + +// ELF 0x33C340: the unit's current equipment information decides the arm - object type bit +// 0x10 (`testb $0x10,0x4(%eax)`, the air bit the temperature samples also test) orders it as an +// air bot. The image does not check the information for null. eax is whatever the arm leaves. +void AIStrategicArea::orderBot(int side, const std::list& objects, int unit, ISAI* sai) +{ + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (information->getObjectTypeFlags() & 0x10u) + { + orderAirBot(side, objects, unit, sai); + return; + } + orderNormalBot(side, objects, unit, sai); +} + +// ELF 0x33C430: an air path 75 above the terrain (IAITerrain::getHeight, +0x08) at this area's +// position (no objects), at the one object's, or at every object after the first. The cruise +// altitude is min(m_size[side], 4.0f for object type bit 0x20 else 40.0f) (`fcmovnbe`); the +// waypoint is WPAltitudeMoveTo(altitude, 120.0f, 50.0f, 2, path) through checkPointer (0x33C650), +// handed to the bot (+0x44, also when the allocation failed). The image does not check the +// information for null. +void AIStrategicArea::orderAirBot(int side, const std::list& objects, int unit, ISAI*) +{ + std::list path; + float altitude = 1.0f; + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + const IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float clearance = (information->getObjectTypeFlags() & 0x20u) ? 4.0f : 40.0f; + const std::size_t count = objects.size(); + if (count == 0 || count == 1) + { + const Vec2& anchor = count == 0 ? getPosition(side) : objects.front()->getPosition(side); + const float x = anchor.x; + Vec3 point; + point.y = terrain->getHeight(anchor.x, anchor.y) + 75.0f; + point.x = x; + point.z = anchor.y; + path.push_back(point); + altitude = m_size[side] > clearance ? clearance : m_size[side]; + } + else + { + std::list::const_iterator it = objects.begin(); + for (++it; it != objects.end(); ++it) + { + const Vec2& anchor = (*it)->getPosition(side); + const float x = anchor.x; + Vec3 point; + point.y = terrain->getHeight(anchor.x, anchor.y) + 75.0f; + point.x = x; + point.z = anchor.y; + path.push_back(point); + altitude = m_size[side] > clearance ? clearance : m_size[side]; + } + } + bot->setWaypoints(checkPointer(new WPAltitudeMoveTo(altitude, 120.0f, 50.0f, 2, path))); +} + +// ELF 0x33A2F0 (caller SquadMember::moveToGoalPos 0x1B4240): the side's route map +// (`0x16c(%edi,%esi,4)`, i.e. m_mapsA / m_mapsB for side 1 / 2, first group element) is searched +// for `from`; when found the route is copied out (list operator=) and the answer is true. +bool AIStrategicArea::getRouteList(int side, AIStrategicArea* from, std::list& route) +{ + bool found = false; + std::map >& routes = (side == 1 ? m_mapsA : m_mapsB)[0]; + std::map >::iterator it = routes.find(from); + if (it != routes.end()) + { + found = true; + route = it->second; + } + return found; +} + +namespace { + +float squaredDistance(const Vec3& a, const Vec3& b) +{ + const float dx = a.x - b.x; + const float dy = a.y - b.y; + const float dz = a.z - b.z; + return dx * dx + dy * dy + dz * dz; } -void AIStrategicArea::setAsDirty(int) +// (a - origin) . (b - origin): positive when a lies on the side of origin facing b. +float dotFrom(const Vec3& origin, const Vec3& a, const Vec3& b) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::setAsDirty"); + return (a.x - origin.x) * (b.x - origin.x) + (a.y - origin.y) * (b.y - origin.y) + + (a.z - origin.z) * (b.z - origin.z); } -int AIStrategicArea::orderBot(int, const std::list&, int, ISAI*) +// The inline AIRandom draw of orderNormalBot (0x33D390 / 0x33E764): low 0.0f, high the waypoint +// count (`fildll` of the zero-extended size, stored to float), (high - low) * (draw * 2^-32) + low +// stored to float, then `cvttss2si`. +std::size_t randomWaypointIndex(std::size_t count) { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicArea::orderBot"); + const float low = 0.0f; + const float high = static_cast(static_cast(count)); + const double draw = static_cast(AIRandom::m_instance->next()) * static_cast(2.32830644e-10f); + return static_cast(static_cast(static_cast((high - low) * draw + low))); +} + +// [CHOSEN] helper for a sequence orderNormalBot repeats in its three arms (0x33CB6E, 0x33E205, +// 0x33D6B2): randomizePos(side, 0.8f) around `object`, up to twenty candidates checked against +// the ordering area's island for the map (IAIPathfinding +0x30, always the ordering area's +// +0x118 data), then the object's order position (slot 5, (map, side)). +void findOrderPosition(const AIStrategicArea* area, AIStrategicObject* object, int side, int map, + int equipment, Vec3& position) +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + object->randomizePos(side, 0.8f, position); + for (int tries = 0; tries <= 19; ++tries) + { + if (pathfinding->isValidPosition(map, equipment, position, area->m_mapData[map].m_island, true)) + return; + object->randomizePos(side, 0.8f, position); + } + position = object->getOrderPos(map, side); +} + +// [CHOSEN] helper for the `hasSameAssignedAreas` arm (0x33DC66 / 0x33EB83): the bot keeps its +// current waypoint (through getBotWaypoint) when it still leads towards `goal` and is closer to it +// than the bot; it is then stored again (Bot +0x20C) and the stored one (+0x210) becomes a goal +// with area -1. +bool keepCurrentWaypoint(AIStrategicArea* area, Bot* bot, Information* information, int side, int map, + const Vec3& botPosition, const Vec3& goal, float distance, + const std::vector& waypoints, WPMoveTo::GoalList& goals) +{ + const Vec3 current = static_cast(bot)->getCurrentWaypoint(); + const Vec3 from = information->getPosition(); + const Vec3 next = area->getBotWaypoint(from, current, waypoints, side); + if (dotFrom(botPosition, next, goal) > 0.0f && squaredDistance(next, goal) < distance) + { + static_cast(bot)->setCurrentWaypoint(next, map); + const Vec3 stored = static_cast(bot)->getCurrentWaypoint(); + goals.push_back(std::make_pair(stored, -1)); + return true; + } + return false; +} + +bool isOrderableControlPoint(const AIStrategicArea* area, int side) +{ + return area->hasObjectTypeFlag(AIStrategicObject::ControlPoint) + && area->m_controlPointId != 0xFFFFFFFFu && area->getStatus(side) != StatusMap::Owned; +} + +} // namespace + +// ELF 0x33C940 (0x33C940..0x33EF80). A ground unit's goal list (WPMoveTo goals, radius 60): +// * no objects: this area's control point (getControlpointPos, goal radius 0) when the area is a +// control point (+0x13C set, side status not Owned); else the bot's own position when it is +// inside the area and valid on the map, else a randomized order position (findOrderPosition); +// radius m_size[side] / 4 + the bot's diameter (IPIPhysical +0x2C, `fadd %st,%st`). +// * one object: a route waypoint between the bot's current strategic position (ISAI +0xB4) and +// the object first (AIStrategicObjectManager::getWaypoints; Bot +0x200..+0x214 track the +// assigned pair): the kept current waypoint, or one of three random picks that lies towards +// this area's position and closer to it than the bot, with a valid polygon. Then the object's +// (or this control point's) position with this area's index. +// * several objects: the same per consecutive pair (only the first pair updates the bot's +// assigned areas; only the first pick is direction-tested), each object's position with its own +// index; the radius is the last object's. +// Bot +0x200..+0x214 are declared on BotMain only (the established static_cast form). +// The waypoint list replaces the bot's unless SquadMember::isSameWaypointList says it is the same +// (then it is deleted). The image does not check the information or the squad member for null. +// ELF 0x33C940. +void AIStrategicArea::orderNormalBot(int side, const std::list& objects, int unit, ISAI* sai) +{ + WPMoveTo::GoalList goals; + float radius = 1.0f; + Vec2 botPosition2; + botPosition2.x = 0.0f; + botPosition2.y = 0.0f; + Vec3 controlPointPosition; + controlPointPosition.x = 0.0f; + controlPointPosition.y = 0.0f; + controlPointPosition.z = 0.0f; + Vec3 position = controlPointPosition; + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + Bot* const bot = IBotManager::instance->getBotFromId(unit); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + IPIMobile* const mobile = information->getMobile(); + const float radiusPhysical = information->getPhysical()->getRadius(); + const float diameter = radiusPhysical + radiusPhysical; + const int map = mobile->getVehicleNumber(); + const int equipment = information->getUnit()->getEquipmentType(); + const Vec3& botPosition = information->getPosition(); + vec3ToVec2XZ(botPosition, botPosition2); + WPMoveTo* waypoint = 0; + + if (objects.empty()) + { + isLandingZoneUser(equipment); // 0x33CAB8: the answer is unused + if (isOrderableControlPoint(this, side)) + { + getControlpointPos(this, side, map, equipment, botPosition, controlPointPosition); + goals.push_back(std::make_pair(controlPointPosition, m_index)); + waypoint = checkPointer(new WPMoveTo(0.0f, 60.0f, 2, goals)); + } + else + { + bool found = false; + if (isInside(botPosition2) + && pathfinding->isValidPosition(map, equipment, information->getPosition(), + m_mapData[map].m_island, true)) + { + position = information->getPosition(); + found = true; + } + if (!found) + findOrderPosition(this, this, side, map, equipment, position); + goals.push_back(std::make_pair(position, m_index)); + waypoint = checkPointer(new WPMoveTo(m_size[side] * 0.25f + diameter, 60.0f, 2, goals)); + } + } + else if (objects.size() == 1) + { + AIStrategicObject* const object = objects.front(); + if (object->getType() == 0) + static_cast(object)->isLandingZoneUser(equipment); // unused + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + const int current = sai->getBotCurrentPos(unit); + const int target = object->getIndex(); + if (current != -1 && current != target) + { + // The goal of the route is this area's position (slot 3 on `this`, height m_f148). + Vec3 goal; + goal.x = 0.0f; + goal.y = 0.0f; + goal.z = 0.0f; + vec2ToVec3XZ(getPosition(side), goal); + goal.y = m_f148; + static_cast(bot)->setNewAssignedAreas(current, target); + const std::vector& waypoints = manager->getWaypoints(map, current, target); + const float distance = squaredDistance(goal, botPosition); + if (static_cast(bot)->hasSameAssignedAreas(map)) + { + keepCurrentWaypoint(this, bot, information, side, map, botPosition, goal, distance, + waypoints, goals); + } + else + { + bool added = false; + if (!waypoints.empty()) + { + for (int tries = 0;;) + { + const SAWayPoint* const candidate = waypoints[randomWaypointIndex(waypoints.size())]; + if (dotFrom(botPosition, candidate->getPosition(), goal) > 0.0f + && squaredDistance(candidate->getPosition(), goal) < distance + && candidate->getPolygon() != 0xFFFFFFFFu) + { + goals.push_back(std::make_pair(candidate->getPosition(), -1)); + static_cast(bot)->setCurrentWaypoint(candidate->getPosition(), map); + added = true; + break; + } + if (++tries > 2) + break; + } + } + if (!added) + static_cast(bot)->resetAssignedAreas(); + } + static_cast(bot)->copyAssignedAreas(); + } + if (object == this && isOrderableControlPoint(this, side)) + { + getControlpointPos(this, side, map, equipment, botPosition, controlPointPosition); + goals.push_back(std::make_pair(controlPointPosition, m_index)); + waypoint = checkPointer(new WPMoveTo(0.0f, 60.0f, 2, goals)); + } + else + { + findOrderPosition(this, object, side, map, equipment, position); + goals.push_back(std::make_pair(position, m_index)); + waypoint = checkPointer(new WPMoveTo(objects.front()->m_size[side] * 0.25f + diameter, + 60.0f, 2, goals)); + } + } + else + { + int previous = sai->getBotCurrentPos(unit); + bool first = true; + bool assigned = false; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + for (std::list::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + AIStrategicObject* const object = *it; + const int target = object->getIndex(); + if (previous != -1 && previous != target) + { + Vec3 goal; + goal.x = 0.0f; + goal.y = 0.0f; + goal.z = 0.0f; + vec2ToVec3XZ(object->getPosition(side), goal); + goal.y = object->m_f148; + const std::vector& waypoints = manager->getWaypoints(map, previous, target); + bool added = false; + const float distance = squaredDistance(goal, botPosition); + if (!assigned) + { + static_cast(bot)->setNewAssignedAreas(previous, target); + if (static_cast(bot)->hasSameAssignedAreas(map)) + added = keepCurrentWaypoint(this, bot, information, side, map, botPosition, goal, + distance, waypoints, goals); + static_cast(bot)->copyAssignedAreas(); + } + if (waypoints.empty()) + static_cast(bot)->resetAssignedAreas(); // 0x33DBEB, whatever `assigned` is + if (!waypoints.empty() && !added) + { + for (int tries = 0;;) + { + const SAWayPoint* const candidate = waypoints[randomWaypointIndex(waypoints.size())]; + if ((!first || dotFrom(botPosition, candidate->getPosition(), goal) > 0.0f) + && candidate->getPolygon() != 0xFFFFFFFFu + && squaredDistance(candidate->getPosition(), goal) < distance) + { + goals.push_back(std::make_pair(candidate->getPosition(), -1)); + if (!assigned) + static_cast(bot)->setCurrentWaypoint(candidate->getPosition(), map); + added = true; + break; + } + if (++tries > 2) + break; + } + if (!assigned && !added) + static_cast(bot)->resetAssignedAreas(); + } + assigned = true; + } + first = false; + if (object == this && isOrderableControlPoint(this, side)) + { + getControlpointPos(this, side, map, equipment, botPosition, controlPointPosition); + goals.push_back(std::make_pair(controlPointPosition, m_index)); + radius = 0.0f; + } + else + { + findOrderPosition(this, object, side, map, equipment, position); + goals.push_back(std::make_pair(position, object->getIndex())); + radius = object->m_size[side] * 0.25f + diameter; + } + previous = target; + } + waypoint = checkPointer(new WPMoveTo(radius, 60.0f, 2, goals)); + } + + // 0x33CDA0: the bot's list (+0x40) is read before its squad member (+0x140). + WaypointList* const currentList = bot->getWaypoints(); + if (!bot->getSquadMember()->isSameWaypointList(currentList, waypoint)) + bot->setWaypoints(waypoint); + else + delete waypoint; // slot 1 when non-null } // The size uses side, unlike the // position's side-1 index above. Unordered distance takes the division arm. +// ELF 0x33AA80. float AIStrategicArea::gravity(float distance, int side) { if (distance <= 1.0f) @@ -691,6 +1663,305 @@ float AIStrategicArea::gravity(float distance, int side) return static_cast(m_size[side] / (wideDistance * wideDistance)); } +// ELF 0x339890 (added by ai-bot). The flag test is vtable +0x4C with 0x10 (ControlPoint). +bool AIStrategicArea::isOrderPosOutsideCpRadius(int map, int side) +{ + bool outside = false; + if (hasObjectTypeFlag(ControlPoint)) + { + const Vec3 order = getOrderPos(map, side); + float radius = 0.0f; + Vec3 centre; + centre.x = 0.0f; + centre.y = 0.0f; + centre.z = 0.0f; + bool active; + static_cast(CommonSingletonServer::m_iaiGame) + ->getControlPointInfo(m_controlPointId, centre, radius, active); + const float dx = order.x - centre.x; + const float dy = order.y - centre.y; + const float dz = order.z - centre.z; + if (std::sqrt(dx * dx + dy * dy + dz * dz) > radius) + outside = true; + } + return outside; +} + +// ELF 0x338FF0 (added by ai-bot). The records are read as two Vec3 (+0 / +0xC of the node value). +bool AIStrategicArea::getClosestFlankingPositions(Vec3 position, Vec3& first, Vec3& second) +{ + bool found = false; + float best = 3.40282347e+38f; + for (std::list >::const_iterator it = m_flankPositions.begin(); + it != m_flankPositions.end(); ++it) + { + const Vec3 a = it->first; + const Vec3 b = it->second; + const float dx = a.x - position.x; + const float dy = a.y - position.y; + const float dz = a.z - position.z; + const float d = dx * dx + dy * dy + dz * dz; + if (d < best) + { + best = d; + first = a; + second = b; + found = true; + } + } + return found; +} + +// ELF 0x338EC0. +void AIStrategicArea::addFlankPosition(Vec3 first, Vec3 second) +{ + m_flankPositions.push_back(std::pair(first, second)); +} + +// ELF 0x338F50: a copy of the flanking pairs. +std::list > AIStrategicArea::getFlankPositions() +{ + return m_flankPositions; +} + +// ELF 0x3391A0: appended unless already present. +void AIStrategicArea::addNeighbour(AIStrategicObject* object) +{ + for (int i = 0; i < static_cast(m_neighbours.size()); ++i) + { + if (m_neighbours[i] == object) + return; + } + m_neighbours.push_back(object); +} + +// ELF 0x339230. Shipped defect, preserved: the shift starts at the match, so it overwrites the +// element before the match (index -1 when the match is first) and keeps the match itself; the +// vector then shrinks by one whether or not the object was found. +void AIStrategicArea::removeNeighbour(AIStrategicObject* object) +{ + const int size = static_cast(m_neighbours.size()); + for (int i = 0; i < size; ++i) + { + if (m_neighbours[i] == object) + { + for (int j = i; j < size; ++j) + m_neighbours[j - 1] = m_neighbours[j]; + break; + } + } + m_neighbours.resize(size - 1); +} + +// ELF 0x3393E0: grown by one through resize, unless already present. +void AIStrategicArea::addNeighbouringObject(AIStrategicObject* object) +{ + const int size = static_cast(m_neighbouringObjects.size()); + for (int i = 0; i < size; ++i) + { + if (m_neighbouringObjects[i] == object) + return; + } + m_neighbouringObjects.resize(size + 1); + m_neighbouringObjects[size] = object; +} + +// ELF 0x339500: the neighbours, the neighbouring objects and the attached landing zones. +void AIStrategicArea::removeAllNeighbours() +{ + m_neighbours.resize(0); + m_neighbouringObjects.resize(0); + m_landingZones.resize(0); +} + +// ELF 0x339680: both sides' positions. +void AIStrategicArea::setPosition(const Vec2& position) +{ + m_position[0] = position; + m_position[1] = position; +} + +// ELF 0x3396B0: the same stores as setPosition. +void AIStrategicArea::setCenterPosition(const Vec2& position) +{ + m_position[0] = position; + m_position[1] = position; +} + +// ELF 0x3396F0. +void AIStrategicArea::setTopLeftCorner(const Vec2& corner) +{ + m_centre = corner; +} + +// ELF 0x339710. Before initOrderPoses the position is stored absolute; afterwards the map is +// queried with the stored (old) offset, as initOrderPoses does, and the new position is stored +// relative to the area position together with the island the query answered. Always true. +bool AIStrategicArea::setOrderPos(int map, const Vec3& position) +{ + if (!m_orderPosesInitialised) + { + m_mapData[map].m_offset = position; + return true; + } + + Vec3 areaPosition; + areaPosition.x = 0.0f; + areaPosition.y = 0.0f; + areaPosition.z = 0.0f; + vec2ToVec3XZ(m_position[0], areaPosition); + areaPosition.y = m_f148; + + unsigned int polygon; + unsigned int island; + IAIPathfinding::instance->getPolygon(m_mapData[map].m_offset, map, polygon, island, 1); + + Vec3 delta; + delta.x = position.x - areaPosition.x; + delta.y = position.y - areaPosition.y; + delta.z = position.z - areaPosition.z; + m_mapData[map].m_offset = delta; + m_mapData[map].m_island = island; + return true; +} + +// ELF 0x33A2B0. +int AIStrategicArea::setObjectTypeFlags(int flags) +{ + return m_objectTypeFlags = flags; +} + +// ELF 0x33A2D0. +int AIStrategicArea::addObjectTypeFlag(StrategicObjectType type) +{ + return m_objectTypeFlags |= 1 << type; +} + +// ELF 0x33B580: appends the named zone (grown through resize) and answers its name, or a +// message when the manager has no such zone. The zone name is read directly, not through +// AILandingZone::getName. +std::string AIStrategicArea::attachLandingZone(const std::string& name) +{ + AILandingZone* const zone = AILandingZoneManager::m_instance->getAILandingZone(name); + if (!zone) + return "No zone by that name found"; + + const int size = static_cast(m_landingZones.size()); + m_landingZones.resize(size + 1); + m_landingZones[size] = zone; + return zone->m_name; +} + +// ELF 0x33B6E0: unchecked index. +AILandingZone* AIStrategicArea::getLandingZone(int index) +{ + return m_landingZones[index]; +} + +// ELF 0x33B700: the attached zone with the id, and its index; 0 and -1 when none matches. +AILandingZone* AIStrategicArea::getLandingZone(int id, int& index) +{ + index = 0; + for (std::vector::iterator it = m_landingZones.begin(); + it != m_landingZones.end(); ++it) + { + if ((*it)->getId() == id) + return *it; + ++index; + } + index = -1; + return 0; +} + +// ELF 0x33B780. +std::vector& AIStrategicArea::getLandingZones() +{ + return m_landingZones; +} + +// ELF 0x33B790. +const std::vector& AIStrategicArea::getLandingZones() const +{ + return m_landingZones; +} + +// ELF 0x33B7A0: one attached zone name per line. +std::string AIStrategicArea::listLandingZones() +{ + std::stringstream stream; + for (int i = 0; i < static_cast(m_landingZones.size()); ++i) + { + const std::string name = m_landingZones[i]->m_name; + stream << name << std::endl; + } + return stream.str(); +} + +// ELF 0x33BC40: the attached zone with the smallest squared distance below 1e9; 0 when none. +AILandingZone* AIStrategicArea::getClosestLandingZone(const Vec2& position) +{ + float best = 1e9f; + AILandingZone* closest = 0; + for (std::vector::iterator it = m_landingZones.begin(); + it != m_landingZones.end(); ++it) + { + const float distance = (*it)->getDistanceSqr(position); + if (distance < best) + { + best = distance; + closest = *it; + } + } + return closest; +} + +// ELF 0x33BCC0: the XZ projection through the Vec2 form. +AILandingZone* AIStrategicArea::getClosestLandingZone(const Vec3& position) +{ + Vec2 flat; + flat.x = 0.0f; + flat.y = 0.0f; + vec3ToVec2XZ(position, flat); + return getClosestLandingZone(flat); +} + +// ELF 0x33BD10: the equipment bit isLandingZoneUser tests. +void AIStrategicArea::addToLandingZoneUsers(int equipment) +{ + m_i340 |= 1 << equipment; +} + +// ELF 0x33C260: clears the group bit in every distance record of the side and erases the +// records left without groups. +void AIStrategicArea::cleanUnitDistances(int side, int group) +{ + std::list::iterator it = m_distances[side - 1].begin(); + while (it != m_distances[side - 1].end()) + { + it->m_vehicleGroups &= ~(1 << group); + if (it->m_vehicleGroups == 0) + m_distances[side - 1].erase(it++); + else + ++it; + } +} + +// ELF 0x33F1C0: known vehicles with a free seat within m_f396 of the side's position. +// The ELF passes vec2ToVec3XZ's eax (the output address) as the position; the output local is the +// same object. +void AIStrategicArea::getKnownEmptyVehicles(std::vector& vehicles, int side) const +{ + const IAIInformationEnvironment* const environment = + static_cast(AISingletonServer::m_iaiInformationEnvironment); + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + FreeUnitPred predicate(side); + vec2ToVec3XZ(m_position[side - 1], position); + environment->getObjectsWithinRadius(vehicles, position, m_f396, side, true, &predicate); +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h index 52a292fbc..e0bfae3b5 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h @@ -1,7 +1,6 @@ // Strategic area with explicit bounds or a control-point anchor. // Control-point areas defer initialization until world objects exist. // The base index is used to select the area's debug primitives. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AISTRATEGICAREA_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGICENTITY_AISTRATEGICAREA_H @@ -12,12 +11,14 @@ #include #include "AIStrategicObject.h" +#include "AreaDistanceInfo.h" namespace dice { namespace hfe { namespace ai { class AILandingZone; +class SAWayPoint; class AIStrategicArea : public AIStrategicObject { @@ -39,13 +40,12 @@ class AIStrategicArea : public AIStrategicObject /* +12 */ unsigned int m_island; }; - // [UNRESOLVED] Distance record fields remain opaque pending their readers' type contracts. - struct AreaDistanceInfo { int m_w0; int m_w1; int m_w2; }; - // [UNRESOLVED] List payloads whose original element types have not been identified. struct AreaWord { int m_word; }; - struct AreaRecord { int m_words[6]; }; + // ELF 0x335480 (C2; C1 0x335850): an area with explicit bounds. The first float is the + // base's stored height (m_f148), the second its radius. [INFERRED] parameter names. + AIStrategicArea(const std::string& name, Vec2 topLeft, Vec2 centre, float height, float radius); AIStrategicArea(const std::string& name, unsigned int controlPointId, float radius); // [INFERRED] Initializes area state. Manager-created areas call this during initAreas; @@ -60,6 +60,45 @@ class AIStrategicArea : public AIStrategicObject // Writes the control-point position and radius; returns false for an unassigned id. bool getControlPointPosAndRadius(Vec3& position, float& radius); + // ELF 0x33BD30: bit test of the landing-zone equipment mask (+340). + bool isLandingZoneUser(int equipment); + // ELF 0x33BD50: with the side's distances dirty (+343 + side), rebuild them per vehicle + // group (or for group 0 when there are none). + void validateDistances(int side); + void validateDistances(int side, int group); // ELF 0x33BE30 + void insertUnitDistances(int side, int group); // ELF 0x33BF90 + void getDistances(int side, std::list >& distances, + std::map >& routes, + std::map& costs, int groupMask); // ELF 0x33AAC0 + + // ELF 0x33F180 / 0x33F130: inside the box from m_centre around the side-1 position (+0x84); + // the Vec3 form tests its XZ projection. + bool isInside(const Vec2& point) const; + bool isInside(const Vec3& point) const; + // ELF 0x3396E0: the address of the side-1 position (+0x84). Read by + // CommunicationHub::enemySpottedByAI. + const Vec2& getCenterPosition() const; + // ELF 0x339890 (added by ai-bot for closeAndShouldAvoidVehicles): a control point area + // (hasObjectTypeFlag(16)) whose order position for (map, side) lies beyond the control point's + // radius (IAIGame::getControlPointInfo(m_controlPointId)). + bool isOrderPosOutsideCpRadius(int map, int side); + // ELF 0x338FF0 (added by ai-bot for SquadCoordinator::squadManeuverStaticFlank): the flanking + // pair (+392 records: two Vec3) whose first position is closest to `position`; false when none. + bool getClosestFlankingPositions(Vec3 position, Vec3& first, Vec3& second); + + // ELF 0x33EF80: answers the second position; the first and the waypoint list are unused. + Vec3 getBotWaypoint(Vec3 from, Vec3 to, const std::vector& waypoints, int map); + // ELF 0x339AB0. + void getControlpointPos(AIStrategicObject* object, int side, int unit, int equipment, + const Vec3& from, Vec3& position); + + // ELF 0x33C430 / 0x33C940: orderBot's two arms (air units / everything else). Neither sets + // eax (both end in the goal list's deallocate), so they and orderBot answer nothing. + void orderAirBot(int side, const std::list& objects, int unit, ISAI* sai); + void orderNormalBot(int side, const std::list& objects, int unit, ISAI* sai); + // ELF 0x33A2F0. Declared by ai-bot for SquadMember::moveToGoalPos (0x1B4240). + bool getRouteList(int side, AIStrategicArea* from, std::list& route); + // Virtual declaration order: thirty-four ELF slots. virtual ~AIStrategicArea(); // slots 0/1, @@ -67,14 +106,14 @@ class AIStrategicArea : public AIStrategicObject // slots 3 and 4 are AIStrategicObject::getPosition / ::setPosition - not overridden virtual Vec3 getOrderPos(int a, int b) const; // slot 5, - virtual void updateTemperature(const Strategy* strategy, int side); // slot 6, + virtual float updateTemperature(const Strategy* strategy, int side); // slot 6, ELF 0x33A0F0 virtual void update(int side, ISAI* sai, bool& changed); // slot 7 virtual int getChangedAttackDefence(int side); // slot 8, virtual float getControlPointTakeOverCounter(); // slot 9 virtual bool isEnemyTakingOverBase(int side); // slot 10, - virtual int calculateDefenseNeed(int side); // slot 11, - virtual int calculateAttackValue(int side); // slot 12, - virtual int calculateAttackCost(int side); // slot 13, + virtual float calculateDefenseNeed(int side); // slot 11, + virtual float calculateAttackValue(int side); // slot 12, + virtual float calculateAttackCost(int side); // slot 13, virtual bool isNeighbour(AIStrategicObject* object) const; // slot 14, virtual bool hasNeighbourWithStatus(StatusMap::Status status, int side) const; // slot 15, @@ -87,29 +126,58 @@ class AIStrategicArea : public AIStrategicObject virtual bool hasObjectTypeFlags(int flags) const; // slot 20, virtual int getTacticalStatus(int side) const; // slot 21, virtual bool isAreaTakeable(); // slot 22, - virtual int collectSquadResources(int side, ISAI* sai); // slot 23, - virtual int collectAdditionalSquadResources(int side, int amount, ISAI* sai); + virtual bool collectSquadResources(int side, ISAI* sai); // slot 23, ELF 0x33A380 + virtual int collectAdditionalSquadResources(int amount, int side, ISAI* sai); // slot 24, - virtual int releaseSurplus(int side); // slot 25, + virtual bool releaseSurplus(int side); // slot 25, ELF 0x33A6A0 virtual float gravity(const Vec3& position, int side); // slot 26, virtual float gravity(const Vec2& position, int side); // slot 27, virtual bool retainBot(int side, int a, ISAI* sai); // slot 28, virtual float getXExtent(int side) const; // slot 29, virtual float getZExtent(int side) const; // slot 30, virtual void setAsDirty(int side); // slot 31, - virtual int orderBot(int side, const std::list& objects, - int a, ISAI* sai); // slot 32, + virtual void orderBot(int side, const std::list& objects, + int unit, ISAI* sai); // slot 32, ELF 0x33C340 // Additional virtual overload declared after the inherited slots. virtual float gravity(float distance, int side); // slot 33, -// [FRONTIER] Additional area operations remain undeclared until their signatures are established. + // Non-virtual area operations called by AIStrategicObjectManager and the console bindings. + void addFlankPosition(Vec3 first, Vec3 second); // ELF 0x338EC0 + std::list > getFlankPositions(); // ELF 0x338F50 + void addNeighbour(AIStrategicObject* object); // ELF 0x3391A0 + void removeNeighbour(AIStrategicObject* object); // ELF 0x339230 + void addNeighbouringObject(AIStrategicObject* object); // ELF 0x3393E0 + void removeAllNeighbours(); // ELF 0x339500 + // The base's virtual setPosition(int, const Vec2&) stays visible beside this overload. + using AIStrategicObject::setPosition; + void setPosition(const Vec2& position); // ELF 0x339680 + void setCenterPosition(const Vec2& position); // ELF 0x3396B0 + void setTopLeftCorner(const Vec2& corner); // ELF 0x3396F0 + bool setOrderPos(int map, const Vec3& position); // ELF 0x339710 + // Both answer the new flag word: AIStrategicObjectManager's forwarders (ELF 0x346850, + // 0x3467B0) return the call's eax as their own int result. + int setObjectTypeFlags(int flags); // ELF 0x33A2B0 + int addObjectTypeFlag(StrategicObjectType type); // ELF 0x33A2D0 + std::string attachLandingZone(const std::string& name); // ELF 0x33B580 + AILandingZone* getLandingZone(int index); // ELF 0x33B6E0 + AILandingZone* getLandingZone(int id, int& index); // ELF 0x33B700 + std::vector& getLandingZones(); // ELF 0x33B780 + const std::vector& getLandingZones() const; // ELF 0x33B790 + std::string listLandingZones(); // ELF 0x33B7A0 + AILandingZone* getClosestLandingZone(const Vec2& position); // ELF 0x33BC40 + AILandingZone* getClosestLandingZone(const Vec3& position); // ELF 0x33BCC0 + void addToLandingZoneUsers(int equipment); // ELF 0x33BD10 + void cleanUnitDistances(int side, int group); // ELF 0x33C260 + void getKnownEmptyVehicles(std::vector& vehicles, int side) const; // ELF 0x33F1C0 // layout, ELF offsets, read store by store out of the constructor // The base occupies 0..267. MSVC's own offsets will differ - a libstdc++ `std::list` is four // bytes and a `std::string` is four. These are documentation, not a layout claim for this build. /* +268 */ std::list m_list268; // [UNRESOLVED] - landing zones? node 12 B - /* +272 */ Vec2 m_centre; // zeroed; getXExtent/getZExtent subtract it + // The top-left corner: the bounded constructor and setTopLeftCorner store it; [INFERRED] + // name kept from the control-point path, which derives it from the control-point radius. + /* +272 */ Vec2 m_centre; // getXExtent/getZExtent subtract it /* +280 */ MapData* m_mapData; // new MapData[IAIPathfinding::getNumberOfMaps] // Separate vectors for neighboring areas and other neighboring strategic objects. /* +284 */ std::vector m_neighbours; @@ -118,11 +186,11 @@ class AIStrategicArea : public AIStrategicObject /* +312 */ int m_objectTypeFlags; // 0; `getObjectTypeFlags` returns exactly this /* +316 */ unsigned int m_controlPointId; // the second script argument, e.g. 502 // [UNRESOLVED] Both fields are initialized to 25; their meanings are unknown. - /* +320 */ int m_i320; // = 25 - /* +324 */ int m_i324; // = 25 + /* +320 */ int m_i320; // = 25; tactical status, side 1 (getTacticalStatus) + /* +324 */ int m_i324; // = 25; tactical status, side 2 // Landing zones associated with this area. /* +328 */ std::vector m_landingZones; - /* +340 */ int m_i340; // 0 [UNRESOLVED] + /* +340 */ int m_i340; // 0; landing-zone equipment bit mask // Per-vehicle-group arrays; each allocation has at least one element. // [INFERRED] Container element types remain partly uncertain. Side-indexed flags use side - 1. /* +344 */ bool m_distancesDirty[2]; // both = true [INFERRED] name @@ -130,31 +198,33 @@ class AIStrategicArea : public AIStrategicObject /* +348 */ bool* m_flagsA; // new bool[groups], all true [UNRESOLVED] /* +352 */ bool* m_flagsB; // new bool[groups], all true [UNRESOLVED] /* +356 */ bool m_sideEnabled[2]; // both true; [INFERRED] name, update side gates - /* +358 */ bool m_b358; // false [UNRESOLVED] (the constructor's) + /* +358 */ bool m_showNeighbours; // false; console showNeighbours /* +359 */ char m_pad359[1]; /* +360 */ std::list >* m_listsA; // [group] /* +364 */ std::list >* m_listsB; // [group] - /* +368 */ std::map* m_mapsA; // [group] - /* +372 */ std::map* m_mapsB; // [group] + /* +368 */ std::map >* m_mapsA; // list-valued (validateDistances teardown); [group] + /* +372 */ std::map >* m_mapsB; // list-valued (validateDistances teardown); [group] /* +376 */ std::map* m_mapsC; // [group] /* +380 */ std::map* m_mapsD; // [group] // Per-side distance records, indexed by side - 1 like m_distancesDirty. /* +384 */ std::list m_distances[2]; - /* +392 */ std::list m_list392; // node + // Flanking position pairs (addFlankPosition / getClosestFlankingPositions); node 0x20. + /* +392 */ std::list > m_flankPositions; // Stored doubled extent, initialized to twice m_size[1]. /* +396 */ float m_f396; // = 2 * m_size[1] [UNRESOLVED] meaning - /* +400 */ int m_i400; // 1 [UNRESOLVED] - /* +404 */ bool m_b404; // true + // -1 from both constructors. Read as a layer by AIStrategicObjectManager: neighbours must share + // it (addNeighbour) and streamWaypoints filters on it. [INFERRED] meaning; no writer known. + /* +400 */ int m_i400; + /* +404 */ bool m_visible; // true; console setVisible/getVisible /* +405 */ bool m_statusChanged; // false; update stores its changed output here // Additional state initialized by internalConstructorCall. /* +406 */ bool m_enemyTakeover[2]; // both false; [INFERRED] name, update's side flags /* +408 */ float m_f408; // = 1.0f [UNRESOLVED] /* +412 */ float m_f412; // = 1.0f [UNRESOLVED] - /* +416 */ int m_i416; // 0 [UNRESOLVED] - /* +420 */ int m_i420; // 0 [UNRESOLVED] - /* +424 */ int m_i424; // 0 [UNRESOLVED] - // Selects control-point initialization; explicit-position construction sets it false - // and uses control point id -1. + // Both constructors store 0.0f to all three words. [UNRESOLVED] meaning. + /* +416 */ Vec3 m_v416; + // Selects control-point initialization; the bounded constructor sets it false and uses + // control point id -1. /* +428 */ bool m_fromControlPoint; // true // Raised by `initOrderPoses` and by nothing else; both constructors clear it. [INFERRED] /* +429 */ bool m_orderPosesInitialised; // false diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp index 3de86528b..a45fc1324 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp @@ -1,11 +1,23 @@ // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIStrategicObject operations. #include "AIStrategicObject.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x342FE0, __tcf_0 0x343040, _GLOBAL__I 0x343070). +#include + +#include + #include "../AIStrategic/SAI.h" // EnemyStatistics - the four objects the constructor makes #include "../Main/AIDllFrontier.h" #include "../Main/AIMain.h" +#include "../Main/AIRandom.h" +#include "../Main/AISettingsInterfaces.h" // IAISettings::getVehicleGroup +#include "../Main/CommonSingletonServer.h" +#include "../Main/IBotManager.h" +#include "../AIBot/BotMain.h" // Bot::getCurrentEquipment +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" namespace dice { namespace hfe { @@ -13,6 +25,7 @@ namespace ai { // Initializes strategic-object state and its owned enemy-statistics records. +// ELF 0x340C60 (C2; C1 0x341190). AIStrategicObject::AIStrategicObject(float radius, float f148) : m_position() // the two-iteration zeroing loop at +132, in member-declaration position { @@ -67,23 +80,28 @@ AIStrategicObject::AIStrategicObject(float radius, float f148) m_category = -1; } -// [FRONTIER] Destruction requires ordered statistics and container teardown. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when the destructor is recovered. +// ELF 0x341600 (D2; D1 0x3418F0, D0 0x341BE0): deletes the four EnemyStatistics (+4..+0x10, each +// tested for null); the sets (+0x100 down to +0x14) go as members. AIStrategicObject::~AIStrategicObject() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObject::~AIStrategicObject"); + for (int i = 0; i < 4; ++i) + { + if (m_statistics[i]) + delete m_statistics[i]; + } } // native set size, side is one-based. // ELF getAssignedUnits(int) at returns the matching set; the two old STL layouts // place their counts four bytes apart. SAI::updateStates tests the signed result against zero. +// ELF 0x3423A0. int AIStrategicObject::getNumberOfAssignedUnits(int side) const { return static_cast(m_set68[side - 1].size()); } // byte at this + 0xEB + side, no bounds guard. +// ELF 0x341FD0. bool AIStrategicObject::isAttack(int side) const { return m_attack[side - 1]; @@ -93,6 +111,7 @@ bool AIStrategicObject::isAttack(int side) const // statistics pointer is at +4, so the side is one-based. The caller passes this // borrowed address to EnemyStatistics::add(EnemyStatistics&); pointer versus // reference return spelling is [INFERRED]. No null or side guard is present. +// ELF 0x3425E0. EnemyStatistics& AIStrategicObject::getBattleStatistics(int side) const { return *m_statistics[side - 1]; @@ -101,6 +120,7 @@ EnemyStatistics& AIStrategicObject::getBattleStatistics(int side) const // Returns the signed count of released resources, or zero when a commander refuses. // Re-queries the SAI after the commander callback and reads the object index afterward. // The downstream SAI release operation remains a named frontier. +// ELF 0x342090. int AIStrategicObject::releaseAssignedResources(int side) { if (IAIMain::m_instance->getSAI(side)->isPlayerCommander()) @@ -110,64 +130,432 @@ int AIStrategicObject::releaseAssignedResources(int side) return sai->releaseSquadsFromObject(m_index, side); } +// ELF 0x3422A0. +std::set& AIStrategicObject::getAvailableBots(bool attackers, int side) +{ + if (attackers) + return m_set20[side - 1]; + return m_set44[side - 1]; +} + +// ELF 0x3422D0. +std::set& AIStrategicObject::getAvailableAttackers(int side) +{ + return m_set20[side - 1]; +} + +// ELF 0x3422F0. +std::set& AIStrategicObject::getAvailableDefenders(int side) +{ + return m_set44[side - 1]; +} + +// ELF 0x3426E0. +bool AIStrategicObject::unregisterAvailableAttacker(std::set::iterator& it, int side) +{ + std::set& units = m_set20[side - 1]; + if (it == units.end()) + return false; + units.erase(it++); + return true; +} + +// ELF 0x342780. +bool AIStrategicObject::unregisterAvailableDefender(std::set::iterator& it, int side) +{ + std::set& units = m_set44[side - 1]; + if (it == units.end()) + return false; + units.erase(it++); + return true; +} + +// ELF 0x341FF0. +bool AIStrategicObject::registerAvailableAttacker(int unit, int side) +{ + m_set20[side - 1].insert(unit); + return true; +} + +// ELF 0x342040. +bool AIStrategicObject::registerAvailableDefender(int unit, int side) +{ + m_set44[side - 1].insert(unit); + return true; +} + +// ELF 0x342600. +bool AIStrategicObject::unregisterAvailableAttacker(int unit, int side) +{ + std::set::iterator it = m_set20[side - 1].find(unit); + return unregisterAvailableAttacker(it, side); +} + +// ELF 0x342670. +bool AIStrategicObject::unregisterAvailableDefender(int unit, int side) +{ + std::set::iterator it = m_set44[side - 1].find(unit); + return unregisterAvailableDefender(it, side); +} + +// ELF 0x342310. +std::set& AIStrategicObject::getAssignedUnits(int side) +{ + return m_set68[side - 1]; +} + +// ELF 0x3423E0. +std::set& AIStrategicObject::getPresentUnits(int side) +{ + return m_set92[side - 1]; +} + +// ELF 0x342400. +bool AIStrategicObject::isPresentUnit(int unit, int side) const +{ + return m_set92[side - 1].find(unit) != m_set92[side - 1].end(); +} + +// ELF 0x342460. +std::pair::iterator, bool> AIStrategicObject::setAsPresentUnit(int unit, int side) +{ + return m_set92[side - 1].insert(unit); +} + +// ELF 0x342550. +void AIStrategicObject::removeAsPresentUnit(std::set::iterator& it, int side) +{ + m_set92[side - 1].erase(it++); +} + +// ELF 0x3424C0. +std::set::iterator AIStrategicObject::removeAsPresentUnit(int unit, int side) +{ + std::set::iterator it = m_set92[side - 1].find(unit); + if (it != m_set92[side - 1].end()) + removeAsPresentUnit(it, side); + return it; +} + +// ELF 0x342E80. +bool AIStrategicObject::isAllowedVehicleGroup(int group) const +{ + return (m_i244 >> group) & 1; +} + +// ELF 0x342EA0. +bool AIStrategicObject::allowsSomeVehicleGroups(int groupMask) const +{ + return (m_i244 & groupMask) != 0; +} + +// Two draws (AIRandom, the inline tempering), x then z: offset = draw * extent * scale - +// 0.5 * extent, each extent queried twice (`call *0x74/*0x78` per use). +// ELF 0x342B80. +void AIStrategicObject::randomizePos(int side, float scale, Vec3& position) +{ + AIRandom* const random = AIRandom::m_instance; + const float drawX = random->nextFloat(); + const float scaledX = getXExtent(side) * drawX * scale; + const float dx = scaledX - getXExtent(side) * 0.5f; + const float drawZ = random->nextFloat(); + const float scaledZ = drawZ * getZExtent(side) * scale; + const float dz = scaledZ - getZExtent(side) * 0.5f; + position.x = dx + m_position[side - 1].x; + position.y = m_f148; + position.z = dz + m_position[side - 1].y; +} + +// Kept in x87 extended precision in the image: the angle (draw * 2 * pi, rodata 3.14159274f) and +// the distance chain; sinf/cosf take the float angle. The direction is the image's +// (1,0,0) * sin + (0,0,1) * cos sum, zero products included. +// ELF 0x342990. +void AIStrategicObject::randomizeControlpointPos(float scale, float spread, Vec3& position) +{ + AIRandom* const random = AIRandom::m_instance; + const double turn = static_cast(random->next()) * static_cast(2.32830644e-10f); + const double angle = (turn + turn) * static_cast(3.14159274f); + const double draw = static_cast(random->next()) * static_cast(2.32830644e-10f); + const float distance = static_cast( + (0.5 + draw * (static_cast(spread) - 0.5)) * scale); + const double s = std::sin(static_cast(angle)); + const double c = std::cos(static_cast(angle)); + const double dirX = s * 1.0 + c * 0.0; + const double dirY = c * 0.0 + s * 0.0; + const double dirZ = c * 1.0 + s * 0.0; + position.x = static_cast(dirX * distance + position.x); + position.y = static_cast(dirY * distance + position.y); + position.z = static_cast(dirZ * distance + position.z); +} + +// ELF 0x342EF0. +bool AIStrategicObject::isExpelledUnit(int equipment) const +{ + return (m_i248 >> equipment) & 1; +} + +// ELF 0x341FB0. +void AIStrategicObject::setAttack(bool attack, int side) +{ + m_attack[side - 1] = attack; +} + +// ELF 0x342940. +float AIStrategicObject::getAssignedPartOfWantedStrength(int side) const +{ + const int need = m_resourceNeed[side - 1]; + if (!need) + return 1.0f; + return static_cast(m_assignedSquadStrength[side - 1] / need); +} + // The ten accessors. Every one of them is between seven and thirty-three bytes in the image. // Returns type code 3; AIStrategicArea returns 0. // [UNRESOLVED] These codes are not established as StrategicObjectType values. +// ELF 0x343280. int AIStrategicObject::getType() const { return 3; } // - `return (char *)this + 8 * side + 124;`, i.e. the 1-based fold. See the header. +// ELF 0x340B20. const Vec2& AIStrategicObject::getPosition(int side) const { return m_position[side - 1]; } // - two dword stores, a memberwise Vec2 copy. +// ELF 0x340B40. void AIStrategicObject::setPosition(int side, const Vec2& position) { m_position[side - 1] = position; } // Returns bit 27. [UNRESOLVED] No named StrategicObjectType enumerator covers that bit. +// ELF 0x343290. int AIStrategicObject::getObjectTypeFlags() const { return 0x8000000; } +// ELF 0x3432A0. bool AIStrategicObject::hasObjectTypeFlag(StrategicObjectType) const { return false; } +// ELF 0x3432B0. bool AIStrategicObject::hasObjectTypeFlags(int) const { return false; } +// ELF 0x3432C0. float AIStrategicObject::gravity(const Vec3&, int) { return 0.0f; } +// ELF 0x3432E0. float AIStrategicObject::gravity(const Vec2&, int) { return 0.0f; } // Returns twice the side-specific size for both axes; base strategic objects are square. +// ELF 0x343300. float AIStrategicObject::getXExtent(int side) const { return m_size[side] + m_size[side]; } +// ELF 0x343320. float AIStrategicObject::getZExtent(int side) const { return m_size[side] + m_size[side]; } +// ELF 0x342FC0: the current statuses (+0x74/+0x78) take the initial ones (+0x7C/+0x80). +void AIStrategicObject::resetStatus() +{ + m_status[0] = m_status[2]; + m_status[1] = m_status[3]; +} + +// ELF 0x341ED0. +void AIStrategicObject::setSide(int side) +{ + if (side == 1) + { + m_status[0] = StatusMap::Owned; + m_status[2] = StatusMap::Owned; + m_status[1] = StatusMap::Hostile; + m_status[3] = StatusMap::Hostile; + } + else if (side == 2) + { + m_status[0] = StatusMap::Hostile; + m_status[2] = StatusMap::Hostile; + m_status[1] = StatusMap::Owned; + m_status[3] = StatusMap::Owned; + } + else + { + m_status[2] = StatusMap::Neutral; + m_status[3] = StatusMap::Neutral; + } +} + +// ELF 0x341F40. +int AIStrategicObject::getSide() +{ + if (m_status[2] == StatusMap::Owned) + return 1; + return m_status[3] == StatusMap::Owned ? 2 : 0; +} + +// ELF 0x341F70. +void AIStrategicObject::setPriority(int priority, int side) +{ + m_unresolved212[side - 1] = priority; +} + +// ELF 0x341F90. +int AIStrategicObject::getPriority(int side) const +{ + return m_unresolved212[side - 1]; +} + +// ELF 0x342110. +bool AIStrategicObject::releaseAssignedUnit(int unit, int side) +{ + std::set::iterator it = m_set68[side - 1].find(unit); + if (it == m_set68[side - 1].end()) + return false; + return IAIMain::m_instance->getSAI(side)->releaseUnitFromObject(m_index, it, side); +} + +// ELF 0x3421C0. The find in the chosen available set is the image's (its result is unused). +bool AIStrategicObject::bookBot(bool attacker, int side, std::set::iterator& it) +{ + const int unit = *it; + if (attacker) + m_set20[side - 1].find(unit); + else + m_set44[side - 1].find(unit); + Bot* const bot = IBotManager::instance->getBotFromId(unit); + InformationManager* const manager = informationManager; + Information* const information = manager->getInformation(bot->getCurrentEquipment()); + return information && information->getUnit(); +} + +// ELF 0x342330. +int AIStrategicObject::getNumberOfAvailableBots(bool attackers, int side) const +{ + if (attackers) + return static_cast(m_set20[side - 1].size()); + return static_cast(m_set44[side - 1].size()); +} + +// ELF 0x342360. +int AIStrategicObject::getNumberOfAvailableAttackers(int side) const +{ + return static_cast(m_set20[side - 1].size()); +} + +// ELF 0x342380. +int AIStrategicObject::getNumberOfAvailableDefenders(int side) const +{ + return static_cast(m_set44[side - 1].size()); +} + +// ELF 0x3423C0. +int AIStrategicObject::getNumberOfPresentUnits(int side) const +{ + return static_cast(m_set92[side - 1].size()); +} + +// ELF 0x3425F0. +EnemyStatistics& AIStrategicObject::getStrategicStatistics(int side) const +{ + return *m_statistics[side + 1]; +} + +// ELF 0x342820. +int AIStrategicObject::unregisterAllAvailableAttackers(int side) +{ + const int count = static_cast(m_set20[side - 1].size()); + m_set20[side - 1].clear(); + return count; +} + +// ELF 0x3428B0. +int AIStrategicObject::unregisterAllAvailableDefenders(int side) +{ + const int count = static_cast(m_set44[side - 1].size()); + m_set44[side - 1].clear(); + return count; +} + +// ELF 0x342D40. +void AIStrategicObject::addAllowedUnit(int equipment) +{ + addAllowedVehicleGroup( + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment)); +} + +// ELF 0x342D90. +void AIStrategicObject::addAllowedVehicleGroup(int group) +{ + if (m_i244 == -1) + m_i244 = 0; + m_i244 |= 1 << group; +} + +// ELF 0x342DD0. +void AIStrategicObject::addAllowedVehicleGroup(const std::string& group) +{ + addAllowedVehicleGroup( + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(group)); +} + +// ELF 0x342E20. +int AIStrategicObject::getAllowedVehicleGroups() const +{ + return m_i244; +} + +// ELF 0x342E30. +bool AIStrategicObject::isAllowedUnit(int equipment) const +{ + return isAllowedVehicleGroup( + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment)); +} + +// ELF 0x342EC0. +void AIStrategicObject::addExpelledUnit(int equipment) +{ + m_i248 |= 1 << equipment; +} + +// ELF 0x342EE0. +int AIStrategicObject::getExpelledVehicleTypes() const +{ + return m_i248; +} + +// ELF 0x342F10. +bool AIStrategicObject::removeGrouping(int group) +{ + std::set::iterator it = m_set256.find(group); + if (it == m_set256.end()) + return false; + m_set256.erase(it); + return true; +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h index 6d1584141..e7dc5992b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h @@ -1,5 +1,4 @@ // Base interface and shared state for strategic objects. Preserve virtual declaration order. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AISTRATEGICOBJECT_H // [INFERRED] guard style @@ -7,6 +6,7 @@ #include #include +#include // Vec2 and Vec3 cannot be forward-declared in this tree: both are typedefs to // `dice::hfe::Math::Vec2/Vec3`, so a local `struct Vec3;` is a redefinition with a different basic @@ -70,14 +70,14 @@ class AIStrategicObject // and parameter list below is taken from the matching slot of `AIStrategicArea`'s vtable; the // return types are [INFERRED] from whether the override leaves its result in eax or in st0. virtual Vec3 getOrderPos(int a, int b) const = 0; // slot 5 - virtual void updateTemperature(const Strategy* strategy, int side) = 0; // slot 6 + virtual float updateTemperature(const Strategy* strategy, int side) = 0; // slot 6; SAI discards st0 virtual void update(int side, ISAI* sai, bool& changed) = 0; // slot 7; paired Area body has no return virtual int getChangedAttackDefence(int side) = 0; // slot 8 virtual float getControlPointTakeOverCounter() = 0; // slot 9; ST0 float chain virtual bool isEnemyTakingOverBase(int side) = 0; // slot 10 - virtual int calculateDefenseNeed(int side) = 0; // slot 11 - virtual int calculateAttackValue(int side) = 0; // slot 12 - virtual int calculateAttackCost(int side) = 0; // slot 13 + virtual float calculateDefenseNeed(int side) = 0; // slot 11 + virtual float calculateAttackValue(int side) = 0; // slot 12 + virtual float calculateAttackCost(int side) = 0; // slot 13 virtual bool isNeighbour(AIStrategicObject* object) const = 0; // slot 14 virtual bool hasNeighbourWithStatus(StatusMap::Status status, int side) const = 0; // slot 15 virtual bool isNeighbouringObject(AIStrategicObject* object) const = 0; // slot 16 @@ -90,9 +90,9 @@ class AIStrategicObject virtual int getTacticalStatus(int side) const = 0; // slot 21 virtual bool isAreaTakeable() = 0; // slot 22 - virtual int collectSquadResources(int side, ISAI* sai) = 0; // slot 23 - virtual int collectAdditionalSquadResources(int side, int amount, ISAI* sai) = 0; // slot 24 - virtual int releaseSurplus(int side) = 0; // slot 25 + virtual bool collectSquadResources(int side, ISAI* sai) = 0; // slot 23 + virtual int collectAdditionalSquadResources(int amount, int side, ISAI* sai) = 0; // slot 24 + virtual bool releaseSurplus(int side) = 0; // slot 25 virtual float gravity(const Vec3& position, int side); // slot 26, virtual float gravity(const Vec2& position, int side); // slot 27, @@ -103,19 +103,90 @@ class AIStrategicObject virtual float getZExtent(int side) const; // slot 30, virtual void setAsDirty(int side) = 0; // slot 31 - virtual int orderBot(int side, const std::list& objects, + // void: AIStrategicArea::orderBot (ELF 0x33C340) passes through its arms' eax, which neither + // arm sets. + virtual void orderBot(int side, const std::list& objects, int a, ISAI* sai) = 0; // slot 32 int getNumberOfAssignedUnits(int side) const; + // ELF 0x341ED0 / 0x341F40: the per-side statuses for owner 1 or 2 (any other value marks + // only the second pair Neutral); getSide answers 1, 2 or 0 from the second pair. + void setSide(int side); + int getSide(); + void setPriority(int priority, int side); // ELF 0x341F70 + int getPriority(int side) const; // ELF 0x341F90 + // ELF 0x342110: hands an assigned unit back through the side's SAI; false when unassigned. + bool releaseAssignedUnit(int unit, int side); + // ELF 0x3421C0: whether the unit under the iterator drives a known unit (its current + // equipment's information has a unit part). + bool bookBot(bool attacker, int side, std::set::iterator& it); + int getNumberOfAvailableBots(bool attackers, int side) const; // ELF 0x342330 + int getNumberOfAvailableAttackers(int side) const; // ELF 0x342360 + int getNumberOfAvailableDefenders(int side) const; // ELF 0x342380 + int getNumberOfPresentUnits(int side) const; // ELF 0x3423C0 + // ELF 0x3425F0: m_statistics[side + 1], the second (size-2) pair. Reference spelling + // [INFERRED], as getBattleStatistics. + EnemyStatistics& getStrategicStatistics(int side) const; + // ELF 0x342820 / 0x3428B0: empty the side's available set; answer the count it held + // (the image reloads the pre-clear size into eax). [INFERRED] int. + int unregisterAllAvailableAttackers(int side); + int unregisterAllAvailableDefenders(int side); + // ELF 0x342D40 / 0x342D90 / 0x342DD0: set a vehicle-group bit of +0xF4, which a -1 ("all") + // mask first resets to 0; the equipment and name forms map through IAISettings. + void addAllowedUnit(int equipment); + void addAllowedVehicleGroup(int group); + void addAllowedVehicleGroup(const std::string& group); + int getAllowedVehicleGroups() const; // ELF 0x342E20 + bool isAllowedUnit(int equipment) const; // ELF 0x342E30 + void addExpelledUnit(int equipment); // ELF 0x342EC0 + int getExpelledVehicleTypes() const; // ELF 0x342EE0 + // ELF 0x342F10: erases the group from m_set256; false when absent. + bool removeGrouping(int group); bool isAttack(int side) const; + void setAttack(bool attack, int side); // ELF 0x341FB0 + // ELF 0x342940: assigned squad strength / resource need (integer division), 1 without need. + float getAssignedPartOfWantedStrength(int side) const; // Borrowed mutable statistics at m_statistics[side - 1]; reference spelling is [INFERRED]. EnemyStatistics& getBattleStatistics(int side) const; int releaseAssignedResources(int side); + // ELF 0x3422A0..0x342300: the per-side available-unit sets (m_set20 attackers, m_set44 + // defenders), one-based side. Reference spelling [INFERRED]. + std::set& getAvailableBots(bool attackers, int side); + std::set& getAvailableAttackers(int side); + std::set& getAvailableDefenders(int side); + // ELF 0x3426E0 / 0x342780: erase the unit under the iterator and advance it; false at end(). + bool unregisterAvailableAttacker(std::set::iterator& it, int side); + bool unregisterAvailableDefender(std::set::iterator& it, int side); + bool registerAvailableAttacker(int unit, int side); // ELF 0x341FF0; always true + bool registerAvailableDefender(int unit, int side); // ELF 0x342040; always true + bool unregisterAvailableAttacker(int unit, int side); // ELF 0x342600 + bool unregisterAvailableDefender(int unit, int side); // ELF 0x342670 + // ELF 0x342310 / 0x3423E0..0x342550: assigned (m_set68) and present (m_set92) units. + std::set& getAssignedUnits(int side); + std::set& getPresentUnits(int side); + bool isPresentUnit(int unit, int side) const; + std::pair::iterator, bool> setAsPresentUnit(int unit, int side); + void removeAsPresentUnit(std::set::iterator& it, int side); + // ELF 0x3424C0: find in the present set, erase when found; answers the find result. + std::set::iterator removeAsPresentUnit(int unit, int side); + // ELF 0x342E80 / 0x342EF0: bit tests of the vehicle-group mask (+0xF4) and the expelled + // equipment mask (+0xF8). + bool isAllowedVehicleGroup(int group) const; + bool isExpelledUnit(int equipment) const; + // ELF 0x342EA0: `mov 0xf4(%eax),%eax; and %edx,%eax; setne` - any bit of a group mask. + bool allowsSomeVehicleGroups(int groupMask) const; + // ELF 0x342B80: a uniform point in the side's extent box (slots 29/30) scaled by `scale`, + // around the side's position, at height m_f148. + void randomizePos(int side, float scale, Vec3& position); + // ELF 0x342990: position += (sin a, 0, cos a) * scale * (0.5 + draw * (spread - 0.5)), a a + // uniform angle. + void randomizeControlpointPos(float scale, float spread, Vec3& position); // [INFERRED] accessor names/forms. SAI::updateStates and the area's neighbour scans inline // these loads: status is at +0x70 + 4*side and index at +0xF0 in both shipped x86 ports. StatusMap::Status getStatus(int side) const { return m_status[side - 1]; } int getIndex() const { return m_index; } + void resetStatus(); // ELF 0x342FC0 // [CHOSEN, not recovered] Public fields allow manager access; the original may have // used friendship instead. Offsets document ELF layout and do not constrain modern STL sizes. @@ -135,7 +206,10 @@ class AIStrategicObject /* +132 */ Vec2 m_position[2]; /* +148 */ float m_f148; // the constructor's second argument; -666.0f from every caller - /* +152 */ float m_size[3]; // [0] = the radius argument, [1] and [2] zeroed; read by side + // Console basicTemperature is element zero; update adds it to both temperature pairs. + // Keep the shared array spelling used by side-radius readers in other subsystems. + enum { kBasicTemperature = 0 }; + /* +152 */ float m_size[3]; // [kBasicTemperature] baseline temperature; [1..2] side radii /* +164 */ float m_f164[4]; // all four set to the radius argument [UNRESOLVED] // Paired Area::update reads/writes these as floats, not the formerly guessed ints. // [INFERRED] names; one-based side pairs, all zeroed by the base constructor. @@ -143,13 +217,13 @@ class AIStrategicObject /* +188 */ float m_friendlyRatio[2]; /* +196 */ float m_friendlyBattleStrength[2]; /* +204 */ float m_enemyBattleStrength[2]; - /* +212 */ int m_unresolved212[2]; // zeroed; these two preceding counts remain unidentified + /* +212 */ int m_unresolved212[2]; // zeroed; the per-side priority (setPriority / getPriority) /* +220 */ int m_resourceNeed[2]; /* +228 */ int m_assignedSquadStrength[2]; /* +236 */ bool m_attack[2]; // both true; isAttack(side) reads [side - 1] /* +240 */ int m_index; // not initialised here - addStrategicObject assigns it - /* +244 */ int m_i244; // 1 [UNRESOLVED] - /* +248 */ int m_i248; // 0 [UNRESOLVED] + /* +244 */ int m_i244; // -1; allowed vehicle-group bit mask (isAllowedVehicleGroup) + /* +248 */ int m_i248; // 0; expelled equipment bit mask (isExpelledUnit) /* +252 */ int m_category; // 1 until createFromControlPoint or create sets it /* +256 */ std::set m_set256; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp index cff7ed937..7180e795e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp @@ -1,13 +1,29 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIStrategicObjectManager operations. - #include "AIStrategicObjectManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34A400, __tcf_0 0x34A460, _GLOBAL__I 0x34A490). +#include + #include "AIStrategicArea.h" // createFromControlPoint constructs one +#include +#include // checkLayerStrList's strtok +#include "../AIKnowledge/Information.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../AIBot/SquadManager.h" // haveHumanPlayerOnOwnSide +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../../Math/Mat4.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "SAWayPoint.h" // the destructor and postLoadInitAreas own them #include "../AIUtils/checkPointer.h" #include "../AIUtils/DebugRendering/AIRenderUtil.h" // addStrategicObject's null-guarded tail #include "../Main/AIDllFrontier.h" -#include "../../../../Core/ConsoleObjectMacro.h" // the aiStrategicArea.* binding at the foot +#include "../Main/AISettingsInterfaces.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" +#include "../Main/AIStreamOperators.h" // StrategicObjectType names +#include "../../../../Core/StringUtil.h" // formatString namespace dice { namespace hfe { @@ -15,10 +31,70 @@ namespace ai { AIStrategicObjectManager* AIStrategicObjectManager::m_instance = 0; +// ELF 0x344F30: the object with the strongest gravity at the position among those allowing the +// equipment's vehicle group and not expelling it; areas that use the vehicle as a landing-zone +// user are skipped when a vehicle is given. Objects are not null-checked; ties keep the first. +AIStrategicObject* AIStrategicObjectManager::getClosestObject(const Vec3& position, int equipment, + int vehicle, int side) const +{ + AIStrategicObject* best = 0; + float bestGravity = 0.0f; + const int group = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment); + for (std::vector::const_iterator it = m_strategicObjects.begin(); + it != m_strategicObjects.end(); ++it) + { + if (!(*it)->isAllowedVehicleGroup(group) || (*it)->isExpelledUnit(equipment)) + continue; + if ((*it)->getType() == 0 && vehicle != -1 + && static_cast(*it)->isLandingZoneUser(vehicle)) + continue; + const float gravity = (*it)->gravity(position, side); + if (gravity > bestGravity) + { + bestGravity = gravity; + best = *it; + } + } + return best; +} + +// ELF 0x344E80, added by ai-w1-e-fire for BBPFireInfantery::createPlanInternal (0x265DA6; +// coord/ai-requests.md 2026-11-01): as getClosestObject(position, side), but only objects whose +// status for the side is 0 (`status == 0` when the flag is set, `status != 0` otherwise). The +// gravity is evaluated before the status test, as in the image. +AIStrategicObject* AIStrategicObjectManager::getClosestObject(const Vec3& position, int side, + bool statusZero) const +{ + AIStrategicObject* closest = 0; + float best = -1.0f; + for (std::vector::const_iterator it = m_strategicObjects.begin(); + it != m_strategicObjects.end(); ++it) + { + const double gravity = (*it)->gravity(position, side); + const bool zero = (*it)->getStatus(side) == 0; + if (zero != statusZero) + continue; + if (gravity > best) + { + best = static_cast(gravity); + closest = *it; + } + } + return closest; +} + +// ELF 0x346D40: the active-area cursor is the lookup result, end() when not found. +bool AIStrategicObjectManager::setActive(std::string name) +{ + m_activeArea = m_strategicAreas.find(name); + return m_activeArea != m_strategicAreas.end(); +} + // "Closest" is the greatest virtual gravity // starting at -1, not a distance calculation here. Strict comparison preserves // first-wins ties and ignores unordered results. Both ports reload the selected // pointer after gravity and the vector end on each iteration; neither guards nulls. +// ELF 0x344DF0. AIStrategicObject* AIStrategicObjectManager::getClosestObject( const Vec3& position, int side) const { @@ -44,6 +120,26 @@ AIStrategicObject* AIStrategicObjectManager::getClosestObject( // lea eax, [this+12] ; -> this+12 // so any non-zero selects the second list. Written literally. +// ELF 0x343340 (C2; C1 0x343380): both lists empty. +AIStrategicObjectManager::WPContainer::WPContainer() + : m_wayPointsA() + , m_wayPointsB() +{ +} + +// ELF 0x3433C0 (C2; C1 0x3434F0): member-wise vector copies. +AIStrategicObjectManager::WPContainer::WPContainer(const WPContainer& other) + : m_wayPointsA(other.m_wayPointsA) + , m_wayPointsB(other.m_wayPointsB) +{ +} + +// ELF 0x343660 (D2; D1 0x3436D0): the vectors go as members; the waypoints are not deleted here. +AIStrategicObjectManager::WPContainer::~WPContainer() +{ +} + +// ELF 0x343640. std::vector& AIStrategicObjectManager::WPContainer::getWayPoints(int type) { if (type) @@ -52,6 +148,7 @@ std::vector& AIStrategicObjectManager::WPContainer::getWayPoints(in return m_wayPointsA; } +// ELF 0x343620. const std::vector& AIStrategicObjectManager::WPContainer::getWayPoints(int type) const { if (type) @@ -60,11 +157,26 @@ const std::vector& AIStrategicObjectManager::WPContainer::getWayPoi return m_wayPointsA; } +// ELF 0x348E20: the container of the unordered area pair (min, max) - found unchecked, as in the +// image - and its list of the given type. +const std::vector& AIStrategicObjectManager::getWaypoints(int type, int a, int b) const +{ + const std::pair key(a < b ? a : b, a > b ? a : b); + return m_wayPoints.find(key)->second.getWayPoints(type); +} + +// ELF 0x348EB0: by the two areas' indices (+0xF0). +const std::vector& AIStrategicObjectManager::getWaypoints(int type, const AIStrategicArea* a, + const AIStrategicArea* b) const +{ + return getWaypoints(type, a->getIndex(), b->getIndex()); +} + // Initializes strategic-area collections and the active selection. AIStrategicObjectManager::AIStrategicObjectManager() - : m_areasInitialised(false) - , m_b84(false) + : m_debugEnabled(false) + , m_drawVehicleSearchRadii(false) , m_wayPointsToDrawFirst(-1) , m_wayPointsToDrawSecond(-1) { @@ -123,6 +235,7 @@ AIStrategicObjectManager::~AIStrategicObjectManager() // Initializes areas and waypoints after level loading, before pathfinding-map initialization. // Waypoint containers use an unordered area pair as their key. +// ELF 0x347CF0. void AIStrategicObjectManager::postLoadInitAreas() { WPContainer prototype; @@ -176,6 +289,7 @@ void AIStrategicObjectManager::postLoadInitAreas() // `_List_base::__clear`, which in this libstdc++ both frees the nodes and re-links the header, so // the source is `clear` and calling it twice (here and again from `~list`) is safe. +// ELF 0x349A10. void AIStrategicObjectManager::deleteBridges() { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -189,6 +303,7 @@ void AIStrategicObjectManager::deleteBridges() // Tracks each announced AI-enabled bridge segment by object pointer. Lookup stops at // the first match; unknown objects are ignored by update and removal operations. +// ELF 0x3498E0. void AIStrategicObjectManager::createBridgeSegment(IAIObject* object) { BridgeSegment* const segment = new BridgeSegment; // zeroes the position only - +4 stays unset @@ -202,6 +317,7 @@ void AIStrategicObjectManager::createBridgeSegment(IAIObject* object) } // The record is freed with a bare delete (a plain struct), then its node is erased. +// ELF 0x349970. void AIStrategicObjectManager::removeBridgeSegment(IAIObject* object) { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -216,6 +332,7 @@ void AIStrategicObjectManager::removeBridgeSegment(IAIObject* object) } } +// ELF 0x349E00. void AIStrategicObjectManager::bridgeSegmentDestroyed(IAIObject* object, int value) { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -230,7 +347,57 @@ void AIStrategicObjectManager::bridgeSegmentDestroyed(IAIObject* object, int val } } +// ELF 0x349ED0 (listing). Every segment's information position is read first (the object's +// information for side 1, IAIObject +0xB8, through the information manager; Information +0x30), +// including for intact segments, and neither lookup is null-tested. A destroyed segment counts +// unless it was destroyed by a human of `side` (the destroying player's id is +4; +// IAIPlayerFactory +0x20, getSide +0x6C, getIsAIPlayer +0x88) or, with no such player, a human of +// `side` is in the game (SquadManager::haveHumanPlayerOnOwnSide) - both only when no repair was +// requested. The nearest by squared distance from `from` to the information position wins: its +// record position and that squared distance are written out and its object returned; 0 for none. +IAIObject* AIStrategicObjectManager::getClosestDestroyedBridgeSegment(Vec3 from, bool repairRequested, int side, + Vec3& position, float& distance) +{ + IAIObject* closest = 0; + float best = 3.4028235e38f; + Vec3 segmentPosition = { 0.0f, 0.0f, 0.0f }; + IAIPlayerFactory* const players = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + for (std::list::iterator i = m_bridgeSegments.begin(); i != m_bridgeSegments.end(); ++i) + { + BridgeSegment* const segment = *i; + segmentPosition = informationManager->getInformation(segment->m_object->getInformation(1))->getPosition(); + if (!segment->m_destroyed) + continue; + bool ownHuman = false; + IAIPlayer* const destroyer = players->getPlayerFromId(segment->m_i4); // +0x20 + if (destroyer) + { + if (destroyer->getSide() == side) // +0x6C + ownHuman = !destroyer->getIsAIPlayer(); // +0x88 + } + else if (SquadManager::m_instance->haveHumanPlayerOnOwnSide(side)) + { + ownHuman = true; + } + if (!repairRequested && ownHuman) + continue; + const float dx = segmentPosition.x - from.x; + const float dy = segmentPosition.y - from.y; + const float dz = segmentPosition.z - from.z; + const float d = dx * dx + dy * dy + dz * dz; + if (best > d) + { + best = d; + closest = segment->m_object; + distance = d; + position = segment->m_position; + } + } + return closest; +} + // Only the flag is cleared; +4 keeps the value the destruction wrote. +// ELF 0x349E70. void AIStrategicObjectManager::bridgeSegmentRepaired(IAIObject* object) { for (std::list::iterator i = m_bridgeSegments.begin(); @@ -243,35 +410,122 @@ void AIStrategicObjectManager::bridgeSegmentRepaired(IAIObject* object) } } } -// [FRONTIER] Reset operations require the remaining strategic-area lifecycle behavior. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate area resets and collection rebuilding. +// ELF 0x345150 (from BF2AI::clear): clears the initialised flag, deletes every named area (slot 1) +// while erasing it node by node, clears the area names, points the active area at end(), empties +// the object list, the category lists and the category names (each through resize(0), the +// `size == 0 ? _M_fill_insert : erase` pair), then erases the category map node by node. The way +// points and bridge segments are left alone. Always true. bool AIStrategicObjectManager::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObjectManager::reset"); + m_debugEnabled = false; + for (std::map::iterator area = m_strategicAreas.begin(); + area != m_strategicAreas.end();) + { + if (area->second) + delete area->second; + m_strategicAreas.erase(area++); + } + if (!m_areaNames.empty()) + m_areaNames.clear(); + m_activeArea = m_strategicAreas.end(); + m_strategicObjects.resize(0, 0); + m_objectsByCategory.resize(0, std::vector()); + m_categoryNames.resize(0, std::string()); + for (std::map::iterator category = m_categories.begin(); category != m_categories.end();) + m_categories.erase(category++); + return true; } +// ELF 0x345520: clears the initialised flag and resets every area's status; always true. bool AIStrategicObjectManager::resetAreas() { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObjectManager::resetAreas"); + m_debugEnabled = false; + for (std::map::iterator it = m_strategicAreas.begin(); + it != m_strategicAreas.end(); ++it) + it->second->resetStatus(); + return true; +} + +// ELF 0x349A80. Every segment is marked intact again and gets its direction (+0x0C) back: the +// unit vector to the first other segment whose squared distance d lies in (0.01, (2r + 5)^2), +// r being this segment's physical radius (the bound is stored as a float before the compare); +// without such a neighbour, the object's transformation row 2 (+0x20). A neighbour distance is +// kept as is when |d - 1| < FLT_EPSILON and becomes zero when |d| < FLT_EPSILON. +// [CHOSEN, not recovered] x87 extended intermediates are carried in double here. +void AIStrategicObjectManager::resetBridges() +{ + for (std::list::iterator it = m_bridgeSegments.begin(); it != m_bridgeSegments.end(); ++it) + { + BridgeSegment* const segment = *it; + segment->m_destroyed = false; + Information* const information = + informationManager->getInformation(segment->m_object->getHandle(1)); + const Vec3 position = information->getPosition(); + const double radius = information->getPhysical()->getRadius(); + const float bound = static_cast((radius + radius + 5.0f) * (radius + radius + 5.0f)); + bool found = false; + for (std::list::iterator other = m_bridgeSegments.begin(); + other != m_bridgeSegments.end(); ++other) + { + Information* const neighbour = + informationManager->getInformation((*other)->m_object->getHandle(1)); + const Vec3& q = neighbour->getPosition(); + const double dx = static_cast(q.x) - position.x; + const double dy = static_cast(q.y) - position.y; + const double dz = static_cast(q.z) - position.z; + Vec3 diff; + diff.x = static_cast(dx); + diff.y = static_cast(dy); + diff.z = static_cast(dz); + const double distanceSq = dx * dx + dy * dy + dz * dz; + if (!(distanceSq > 0.01f) || !(bound > distanceSq)) + continue; + found = true; + if (!(std::fabs(distanceSq - 1.0f) < 1.1920928955078125e-07f)) + { + if (!(std::fabs(distanceSq) < 1.1920928955078125e-07f)) + { + const double scale = 1.0f / std::sqrt(distanceSq); + diff.x = static_cast(diff.x * scale); + diff.y = static_cast(diff.y * scale); + diff.z = static_cast(diff.z * scale); + } + else + diff.x = diff.y = diff.z = 0.0f; + } + segment->m_position = diff; + break; + } + if (!found) + { + const Mat4& transformation = segment->m_object->getTransformation(); + segment->m_position.x = transformation.m[8]; + segment->m_position.y = transformation.m[9]; + segment->m_position.z = transformation.m[10]; + } + } } // The accessors that are two or three instructions. Each is transcribed from its own body; none of // them needs a type this file does not have. // `BF2AI::clear` destroys the object through this rather than through the // static, which is the only reason it exists. +// ELF 0x3448F0. AIStrategicObjectManager* AIStrategicObjectManager::getInstance() { return m_instance; } // - `return (char *)this + 4;` +// ELF 0x344AD0. const std::vector& AIStrategicObjectManager::getStrategicObjects() const { return m_strategicObjects; } // - the byte difference shifted right by two, i.e. the element count. +// ELF 0x344AE0. int AIStrategicObjectManager::getNumberOfStrategicObjects() const { return (int)m_strategicObjects.size(); @@ -285,17 +539,20 @@ AIStrategicObjectManager::getStrategicObjectsOfCategory(int category) const } // - same shape, four bytes per `std::string`, again unchecked. +// ELF 0x347910. const std::string& AIStrategicObjectManager::getCategoryName(int category) const { return m_categoryNames[category]; } +// ELF 0x345610. int AIStrategicObjectManager::getNumberOfCategories() { return (int)m_categoryNames.size(); } // - `return (char *)this + 32;` +// ELF 0x3476A0. const std::map& AIStrategicObjectManager::getStrategicAreas() const { return m_strategicAreas; @@ -303,6 +560,7 @@ const std::map& AIStrategicObjectManager::getStra // Returns null while no area is active - `m_activeArea` starts at `end` and // the constructor is the only thing that puts it there. +// ELF 0x345630. AIStrategicArea* AIStrategicObjectManager::getActiveArea() { if (m_activeArea != m_strategicAreas.end()) @@ -312,6 +570,7 @@ AIStrategicArea* AIStrategicObjectManager::getActiveArea() } // This one checks both ends, and returns null rather than clamping. +// ELF 0x344910. AIStrategicObject* AIStrategicObjectManager::getStrategicObject(int index) const { if (index < 0) @@ -323,21 +582,51 @@ AIStrategicObject* AIStrategicObjectManager::getStrategicObject(int index) const return m_strategicObjects[index]; } +// ELF 0x344940 (added by air/s2 for GuardPosition::update): the named area, null when unknown. +AIStrategicObject* AIStrategicObjectManager::getStrategicObject(const std::string& name) const +{ + const std::map::const_iterator it = m_strategicAreas.find(name); + if (it != m_strategicAreas.end()) + return it->second; + return 0; +} + +// ELF 0x3449E0 (added by ai-bot for WPMoveTo::getUrgency): the object at `index` when its type +// (vtable +8, getType) is 0 - an area - else null; out-of-range indices give null. +AIStrategicArea* AIStrategicObjectManager::getStrategicArea(int index) const +{ + if (index < 0 || index >= (int)m_strategicObjects.size()) + return 0; + if (m_strategicObjects[index]->getType() != 0) + return 0; + return static_cast(m_strategicObjects[index]); +} + // Disables waypoint drawing by clearing the first key component; leaves the second unchanged. +// ELF 0x349390. void AIStrategicObjectManager::clearWaypointToDraw() { m_wayPointsToDrawFirst = -1; } -// [FRONTIER] Waypoint drawing cleanup remains unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIStrategicObjectManager operation. +// ELF 0x349040: every waypoint container (+0x58), type 0 then type 1, undraws each waypoint. void AIStrategicObjectManager::undrawWayPoints() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIStrategicObjectManager::undrawWayPoints"); + for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); + it != m_wayPoints.end(); ++it) + { + for (int type = 0; type < 2; ++type) + { + const std::vector& points = it->second.getWayPoints(type); + for (std::vector::const_iterator wp = points.begin(); wp != points.end(); ++wp) + (*wp)->undraw(); + } + } } // Returns the category id for an existing name. The caller must ensure that exact // name exists; merely having a nonempty category map is insufficient. +// ELF 0x347930. int AIStrategicObjectManager::getCategoryFromName(const std::string& name) const { return m_categories.find(name)->second; @@ -345,6 +634,7 @@ int AIStrategicObjectManager::getCategoryFromName(const std::string& name) const // Adds an object to the category table and assigns its index. The object and category must be valid. // Other category rows retain null entries at that index. +// ELF 0x344B20. void AIStrategicObjectManager::addStrategicObject(AIStrategicObject* object) { const int index = (int)m_strategicObjects.size(); @@ -368,6 +658,7 @@ void AIStrategicObjectManager::addStrategicObject(AIStrategicObject* object) } // Initializes areas with explicit bounds. Control-point areas wait for postLoadInit(). +// ELF 0x345590. void AIStrategicObjectManager::initAreas() { for (std::map::iterator i = m_strategicAreas.begin(); @@ -380,6 +671,7 @@ void AIStrategicObjectManager::initAreas() // Creates a strategic area from a named control point and selects it. // Returns false and clears the active selection when creation is refused. +// ELF 0x345C40. bool AIStrategicObjectManager::createFromControlPoint(const std::string& name, unsigned controlPointId, float radius, @@ -411,35 +703,624 @@ bool AIStrategicObjectManager::createFromControlPoint(const std::string& name, return true; } -// Console bindings for strategic-area configuration. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x344990: bounded by the object count, not by the category row. Unchecked category. +AIStrategicObject* AIStrategicObjectManager::getStrategicObjectOfCategory(int index, int category) const +{ + if (index < 0 || index >= static_cast(m_strategicObjects.size())) + return 0; + return m_objectsByCategory[category][index]; +} -namespace { +// ELF 0x344A40: as getStrategicObjectOfCategory, but only an area (getType() == 0). +AIStrategicArea* AIStrategicObjectManager::getStrategicAreaOfCategory(int index, int category) const +{ + if (index < 0 || index >= static_cast(m_strategicObjects.size())) + return 0; + if (!m_objectsByCategory[category][index] || m_objectsByCategory[category][index]->getType() != 0) + return 0; + return static_cast(m_objectsByCategory[category][index]); +} + +// ELF 0x344D00: clears the object's category slot (when its category is in range) and erases the +// first matching entry of the object list. Later objects keep their stored indices. +AIStrategicObject* AIStrategicObjectManager::removeStrategicObject(int index) +{ + if (index < 0 || index >= static_cast(m_strategicObjects.size())) + return 0; + + AIStrategicObject* const object = m_strategicObjects[index]; + const int category = object->m_category; + if (category >= 0 && category < static_cast(m_objectsByCategory.size())) + m_objectsByCategory[category][index] = 0; + + for (std::vector::iterator it = m_strategicObjects.begin(); + it != m_strategicObjects.end(); ++it) + { + if (*it == object) + { + m_strategicObjects.erase(it); + break; + } + } + return object; +} + +// ELF 0x345020: getClosestObject's vehicle-group form over one category row (0 for a category +// out of range). The vehicle group is queried before the range test. +AIStrategicObject* AIStrategicObjectManager::getClosestObjectinCategory(const Vec3& position, int side, + int category, int equipment, + int vehicle) const +{ + AIStrategicObject* best = 0; + float bestGravity = 0.0f; + const int group = + static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment); + if (category < 0 || category >= static_cast(m_objectsByCategory.size())) + return best; + + const std::vector& objects = m_objectsByCategory[category]; + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + if (!(*it)->isAllowedVehicleGroup(group) || (*it)->isExpelledUnit(equipment)) + continue; + if ((*it)->getType() == 0 && vehicle != -1 + && static_cast(*it)->isLandingZoneUser(vehicle)) + continue; + const float gravity = (*it)->gravity(position, side); + if (gravity > bestGravity) + { + bestGravity = gravity; + best = *it; + } + } + return best; +} + +// ELF 0x345650: unchecked active area. +void AIStrategicObjectManager::setFlankPosition(Vec3 first, Vec3 second) +{ + m_activeArea->second->addFlankPosition(first, second); +} + +// ELF 0x3456D0: createFromControlPoint's sequence around the bounded area constructor. +bool AIStrategicObjectManager::create(std::string name, Vec2 topLeft, Vec2 centre, float height, + float radius, const std::string& category) +{ + if (m_strategicAreas.find(name) != m_strategicAreas.end()) + { + m_activeArea = m_strategicAreas.end(); + return false; + } + + AIStrategicArea* const area = + checkPointer(new AIStrategicArea(name, topLeft, centre, height, radius)); + if (!area) + { + m_activeArea = m_strategicAreas.end(); + return false; + } + + if (getNumberOfCategories() <= 0) + area->m_category = 0; + else + area->m_category = getCategoryFromName(category); + + AIStrategicObjectManager::getInstance()->addStrategicObject(area); + + m_strategicAreas[name] = area; + m_areaNames[area] = name; + m_activeArea = m_strategicAreas.find(name); + return true; +} + +// ELF 0x3461A0: unlinks the active area from its neighbours, drops both name entries, its debug +// rendering and its object slot, then deletes it. AIRenderUtil::m_instance is not null-checked. +bool AIStrategicObjectManager::removeActive() +{ + if (m_activeArea == m_strategicAreas.end()) + return false; + AIStrategicArea* area = m_activeArea->second; + if (!area) + return false; + + for (std::vector::iterator it = area->m_neighbours.begin(); + it != area->m_neighbours.end(); ++it) + static_cast(*it)->removeNeighbour(area); + + std::map::iterator name = m_areaNames.find(area); + if (name != m_areaNames.end()) + m_areaNames.erase(name); + m_strategicAreas.erase(m_activeArea); + m_activeArea = m_strategicAreas.end(); + + AIRenderUtil::m_instance->unrenderStrategicArea(area); + AIRenderUtil::m_instance->updateNumberOfStrategicAreas(); + removeStrategicObject(area->m_index); + delete area; + return true; +} + +// ELF 0x3463B0: the active area (unchecked) gains the named area as a neighbour and the named +// area gains the active one as a neighbouring object. +bool AIStrategicObjectManager::addNeighbour(std::string name) +{ + std::map::iterator it = m_strategicAreas.find(name); + if (it == m_strategicAreas.end()) + return false; + if (m_activeArea->second->m_i400 != it->second->m_i400) + return false; + m_activeArea->second->addNeighbour(it->second); + it->second->addNeighbouringObject(m_activeArea->second); + return true; +} + +// ELF 0x346460: both directions, in the image's call order. +bool AIStrategicObjectManager::addTwoWayNeighbour(std::string first, std::string second) +{ + std::map::iterator a = m_strategicAreas.find(first); + if (a == m_strategicAreas.end()) + return false; + std::map::iterator b = m_strategicAreas.find(second); + if (b == m_strategicAreas.end()) + return false; + if (a->second->m_i400 != b->second->m_i400) + return false; + a->second->addNeighbour(b->second); + b->second->addNeighbouringObject(a->second); + b->second->addNeighbour(a->second); + a->second->addNeighbouringObject(b->second); + return true; +} + +// ELF 0x346590. +void AIStrategicObjectManager::removeAllNeighbours() +{ + if (m_activeArea != m_strategicAreas.end()) + m_activeArea->second->removeAllNeighbours(); +} + +// ELF 0x3465D0: the active area's neighbour names, each followed by a newline ("" without an +// active area). The neighbour list is copied first; the name lookups are unchecked. +std::string AIStrategicObjectManager::getNeighbours() +{ + if (m_activeArea == m_strategicAreas.end()) + return ""; + + const std::vector neighbours = m_activeArea->second->m_neighbours; + std::string names; + for (std::vector::const_iterator it = neighbours.begin(); + it != neighbours.end(); ++it) + { + names.append(m_areaNames.find(static_cast(*it))->second); + names.append("\n"); + } + return names; +} + +// ELF 0x3467B0. +int AIStrategicObjectManager::addObjectTypeFlag(AIStrategicObject::StrategicObjectType type) +{ + if (m_activeArea == m_strategicAreas.end() || type == 27) + return -1; + return m_activeArea->second->addObjectTypeFlag(type); +} + +// ELF 0x346800. Shipped defect, preserved: the bit is toggled (xor), not cleared. +int AIStrategicObjectManager::removeObjectTypeFlag(AIStrategicObject::StrategicObjectType type) +{ + if (m_activeArea == m_strategicAreas.end() || type == 27) + return -1; + return m_activeArea->second->m_objectTypeFlags ^= 1 << type; +} + +// ELF 0x346850. +int AIStrategicObjectManager::setObjectTypeFlags(int flags) +{ + if (m_activeArea == m_strategicAreas.end()) + return -1; + return m_activeArea->second->setObjectTypeFlags(flags); +} + +// ELF 0x3468A0: through the virtual getter (slot 18). +int AIStrategicObjectManager::getObjectTypeFlags() +{ + if (m_activeArea == m_strategicAreas.end()) + return -1; + return m_activeArea->second->getObjectTypeFlags(); +} + +// ELF 0x3468D0. +void AIStrategicObjectManager::removeAllObjectTypeFlags() +{ + if (m_activeArea != m_strategicAreas.end()) + m_activeArea->second->m_objectTypeFlags = 0; +} + +// ELF 0x346900: " " per line for the types 1..20. +std::string AIStrategicObjectManager::getObjectTypeFlagMapping() const +{ + std::stringstream stream; + for (unsigned int type = 1; type < 21; ++type) + stream << type << " " << static_cast(type) << std::endl; + return stream.str(); +} + +// ELF 0x346DB0: the active area's name, "" without one. +std::string AIStrategicObjectManager::getActive() const +{ + if (m_activeArea == m_strategicAreas.end()) + return ""; + return m_activeArea->first; +} + +// ELF 0x346E20: every area name, one per line. +std::string AIStrategicObjectManager::list() const +{ + std::stringstream stream; + for (std::map::const_iterator it = m_strategicAreas.begin(); + it != m_strategicAreas.end(); ++it) + { + const std::string name = it->first; + stream << name << std::endl; + } + return stream.str(); +} + +// ELF 0x3471A0: false without an active area or pathfinding, or for an unknown map name. +bool AIStrategicObjectManager::setOrderPosition(std::string map, const Vec3& position) +{ + if (m_activeArea == m_strategicAreas.end() || !IAIPathfinding::instance) + return false; + const int id = IAIPathfinding::instance->getMapIdFromName(map); + if (id == -1) + return false; + return m_activeArea->second->setOrderPos(id, position); +} + +// ELF 0x347240: the active area's order position on the named map; zero otherwise. +Vec3 AIStrategicObjectManager::getOrderPosition(std::string map) +{ + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + if (m_activeArea == m_strategicAreas.end() || !IAIPathfinding::instance) + return position; + const int id = IAIPathfinding::instance->getMapIdFromName(map); + if (id == -1) + return position; + return m_activeArea->second->getOrderPos(id, 1); +} + +// ELF 0x347300: " x/y/z" per pathfinding map for the active area; "" without an +// active area or pathfinding. The image inlines the x/y/z stream operator. +std::string AIStrategicObjectManager::listOrderPositions() +{ + if (m_activeArea == m_strategicAreas.end() || !IAIPathfinding::instance) + return ""; + + std::ostringstream stream; + for (unsigned int map = 0; map < static_cast(IAIPathfinding::instance->getNumberOfMaps()); + ++map) + { + const std::string& name = IAIPathfinding::instance->getMapNameFromId(map); + const Vec3 position = m_activeArea->second->getOrderPos(map, 1); + stream << map << " " << name << " " << position.x << '/' << position.y << '/' << position.z + << "\n"; + } + return stream.str(); +} + +// ELF 0x3476B0: the area names joined by newlines. +std::string AIStrategicObjectManager::getStrategicAreaNames() +{ + std::string names; + for (std::map::const_iterator it = m_strategicAreas.begin(); + it != m_strategicAreas.end(); ++it) + names = names.empty() ? it->first : names + "\n" + it->first; + return names; +} + +// ELF 0x3478D0: the active area's side-1 position (slot 3); unchecked active area. +Vec2 AIStrategicObjectManager::getPosition() const +{ + return m_activeArea->second->getPosition(1); +} + +// ELF 0x347980: a new last category, its name index and an object row as long as the object list. +void AIStrategicObjectManager::createNewCategory(const std::string& name) +{ + const int index = static_cast(m_categoryNames.size()); + m_categoryNames.resize(index + 1); + m_categoryNames[index] = name; + m_categories.insert(std::make_pair(name, index)); + m_objectsByCategory.resize(index + 1); + m_objectsByCategory[index].resize(m_strategicObjects.size()); +} + +// ELF 0x347C80: false for an unknown area name. +bool AIStrategicObjectManager::isInside(const std::string& name, const Vec2& position) +{ + std::map::iterator it = m_strategicAreas.find(name); + if (it == m_strategicAreas.end()) + return false; + return it->second->isInside(position); +} + +// ELF 0x348020: a waypoint on the named map between two different areas, keyed by their +// (lower, higher) indices; the container is created on first use. +void AIStrategicObjectManager::addWayPoint(const Vec3& position, const std::string& map, + const std::string& first, const std::string& second) +{ + std::map::iterator a = m_strategicAreas.find(first); + if (a == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1144, "") + << first << " is not the name of a valid strategic area."; + return; + } + std::map::iterator b = m_strategicAreas.find(second); + if (b == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1151, "") + << second << " is not the name of a valid strategic area."; + return; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } + if (low == high) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1171, "") + << "Must have two different strategic areas when adding waypoints."; + return; + } -const char* const kAiStrategicAreaConsoleTag = "aiStrategicArea"; + WPContainer container; + std::map, WPContainer>::iterator it = + m_wayPoints.insert(std::make_pair(std::make_pair(low->m_index, high->m_index), container)).first; + const int id = IAIPathfinding::instance->getMapIdFromName(map); + std::vector& points = it->second.getWayPoints(id); + points.push_back(checkPointer(new SAWayPoint(position, id))); +} -void consoleAiStrategicAreaCreateFromControlPoint(const std::string& name, - unsigned int controlPointId, - float radius) +// ELF 0x348630: deletes the waypoint of the pair's list closest to `position` within a squared +// distance of 10; false when none is that close or a name is unknown. Same-area pairs are not +// refused here, and the container lookup is unchecked. +bool AIStrategicObjectManager::removeWayPoint(const Vec3& position, const std::string& map, + const std::string& first, const std::string& second) { - // No null check on the singleton, matching every other console forwarder in this DLL: - // `BF2AI::init` builds the manager as step 17 during `initDll`, and `GameLogic::load` runs - // `StrategicAreas.ai` long afterwards. The `isObjectActive` test below is the real guard. - AIStrategicObjectManager::getInstance()->createFromControlPoint( - name, controlPointId, radius, std::string()); // [CHOSEN] empty category - see above + std::map::iterator a = m_strategicAreas.find(first); + if (a == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1191, "") + << first << " is not the name of a valid strategic area."; + return false; + } + std::map::iterator b = m_strategicAreas.find(second); + if (b == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1198, "") + << second << " is not the name of a valid strategic area."; + return false; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } + + const std::pair key(low->m_index, high->m_index); + std::map, WPContainer>::iterator it = m_wayPoints.find(key); + const int id = IAIPathfinding::instance->getMapIdFromName(map); + std::vector& points = it->second.getWayPoints(id); + + float best = 10.0f; + std::vector::iterator closest = points.end(); + for (std::vector::iterator wp = points.begin(); wp != points.end(); ++wp) + { + const Vec3& at = (*wp)->getPosition(); + const float dx = at.x - position.x; + const float dy = at.y - position.y; + const float dz = at.z - position.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + { + closest = wp; + best = distance; + } + } + if (closest == points.end()) + return false; + + delete *closest; + points.erase(closest); + return true; } -} // anonymous namespace +// ELF 0x348A90: deletes every waypoint of the pair's list on the named map and empties it +// (resize(0)). The container lookup is unchecked. +void AIStrategicObjectManager::clearWayPoints(const std::string& map, const std::string& first, + const std::string& second) +{ + std::map::iterator a = m_strategicAreas.find(first); + if (a == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1253, "") + << first << " is not the name of a valid strategic area."; + return; + } + std::map::iterator b = m_strategicAreas.find(second); + if (b == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1260, "") + << second << " is not the name of a valid strategic area."; + return; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } -BF2_CONSOLE_OBJECT("aiStrategicArea", 2, 0) -BF2_CONSOLE_METHOD_3(createFromControlPoint, consoleAiStrategicAreaCreateFromControlPoint, - AIStrategicObjectManager::getInstance() != 0, - std::string, unsigned int, float, kAiStrategicAreaConsoleTag) + const std::pair key(low->m_index, high->m_index); + std::map, WPContainer>::iterator it = m_wayPoints.find(key); + const int id = IAIPathfinding::instance->getMapIdFromName(map); + std::vector& points = it->second.getWayPoints(id); + for (std::vector::iterator wp = points.begin(); wp != points.end(); ++wp) + delete *wp; + points.resize(0); +} -// Handed to the console registry by AIModule::init, beside the `ai` and `aiSettings` lists. -ConsoleObjectList& aiStrategicAreaConsoleObjects() +// ELF 0x348F00: the selected pair's waypoints (lookup unchecked), or every container's when either +// half of the selection is -1; type 0 then type 1. +void AIStrategicObjectManager::drawWayPoints() const { - return consoleBindingList(kAiStrategicAreaConsoleTag); + if (m_wayPointsToDrawFirst != -1 && m_wayPointsToDrawSecond != -1) + { + const std::pair key(m_wayPointsToDrawFirst, m_wayPointsToDrawSecond); + const WPContainer& container = m_wayPoints.find(key)->second; + const std::vector& infantry = container.getWayPoints(0); + for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) + (*wp)->draw(); + const std::vector& vehicles = container.getWayPoints(1); + for (std::vector::const_iterator wp = vehicles.begin(); wp != vehicles.end(); ++wp) + (*wp)->draw(); + return; + } + + for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); + it != m_wayPoints.end(); ++it) + { + const std::vector& infantry = it->second.getWayPoints(0); + for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) + (*wp)->draw(); + const std::vector& vehicles = it->second.getWayPoints(1); + for (std::vector::const_iterator wp = vehicles.begin(); wp != vehicles.end(); ++wp) + (*wp)->draw(); + } +} + +// ELF 0x349100: selects the pair (lower, higher index) whose waypoints drawWayPoints shows. +void AIStrategicObjectManager::setWayPointsToDraw(const std::string& first, const std::string& second) +{ + std::map::iterator a = m_strategicAreas.find(first); + if (a == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1371, "") + << first << " is not the name of a valid strategic area."; + return; + } + std::map::iterator b = m_strategicAreas.find(second); + if (b == m_strategicAreas.end()) + { + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1378, "") + << second << " is not the name of a valid strategic area."; + return; + } + + AIStrategicArea* low = b->second; + AIStrategicArea* high = a->second; + if (a->second->m_index < b->second->m_index) + { + low = a->second; + high = b->second; + } + m_wayPointsToDrawFirst = low->m_index; + m_wayPointsToDrawSecond = high->m_index; +} + +namespace { + +// ELF 0x3493B0: whether the decimal layer is one of the "|"-separated entries. strtok runs on +// the copy's buffer. +bool checkLayerStrList(const std::string& list, int layer) +{ + std::string copy = list; + const std::string wanted = formatString("%d", layer); + char* token = std::strtok(const_cast(copy.c_str()), "|"); + while (token) + { + if (std::string(token) == wanted) + return true; + token = std::strtok(0, "|"); + } + return false; +} + +} // namespace + +// ELF 0x349610. The image inlines the x/y/z stream operator. +void AIStrategicObjectManager::streamWaypoints(std::ostringstream& out, + const std::string& excludedLayers) const +{ + for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); + it != m_wayPoints.end(); ++it) + { + AIStrategicArea* const first = getStrategicArea(it->first.first); + if (!excludedLayers.empty() && checkLayerStrList(excludedLayers, first->m_i400)) + continue; + AIStrategicArea* const second = getStrategicArea(it->first.second); + + const std::vector& infantry = it->second.getWayPoints(0); + for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) + { + const Vec3& at = (*wp)->getPosition(); + out << "aiStrategicArea.addWayPoint " << at.x << '/' << at.y << '/' << at.z + << " Infantry " << first->m_name << " " << second->m_name << std::endl; + } + const std::vector& vehicles = it->second.getWayPoints(1); + for (std::vector::const_iterator wp = vehicles.begin(); wp != vehicles.end(); ++wp) + { + const Vec3& at = (*wp)->getPosition(); + out << "aiStrategicArea.addWayPoint " << at.x << '/' << at.y << '/' << at.z + << " Vehicle " << first->m_name << " " << second->m_name << std::endl; + } + } +} + +// ELF 0x34A150: queries every area's order position on every map and discards them (the copy of +// the area map and the loop survive in the image; the checks they fed are compiled out). +void AIStrategicObjectManager::checkAllOrderPositions() const +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + const std::map areas = getStrategicAreas(); + for (std::map::const_iterator it = areas.begin(); it != areas.end(); + ++it) + { + AIStrategicArea* const area = it->second; + const int maps = pathfinding->getNumberOfMaps(); + for (int map = 0; map < maps; ++map) + area->getOrderPos(map, 1); + } +} + +// ELF 0x34A350: walks every container's two lists without effect (the image keeps the empty +// loops; whatever they checked is compiled out). +void AIStrategicObjectManager::checkAllWayPoints() const +{ + for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); + it != m_wayPoints.end(); ++it) + { + for (int type = 0; type < 2; ++type) + { + const std::vector& points = it->second.getWayPoints(type); + for (std::vector::const_iterator wp = points.begin(); wp != points.end(); ++wp) + { + } + } + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h index e18fab36b..faa61eefa 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -13,6 +14,7 @@ // `dice::hfe::Math::Vec2/Vec3`, not classes in `dice::hfe`, so a local `struct Vec3;` is a // redefinition with a different basic type (C2371). The header has to come in. #include "../../../../Math/Vec3.h" +#include "AIStrategicObject.h" // StrategicObjectType namespace dice { namespace hfe { @@ -30,6 +32,10 @@ class AIStrategicObjectManager class WPContainer { public: + WPContainer(); // ELF 0x343340 (C2; C1 0x343380) + WPContainer(const WPContainer& other); // ELF 0x3433C0 (C2; C1 0x3434F0) + ~WPContainer(); // ELF 0x343660 (D2; D1 0x3436D0) + std::vector& getWayPoints(int type); const std::vector& getWayPoints(int type) const; @@ -71,11 +77,14 @@ class AIStrategicObjectManager AIStrategicObject* getStrategicObject(const std::string&) const; AIStrategicObject* getStrategicObjectOfCategory(int, int) const; void addStrategicObject(AIStrategicObject*); - void removeStrategicObject(int); + // ELF 0x344D00: the removed object, or 0 for an index out of range. + AIStrategicObject* removeStrategicObject(int index); AIStrategicObject* getClosestObject(const Vec3&, int) const; AIStrategicObject* getClosestObject(const Vec3&, int, bool) const; AIStrategicObject* getClosestObject(const Vec3&, int, int, int) const; - AIStrategicObject* getClosestObjectinCategory(const Vec3&, int, int, int, int) const; + // ELF 0x345020. [INFERRED] parameter names, from their uses. + AIStrategicObject* getClosestObjectinCategory(const Vec3& position, int side, int category, + int equipment, int vehicle) const; // strategic areas AIStrategicArea* getStrategicArea(int) const; @@ -83,24 +92,29 @@ class AIStrategicObjectManager const std::map& getStrategicAreas() const; std::string getStrategicAreaNames(); AIStrategicArea* getActiveArea(); - void setActive(std::string); + bool setActive(std::string name); // ELF 0x346D40; answers whether the name was found std::string getActive() const; // Initializes strategic areas; has no return value. void initAreas(); void postLoadInitAreas(); Vec2 getPosition() const; bool isInside(const std::string&, const Vec2&); - void create(std::string, Vec2, Vec2, float, float, const std::string&); + // ELF 0x3456D0: answers false (and clears the active area) for a duplicate name or a failed + // allocation, true after creating and selecting the area. + bool create(std::string name, Vec2 topLeft, Vec2 centre, float height, float radius, + const std::string& category = ""); // ConsoleClass417 passes "" for five arguments // Creates an area from a control point. Returns false for duplicate names or allocation // failure and true after successful creation. - bool createFromControlPoint(const std::string&, unsigned, float, const std::string&); - void removeActive(); + // ConsoleClass419 passes "" when the category is omitted. + bool createFromControlPoint(const std::string&, unsigned, float, const std::string& = ""); + bool removeActive(); // ELF 0x3461A0; false without an active area void setFlankPosition(Vec3, Vec3); std::string list() const; // neighbours - void addNeighbour(std::string); - void addTwoWayNeighbour(std::string, std::string); + // ELF 0x3463B0 / 0x346460: false for an unknown name or areas of different layers (+0x190). + bool addNeighbour(std::string); + bool addTwoWayNeighbour(std::string, std::string); void removeAllNeighbours(); std::string getNeighbours(); @@ -111,9 +125,10 @@ class AIStrategicObjectManager void createNewCategory(const std::string&); // object type flags - void addObjectTypeFlag(int); - void removeObjectTypeFlag(int); - void setObjectTypeFlags(int); + // The active area's new flag word, or -1 without an active area (or for type 27). + int addObjectTypeFlag(AIStrategicObject::StrategicObjectType); // ELF 0x3467B0 + int removeObjectTypeFlag(AIStrategicObject::StrategicObjectType); // ELF 0x346800 + int setObjectTypeFlags(int); // ELF 0x346850 int getObjectTypeFlags(); void removeAllObjectTypeFlags(); std::string getObjectTypeFlagMapping() const; @@ -122,11 +137,11 @@ class AIStrategicObjectManager bool setOrderPosition(std::string, const Vec3&); Vec3 getOrderPosition(std::string); std::string listOrderPositions(); - std::string checkAllOrderPositions() const; + void checkAllOrderPositions() const; // ELF 0x34A150: no result (plain retl) // waypoints void addWayPoint(const Vec3&, const std::string&, const std::string&, const std::string&); - void removeWayPoint(const Vec3&, const std::string&, const std::string&, const std::string&); + bool removeWayPoint(const Vec3&, const std::string&, const std::string&, const std::string&); void clearWayPoints(const std::string&, const std::string&, const std::string&); const std::vector& getWaypoints(int, int, int) const; const std::vector& getWaypoints(int, const AIStrategicArea*, const AIStrategicArea*) const; @@ -134,7 +149,10 @@ class AIStrategicObjectManager void undrawWayPoints() const; void setWayPointsToDraw(const std::string&, const std::string&); void clearWaypointToDraw(); - std::string checkAllWayPoints() const; + void checkAllWayPoints() const; // ELF 0x34A350: no result (plain retl) + // ELF 0x349610: an `aiStrategicArea.addWayPoint` line per waypoint, skipping containers whose + // first area's layer is listed in `excludedLayers` ("|"-separated). + void streamWaypoints(std::ostringstream& out, const std::string& excludedLayers) const; // bridges void createBridgeSegment(IAIObject*); @@ -143,7 +161,11 @@ class AIStrategicObjectManager void resetBridges(); void bridgeSegmentDestroyed(IAIObject*, int); void bridgeSegmentRepaired(IAIObject*); - bool getClosestDestroyedBridgeSegment(Vec3, bool, int, Vec3&, float&); + // Returns the nearest destroyed segment's object (ELF 0x349ED0 returns the pointer; the mangled + // name carries no return type). `position` receives the segment record's position, `distance` + // the squared distance. + IAIObject* getClosestDestroyedBridgeSegment(Vec3 from, bool repairRequested, int side, Vec3& position, + float& distance); static AIStrategicObjectManager* m_instance; @@ -154,9 +176,10 @@ class AIStrategicObjectManager // pointer, a node count and four bytes of empty comparator) and a `std::list` in four. /* +4 */ std::vector m_strategicObjects; /* +16 */ std::vector > m_objectsByCategory; - // [UNRESOLVED] Cleared by construction and resets, but no implemented method sets or - // reads it. The current name does not establish its meaning. - /* +28 */ bool m_areasInitialised; +public: + // [CHOSEN, not recovered] Visibility for the generated inline debug control. + /* +28 */ bool m_debugEnabled; // false; console enableDebug +private: /* +32 */ std::map m_strategicAreas; // The reverse index. Its value type is `std::string` - read straight off the destructor's // `_Rb_tree, ...>` teardown. @@ -167,12 +190,13 @@ class AIStrategicObjectManager /* +56 */ std::map::iterator m_activeArea; /* +60 */ std::map m_categories; /* +72 */ std::vector m_categoryNames; - // Written 0 by the constructor and never touched again anywhere in this class. [UNRESOLVED]. - /* +84 */ bool m_b84; +public: + // [CHOSEN, not recovered] Visibility for the generated inline drawing control. + /* +84 */ bool m_drawVehicleSearchRadii; // false; console drawVehicleSearchRadi +private: /* +88 */ std::map, WPContainer> m_wayPoints; // The two halves of a `m_wayPoints` key, both -1 for "nothing selected". - // `clearWaypointToDraw` resets only the first of the two. `drawWayPoints` tests - // only the first as well, so the stale second half is never read - but it is left stale. + // `clearWaypointToDraw` resets only the first of the two; `drawWayPoints` tests both. /* +100 */ int m_wayPointsToDrawFirst; /* +104 */ int m_wayPointsToDrawSecond; /* +108 */ std::list m_bridgeSegments; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp new file mode 100644 index 000000000..9831b1067 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp @@ -0,0 +1,409 @@ +// [INFERRED] Source placement: the TU's static initializer is _GLOBAL__I__ZN4dice3hfe2ai14AreaAssignmentC2Ev. + +#include "AreaAssignment.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34E7F0, __tcf_0 0x34E850, _GLOBAL__I 0x34E880). +#include + +#include "../AIStrategic/SAI.h" // EnemyStatistics + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x34D5A0 (C2; C1 0x34D630). +AreaAssignment::AreaAssignment() + : m_effectiveTarget(0), m_effectiveAssigned(0), m_assigned(0), m_target(0), m_testAssigned(0) + , m_testEffectiveAssigned(0), m_testQuotient(0), m_testDifference(0), m_testAssignedCount(0) + , m_assignedCount(0), m_targetCount(0), m_difference(0), m_quotient(0) + , m_sqrDistDifference(-1.0f), m_sqrDistTestDifference(-1.0f), m_sqrDistQuotient(-1.0f) + , m_sqrDistTestQuotient(-1.0f), m_size(0), m_calculated(false), m_b49(true) +{ +} + +// ELF 0x34D6C0 (C2; C1 0x34D770). +AreaAssignment::AreaAssignment(int size) + : m_effectiveTarget(0), m_effectiveAssigned(0), m_assigned(0), m_target(0), m_testAssigned(0) + , m_testEffectiveAssigned(0), m_testQuotient(0), m_testDifference(0), m_testAssignedCount(0) + , m_assignedCount(0), m_targetCount(0), m_difference(0), m_quotient(0) + , m_sqrDistDifference(-1.0f), m_sqrDistTestDifference(-1.0f), m_sqrDistQuotient(-1.0f) + , m_sqrDistTestQuotient(-1.0f), m_size(0), m_calculated(false), m_b49(true) +{ + setSize(size); +} + +// ELF 0x34D820 (C2; C1 0x34D990): fresh arrays of the other's size, then flags, the four +// results and every array element. +AreaAssignment::AreaAssignment(const AreaAssignment& other) + : m_effectiveTarget(0), m_effectiveAssigned(0), m_assigned(0), m_target(0), m_testAssigned(0) + , m_testEffectiveAssigned(0), m_testQuotient(0), m_testDifference(0), m_testAssignedCount(0) + , m_assignedCount(0), m_targetCount(0), m_difference(0), m_quotient(0), m_size(0) +{ + setSize(other.m_size); + m_calculated = other.m_calculated; + m_b49 = other.m_b49; + m_sqrDistDifference = other.m_sqrDistDifference; + m_sqrDistTestDifference = other.m_sqrDistTestDifference; + m_sqrDistQuotient = other.m_sqrDistQuotient; + m_sqrDistTestQuotient = other.m_sqrDistTestQuotient; + for (int i = 0; i < m_size; ++i) + { + m_assigned[i] = other.m_assigned[i]; + m_target[i] = other.m_target[i]; + m_difference[i] = other.m_difference[i]; + m_quotient[i] = other.m_quotient[i]; + m_assignedCount[i] = other.m_assignedCount[i]; + m_testAssigned[i] = other.m_testAssigned[i]; + m_testEffectiveAssigned[i] = other.m_testEffectiveAssigned[i]; + m_testQuotient[i] = other.m_testQuotient[i]; + m_testDifference[i] = other.m_testDifference[i]; + m_testAssignedCount[i] = other.m_testAssignedCount[i]; + m_targetCount[i] = other.m_targetCount[i]; + m_effectiveTarget[i] = other.m_effectiveTarget[i]; + m_effectiveAssigned[i] = other.m_effectiveAssigned[i]; + } +} + +// ELF 0x34DB00 (D2; D1 0x34DC60). +AreaAssignment::~AreaAssignment() +{ + delete[] m_assigned; + delete[] m_target; + delete[] m_difference; + delete[] m_quotient; + delete[] m_assignedCount; + delete[] m_targetCount; + delete[] m_effectiveTarget; + delete[] m_effectiveAssigned; + delete[] m_testAssigned; + delete[] m_testEffectiveAssigned; + delete[] m_testQuotient; + delete[] m_testDifference; + delete[] m_testAssignedCount; +} + +// ELF 0x34DDC0. +void AreaAssignment::setSize(int size) +{ + if (!m_size) + { + m_size = size; + m_assigned = new float[m_size]; + m_target = new float[m_size]; + m_targetCount = new int[m_size]; + m_difference = new float[m_size]; + m_quotient = new float[m_size]; + m_assignedCount = new int[m_size]; + m_effectiveAssigned = new float[m_size]; + m_effectiveTarget = new float[m_size]; + m_testAssigned = new float[m_size]; + m_testEffectiveAssigned = new float[m_size]; + m_testQuotient = new float[m_size]; + m_testDifference = new float[m_size]; + m_testAssignedCount = new int[m_size]; + } + for (int i = 0; i < m_size; ++i) + { + m_assigned[i] = 0.0f; + m_target[i] = 0.0f; + m_difference[i] = 0.0f; + m_quotient[i] = 0.0f; + m_assignedCount[i] = 0; + m_testAssigned[i] = 0.0f; + m_testEffectiveAssigned[i] = 0.0f; + m_testQuotient[i] = 0.0f; + m_testDifference[i] = 0.0f; + m_testAssignedCount[i] = 0; + m_targetCount[i] = 0; + m_effectiveTarget[i] = 0.0f; + m_effectiveAssigned[i] = 0.0f; + } + m_calculated = false; +} + +// ELF 0x34DF50: the target and its truncated counts; the assignment is cleared. +float* AreaAssignment::setVecToMatch(float* strength, float* count) +{ + for (int i = 0; i < m_size; ++i) + { + m_target[i] = strength[i]; + m_targetCount[i] = static_cast(count[i]); + m_assigned[i] = 0.0f; + m_assignedCount[i] = 0; + } + m_calculated = false; + return m_target; +} + +// ELF 0x34DFC0: as above from the statistics' strength and count arrays. +float* AreaAssignment::setVecToMatch(EnemyStatistics* statistics) +{ + float* const strength = statistics->m_strength; + float* const count = statistics->m_count; + for (int i = 0; i < m_size; ++i) + { + m_target[i] = strength[i]; + m_targetCount[i] = static_cast(count[i]); + m_assigned[i] = 0.0f; + m_assignedCount[i] = 0; + } + m_calculated = false; + return m_target; +} + +// ELF 0x34E050. +int AreaAssignment::getNumberOfAssignedUnits() +{ + int units = 0; + for (int i = 0; i < m_size; ++i) + units += m_assignedCount[i]; + return units; +} + +// ELF 0x34E080. As shipped, the target strength is divided by the assigned count and the +// assigned strength by the target count; a zero numerator or count gives 0. +void AreaAssignment::calculateEffectiveStrengths() +{ + for (int i = 0; i < m_size; ++i) + { + if (m_target[i] != 0.0f && m_assignedCount[i] != 0) + m_effectiveTarget[i] = m_target[i] / static_cast(m_assignedCount[i]); + else + m_effectiveTarget[i] = 0.0f; + if (m_assigned[i] != 0.0f && m_targetCount[i] != 0) + m_effectiveAssigned[i] = m_assigned[i] / static_cast(m_targetCount[i]); + else + m_effectiveAssigned[i] = 0.0f; + } + m_calculated = true; +} + +// ELF 0x34E130: difference = effective target - effective assigned. +void AreaAssignment::calculateDifference() +{ + add(-1.0f, m_difference, m_effectiveTarget, m_effectiveAssigned); +} + +// ELF 0x34E180. +float* AreaAssignment::getDifference() +{ + return m_difference; +} + +// ELF 0x34E190. +float AreaAssignment::calculateSqrDistDifference() +{ + return m_sqrDistDifference = sqrDist(m_difference); +} + +// ELF 0x34E1D0. +float AreaAssignment::getSqrDistDifference() +{ + return m_sqrDistDifference; +} + +// ELF 0x34E1E0. +float* AreaAssignment::getQuotient() +{ + return m_quotient; +} + +// ELF 0x34E1F0. +void AreaAssignment::calculateQuotient() +{ + quotient(m_quotient, m_effectiveAssigned); +} + +// ELF 0x34E230. +float AreaAssignment::getSummedQuotient() +{ + return sum(m_quotient); +} + +// ELF 0x34E260. +float AreaAssignment::calculateSqrDistQuotient() +{ + return m_sqrDistQuotient = sqrDist(m_quotient); +} + +// ELF 0x34E2A0. +float AreaAssignment::getSqrDistQuotient() +{ + return m_sqrDistQuotient; +} + +// ELF 0x34E2B0. +void AreaAssignment::calculate() +{ + calculateEffectiveStrengths(); + calculateQuotient(); + calculateDifference(); + calculateSqrDistQuotient(); + calculateSqrDistDifference(); +} + +// ELF 0x34E300: test strength = strength + test strength; one more test unit at `index`. +float* AreaAssignment::addTestStrength(float* strength, int index) +{ + add(1.0f, m_testAssigned, strength, m_testAssigned); + ++m_testAssignedCount[index]; + return m_testAssigned; +} + +// ELF 0x34E360. +void AreaAssignment::calculateTestDifference() +{ + add(-1.0f, m_testDifference, m_effectiveTarget, m_testEffectiveAssigned); +} + +// ELF 0x34E3B0. +float* AreaAssignment::getTestDifference() +{ + return m_testDifference; +} + +// ELF 0x34E3C0. Shipped defect, preserved: the result is not stored in m_sqrDistTestDifference. +float AreaAssignment::calculateSqrDistTestDifference() +{ + return sqrDist(m_testDifference); +} + +// ELF 0x34E3F0. +float AreaAssignment::getSqrDistTestDifference() +{ + return m_sqrDistTestDifference; +} + +// ELF 0x34E400. +float AreaAssignment::summedTestStrength() +{ + return sum(m_testAssigned); +} + +// ELF 0x34E430. +void AreaAssignment::calculateTestQuotient() +{ + quotient(m_testQuotient, m_testEffectiveAssigned); +} + +// ELF 0x34E470. +float* AreaAssignment::getTestQuotient() +{ + return m_testQuotient; +} + +// ELF 0x34E480. +float AreaAssignment::getSummedTestQuotient() +{ + return sum(m_testQuotient); +} + +// ELF 0x34E4B0. +float AreaAssignment::calculateSqrDistTestQuotient() +{ + return m_sqrDistTestQuotient = sqrDist(m_testQuotient); +} + +// ELF 0x34E4F0. +float AreaAssignment::getSqrDistTestQuotient() +{ + return m_sqrDistTestQuotient; +} + +// ELF 0x34E500. +float* AreaAssignment::addStrength(float* strength, int index) +{ + add(1.0f, m_assigned, strength); + ++m_assignedCount[index]; + m_calculated = false; + return m_assigned; +} + +// ELF 0x34E560. +void AreaAssignment::makeTestActual() +{ + for (int i = 0; i < m_size; ++i) + { + m_assigned[i] = m_testAssigned[i]; + m_effectiveAssigned[i] = m_testEffectiveAssigned[i]; + m_quotient[i] = m_testQuotient[i]; + m_difference[i] = m_testDifference[i]; + m_assignedCount[i] = m_testAssignedCount[i]; + } +} + +// ELF 0x34E5C0. +void AreaAssignment::resetTestCase() +{ + for (int i = 0; i < m_size; ++i) + { + m_testAssigned[i] = m_assigned[i]; + m_testEffectiveAssigned[i] = m_effectiveAssigned[i]; + m_testQuotient[i] = m_quotient[i]; + m_testDifference[i] = m_difference[i]; + m_testAssignedCount[i] = m_assignedCount[i]; + } +} + +// ELF 0x34E620: any negative difference entry. +bool AreaAssignment::hasNegativeStrength() +{ + for (int i = 0; i < m_size; ++i) + { + if (m_difference[i] < 0.0f) + return true; + } + return false; +} + +// ELF 0x34E670: out = in / effective target, 0 where either is 0. +void AreaAssignment::quotient(float* out, float* in) +{ + for (int i = 0; i < m_size; ++i) + { + if (in[i] == 0.0f || m_effectiveTarget[i] == 0.0f) + out[i] = 0.0f; + else + out[i] = in[i] / m_effectiveTarget[i]; + } +} + +// ELF 0x34E6E0: inOut += factor * in. +void AreaAssignment::add(float factor, float* inOut, float* in) +{ + for (int i = 0; i < m_size; ++i) + inOut[i] = inOut[i] + factor * in[i]; +} + +// ELF 0x34E720: out = in + factor * scaled. +void AreaAssignment::add(float factor, float* out, float* in, float* scaled) +{ + for (int i = 0; i < m_size; ++i) + out[i] = in[i] + factor * scaled[i]; +} + +// ELF 0x34E760. +float AreaAssignment::sum(float* values) +{ + float total = 0.0f; + for (int i = 0; i < m_size; ++i) + total += values[i]; + return total; +} + +// ELF 0x34E7A0. +float AreaAssignment::sqrDist(float* values) +{ + float total = 0.0f; + for (int i = 0; i < m_size; ++i) + { + if (values[i] > 0.0f) + total += values[i] * values[i]; + } + return total; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.h new file mode 100644 index 000000000..444364b14 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.h @@ -0,0 +1,97 @@ +// Per-equipment strength bookkeeping for matching assigned units against a target distribution +// (libaidll.so AreaAssignment.cpp, 0x34D5A0..0x34E8A0). Nothing in the shipped image constructs +// one: every caller is another AreaAssignment member. +// [INFERRED] Source placement and member names; the offsets are the ELF layout. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AREAASSIGNMENT_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_AREAASSIGNMENT_H + +namespace dice { +namespace hfe { +namespace ai { + +class EnemyStatistics; + +class AreaAssignment +{ +public: + AreaAssignment(); // ELF 0x34D5A0 (C2; C1 0x34D630) + explicit AreaAssignment(int size); // ELF 0x34D6C0 (C2; C1 0x34D770) + AreaAssignment(const AreaAssignment& other); // ELF 0x34D820 (C2; C1 0x34D990) + ~AreaAssignment(); // ELF 0x34DB00 (D2; D1 0x34DC60) + + // Allocates the thirteen arrays on first use (a later call keeps the old size and only + // clears them). + void setSize(int size); + // Both answer the target-strength array (the image reloads +0xC into eax). [INFERRED] type. + float* setVecToMatch(float* strength, float* count); + float* setVecToMatch(EnemyStatistics* statistics); + int getNumberOfAssignedUnits(); + + void calculateEffectiveStrengths(); + void calculateDifference(); + float* getDifference(); + float calculateSqrDistDifference(); + float getSqrDistDifference(); + float* getQuotient(); + void calculateQuotient(); + float getSummedQuotient(); + float calculateSqrDistQuotient(); + float getSqrDistQuotient(); + void calculate(); + + // Both answer the strength array they add into (explicit reload in the image). + float* addTestStrength(float* strength, int index); + void calculateTestDifference(); + float* getTestDifference(); + float calculateSqrDistTestDifference(); + float getSqrDistTestDifference(); + float summedTestStrength(); + void calculateTestQuotient(); + float* getTestQuotient(); + float getSummedTestQuotient(); + float calculateSqrDistTestQuotient(); + float getSqrDistTestQuotient(); + float* addStrength(float* strength, int index); + void makeTestActual(); + void resetTestCase(); + bool hasNegativeStrength(); + + // Element-wise helpers over m_size entries. The void returns are [INFERRED]: their + // callers forward eax without using it. + void quotient(float* out, float* in); + void add(float factor, float* inOut, float* in); + void add(float factor, float* out, float* in, float* scaled); + float sum(float* values); + // The sum of the squares of the positive entries. + float sqrDist(float* values); + +private: + /* +0x00 */ float* m_effectiveTarget; // m_target / m_assignedCount + /* +0x04 */ float* m_effectiveAssigned; // m_assigned / m_targetCount + /* +0x08 */ float* m_assigned; + /* +0x0C */ float* m_target; + /* +0x10 */ float* m_testAssigned; + /* +0x14 */ float* m_testEffectiveAssigned; + /* +0x18 */ float* m_testQuotient; + /* +0x1C */ float* m_testDifference; + /* +0x20 */ int* m_testAssignedCount; + /* +0x24 */ int* m_assignedCount; + /* +0x28 */ int* m_targetCount; + /* +0x2C */ float* m_difference; + /* +0x30 */ float* m_quotient; + /* +0x34 */ float m_sqrDistDifference; + // -1 from the constructors; calculateSqrDistTestDifference does not store its result here. + /* +0x38 */ float m_sqrDistTestDifference; + /* +0x3C */ float m_sqrDistQuotient; + /* +0x40 */ float m_sqrDistTestQuotient; + /* +0x44 */ int m_size; + /* +0x48 */ bool m_calculated; // set by calculateEffectiveStrengths + /* +0x49 */ bool m_b49; // true from every constructor [UNRESOLVED] +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AREAASSIGNMENT_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp new file mode 100644 index 000000000..fcbf50678 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp @@ -0,0 +1,35 @@ +// [INFERRED] Source placement: see AreaDistanceInfo.h. + +#include "AreaDistanceInfo.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x34E8A0: `movl $0x0,(%eax); movl $0x0,0x4(%eax); movl <0.0f>,0x8(%eax)`. +AreaDistanceInfo::AreaDistanceInfo() + : m_vehicleGroups(0) + , m_area(0) + , m_distance(0.0f) +{ +} + +// ELF 0x34E900: three word copies. +AreaDistanceInfo::AreaDistanceInfo(const AreaDistanceInfo& other) + : m_vehicleGroups(other.m_vehicleGroups) + , m_area(other.m_area) + , m_distance(other.m_distance) +{ +} + +// ELF 0x34E940: the arguments in field order. +AreaDistanceInfo::AreaDistanceInfo(int vehicleGroups, AIStrategicArea* area, float distance) + : m_vehicleGroups(vehicleGroups) + , m_area(area) + , m_distance(distance) +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.h new file mode 100644 index 000000000..362f4fb25 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.h @@ -0,0 +1,31 @@ +// One entry of an area's per-side distance list (AIStrategicArea::m_distances): a strategic +// area, its route distance from the owner, and the vehicle groups that reach it at that distance. +// [INFERRED] Source placement and field names: the ctors sit between AreaAssignment.cpp and +// SAWayPoint.cpp in libaidll.so (0x34E8A0..0x34E960) without a FILE symbol of their own. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AREADISTANCEINFO_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_AREADISTANCEINFO_H + +namespace dice { +namespace hfe { +namespace ai { + +class AIStrategicArea; + +// dice::hfe::ai::AreaDistanceInfo (namespace scope in the ELF mangling), twelve bytes. +struct AreaDistanceInfo +{ + AreaDistanceInfo(); // ELF 0x34E8A0 + AreaDistanceInfo(const AreaDistanceInfo& other); // ELF 0x34E900 + AreaDistanceInfo(int vehicleGroups, AIStrategicArea* area, float distance); // ELF 0x34E940 + + /* +0 */ int m_vehicleGroups; // bit mask, 1 << group (insertUnitDistances) + /* +4 */ AIStrategicArea* m_area; + /* +8 */ float m_distance; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_AREADISTANCEINFO_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp new file mode 100644 index 000000000..429421d35 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp @@ -0,0 +1,122 @@ +// CPNode. Evidence: libaidll.so 1.5.3153 (ia-32), see CPNode.h. + +#include "CPNode.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x35C440, __tcf_0 0x35C4A0, _GLOBAL__I 0x35C4D0). +#include + +#include "../../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x35BAC0 (C2; C1 0x35BB00): six zero words. +CPNode::CPNode() + : m_parent(0) + , m_next(0) + , m_prev(0) + , m_key(0) + , m_g(0.0f) + , m_f(0.0f) +{ +} + +// ELF 0x35BB40 (C2; C1 0x35BCC0). The cover position goes through checkPointer. +CPNode::CPNode(CPNode* parent, int coverPosition) + : m_parent(parent) + , m_next(0) + , m_prev(0) + , m_key(checkPointer(CoverPositionManager::m_instance->m_coverPositions[coverPosition])) + , m_g(0.0f) + , m_f(0.0f) +{ +} + +// ELF 0x35BE40 (C2; C1 0x35BE70): every word copied. +CPNode::CPNode(const CPNode& other) + : m_parent(other.m_parent) + , m_next(other.m_next) + , m_prev(other.m_prev) + , m_key(other.m_key) + , m_g(other.m_g) + , m_f(other.m_f) +{ +} + +// ELF 0x35BEA0 (D2; D1 0x35BEB0). +CPNode::~CPNode() +{ +} + +// ELF 0x35BEC0. +void CPNode::setCoverPosition(int index) +{ + m_key = checkPointer(CoverPositionManager::m_instance->m_coverPositions[index]); +} + +// ELF 0x35C010. +void CPNode::setCoverPosition(CoverPosition* coverPosition) +{ + m_key = coverPosition; +} + +// ELF 0x35C020. An empty neighbour set is tested by its size; the iterator then starts at begin. +CPNode* CPNode::expandFirst(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it) +{ + if (m_key->m_moveNeighbours.empty()) + { + status = nodeStatus::kInvalid; + return 0; + } + it = m_key->m_moveNeighbours.begin(); + const int neighbour = *it; + ++it; + getStatus(manager, status, neighbour); + return manager->getNewNode(this, neighbour); +} + +// ELF 0x35C1E0. +CPNode* CPNode::expand(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it) +{ + if (it == m_key->m_moveNeighbours.end()) + { + status = nodeStatus::kInvalid; + return 0; + } + const int neighbour = *it; + ++it; + getStatus(manager, status, neighbour); + return manager->getNewNode(this, neighbour); +} + +// ELF 0x35C3A0. The goal test comes first (0x35C3B8). The manager's +0x14 filter, when non-null, +// is then asked through its virtual +8 with the position (0x35C420..0x35C42C), and a false byte +// gives kInvalid (0x35C3C9 / 0x35C413). The filter is always null in retail (see CPNodeFilter), +// so that arm is never taken; it is kept as shipped. +void CPNode::getStatus(CPNodeManager* manager, nodeStatus::Status& status, int coverPosition) +{ + if (manager->m_goal == coverPosition) + { + status = nodeStatus::kGoal; + return; + } + bool mayEnter = true; + if (manager->m_filter != 0) + mayEnter = manager->m_filter->mayEnter(coverPosition); + if (!mayEnter) + { + status = nodeStatus::kInvalid; + return; + } + const std::pair& flags = manager->m_status[coverPosition]; + if (flags.first) + status = nodeStatus::kOpen; + else + status = flags.second ? nodeStatus::kClosed : nodeStatus::kUnvisited; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.h new file mode 100644 index 000000000..e834fc33a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.h @@ -0,0 +1,129 @@ +// The cover-position A* node: a cover position reached from its parent. Its neighbours are the +// cover position's move neighbours (CoverPosition +0x2C). The CPNodeManager inlines the search +// templates call are defined here, after both classes are complete. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x35BAC0..0x35C4D0 (CPNode's own functions and the +// TU's static initialisation; its first symbol names CPNode::CPNode()). [INFERRED] Placement +// AIStrategicEntity/CoverPosition/CPNode.cpp; no __FILE__ string attests it. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODE_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODE_H + +#include + +#include "../../AIUtils/checkPointer.h" +#include "../../Main/AIPathfindingSearchTypes.h" // nodeStatus +#include "CPNodeManager.h" +#include "CoverPosition.h" +#include "CoverPositionManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// 24 bytes (operator new(0x18) in expandFirst, expand and CoverPositionManager::search). +class CPNode +{ +public: + // The iterator over a cover position's move neighbours that expandFirst / expand advance. + typedef std::set::const_iterator NeighbourIterator; + + CPNode(); + // A node on cover position `coverPosition`, reached from `parent`; costs and links cleared. + CPNode(CPNode* parent, int coverPosition); + CPNode(const CPNode& other); + ~CPNode(); + + // Points the node at cover position `index` of CoverPositionManager::m_instance. + void setCoverPosition(int index); + void setCoverPosition(CoverPosition* coverPosition); + + // Neighbour iteration for AStarResource::update: the next move neighbour as a node (from the + // manager's pool) and its status, or null with kInvalid when there is none. + CPNode* expandFirst(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it); + CPNode* expand(CPNodeManager* manager, nodeStatus::Status& status, NeighbourIterator& it); + // kGoal for the manager's goal, kInvalid when the manager's filter refuses it, else kOpen, + // kClosed or kUnvisited from the manager's per-position flags. + void getStatus(CPNodeManager* manager, nodeStatus::Status& status, int coverPosition); + + // [INFERRED] The node has no depth word: AStarResource::update tests the search depth + // limit against the constant 0. + static const int m_depth = 0; + + // [INFERRED] names; offsets from the constructors and the search templates. + /* +0 */ CPNode* m_parent; + /* +4 */ CPNode* m_next; // hash chain and the manager's free-list link + /* +8 */ CPNode* m_prev; // hash chain back link + /* +12 */ CoverPosition* m_key; // the cover position; the search compares nodes by it + /* +16 */ float m_g; // cost from the start + /* +20 */ float m_f; // the open tree's order +}; + +// The Hash hooks (AIPathfindingSearchTypes.h): a CPNode hashes to its cover position's index with +// no modulus (Hash::insert 0x359B20, get 0x35B8C0, remove 0x35B960) and compares by cover +// position pointer. +inline int hashIndexOf(const CPNode* node, int) +{ + return node->m_key->m_id; +} + +inline bool hashKeyEquals(const CPNode* a, const CPNode* b) +{ + return a->m_key == b->m_key; +} + +// The manager's inline operations, as AStarResource (0x359BC0, 0x35B7D0) and +// CoverPositionManager::search inline them. [INFERRED] names (shared with QTSearchNodeManager). + +inline void CPNodeManager::setNodeOpen(CPNode* node) +{ + m_status[node->m_key->m_id].first = true; +} + +inline void CPNodeManager::setNodeClosed(CPNode* node) +{ + m_status[node->m_key->m_id].first = false; + m_status[node->m_key->m_id].second = true; +} + +inline void CPNodeManager::recycleNode(CPNode* node) +{ + if (node != 0) + { + node->m_next = m_nodes; + m_nodes = node; + } +} + +// A cheaper route through `from`: the cost is the distance-table entry plus from's g. Shipped +// defect, preserved: only f changes, by -(g + cost); g and the parent keep their old values. +inline bool CPNodeManager::updateNode(CPNode* from, CPNode* existing, int) +{ + const float cost = CoverPositionManager::m_instance->getDistance(from->m_key->m_id, + existing->m_key->m_id) + + from->m_g; + if (cost < existing->m_g) + { + existing->m_f -= existing->m_g + cost; + return true; + } + return false; +} + +// A node on `coverPosition` reached from `parent`: the head of the free list, re-pointed, or a new +// one. A reused node keeps its old costs. +inline CPNode* CPNodeManager::getNewNode(CPNode* parent, int coverPosition) +{ + CPNode* node = m_nodes; + if (node == 0) + return checkPointer(new CPNode(parent, coverPosition)); + m_nodes = node->m_next; + node->setCoverPosition(coverPosition); + node->m_parent = parent; + return node; +} + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp index f5dce23af..b2e89ae14 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp @@ -1,39 +1,52 @@ -// [INFERRED] Source placement. +// CPNodeManager. Evidence: libaidll.so 1.5.3153 (ia-32), see CPNodeManager.h. #include "CPNodeManager.h" -#include "../../Main/AIDllFrontier.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x35C800, __tcf_0 0x35C860, _GLOBAL__I 0x35C890). +#include + +#include "CPNode.h" +#include "CoverPositionManager.h" namespace dice { namespace hfe { namespace ai { -// Six words: three for the vector, a null chain head, -1, and a zero. +// ELF 0x35C4F0 (C2; C1 0x35C530): the empty vector, a null pool, goal -1, no filter. CPNodeManager::CPNodeManager() : m_nodes(0) - , m_i16(-1) - , m_i20(0) + , m_goal(-1) + , m_filter(0) { } -// [FRONTIER] Node-pool destruction requires complete CPNode ownership and linkage. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding CPNodeManager operation. - +// ELF 0x35C5F0 (D1; D2 0x35C570): every pooled node is unlinked and deleted (CPNode D1 0x35BEB0, +// then operator delete); the vector goes as a member. CPNodeManager::~CPNodeManager() { - BF2_AI_FRONTIER("dice::hfe::ai::CPNodeManager::~CPNodeManager"); + while (m_nodes != 0) + { + CPNode* const node = m_nodes; + m_nodes = node->m_next; + delete node; + } } -// - walks the same chain. [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x35C670. void CPNodeManager::init() { - BF2_AI_FRONTIER("dice::hfe::ai::CPNodeManager::init"); + m_status.resize(CoverPositionManager::m_instance->m_coverPositions.size(), + std::pair(false, false)); } -// - likewise. [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x35C710: resize(0) (the empty-vector arm calls _M_fill_insert with a count of 0, so this +// is resize rather than clear), then the init sizing. void CPNodeManager::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::CPNodeManager::reset"); + m_status.resize(0, std::pair(false, false)); + m_status.resize(CoverPositionManager::m_instance->m_coverPositions.size(), + std::pair(false, false)); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h index 42e6b056a..8619ddc46 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.h @@ -1,10 +1,12 @@ -// Node manager for cover-position searches. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// The node pool and per-position open/closed flags of one cover-position search. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x35C4F0..0x35C890 (constructors, destructors, init, +// reset, the TU's static initialisation and the vector >::erase instantiation). +// [INFERRED] Placement AIStrategicEntity/CoverPosition/CPNodeManager.cpp. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODEMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_CPNODEMANAGER_H +#include #include namespace dice { @@ -13,25 +15,58 @@ namespace ai { class CPNode; +// [CHOSEN, not recovered] Interface of CPNodeManager::m_filter, declared under AGENTS.md's +// null-only member pointer clause. libaidll.so writes that member only as null (constructors +// ELF 0x35C51B / 0x35C55B; amd-64 0x3962A6 / 0x3962D6), and no setter, copy, engine producer or +// vtable exists in any inspected image. So the single call through it (CPNode::getStatus, +// 0x35C429 `call [eax+8]`; amd-64 0x3958FE `call [rax+0x10]`) is never taken in retail. +// The call site proves only: receiver, one int position argument, a tested byte result. +// [UNRESOLVED] Original class, method names and leading slots. The two leading slots are not +// claimed to be destructors. Never give this interface an implementation, setter or factory. +class CPNodeFilter +{ +public: + virtual void chosenSlot0() = 0; // +0x00 [CHOSEN] + virtual void chosenSlot1() = 0; // +0x04 [CHOSEN] + virtual bool mayEnter(int coverPosition) = 0; // +0x08 [CHOSEN] name; bool for the tested byte + +protected: + ~CPNodeFilter() {} +}; + class CPNodeManager { public: CPNodeManager(); - ~CPNodeManager(); // , not virtual + ~CPNodeManager(); // not virtual + // Sizes the flags to the cover-position count, new entries (false, false). void init(); + // Clears every flag, then sizes them as init does. The node pool is kept. void reset(); + // [INFERRED] inline and empty, added by ai-nav: ~PathfindingEngine (ELF 0x3593F0, the CPNode + // instantiation) has no call between `+0xC = -1` and `+0x1C = -1` where the QTSearchNode + // (0x3AE784) and ClusterNode (0x3AE994) instantiations call returnReset, and the image has no + // CPNodeManager::returnReset symbol. + void returnReset() {} + + // Inline in retail; defined in CPNode.h. + void setNodeOpen(CPNode* node); + void setNodeClosed(CPNode* node); + void recycleNode(CPNode* node); + bool updateNode(CPNode* from, CPNode* existing, int maxSearchDepth); + CPNode* getNewNode(CPNode* parent, int coverPosition); -private: - // layout, , every word read from the 54-byte constructor - // The element size of the vector is two bytes: the destructor computes its count as - // `(end_of_storage - start) >> 1` and frees `2 * count`. What the shorts are is [UNRESOLVED]. - /* +0 */ std::vector m_v0; - // The head of a singly linked chain of nodes threaded through `CPNode + 4`; the destructor - // unlinks and deletes every one of them. - /* +12 */ CPNode* m_nodes; // [INFERRED] name - /* +16 */ int m_i16; // = -1 [UNRESOLVED] - the only non-zero the constructor writes - /* +20 */ int m_i20; // = 0 [UNRESOLVED] + // Layout from the 54-byte constructor; names [INFERRED]. + // Per cover position: (open, closed). setNodeOpen sets first; setNodeClosed clears first and + // sets second (the vector > instantiations in this TU and CPNode::getStatus). + /* +0 */ std::vector > m_status; + // The free list of recycled nodes, threaded through CPNode::m_next; the destructor deletes it. + /* +12 */ CPNode* m_nodes; + /* +16 */ int m_goal; // = -1; the goal's cover-position index (CoverPositionManager::search) + // = 0 and never written elsewhere in any inspected image. CPNode::getStatus asks a non-null one + // through its virtual +8 whether a position may be entered (see CPNodeFilter). + /* +20 */ CPNodeFilter* m_filter; }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp new file mode 100644 index 000000000..3f3eadb98 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp @@ -0,0 +1,352 @@ +// CoverPosition. Evidence: libaidll.so 1.5.3153 (ia-32), see CoverPosition.h. + +#include "CoverPosition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x354C20, __tcf_0 0x354C80, _GLOBAL__I 0x354CB0). +#include + +#include + +#include "CoverPositionManager.h" +#include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment +#include "../../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// Lets only mobile objects block a line (vtable ELF 0x4BF780, typeinfo names this TU's anonymous +// namespace). +class MobilePredicate : public AIObjectPredicate +{ +public: + // ELF 0x356580 (weak): IAIObject +0x70. + virtual bool predicate(IAIObject* object) { return object->isMobile(); } +}; + +} // namespace + +// ELF 0x352AE0 (C2; C1 0x352C90): the corners; the id is left for the manager. +CoverPosition::CoverPosition(const Vec2& min, const Vec2& max) + : m_min(min) + , m_max(max) +{ +} + +// ELF 0x352EA0 (D1; D2 0x352D80): the set and the two maps go as members. +CoverPosition::~CoverPosition() +{ +} + +// ELF 0x352FC0. Shipped: the found iterator is dereferenced without an end check. +bool CoverPosition::canSee(CoverPosition* other) +{ + std::map::iterator it = m_attackable.find(other->m_id); + return it->second.m_type != ConnectionType::kBlocked && + it->second.m_type != ConnectionType::kUnknown; +} + +// ELF 0x353020. The candidates are this position's corners in Corner order; the first strictly +// better corner value wins, starting from kBlocked. +bool CoverPosition::findHighestVisibilityCorner(CoverPosition* other, Vec2& corner) +{ + bool found = false; + std::map::iterator it = m_attackable.find(other->m_id); + if (it != m_attackable.end()) + { + found = true; + int best = ConnectionType::kBlocked; + std::vector corners; + Vec2 point = m_min; + corners.push_back(point); + point.y = m_max.y; + corners.push_back(point); + point.x = m_max.x; + corners.push_back(point); + point.y = m_min.y; + corners.push_back(point); + corner = point; + for (unsigned int i = 0; i < it->second.m_corners.size(); ++i) + { + if (it->second.m_corners[i] < best) + { + best = it->second.m_corners[i]; + corner = corners[i]; + } + } + } + return found; +} + +// ELF 0x353250. As findHighestVisibilityCorner, starting from kVisible and taking the first +// strictly worse corner. +bool CoverPosition::findLowestVisibilityCorner(CoverPosition* other, Vec2& corner) +{ + bool found = false; + std::map::iterator it = m_attackable.find(other->m_id); + if (it != m_attackable.end()) + { + found = true; + int worst = ConnectionType::kVisible; + std::vector corners; + Vec2 point = m_min; + corners.push_back(point); + point.y = m_max.y; + corners.push_back(point); + point.x = m_max.x; + corners.push_back(point); + point.y = m_min.y; + corners.push_back(point); + corner = point; + for (unsigned int i = 0; i < it->second.m_corners.size(); ++i) + { + if (it->second.m_corners[i] > worst) + { + worst = it->second.m_corners[i]; + corner = corners[i]; + } + } + } + return found; +} + +// ELF 0x353480. +bool CoverPosition::isReachableNeighbour(int index) const +{ + return m_moveNeighbours.find(index) != m_moveNeighbours.end(); +} + +// ELF 0x3534D0. +bool CoverPosition::isAttackableNeighbour(int index) const +{ + return m_attackable.find(index) != m_attackable.end(); +} + +// ELF 0x353520. +bool CoverPosition::isDefendableNeighbour(int index) const +{ + return m_defendable.find(index) != m_defendable.end(); +} + +// ELF 0x353570. Per axis the facing edges when the boxes are apart, else the larger minimum on +// both sides. +float CoverPosition::getShortestDistance(CoverPosition* other) const +{ + float x0; + float x1; + if (m_min.x > other->m_max.x) + { + x0 = m_min.x; + x1 = other->m_max.x; + } + else if (other->m_min.x > m_max.x) + { + x0 = m_max.x; + x1 = other->m_min.x; + } + else + { + x0 = other->m_min.x < m_min.x ? m_min.x : other->m_min.x; + x1 = x0; + } + + float y0; + float y1; + if (m_min.y > other->m_max.y) + { + y0 = m_min.y; + y1 = other->m_max.y; + } + else if (other->m_min.y > m_max.y) + { + y0 = m_max.y; + y1 = other->m_min.y; + } + else + { + y0 = other->m_min.y < m_min.y ? m_min.y : other->m_min.y; + y1 = y0; + } + + return sqrtf((y1 - y0) * (y1 - y0) + (x1 - x0) * (x1 - x0)); +} + +// ELF 0x353660. The end is re-read after every call. +void CoverPosition::updateAttacks(bool force) +{ + std::vector& positions = CoverPositionManager::m_instance->m_coverPositions; + for (std::vector::iterator it = positions.begin(); it != positions.end(); ++it) + { + if (*it != this) + updateAttacks(*it, force); + } +} + +// ELF 0x3536C0 (4.8 KB, most of it the inlined ConnectionType copies). The target corners go +// (min, min), (max, min), (max, max), (min, max); the looking corners in Corner order. The +// overall attack value starts as the first corner's; afterwards it stays only while the corners +// agree and becomes kPartial otherwise. The defend value follows the corners with +// visible -> visible, partial -> partial unless already visible, blocked -> unchanged. Shipped, +// preserved: a link created by this call is left at its defaults unless `force` is set. +void CoverPosition::updateAttacks(CoverPosition* other, bool force) +{ + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec3 eye = { 0.0f, 0.0f, 0.0f }; + + Vec3 target0; + target0.x = other->m_min.x; + target0.y = terrain->getHeight(other->m_min.x, other->m_min.y) + 0.3f; + target0.z = other->m_min.y; + Vec3 target1; + target1.x = other->m_max.x; + target1.y = terrain->getHeight(other->m_max.x, other->m_min.y) + 0.3f; + target1.z = other->m_min.y; + Vec3 target2; + target2.x = other->m_max.x; + target2.y = terrain->getHeight(other->m_max.x, other->m_max.y) + 0.3f; + target2.z = other->m_max.y; + Vec3 target3; + target3.x = other->m_min.x; + target3.y = terrain->getHeight(other->m_min.x, other->m_max.y) + 0.3f; + target3.z = other->m_max.y; + + std::pair::iterator, bool> attackLink = + m_attackable.insert(std::make_pair(other->m_id, ConnectionType())); + if (!force && attackLink.second) + return; + + std::map::iterator defendLink = + other->m_defendable.insert(std::make_pair(m_id, ConnectionType())).first; + ConnectionType& attack = attackLink.first->second; + ConnectionType& defend = defendLink->second; + + eye.x = m_min.x; + eye.z = m_min.y; + eye.y = terrain->getHeight(m_min.x, m_min.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner0); + eye.x = m_min.x; + eye.z = m_max.y; + eye.y = terrain->getHeight(m_min.x, m_max.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner1); + eye.x = m_max.x; + eye.z = m_max.y; + eye.y = terrain->getHeight(m_max.x, m_max.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner2); + eye.x = m_max.x; + eye.z = m_min.y; + eye.y = terrain->getHeight(m_max.x, m_min.y) + 1.5f; + updateCorner(eye, target0, target1, target2, target3, attack, defend, ConnectionType::kCorner3); + + for (int i = 0; i < 4; ++i) + { + if (attack.m_type == ConnectionType::kUnknown) + { + switch (attack.m_corners[i]) + { + case ConnectionType::kVisible: + attack.m_type = ConnectionType::kVisible; + defend.m_type = ConnectionType::kVisible; + break; + case ConnectionType::kPartial: + attack.m_type = ConnectionType::kPartial; + defend.m_type = ConnectionType::kPartial; + break; + case ConnectionType::kBlocked: + attack.m_type = ConnectionType::kBlocked; + defend.m_type = ConnectionType::kBlocked; + break; + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp", 393, "") + << "Unknown connectiontype."; + break; + } + } + else + { + attack.m_type = attack.m_corners[i] == attack.m_type ? attack.m_corners[i] + : ConnectionType::kPartial; + switch (attack.m_corners[i]) + { + case ConnectionType::kVisible: + defend.m_type = ConnectionType::kVisible; + break; + case ConnectionType::kPartial: + defend.m_type = defend.m_type != ConnectionType::kVisible ? ConnectionType::kPartial + : ConnectionType::kVisible; + break; + case ConnectionType::kBlocked: + break; + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp", 424, "") + << "Unknown connectiontype."; + break; + } + } + } +} + +// ELF 0x3549A0. Each line is tested with IAIObjectEnvironment::collideLineWithWorld (+0x44, only +// mobile objects block) and stored in both links; the target corners land in line slots 0, 3, 2 +// and 1. +int CoverPosition::updateCorner(const Vec3& eye, const Vec3& corner0, const Vec3& corner1, + const Vec3& corner2, const Vec3& corner3, ConnectionType& attack, + ConnectionType& defend, const ConnectionType::Corner& corner) +{ + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + MobilePredicate predicate; + int clear = 0; + + bool visible = !environment->collideLineWithWorld(eye, corner0, &predicate, 0); + ConnectionType::NeighbourConnection line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][0] = line; + defend.m_lines[corner][0] = line; + if (visible) + ++clear; + + visible = !environment->collideLineWithWorld(eye, corner1, &predicate, 0); + line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][3] = line; + defend.m_lines[corner][3] = line; + if (visible) + ++clear; + + visible = !environment->collideLineWithWorld(eye, corner2, &predicate, 0); + line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][2] = line; + defend.m_lines[corner][2] = line; + if (visible) + ++clear; + + visible = !environment->collideLineWithWorld(eye, corner3, &predicate, 0); + line = visible ? ConnectionType::kVisible : ConnectionType::kBlocked; + attack.m_lines[corner][1] = line; + defend.m_lines[corner][1] = line; + if (visible) + ++clear; + + if (clear == 0) + attack.m_corners[corner] = ConnectionType::kBlocked; + else if (clear == 4) + attack.m_corners[corner] = ConnectionType::kVisible; + else + attack.m_corners[corner] = ConnectionType::kPartial; + defend.m_corners[corner] = attack.m_corners[corner]; + return clear; +} + +// ELF 0x354C10: empty. +void CoverPosition::updateMoveNeighbours() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.h new file mode 100644 index 000000000..8f8332e03 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.h @@ -0,0 +1,108 @@ +// A rectangular cover position and its visibility links to the other positions. +// Evidence: libaidll.so 1.5.3153 (ia-32), attested file +// AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp (the Debug __FILE__ strings and the +// anonymous namespace of MobilePredicate), ELF 0x352AE0..0x354CB0 plus its map / vector +// instantiations up to 0x356670. Size 0x38 (operator new(0x38) in +// CoverPositionManager::createCoverPosition). + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITION_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITION_H + +#include +#include +#include + +#include "../../../../../Math/Vec3.h" // Vec2, Vec3 + +namespace dice { +namespace hfe { +namespace ai { + +// How well one cover position sees another: an overall value, one per corner of the looking +// position, and one per line from each of its corners to each corner of the other. 28 bytes (the +// map node is 0x30). Inline throughout; the default constructor is the inlined +// `-1, resize(4, -1), resize(4, corners)` sequence of CoverPosition::updateAttacks. +class ConnectionType +{ +public: + // [INFERRED] enumerator names; the values are the stored ones. Lines are kVisible or + // kBlocked; a corner is kVisible when all four of its lines are clear, kBlocked when none is, + // else kPartial. + enum NeighbourConnection + { + kUnknown = -1, + kVisible = 0, + kPartial = 1, + kBlocked = 2 + }; + + // The looking position's corners, in the order updateAttacks visits them: (min.x, min.y), + // (min.x, max.y), (max.x, max.y), (max.x, min.y). [INFERRED] enumerator names. + enum Corner + { + kCorner0 = 0, + kCorner1 = 1, + kCorner2 = 2, + kCorner3 = 3 + }; + + ConnectionType() + : m_type(kUnknown) + { + m_corners.resize(4, kUnknown); + m_lines.resize(4, m_corners); + } + + // [INFERRED] names. + /* +0 */ NeighbourConnection m_type; + /* +4 */ std::vector m_corners; + /* +16 */ std::vector > m_lines; +}; + +class CoverPosition +{ +public: + // The two corners are stored as given (CoverPositionManager orders them first). + CoverPosition(const Vec2& min, const Vec2& max); + ~CoverPosition(); + + // Whether this position's link to `other` is neither blocked nor unknown. Looks the link up + // without an end check. + bool canSee(CoverPosition* other); + // The corner of this position that sees `other` best (worst), true when a link to `other` + // exists; `corner` starts as the last corner and is untouched without a link. + bool findHighestVisibilityCorner(CoverPosition* other, Vec2& corner); + bool findLowestVisibilityCorner(CoverPosition* other, Vec2& corner); + bool isReachableNeighbour(int index) const; + bool isAttackableNeighbour(int index) const; + bool isDefendableNeighbour(int index) const; + // The gap between the two boxes (0 where they overlap on both axes). + float getShortestDistance(CoverPosition* other) const; + // updateAttacks(other, force) against every other cover position. + void updateAttacks(bool force); + // Line-of-sight from this position's corners (1.5 above the terrain) to `other`'s (0.3 above), + // stored in this position's attack link to `other` and in `other`'s defend link to this one. + // Without `force` an existing link is recomputed and a new one is left at its defaults. + void updateAttacks(CoverPosition* other, bool force); + // One looking corner against the other position's four corners; answers the clear-line count. + // [INFERRED] int return (the counter is a 32-bit word returned in eax; callers ignore it). + int updateCorner(const Vec3& eye, const Vec3& corner0, const Vec3& corner1, const Vec3& corner2, + const Vec3& corner3, ConnectionType& attack, ConnectionType& defend, + const ConnectionType::Corner& corner); + // Empty in retail: the move-neighbour set is never filled. + void updateMoveNeighbours(); + + // Layout from the constructor (0x352C90); names [INFERRED]. + /* +0 */ Vec2 m_min; + /* +8 */ Vec2 m_max; + /* +16 */ int m_id; // the index in CoverPositionManager; written by createCoverPosition + /* +20 */ std::map m_attackable; // isAttackableNeighbour; keyed by the other's id + /* +32 */ std::map m_defendable; // isDefendableNeighbour + /* +44 */ std::set m_moveNeighbours; // isReachableNeighbour; CPNode's expansion +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITION_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp index 945f741e3..606134d04 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp @@ -1,9 +1,18 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining CoverPositionManager operations. +// CoverPositionManager. Evidence: libaidll.so 1.5.3153 (ia-32), see CoverPositionManager.h. #include "CoverPositionManager.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x359190, __tcf_0 0x3591F0, _GLOBAL__I 0x359220). +#include + +#include +#include + +#include "CPNode.h" +#include "CoverPosition.h" #include "../../AIUtils/checkPointer.h" -#include "../../Main/AIDllFrontier.h" +#include "../../Main/AIRandom.h" namespace dice { namespace hfe { @@ -11,8 +20,8 @@ namespace ai { CoverPositionManager* CoverPositionManager::m_instance = 0; -// Initializes cover-position search resources and their node managers. - +// ELF 0x356680 (C2; C1 0x356F00): the engine, then five search resources (open tree 15, both +// hashes 20) whose ids go to the free list; the first manager becomes the singleton. CoverPositionManager::CoverPositionManager() { m_engine = checkPointer(new CPPathfindingEngine()); @@ -26,16 +35,16 @@ CoverPositionManager::CoverPositionManager() pool->m_searches.push_back(resource); - resource->m_i16 = 0; + resource->m_iterations = 0; resource->m_openSize = 15; resource->m_hashSize = 20; resource->m_open = checkPointer(new BinarySearchTree(15)); - resource->m_closed = checkPointer(new Hash(20)); - resource->m_cache = checkPointer(new Hash(20)); + resource->m_openOverflow = checkPointer(new Hash(20)); + resource->m_closed = checkPointer(new Hash(20)); - resource->m_closed->m_nodeManager = resource->m_nodeManager; - resource->m_cache->m_nodeManager = resource->m_nodeManager; + resource->m_openOverflow->m_nodeManager = resource->m_nodeManager; + resource->m_closed->m_nodeManager = resource->m_nodeManager; pool->m_available.push_back((unsigned int)(pool->m_searches.size() - 1)); } @@ -44,68 +53,299 @@ CoverPositionManager::CoverPositionManager() m_instance = this; } -// [FRONTIER] Cover-position destruction requires cleanup of its search engine and owned positions. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding CoverPositionManager operation. - +// ELF 0x357680 (D1, 337 B; recovered on the client track, docs/macos-c-singleplayer.md): the +// singleton is zeroed when it is this one, the CPNode pathfinding engine is deleted, every cover +// position is deleted (CoverPosition D1 0x352EA0 destroys members only) and the vector emptied; +// the distance table and the position vector then go as members. CoverPositionManager::~CoverPositionManager() { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::~CoverPositionManager"); + if (m_instance == this) + m_instance = 0; + if (m_engine) + delete m_engine; + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + delete m_coverPositions[i]; + m_coverPositions.erase(m_coverPositions.begin(), m_coverPositions.end()); } -// - `return m_coverPositions.back;`, with no empty check. On an empty +// ELF 0x357CF0: `return m_coverPositions.back();`, with no empty check. On an empty // vector it reads one element in front of the buffer. Shipped; preserved. CoverPosition* CoverPositionManager::getLastCoverPosition() const { return m_coverPositions.back(); } -// Cover-position search and query operations remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace each stop when the corresponding CoverPosition behavior is recovered. - -CoverPosition* CoverPositionManager::createCoverPosition(const Vec2&, const Vec2&) +// ELF 0x3577E0. The id is the index; the new table row has one zero per position including the +// new one, then the distances to the earlier positions are filled in. +void CoverPositionManager::createCoverPosition(const Vec2& a, const Vec2& b) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::createCoverPosition"); + Vec2 low = a; + Vec2 high = b; + if (high.x < low.x) + { + high.x = a.x; + low.x = b.x; + } + if (high.y < low.y) + { + high.y = a.y; + low.y = b.y; + } + CoverPosition* const position = checkPointer(new CoverPosition(low, high)); + const int id = static_cast(m_coverPositions.size()); + position->m_id = id; + m_coverPositions.push_back(position); + m_distances.push_back(std::vector(id + 1, 0.0f)); + for (int i = 0; i < id; ++i) + m_distances[id][i] = position->getShortestDistance(m_coverPositions[i]); } -void CoverPositionManager::RandomizeCoverPos(Vec2, Vec2, Vec2&) +// ELF 0x357D10. One random draw per axis. +void CoverPositionManager::RandomizeCoverPos(Vec2 low, Vec2 high, Vec2& out) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::RandomizeCoverPos"); + out.x = (high.x - low.x - 2.0f) * AIRandom::m_instance->nextFloat() + low.x + 1.0f; + out.y = (high.y - low.y - 2.0f) * AIRandom::m_instance->nextFloat() + low.y + 1.0f; } -void CoverPositionManager::RandomizeCoverPosAlongEdge(Vec2, Vec2, Vec2&) +// ELF 0x357E70. A first draw picks the edge direction (at least 0.5: along y); the second the +// offset. The step is taken away from the far side when it would leave the box, and the other +// axis moves 1 inward the same way. Shipped asymmetry, preserved: along x the back step is +// `d - 1`, along y it is `d`. +void CoverPositionManager::RandomizeCoverPosAlongEdge(Vec2 low, Vec2 high, Vec2& out) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::RandomizeCoverPosAlongEdge"); + if (AIRandom::m_instance->nextFloat() >= 0.5f) + { + const float d = (high.y - low.y) * AIRandom::m_instance->nextFloat() * 0.5f; + float y = out.y + d; + if (high.y < y) + y = out.y - d; + out.y = y; + float x = out.x + 1.0f; + if (high.x < x) + x = out.x - 1.0f; + out.x = x; + } + else + { + const float d = (high.x - low.x) * AIRandom::m_instance->nextFloat() * 0.5f; + if (out.x + d <= high.x) + out.x = out.x + (d + 1.0f); + else + out.x = out.x - (d - 1.0f); + float y = out.y + 1.0f; + if (high.y < y) + y = out.y - 1.0f; + out.y = y; + } } -bool CoverPositionManager::isInCoverPosition(Vec2) +// ELF 0x3580E0: the first cover position whose box (+0 min, +8 max, bounds inclusive) holds the +// point, or null. The image answers the pointer (`mov (%edx),%edx; mov %edx,-0x40`), not a bool. +CoverPosition* CoverPositionManager::isInCoverPosition(Vec2 point) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::isInCoverPosition"); + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + { + const Vec2 low = m_coverPositions[i]->m_min; + const Vec2 high = m_coverPositions[i]->m_max; + if (point.x >= low.x && point.y >= low.y && high.x >= point.x && high.y >= point.y) + return m_coverPositions[i]; + } + return 0; } -bool CoverPositionManager::getClosestAttackCoverPosition(const Vec2&, const Vec2&, float, float, - Vec2&) +// ELF 0x3581B0: a cover spot for attacking `to` from `from`. Only when the two are more than 5 +// apart (squared distance > 25): the answer starts as `from`; the reference point is +// from + (to - from) * fraction / 4. Each position whose centre is closer to it than the best so +// far, within maxDistance and within half the squared from-to distance, is found (answer true): +// when `from` is inside its box the answer is `from` (best 0); otherwise the centre, randomized in +// the box (RandomizeCoverPos) - or, when `to` is itself in cover and the position sees that cover +// best from a corner (findHighestVisibilityCorner), a point along that edge. +bool CoverPositionManager::getClosestAttackCoverPosition(const Vec2& from, const Vec2& to, float maxDistance, + float fraction, Vec2& out) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::getClosestAttackCoverPosition"); + bool found = false; + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float distance = dy * dy + dx * dx; + if (!(distance > 25.0f)) + return found; + float best = 3.40282347e+38f; + out.y = from.y; + out.x = from.x; + Vec2 reference; + reference.x = (to.x - from.x) * fraction * 0.25f + from.x; + reference.y = (to.y - from.y) * fraction * 0.25f + from.y; + CoverPosition* const targetCover = isInCoverPosition(to); + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + { + CoverPosition* const cover = m_coverPositions[i]; + const Vec2 low = cover->m_min; + const Vec2 high = cover->m_max; + Vec2 centre; + centre.x = low.x + (high.x - low.x) * 0.5f; + centre.y = low.y + (high.y - low.y) * 0.5f; + const float cx = centre.x - reference.x; + const float cy = centre.y - reference.y; + const float d = cx * cx + cy * cy; + if (!(d < best) || !(d < maxDistance * maxDistance) || !(d < distance * 0.5f)) + continue; + found = true; + if (!(from.x < low.x || from.y < low.y || high.x < from.x || high.y < from.y)) + { + out = from; + best = 0.0f; + continue; + } + best = d; + if (targetCover) + { + if (cover->findHighestVisibilityCorner(targetCover, out)) + { + RandomizeCoverPosAlongEdge(low, high, out); + continue; + } + } + out = centre; + RandomizeCoverPos(low, high, out); + } + return found; } -bool CoverPositionManager::getClosestNavCoverPosition(Vec2, Vec2, Vec2&, CoverPosition*&) +// ELF 0x358610. A centre qualifies when it is closer to `from` than the best so far (and more than +// 0.001 away), closer to `to` than `from` is, closer to `from` than `to` is, and - when `from` is +// in cover - seen from that cover (CoverPosition::canSee, asked before the distance tests). The +// answer is the distance to the chosen centre, or from `from` to `to`. +float CoverPositionManager::getClosestNavCoverPosition(Vec2 from, Vec2 to, Vec2& out, + CoverPosition*& cover) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::getClosestNavCoverPosition"); + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float total = dy * dy + dx * dx; + float best = FLT_MAX; + out.x = to.x; + out.y = to.y; + bool found = false; + CoverPosition* const current = isInCoverPosition(from); + cover = 0; + for (unsigned int i = 0; i < m_coverPositions.size(); ++i) + { + CoverPosition* const position = m_coverPositions[i]; + const Vec2 low = position->m_min; + const Vec2 high = position->m_max; + Vec2 centre; + centre.x = low.x + (high.x - low.x) * 0.5f; + centre.y = low.y + (high.y - low.y) * 0.5f; + bool visible = true; + const float d = (centre.x - from.x) * (centre.x - from.x) + (centre.y - from.y) * (centre.y - from.y); + const float rest = (to.y - centre.y) * (to.y - centre.y) + (to.x - centre.x) * (to.x - centre.x); + if (current != 0) + visible = current->canSee(position); + if (d < best && d > 0.001f && rest < total && d < total && visible) + { + cover = position; + out = centre; + found = true; + best = d; + } + } + if (!found) + best = (to.y - from.y) * (to.y - from.y) + (to.x - from.x) * (to.x - from.x); + return sqrtf(best); } +// ELF 0x3588A0. void CoverPositionManager::finaliseCoverPositions() { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::finaliseCoverPositions"); + for (std::vector::iterator it = m_coverPositions.begin(); + it != m_coverPositions.end(); ++it) + { + (*it)->updateAttacks(true); + (*it)->updateMoveNeighbours(); + } } -void CoverPositionManager::updatePathfinding(double) +// ELF 0x358900: the engine's update, inlined. +void CoverPositionManager::updatePathfinding(double budget) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::updatePathfinding"); + m_engine->update(budget); } -int CoverPositionManager::search(int, int) +// ELF 0x358A40. Inlined, in order: take the first free resource for owner 1 (as +// AIPathfinding::acquireResource, without the locking test; none free gives index UINT_MAX, which +// retail then uses), size the node flags, take a start and a goal node from the pool, reset the +// search (counters, open tree, both hashes, node flags), then either finish at once when both name +// the same position (the goal node goes back to the pool) or record the goal, return its node to +// the pool and open the start. One engine update of 10000 then runs; an owned resource is +// released as AIPathfinding::releaseResource does. The start node is not returned. +bool CoverPositionManager::search(int start, int goal) { - BF2_AI_FRONTIER("dice::hfe::ai::CoverPositionManager::search"); + unsigned int resource; + std::list& available = m_engine->m_available; + if (available.empty()) + resource = 0xFFFFFFFFu; + else + { + std::list::iterator first = available.begin(); + resource = *first; + CPAStarResource* const candidate = m_engine->m_searches[resource]; + if (candidate->m_owner < 0) + { + candidate->m_owner = 1; + available.erase(first); + m_engine->m_inFlight.insert(m_engine->m_inFlight.end(), resource); + } + else + resource = 0xFFFFFFFFu; + } + + CPNodeManager* const manager = m_engine->m_searches[resource]->m_nodeManager; + manager->init(); + CPNode* const startNode = manager->getNewNode(0, start); + CPNode* const goalNode = manager->getNewNode(0, goal); + + CPAStarResource* search = m_engine->m_searches[resource]; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + search = m_engine->m_searches[resource]; + if (startNode->m_key == goalNode->m_key) + { + goalNode->m_next = search->m_nodeManager->m_nodes; + search->m_nodeManager->m_nodes = goalNode; + search->m_status = astarStatus::kFound; + search->m_goal = startNode; + } + else + { + search->m_nodeManager->m_goal = goalNode->m_key->m_id; + goalNode->m_next = search->m_nodeManager->m_nodes; + search->m_nodeManager->m_nodes = goalNode; + search->pushOpenNode(startNode); + search->m_status = astarStatus::kSearching; + } + + m_engine->update(10000.0); + + search = m_engine->m_searches[resource]; + const int status = search->m_status; + if (search->m_owner == 1) + { + search->m_owner = -1; + search = m_engine->m_searches[resource]; + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_status = astarStatus::kIdle; + search->m_owner = -1; + m_engine->m_available.insert(m_engine->m_available.end(), resource); + m_engine->m_inFlight.remove(resource); + } + return status == astarStatus::kFound; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h index 1cb95051a..167c7f1ec 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.h @@ -1,10 +1,13 @@ -// Owns cover-position search resources and queries. -// [FRONTIER] Remaining queries require the cover-position implementation. +// Owns the cover positions, their distance table and the cover-position A* engine. +// Evidence: libaidll.so 1.5.3153 (ia-32), ELF 0x356680..0x359220 plus the engine's CPNode template +// instantiations up to 0x35BA70. [INFERRED] Placement +// AIStrategicEntity/CoverPosition/CoverPositionManager.cpp (the static-init symbol names +// CoverPositionManager::m_instance). #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITIONMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGICENTITY_COVERPOSITION_COVERPOSITIONMANAGER_H -#include +#include #include #include "../../../../../Math/Vec3.h" // Vec2 and Vec3 are typedefs, not classes @@ -18,45 +21,56 @@ namespace ai { class CoverPosition; class CPNode; -// [PLATFORM] The original key is a libstdc++ tree iterator unavailable in MSVC. -// [CHOSEN, not recovered] This iterator substitute preserves current object layout; -// search methods must verify its required semantics before use. -typedef std::map::iterator CPSearchKey; - -typedef PathfindingEngine > +// The search key is the move-neighbour iterator CPNode::expandFirst / expand advance +// (std::_Rb_tree_iterator in the mangled names: libstdc++'s +// set iterator); the path type is vector. +typedef PathfindingEngine::const_iterator, std::vector > CPPathfindingEngine; -typedef AStarResource > +typedef AStarResource::const_iterator, std::vector > CPAStarResource; class CoverPositionManager { public: CoverPositionManager(); - ~CoverPositionManager(); // , not virtual + ~CoverPositionManager(); // not virtual - CoverPosition* createCoverPosition(const Vec2&, const Vec2&); + // A new position over the box spanned by the two points (corners ordered per axis), its + // distances to every existing position appended as a new table row. Returns nothing. + void createCoverPosition(const Vec2& a, const Vec2& b); CoverPosition* getLastCoverPosition() const; - void RandomizeCoverPos(Vec2, Vec2, Vec2&); - void RandomizeCoverPosAlongEdge(Vec2, Vec2, Vec2&); - bool isInCoverPosition(Vec2); - bool getClosestAttackCoverPosition(const Vec2&, const Vec2&, float, float, Vec2&); - bool getClosestNavCoverPosition(Vec2, Vec2, Vec2&, CoverPosition*&); + // Moves `out` to a random point at least 1 inside the box. + void RandomizeCoverPos(Vec2 low, Vec2 high, Vec2& out); + // Moves `out` (a corner) along one of the box's edges by a random fraction of half its length. + void RandomizeCoverPosAlongEdge(Vec2 low, Vec2 high, Vec2& out); + CoverPosition* isInCoverPosition(Vec2 point); // the containing position, not a bool + bool getClosestAttackCoverPosition(const Vec2& from, const Vec2& to, float maxDistance, + float fraction, Vec2& out); + // The closest cover centre between `from` and `to` that the cover `from` is in can see; + // answers the distance to it (or to `to` when none qualifies). + float getClosestNavCoverPosition(Vec2 from, Vec2 to, Vec2& out, CoverPosition*& cover); void finaliseCoverPositions(); - void updatePathfinding(double); - int search(int, int); + void updatePathfinding(double budget); + // A synchronous search between two cover positions; true when it reached the goal. + bool search(int start, int goal); + + // [INFERRED] Inline accessor for the lower-triangular distance table, as the CPNode search + // reads it (m_distances[larger][smaller]). + float getDistance(int a, int b) const + { + return a > b ? m_distances[a][b] : m_distances[b][a]; + } // dice's own capitalisation on the two `Randomize*` methods - initial capital, and the // American spelling next to `finaliseCoverPositions`'s British one, in the same class. static CoverPositionManager* m_instance; -private: - // layout, , read from the constructor and confirmed by the destructor + // Layout from the constructor and destructor; names [INFERRED]. Public: CPNode, + // CPNodeManager and CoverPosition read the positions through m_instance. /* +0 */ std::vector m_coverPositions; - // Never touched by the constructor; the destructor frees the inner buffers with a 12-byte - // stride, so the elements are vectors of a four-byte type. Which type is [UNRESOLVED] - the - // readers are `search` and `getClosestNavCoverPosition`, both frontiers. - /* +12 */ std::vector > m_v12; + // Row i holds the distances from position i to positions 0..i (createCoverPosition). + /* +12 */ std::vector > m_distances; /* +24 */ CPPathfindingEngine* m_engine; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp new file mode 100644 index 000000000..1b1556460 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp @@ -0,0 +1,210 @@ +// Guard positions. Evidence: libaidll.so (ia-32) 0x34EDB0..0x34FA8F. +// [INFERRED] Source placement. + +#include "GuardPosition.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34F9E0, __tcf_0 0x34FA40, _GLOBAL__I 0x34FA70). +#include +#include + +#include "GuardPositionBotDCB.h" +#include "GuardPositionBotSCB.h" +#include "AIStrategicObject.h" +#include "AIStrategicObjectManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/WPMoveTo.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x34EDB0 (C2; C1 0x34EE70). +GuardPosition::GuardPosition(const Vec2& position, CombatStrengthType strengthType, int side, + int kit) + : m_strengthType(strengthType) + , m_active(true) + , m_side(side) + , m_kit(kit) + , m_minDistance(5.0f) + , m_bot(0) + , m_recruited(false) +{ + m_position.x = 0.0f; + m_position.y = 0.0f; + m_position.z = 0.0f; + m_rotation.x = 1.0f; + m_rotation.y = 0.0f; + m_rotation.z = 0.0f; + vec2ToVec3XZ(position, m_position); + m_position.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getHeight(position.x, position.y) + 1.0f; +} + +// ELF 0x34EF30 (D2; D1 0x34EFE0). +GuardPosition::~GuardPosition() +{ +} + +// ELF 0x34F090. +CombatStrengthType GuardPosition::getStrengthType() const +{ + return m_strengthType; +} + +// ELF 0x34F0A0. +const Vec3& GuardPosition::getPosition() const +{ + return m_position; +} + +// ELF 0x34F0B0. +void GuardPosition::setRotation(const Vec3& rotation) +{ + m_rotation = rotation; +} + +// ELF 0x34F0F0. +const Vec3& GuardPosition::getRotation() const +{ + return m_rotation; +} + +// ELF 0x34F100. +void GuardPosition::setActive(bool active) +{ + m_active = active; +} + +// ELF 0x34F110. +bool GuardPosition::getActive() const +{ + return m_active; +} + +// ELF 0x34F120: the same load as getActive. +bool GuardPosition::active() const +{ + return m_active; +} + +// ELF 0x34F130. +void GuardPosition::setSide(int side) +{ + m_side = side; +} + +// ELF 0x34F140. +int GuardPosition::getSide() const +{ + return m_side; +} + +// ELF 0x34F150. +void GuardPosition::setMinDistance(float distance) +{ + m_minDistance = distance; +} + +// ELF 0x34F160. +float GuardPosition::getMinDistance() const +{ + return m_minDistance; +} + +// ELF 0x34F170. +bool GuardPosition::needBot() const +{ + return !m_recruited && m_bot == 0; +} + +// ELF 0x34F190. +void GuardPosition::recruit(Bot* bot) +{ + bot->setDeathCallBack(checkPointer(new GuardPositionBotDCB(bot, this))); + bot->setSpawnCallBack(checkPointer(new GuardPositionBotSCB(bot, this))); + m_bot = bot; + m_recruited = true; + if (bot->isDead()) + { + bot->setIsInTransitionPhase(true); + spawnBot(bot); + } + else + botIsAlive(bot); +} + +// ELF 0x34F4A0. A one-point path to the position: radius m_minDistance, step radius 60, flags 1, +// no last area. +void GuardPosition::botIsAlive(Bot* bot) +{ + std::list path; + path.push_back(m_position); + bot->setWaypoints(checkPointer(new WPMoveTo(m_minDistance, 60.0f, 1, path, -1))); +} + +// ELF 0x34F760. +void GuardPosition::botIsDead(Bot* bot) +{ + bot->setIsInTransitionPhase(true); + lostBot(); +} + +// ELF 0x34F7A0. IAIGameEffector::forceSpawnBot (+0x20) with the position and the facing. +void GuardPosition::spawnBot(Bot* bot) +{ + bot->setSpawnTarget(1, m_kit); + static_cast(CommonSingletonServer::m_iaiGameEffector) + ->forceSpawnBot(bot->getPlayer(), m_position, m_rotation); +} + +// ELF 0x34F820. IAIMain::registerFreeBot (+0x10). +void GuardPosition::lostBot() +{ + IAIMain::m_instance->registerFreeBot(m_bot); + m_bot = 0; +} + +// ELF 0x34F870. The object found by index is not null-tested; one found by name is, and an +// unknown name keeps the condition unresolved for the next update. +void GuardPosition::update() +{ + if (!m_bot) + return; + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + for (std::vector::iterator it = m_areaConditions.begin(); + it != m_areaConditions.end(); ++it) + { + AIStrategicObject* object; + if (it->areaIndex == -1) + { + object = manager->getStrategicObject(it->areaName); + if (!object) + continue; + it->areaIndex = object->getIndex(); + } + else + object = manager->getStrategicObject(it->areaIndex); + if (object->getStatus(m_side) == it->status) + { + lostBot(); + return; + } + } +} + +// ELF 0x34F920. +void GuardPosition::addStrategicAreaAbortCondition(const std::string& areaName, + StatusMap::Status status) +{ + AreaCondition condition; + condition.areaName = areaName; + condition.areaIndex = -1; + condition.status = status; + m_areaConditions.push_back(condition); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h index 68962a4ca..9bfcff03c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h @@ -16,19 +16,38 @@ enum CombatStrengthType : int; class GuardPosition { public: - // Attested signatures, declaration-only: no default or fixture constructor in production. - GuardPosition(const Vec2&, CombatStrengthType, int side, int value36); - // > : only AreaCondition vector/string cleanup. - // The borrowed bot is not deleted and no callback is invoked. - ~GuardPosition() = default; - - bool active() const { return m_active; } // byte +28 - int getSide() const { return m_side; } // int +32 - bool needBot() const - { - // Both images test the byte first. Neither active nor side participates in this predicate. - return !m_flag48 && m_bot == 0; - } + // The position is `position` on the terrain, one metre up; the facing starts at (1, 0, 0). + GuardPosition(const Vec2& position, CombatStrengthType strengthType, int side, int kit); + // Member cleanup only: the borrowed bot is not deleted and no callback is invoked. + ~GuardPosition(); + + CombatStrengthType getStrengthType() const; + const Vec3& getPosition() const; + void setRotation(const Vec3& rotation); + const Vec3& getRotation() const; + void setActive(bool active); + bool getActive() const; + bool active() const; + void setSide(int side); + int getSide() const; + void setMinDistance(float distance); + float getMinDistance() const; + // True while no bot was ever recruited: the recruited flag is tested before the bot. + bool needBot() const; + // Takes `bot`: installs this position's death and spawn callbacks, then either spawns a dead + // bot here or sends a living one on its way. + void recruit(Bot* bot); + // Gives the bot a waypoint list that walks to the position. + void botIsAlive(Bot* bot); + void botIsDead(Bot* bot); + // Sets the bot's spawn target (group 1, this position's kit) and force-spawns it here. + void spawnBot(Bot* bot); + // Hands the bot back to the bot pool. The recruited flag stays set. + void lostBot(); + // Releases the bot when any abort condition holds: an area of the position's side with the + // condition's status. Area indices are resolved by name on first use. + void update(); + void addStrategicAreaAbortCondition(const std::string& areaName, StatusMap::Status status); private: // Area abort condition. New entries start with areaIndex -1. @@ -46,10 +65,10 @@ class GuardPosition /* +24 */ CombatStrengthType m_strengthType; /* +28 */ bool m_active; /* +32 */ int m_side; - /* +36 */ int m_value36; // [UNRESOLVED] constructor's final parameter + /* +36 */ int m_kit; // spawnBot's setSpawnTarget kit [INFERRED name] /* +40 */ float m_minDistance; /* +44 */ Bot* m_bot; - /* +48 */ bool m_flag48; // [UNRESOLVED] name; recruit sets true + /* +48 */ bool m_recruited; // [INFERRED] name; recruit sets it, nothing clears it /* +52 */ std::vector m_areaConditions; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp new file mode 100644 index 000000000..0350c3924 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp @@ -0,0 +1,32 @@ +// GuardPositionBotDCB. Evidence: libaidll.so (ia-32) 0x..0x34FFA0. +// [INFERRED] Source placement. + +#include "GuardPositionBotDCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34FF40, __tcf_0 0x34FFA0, _GLOBAL__I 0x34FFD0). +#include + +#include "GuardPosition.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x (C2; C1 0x34FDB0). +GuardPositionBotDCB::GuardPositionBotDCB(Bot* bot, GuardPosition* guardPosition) + : IBotDeathCallBack(bot) + , m_guardPosition(guardPosition) +{ +} + +// ELF 0x34FE00 (D2; D1 0x34FE50, D0 0x34FE90). +GuardPositionBotDCB::~GuardPositionBotDCB() +{ +} + +// ELF 0x34FED0. Neither pointer is tested. +void GuardPositionBotDCB::reportDeath() +{ + m_guardPosition->botIsDead(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.h new file mode 100644 index 000000000..89db438e4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.h @@ -0,0 +1,27 @@ +// Hands the bot's death to its guard position. +// Placement is [INFERRED]; the class has its own TU in the image. +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTDCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTDCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class GuardPosition; + +class GuardPositionBotDCB : public IBotDeathCallBack +{ +public: + // The guard position is borrowed, not owned. + GuardPositionBotDCB(Bot* bot, GuardPosition* guardPosition); + virtual ~GuardPositionBotDCB(); + virtual void reportDeath(); + +private: + /* +8 */ GuardPosition* m_guardPosition; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp new file mode 100644 index 000000000..124982677 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp @@ -0,0 +1,32 @@ +// GuardPositionBotSCB. Evidence: libaidll.so (ia-32) 0x..0x3501E0. +// [INFERRED] Source placement. + +#include "GuardPositionBotSCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x350180, __tcf_0 0x3501E0, _GLOBAL__I 0x350210). +#include + +#include "GuardPosition.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x (C2; C1 0x34FFF0). +GuardPositionBotSCB::GuardPositionBotSCB(Bot* bot, GuardPosition* guardPosition) + : IBotSpawnCallBack(bot) + , m_guardPosition(guardPosition) +{ +} + +// ELF 0x350040 (D2; D1 0x350090, D0 0x3500D0). +GuardPositionBotSCB::~GuardPositionBotSCB() +{ +} + +// ELF 0x350110. Neither pointer is tested. +void GuardPositionBotSCB::reportSpawn() +{ + m_guardPosition->botIsAlive(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.h new file mode 100644 index 000000000..6b689bfad --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.h @@ -0,0 +1,27 @@ +// Hands the bot's spawn to its guard position. +// Placement is [INFERRED]; the class has its own TU in the image. +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTSCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_GUARDPOSITIONBOTSCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class GuardPosition; + +class GuardPositionBotSCB : public IBotSpawnCallBack +{ +public: + // The guard position is borrowed, not owned. + GuardPositionBotSCB(Bot* bot, GuardPosition* guardPosition); + virtual ~GuardPositionBotSCB(); + virtual void reportSpawn(); + +private: + /* +8 */ GuardPosition* m_guardPosition; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp new file mode 100644 index 000000000..1e8eb5163 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp @@ -0,0 +1,209 @@ +// PatrolPath. Evidence: libaidll.so (ia-32) 0x350230..0x350F80. +// [INFERRED] Source placement. + +#include "PatrolPath.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x350ED0, __tcf_0 0x350F30, _GLOBAL__I 0x350F60). +#include + +#include "PatrolPathBotDCB.h" +#include "PatrolPathBotSCB.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/WPPatrol.h" +#include "../AIStrategicMap/BotSpawner.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain::getTerrainAltitude + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x350230 (C2; C1 0x350360): active, minimum distance 1, patrol speed -1. +PatrolPath::PatrolPath(CombatStrengthType strengthType, int side) + : m_path() + , m_strengthType(strengthType) + , m_active(true) + , m_side(side) + , m_currentResources(0) + , m_requiredResources(0) + , m_minDistance(1.0f) + , m_patrolSpeed(-1.0f) + , m_bots() +{ +} + +// ELF 0x3503E0 (C2; C1 0x3504C0). +PatrolPath::PatrolPath(const std::vector& path, CombatStrengthType strengthType, int side) + : m_path(path) + , m_strengthType(strengthType) + , m_active(true) + , m_side(side) + , m_currentResources(0) + , m_requiredResources(0) + , m_minDistance(1.0f) + , m_patrolSpeed(-1.0f) + , m_bots() +{ +} + +// ELF 0x3505A0 (D2; D1 0x350620). +PatrolPath::~PatrolPath() +{ +} + +// ELF 0x3506A0. +CombatStrengthType PatrolPath::getStrengthType() const +{ + return m_strengthType; +} + +// ELF 0x3506B0. +const std::vector& PatrolPath::getPath() const +{ + return m_path; +} + +// ELF 0x3506C0. +void PatrolPath::addPathPoint(const Vec3& point) +{ + m_path.push_back(point); +} + +// ELF 0x350730. +void PatrolPath::addPathPoint(const Vec2& point) +{ + Vec3 position; + position.x = point.x; + position.y = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(point.x, point.y) + 3.0f; + position.z = point.y; + m_path.push_back(position); +} + +// ELF 0x3507E0. +void PatrolPath::setActive(bool active) +{ + m_active = active; +} + +// ELF 0x3507F0. +bool PatrolPath::getActive() const +{ + return m_active; +} + +// ELF 0x350800. +bool PatrolPath::active() const +{ + return m_active; +} + +// ELF 0x350810. +void PatrolPath::setSide(int side) +{ + m_side = side; +} + +// ELF 0x350820. +int PatrolPath::getSide() const +{ + return m_side; +} + +// ELF 0x350830. +void PatrolPath::setMinDistance(float distance) +{ + m_minDistance = distance; +} + +// ELF 0x350840. +float PatrolPath::getMinDistance() const +{ + return m_minDistance; +} + +// ELF 0x350850. +void PatrolPath::setPatrolSpeed(float speed) +{ + m_patrolSpeed = speed; +} + +// ELF 0x350860. +float PatrolPath::getPatrolSpeed() const +{ + return m_patrolSpeed; +} + +// ELF 0x350870. +void PatrolPath::setRequiredResources(int resources) +{ + m_requiredResources = resources; +} + +// ELF 0x350880. +int PatrolPath::getRequiredResources() const +{ + return m_requiredResources; +} + +// ELF 0x350890. +int PatrolPath::neededResources() const +{ + return m_requiredResources - m_currentResources; +} + +// ELF 0x3508A0. +void PatrolPath::recruit(Bot* bot) +{ + bot->setDeathCallBack(checkPointer(new PatrolPathBotDCB(bot, this))); + bot->setSpawnCallBack(checkPointer(new PatrolPathBotSCB(bot, this))); + if (bot->isDead()) + botIsDead(bot); + else + botIsAlive(bot); + ++m_currentResources; + m_bots.push_back(bot); +} + +// ELF 0x350BF0: a patrol over the path with this patrol's minimum distance as its radius and +// flags 5; the patrol speed goes to its +8 before the bot takes it. +void PatrolPath::botIsAlive(Bot* bot) +{ + WPPatrol* const patrol = checkPointer(new WPPatrol(m_minDistance, 5, m_path)); + patrol->m_float8 = m_patrolSpeed; + bot->setWaypoints(patrol); +} + +// ELF 0x350D70: a respawn group near the first path point; the result is unused. +void PatrolPath::botIsDead(Bot* bot) +{ + bot->setIsInTransitionPhase(true); + BotSpawner::findSuitableSpawnGroup(m_path[0], bot); +} + +// ELF 0x350DC0. Shipped defect, preserved: the current resources are incremented, not +// decremented. The first list entry for the bot is erased. +void PatrolPath::lost(Bot* bot) +{ + ++m_currentResources; + for (std::list::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + if (*it == bot) + { + m_bots.erase(it); + return; + } + } +} + +// ELF 0x350E50: every dead bot in the list goes through botIsDead. +void PatrolPath::update() +{ + for (std::list::iterator it = m_bots.begin(); it != m_bots.end(); ++it) + { + if ((*it)->isDead()) + botIsDead(*it); + } +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h index f666cc113..9cc96bc15 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h @@ -1,4 +1,4 @@ -// Patrol route and bot recruitment state. +// Patrol route and bot recruitment state (libaidll.so PatrolPath.cpp, 0x350230..0x350F80). // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATH_H #define AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATH_H @@ -15,20 +15,39 @@ enum CombatStrengthType : int; class PatrolPath { public: - // Attested signatures, declaration-only: no default or fixture constructor in production. - PatrolPath(CombatStrengthType, int side); - PatrolPath(const std::vector&, CombatStrengthType, int); - // list nodes/sentinel, then the Vec3 vector buffer. - // Ordinary reverse member destruction; bot pointers in the list are not deleted. - ~PatrolPath() = default; - - bool active() const { return m_active; } // +16 / +20 - int getSide() const { return m_side; } // +20 / +24 - int neededResources() const - { - // Signed required-minus-current, with no clamp. recruitBot tests the result > 0. - return m_requiredResources - m_currentResources; - } + PatrolPath(CombatStrengthType strengthType, int side); // ELF 0x350230 (C2; C1 0x350360) + PatrolPath(const std::vector& path, CombatStrengthType strengthType, int side); + // ELF 0x3503E0 (C2; C1 0x3504C0) + // Ordinary member destruction; bot pointers in the list are not deleted. + ~PatrolPath(); // ELF 0x3505A0 (D2; D1 0x350620) + + CombatStrengthType getStrengthType() const; + const std::vector& getPath() const; + void addPathPoint(const Vec3& point); + // The terrain height under the point, three metres up. + void addPathPoint(const Vec2& point); + void setActive(bool active); + bool getActive() const; + bool active() const; // the same load as getActive + void setSide(int side); + int getSide() const; + void setMinDistance(float distance); + float getMinDistance() const; + void setPatrolSpeed(float speed); + float getPatrolSpeed() const; + void setRequiredResources(int resources); + int getRequiredResources() const; + // Signed required-minus-current, with no clamp. recruitBot tests the result > 0. + int neededResources() const; + + // Installs the death/spawn callbacks, starts the patrol (or handles the dead bot) and + // counts the bot in. + void recruit(Bot* bot); + void botIsAlive(Bot* bot); + void botIsDead(Bot* bot); + // As shipped, losing a bot also increments the current resources. + void lost(Bot* bot); + void update(); private: // Member names [INFERRED] from the constructor, getters and recruitment increment. diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp new file mode 100644 index 000000000..5b60eb587 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp @@ -0,0 +1,32 @@ +// PatrolPathBotDCB. Evidence: libaidll.so (ia-32) 0x351090..0x3512B0. +// [INFERRED] Source placement. + +#include "PatrolPathBotDCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x351220, __tcf_0 0x351280, _GLOBAL__I 0x3512B0). +#include + +#include "PatrolPath.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x351090 (C2; C1 0x3510E0). +PatrolPathBotDCB::PatrolPathBotDCB(Bot* bot, PatrolPath* patrolPath) + : IBotDeathCallBack(bot) + , m_patrolPath(patrolPath) +{ +} + +// ELF 0x351130 (D2; D1 0x351170, D0 0x3511B0). +PatrolPathBotDCB::~PatrolPathBotDCB() +{ +} + +// ELF 0x3511F0. Neither pointer is tested. +void PatrolPathBotDCB::reportDeath() +{ + m_patrolPath->botIsDead(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.h new file mode 100644 index 000000000..3623fba79 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.h @@ -0,0 +1,28 @@ +// Hands the bot's death to its patrol path. +// Placement is [INFERRED]; the class has its own TU in the image. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTDCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTDCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class PatrolPath; + +class PatrolPathBotDCB : public IBotDeathCallBack +{ +public: + // The patrol path is borrowed, not owned. + PatrolPathBotDCB(Bot* bot, PatrolPath* patrolPath); + virtual ~PatrolPathBotDCB(); + virtual void reportDeath(); + +private: + /* +8 */ PatrolPath* m_patrolPath; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp new file mode 100644 index 000000000..bcc095cf0 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp @@ -0,0 +1,32 @@ +// PatrolPathBotSCB. Evidence: libaidll.so (ia-32) 0x3512D0..0x3514F0. +// [INFERRED] Source placement. + +#include "PatrolPathBotSCB.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x351460, __tcf_0 0x3514C0, _GLOBAL__I 0x3514F0). +#include + +#include "PatrolPath.h" + +namespace dice { namespace hfe { namespace ai { + +// ELF 0x3512D0 (C2; C1 0x351320). +PatrolPathBotSCB::PatrolPathBotSCB(Bot* bot, PatrolPath* patrolPath) + : IBotSpawnCallBack(bot) + , m_patrolPath(patrolPath) +{ +} + +// ELF 0x351370 (D2; D1 0x3513B0, D0 0x3513F0). +PatrolPathBotSCB::~PatrolPathBotSCB() +{ +} + +// ELF 0x351430. Neither pointer is tested. +void PatrolPathBotSCB::reportSpawn() +{ + m_patrolPath->botIsAlive(m_bot); +} + +} } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.h new file mode 100644 index 000000000..626371bcb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.h @@ -0,0 +1,28 @@ +// Hands the bot's spawn to its patrol path. +// Placement is [INFERRED]; the class has its own TU in the image. + +#ifndef AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTSCB_H +#define AI_AIDLL_AI_AISTRATEGICENTITY_PATROLPATHBOTSCB_H + +#include "../AIBot/BotCallBack.h" + +namespace dice { namespace hfe { namespace ai { + +class Bot; +class PatrolPath; + +class PatrolPathBotSCB : public IBotSpawnCallBack +{ +public: + // The patrol path is borrowed, not owned. + PatrolPathBotSCB(Bot* bot, PatrolPath* patrolPath); + virtual ~PatrolPathBotSCB(); + virtual void reportSpawn(); + +private: + /* +8 */ PatrolPath* m_patrolPath; +}; + +} } } + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp index 29ca657e9..f38719cdd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp @@ -1,10 +1,13 @@ +// Strategic-area waypoints. Evidence: libaidll.so (ia-32) 0x34E980..0x34EDAF. // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SAWayPoint operations. #include "SAWayPoint.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x34ED00, __tcf_0 0x34ED60, _GLOBAL__I 0x34ED90). +#include + #include "../DrawPrimitives/DPManager.h" -#include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" @@ -12,7 +15,7 @@ namespace dice { namespace hfe { namespace ai { -// Five stores and no allocation. +// ELF 0x34E980 (C2; C1 0x34E9C0). Five stores and no allocation. SAWayPoint::SAWayPoint(const Vec3& position, int map) : m_position(position) , m_island(0xFFFFFFFFu) // 1, written as the dword the constructor stores @@ -22,13 +25,13 @@ SAWayPoint::SAWayPoint(const Vec3& position, int map) { } -// Removes the waypoint's debug primitive; the waypoint owns no other heap resources. +// ELF 0x34EA00 (D2; D1 0x34EA30). Removes the waypoint's debug primitive; the waypoint owns no other heap resources. SAWayPoint::~SAWayPoint() { undraw(); } -// Resolves the waypoint polygon with search mode 3 on the trace map and 0 otherwise. +// ELF 0x34EA60. Resolves the waypoint polygon with search mode 3 on the trace map and 0 otherwise. // Requires the pathfinder singleton and preserves its separate reads for query and search. void SAWayPoint::init() { @@ -40,7 +43,7 @@ void SAWayPoint::init() 3 * (traceMap == m_map)); } -// Deletes the debug circle when present and clears its handle unconditionally. +// ELF 0x34ECB0. Deletes the debug circle when present and clears its handle unconditionally. // Safe to repeat after an earlier undraw call. void SAWayPoint::undraw() const { @@ -53,11 +56,36 @@ void SAWayPoint::undraw() const m_debugPrimitive = 0; } -// [FRONTIER] Waypoint drawing requires the remaining primitive-manager interfaces. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding SAWayPoint operation. +// ELF 0x34EAD0. A debug circle at the waypoint: red while it has no polygon, green once resolved; +// draw type 6 on the trace map, 4 otherwise. The first call creates the circle, later calls +// update it in place. void SAWayPoint::draw() const { - BF2_AI_FRONTIER("dice::hfe::ai::SAWayPoint::draw"); + const int type = (IAIPathfinding::instance->getTraceMapIndex() == m_map) ? 6 : 4; + Vec3 normal; + if (!m_debugPrimitive) + { + const unsigned int colour = (m_polygon == 0xFFFFFFFFu) ? 0xFFBB0000u : 0xFF00BB00u; + normal.x = 0.0f; + normal.y = 1.0f; + normal.z = 0.0f; + // DPStaticCircle derives singly from DrawPrimitive (its typeinfo is a + // __si_class_type_info on DrawPrimitive) and the image stores the pointer unadjusted; + // neither class is defined in this tree, hence the cast. [CHOSEN, not recovered] + m_debugPrimitive = reinterpret_cast( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(1.0e9f, colour, m_position, 1.0f, normal, false, type)); + } + else + { + const unsigned int colour = (m_polygon == 0xFFFFFFFFu) ? 0xFFBB0000u : 0xFF00BB00u; + normal.x = 0.0f; + normal.y = 1.0f; + normal.z = 0.0f; + static_cast(CommonSingletonServer::m_iDPManager) + ->setCircleAttributes(m_debugPrimitive, 1.0e9f, colour, m_position, 1.0f, normal, + false, type); + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h index 1dd72315c..15ab8eb52 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.h @@ -1,5 +1,4 @@ // Strategic-area waypoint and its resolved navigation position. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_SAWAYPOINT_H // [INFERRED] guard style @@ -22,9 +21,14 @@ class SAWayPoint // [INFERRED] Initializes the waypoint polygon; no result is returned to its caller. void init(); - void draw() const; // [FRONTIER] + void draw() const; void undraw() const; + // [INFERRED] accessor forms; AIStrategicArea::orderNormalBot (ELF 0x33C940) reads +0 (the + // position) and tests +0x10 against -1 inline. + const Vec3& getPosition() const { return m_position; } + unsigned int getPolygon() const { return m_polygon; } + private: // layout, on the ELF, read store by store out of the constructor /* +0 */ Vec3 m_position; // the constructor's first argument diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.cpp new file mode 100644 index 000000000..affa8a16b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.cpp @@ -0,0 +1,28 @@ +// Camera access for the AI. Evidence: libaidll.so (ia-32) 0x366B20..0x366C9F. + +#include "AICamera.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x366BF0, __tcf_0 0x366C50, _GLOBAL__I 0x366C80). +#include + +#include "../../../../Game/Objects/ICameraObject.h" +#include "../../../../Game/Objects/IPlayer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x366B20. IPlayer::getCamera (+0x180), then ICameraObject::getTransformation(0.0f) (+0x10). +bool AICamera::GetCameraTrans(const world::IPlayer& player, Mat4& transform) +{ + world::ICameraObject* const camera = player.getCamera(); + if (!camera) + return false; + transform = camera->getTransformation(0.0f); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h new file mode 100644 index 000000000..d88a9b3d9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AICamera.h @@ -0,0 +1,28 @@ +// Camera access for the AI. Placement next to TemperatureTreeModifiers is [INFERRED] from the +// image's address order; whether AICamera is a class or a namespace is not attested by the mangled +// name, and a class with a static member is [CHOSEN]. +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_AICAMERA_H +#define AI_AIDLL_AI_AISTRATEGICMAP_AICAMERA_H + +#include "../../../../Math/Mat4.h" + +namespace dice { +namespace hfe { +namespace world { +class IPlayer; +} +namespace ai { + +class AICamera +{ +public: + // Copies the transformation of the player's current camera (taken at time 0) into `transform`. + // False, with `transform` untouched, when the player has no camera. + static bool GetCameraTrans(const world::IPlayer& player, Mat4& transform); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_AICAMERA_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp index 50debb2c1..1a42768ea 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp @@ -1,10 +1,16 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AerialHeightMap operations. +// Cached ground heights for aerial navigation. Evidence: libaidll.so (ia-32) 0x3133B0..0x313D09. #include "AerialHeightMap.h" -#include "../Main/AIDllFrontier.h" +#include +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x313C40, __tcf_0 0x313CA0, _GLOBAL__I 0x313CD0). +#include + #include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment::getMaxHeight +#include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getLevelPath #include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain, the world bounds #include "../../../../IO/File/File.h" @@ -15,6 +21,18 @@ namespace ai { AerialHeightMap* AerialHeightMap::m_instance = 0; +// Filters vehicles out of the height probe: accepts every object that is not mobile. Inline in +// the image (weak ELF 0x313CF0, emitted with this TU), so declared here; its vtable has the one +// predicate slot and no destructor. Placement is [INFERRED]. +class AIObjectPredicateNoVehicles : public AIObjectPredicate +{ +public: + virtual bool predicate(IAIObject* object) + { + return !object->isMobile(); + } +}; + namespace { // The cache's name, spelled dice's way in both directions. "AerialHeighMap" is missing a 't' and @@ -24,7 +42,7 @@ const char* const kHeightMapSuffix = "/AIPathFinding/AerialHeighMap.ahm"; } // namespace -// Starts with cell size 16, zero origin, and no height buffer. +// ELF 0x3133B0 (C2; C1 0x3133F0). Starts with cell size 16, zero origin, and no height buffer. // Construction unconditionally replaces the singleton. AerialHeightMap::AerialHeightMap() : m_cellSize(16.0f) @@ -38,7 +56,7 @@ AerialHeightMap::AerialHeightMap() m_instance = this; } -// it nulls the static unconditionally, without testing `== this`, so destroying a displaced +// ELF 0x313430 (D2; D1 0x313470). It nulls the static unconditionally, without testing `== this`, so destroying a displaced // instance clears the pointer to the live one. Reproduced. AerialHeightMap::~AerialHeightMap() { @@ -48,16 +66,19 @@ AerialHeightMap::~AerialHeightMap() // Samples height above ground. Grid lookup requires a position inside the configured bounds. // An unloaded map returns the missing-height sentinel 9999. +// ELF 0x313960. float AerialHeightMap::getAltitude(const Vec3& position) { return position.y - getGroundHeight(position); } +// ELF 0x3139A0. float AerialHeightMap::getGroundHeight(const Vec3& position) { return getGroundHeight(position.x, position.z); } +// ELF 0x3139E0. float AerialHeightMap::getGroundHeight(float x, float z) { if (!m_heights) @@ -69,7 +90,7 @@ float AerialHeightMap::getGroundHeight(float x, float z) return static_cast(m_heights[column + m_width * row]); } -// Loads the level's cached height grid. Missing cache data leaves the map empty. +// ELF 0x313650. Loads the level's cached height grid. Missing cache data leaves the map empty. void AerialHeightMap::readHeightMapFromFile() { const std::string levelPath = @@ -95,7 +116,7 @@ void AerialHeightMap::readHeightMapFromFile() file.close(); } -// The exact mirror of the reader, field for field and in the same order. It shares the reader's +// ELF 0x3134B0. The exact mirror of the reader, field for field and in the same order. It shares the reader's // silence on failure, and it writes the array unconditionally - a save on an object whose // `m_heights` is still null passes a null pointer and a zero size to `File::write`. void AerialHeightMap::saveHeightMapToFile() @@ -119,7 +140,7 @@ void AerialHeightMap::saveHeightMapToFile() } } -// Builds the aerial height grid from terrain bounds and saves it to the level cache. +// ELF 0x313810. Builds the aerial height grid from terrain bounds and saves it to the level cache. void AerialHeightMap::createHeightMap(int samplesPerAxis) { IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); @@ -142,11 +163,45 @@ void AerialHeightMap::createHeightMap(int samplesPerAxis) saveHeightMapToFile(); } -// [FRONTIER] Computes a cell height from a square sample grid once the required collision query is implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -unsigned short AerialHeightMap::computeHeightAt(int, int, int) +// ELF 0x313A60. The highest of samplesPerAxis^2 probes spread over the cell (at the centres of a +// regular sub-grid): each probe takes IAIObjectEnvironment::getMaxHeight on a vertical line from +// y = 9999 down to y = -9999 (the lower end one metre further along x), ignoring vehicles, and +// then the higher of that and the water level. The probe result is not reset between probes, so a +// query that does not write it keeps the previous probe's height; the first starts at -9999. The +// result is truncated to 16 bits. +unsigned short AerialHeightMap::computeHeightAt(int cellX, int cellZ, int samplesPerAxis) { - BF2_AI_FRONTIER("dice::hfe::ai::AerialHeightMap::computeHeightAt (AIObjectPredicateNoVehicles: IAIObject +0x70)"); + const float cellOriginX = static_cast(cellX) * m_cellSize + m_origin.x; + const float cellOriginZ = static_cast(cellZ) * m_cellSize + m_origin.y; + const float top = 9999.0f; + AIObjectPredicateNoVehicles noVehicles; + float height = -9999.0f; + float highest = -9999.0f; + const float step = m_cellSize / static_cast(samplesPerAxis); + for (int row = 0; row < samplesPerAxis; ++row) + { + const float baseY = 0.0f; + const float offsetZ = (static_cast(row) + 0.5f) * step; + for (int column = 0; column < samplesPerAxis; ++column) + { + Vec3 from; + from.x = (static_cast(column) + 0.5f) * step + cellOriginX; + from.y = baseY + top; + from.z = offsetZ + cellOriginZ; + Vec3 to; + to.x = from.x + 1.0f; + to.y = -9999.0f; + to.z = from.z; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getMaxHeight(from, to, &noVehicles, height); + const float probe = height; + const float water = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getWaterLevel(from.x, from.z); + height = std::max(probe, water); + highest = std::max(highest, height); + } + } + return static_cast(static_cast(highest)); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h index 721291c9e..41b2429ed 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h @@ -1,6 +1,5 @@ // Cached ground heights for aerial navigation. Sampling requires in-range coordinates. // An empty map reports the missing-height sentinel 9999. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AISTRATEGICMAP_AERIALHEIGHTMAP_H @@ -24,11 +23,10 @@ class AerialHeightMap float getGroundHeight(const Vec3&); float getGroundHeight(float, float); - void createHeightMap(int samplesPerAxis); + void createHeightMap(int samplesPerAxis = 4); // ConsoleClass161 passes 4 without an argument // Returns the sampled height as an unsigned 16-bit integer for height-map storage. unsigned short computeHeightAt(int cellX, int cellZ, int samplesPerAxis); - // [FRONTIER] void saveHeightMapToFile(); void readHeightMapFromFile(); diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp index 9892d2f5b..067e276f0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp @@ -2,11 +2,20 @@ #include "BFStrategicEnvironment.h" +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF 0x2E8D50, +// __tcf_0 0x2E8DB0, _GLOBAL__I 0x2E8DE0). +#include + #include #include "../../../../Core/ClassManager.h" #include "../Main/CommonSingletonServer.h" #include "../Main/AIDllFrontier.h" +#include "../Main/AIMain.h" // IAIMain::m_instance->getSAI +#include "../AIBot/BotMain.h" // Bot::getSide / getBotId +#include "../AIStrategic/SAI.h" +#include "../AIStrategicEntity/AIStrategicObject.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" namespace dice { namespace hfe { @@ -39,64 +48,85 @@ BFStrategicEnvironment::~BFStrategicEnvironment() { } -int BFStrategicEnvironment::getEnemyStrengths(Bot *) +// ELF 0x2E8860 / 0x2E88D0: the bot's side SAI rows (ISAI +0x30 / +0x34, by bot id). +float* BFStrategicEnvironment::getEnemyStrengths(Bot* bot) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getEnemyStrengths"); + const int id = bot->getBotId(); + return IAIMain::m_instance->getSAI(bot->getSide())->getEnemyStrengths(id); } -int BFStrategicEnvironment::getEnemyTypes(Bot *) +float* BFStrategicEnvironment::getEnemyTypes(Bot* bot) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getEnemyTypes"); + const int id = bot->getBotId(); + return IAIMain::m_instance->getSAI(bot->getSide())->getEnemyTypes(id); } -int BFStrategicEnvironment::getTemperature(Bot *) +// The Bot* overloads: the bot's current strategic object (ISAI::getBotCurrentPos, +0xB4) through +// the (object, side) overload of this vtable. The (object, side) overloads read the object's +// per-side float (+0xA0/+0xB0/+0xB8/+0xC0/+0xC8 + 4 side), or 0.0f (security: 1.0f) without one. +float BFStrategicEnvironment::getTemperature(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getTemperature"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getTemperature(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getTemperature(int, int) +float BFStrategicEnvironment::getTemperature(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getTemperature"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_f164[side - 1] : 0.0f; } -int BFStrategicEnvironment::getSecurity(Bot *) +float BFStrategicEnvironment::getSecurity(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getSecurity"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getSecurity(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getSecurity(int, int) +float BFStrategicEnvironment::getSecurity(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getSecurity"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_needCurveInput[side - 1] : 1.0f; } -int BFStrategicEnvironment::getControl(Bot *) +float BFStrategicEnvironment::getControl(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getControl"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getControl(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getControl(int, int) +float BFStrategicEnvironment::getControl(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getControl"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_friendlyRatio[side - 1] : 0.0f; } -int BFStrategicEnvironment::getFriendlyBattleStr(Bot *) +float BFStrategicEnvironment::getFriendlyBattleStr(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getFriendlyBattleStr"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getFriendlyBattleStr(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getFriendlyBattleStr(int, int) +float BFStrategicEnvironment::getFriendlyBattleStr(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getFriendlyBattleStr"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_friendlyBattleStrength[side - 1] : 0.0f; } -int BFStrategicEnvironment::getHostileBattleStr(Bot *) +float BFStrategicEnvironment::getHostileBattleStr(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getHostileBattleStr"); + const int side = bot->getSide(); + const int id = bot->getBotId(); + return getHostileBattleStr(IAIMain::m_instance->getSAI(side)->getBotCurrentPos(id), side); } -float BFStrategicEnvironment::getHostileBattleStr(int, int) +float BFStrategicEnvironment::getHostileBattleStr(int object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::BFStrategicEnvironment::getHostileBattleStr"); + AIStrategicObject* const o = AIStrategicObjectManager::getInstance()->getStrategicObject(object); + return o ? o->m_enemyBattleStrength[side - 1] : 0.0f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h index 7cd0ab028..7179c8f1f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.h @@ -25,18 +25,19 @@ class IAIStrategicEnvironment public: IAIStrategicEnvironment(); virtual ~IAIStrategicEnvironment(); - virtual int getEnemyStrengths(Bot *) = 0; - virtual int getEnemyTypes(Bot *) = 0; - virtual int getTemperature(Bot *) = 0; - virtual float getTemperature(int, int) = 0; - virtual int getSecurity(Bot *) = 0; - virtual float getSecurity(int, int) = 0; - virtual int getControl(Bot *) = 0; - virtual float getControl(int, int) = 0; - virtual int getFriendlyBattleStr(Bot *) = 0; - virtual float getFriendlyBattleStr(int, int) = 0; - virtual int getHostileBattleStr(Bot *) = 0; - virtual float getHostileBattleStr(int, int) = 0; + // Return types and constness from the ELF bodies (x87 returns, the ISAI row pointers). + virtual float* getEnemyStrengths(Bot* bot) const = 0; + virtual float* getEnemyTypes(Bot* bot) const = 0; + virtual float getTemperature(Bot* bot) = 0; + virtual float getTemperature(int object, int side) = 0; + virtual float getSecurity(Bot* bot) = 0; + virtual float getSecurity(int object, int side) = 0; + virtual float getControl(Bot* bot) = 0; + virtual float getControl(int object, int side) = 0; + virtual float getFriendlyBattleStr(Bot* bot) = 0; + virtual float getFriendlyBattleStr(int object, int side) = 0; + virtual float getHostileBattleStr(Bot* bot) = 0; + virtual float getHostileBattleStr(int object, int side) = 0; }; // BFStrategicEnvironment - sizeof == 4, from BF2AI::init step 6. @@ -47,18 +48,18 @@ class BFStrategicEnvironment : public IAIStrategicEnvironment virtual ~BFStrategicEnvironment(); // IAIStrategicEnvironment - virtual int getEnemyStrengths(Bot *); - virtual int getEnemyTypes(Bot *); - virtual int getTemperature(Bot *); - virtual float getTemperature(int, int); - virtual int getSecurity(Bot *); - virtual float getSecurity(int, int); - virtual int getControl(Bot *); - virtual float getControl(int, int); - virtual int getFriendlyBattleStr(Bot *); - virtual float getFriendlyBattleStr(int, int); - virtual int getHostileBattleStr(Bot *); - virtual float getHostileBattleStr(int, int); + virtual float* getEnemyStrengths(Bot* bot) const; // ELF 0x2E8860 + virtual float* getEnemyTypes(Bot* bot) const; // ELF 0x2E88D0 + virtual float getTemperature(Bot* bot); // ELF 0x2E8940 + virtual float getTemperature(int object, int side); // ELF 0x2E89C0 + virtual float getSecurity(Bot* bot); // ELF 0x2E8A10 + virtual float getSecurity(int object, int side); // ELF 0x2E8A90 + virtual float getControl(Bot* bot); // ELF 0x2E8AE0 + virtual float getControl(int object, int side); // ELF 0x2E8B60 + virtual float getFriendlyBattleStr(Bot* bot); // ELF 0x2E8BB0 + virtual float getFriendlyBattleStr(int object, int side); // ELF 0x2E8C30 + virtual float getHostileBattleStr(Bot* bot); // ELF 0x2E8C80 + virtual float getHostileBattleStr(int object, int side); // ELF 0x2E8D00 }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp index 527d69d9b..effdebf8f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp @@ -1,6 +1,10 @@ #include "BotSpawner.h" #include #include +// 's ios_base::Init object, m_kitWeightVector and m_pointWeightVector, in that order, are +// this TU's static initialisation (ELF 0x35ED80, _GLOBAL__I 0x35EF60) and teardown (__tcf_0 +// 0x35EE60, __tcf_1 0x35EE90, __tcf_2 0x35EEF0). +#include #include "../Main/AIDllFrontier.h" #include "../Main/AIMain.h" #include "../Main/AIRandom.h" @@ -24,11 +28,13 @@ #include "../AIStrategicEntity/AIStrategicObjectManager.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // getInformation(side) #include "../../../AIInterface/BFKnowledge/KitTemplateManager.h" #include "../../../AIInterface/BFKnowledge/KitTemplate.h" namespace dice { namespace hfe { namespace ai { +std::vector BotSpawner::m_kitWeightVector; std::vector BotSpawner::m_pointWeightVector; namespace { @@ -166,6 +172,82 @@ bool BotSpawner::findSuitableSpawnGroup(float* enemyStrengths, float* enemyCount return true; } +// ELF 0x35D1B0. Spawn selection for a bot that must come back near a position (PatrolPath::botIsDead +// is the only caller and discards the result): the eligible spawn point nearest in XZ, then the +// strategic object closest to that point's position. The strength rows come from the bot's SAI by +// bot id. The game singleton is read twice, as shipped: once for the eligibility and empty-list +// checks, again for the search. Returns true unless the side has no spawn points; a bot that +// already has a spawn group, or whose own spawn point is still eligible, is left as it is. +bool BotSpawner::findSuitableSpawnGroup(const Vec3& position, Bot* bot) +{ + Vec3 spawnPosition = { 0.0f, 0.0f, 0.0f }; + const int side = bot->getSide(); + SAI* const sai = IAIMain::m_instance->getSAI(side); + const int botId = bot->getBotId(); + float* const enemyStrengths = sai->getEnemyStrengths(botId); + float* const enemyCounts = sai->getEnemyTypes(botId); + float* const friendlyStrengths = sai->getFriendlyStrengths(botId); + float* const friendlyCounts = sai->getFriendlyTypes(botId); + if (bot->getPlayer()->getSpawnGroup() > 0) + return true; + + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + if (game->isEligibleSpawnpoint(side, bot->getSpawnPoint())) + { + sai->addSpawnToPoint(bot->getSpawnPoint()); + return true; + } + if (game->getSpawnPointList(side).empty()) + { + bot->setSpawnTarget(-1, 13); + return false; + } + + IAIGame* const searchGame = static_cast(CommonSingletonServer::m_iaiGame); + const std::list& groups = searchGame->getSpawnPointList(side); + int group = 0; + float best = 1.0e9f; + for (std::list::const_iterator it = groups.begin(); it != groups.end(); ++it) + { + if (searchGame->isEligibleSpawnpoint(side, *it)) + { + const float distance = distXZSqr(searchGame->getSpawnPointPosition(*it), position); + if (distance < best) + { + best = distance; + group = *it; + spawnPosition = searchGame->getSpawnPointPosition(group); + } + } + } + + AIStrategicObject* const object = + AIStrategicObjectManager::getInstance()->getClosestObject(spawnPosition, side); + const int kit = findSuitableKit(enemyStrengths, enemyCounts, friendlyStrengths, + friendlyCounts, object, side, bot); + if (object) + bot->setSpawnTarget(object->getIndex(), group, kit); + else + bot->setSpawnTarget(group, kit); + return true; +} + +// ELF 0x35DDE0. Over the six strength types: the squared shortfall of values below counts goes +// to sqrDist, the surplus (including NaN differences) to excess. No caller in the image. +void BotSpawner::sqrDistAndExcess(float* values, int* counts, float& sqrDist, float& excess) +{ + sqrDist = 0.0f; + excess = 0.0f; + for (int i = 0; i < 6; ++i) + { + const float difference = values[i] - static_cast(counts[i]); + if (difference < 0.0f) + sqrDist += difference * difference; + else + excess += difference; + } +} + // Empty input returns 0 without touching the output or static candidates. A // failed nonempty search returns -1, retaining any last output object write. // Deep path and Information forwarding bodies still stop at their actual calls. @@ -356,9 +438,19 @@ KitType BotSpawner::GetRandomKit(SquadMember*) #endif } +// ELF 0x35ED30. Squad leaders may not take kits 4 and 5; everyone else may take any kit. No +// caller in the image. +bool BotSpawner::isAllowedKit(SquadMember* member, KitType kit) +{ + bool allowed = true; + if (member->isSquadLeader() && static_cast(kit - 4) <= 1u) + allowed = false; + return allowed; +} + // Chooses a kit from squad needs and nearby equipment. Always consumes the initial // random-kit selection; only nonleaders can take the medic early return. -// Assigned-squad equipment remains an unimplemented boundary. +// The assigned-squad arm scores the squad's area (ELF 0x35E3C0). int BotSpawner::findSuitableKit(const float*, const float*, const float*, const float*, AIStrategicObject* object, int side, Bot* bot) { @@ -553,10 +645,87 @@ int BotSpawner::findSuitableKit(const float*, const float*, const float*, const } if (squad->isSquadAssignedToAnyArea()) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] - // [RETIRE-WHEN: aidll-02-skeleton] Recover the assigned squad's - // equipment scan, area geometry and scoring (the kitCounts consumer). - BF2_AI_FRONTIER("dice::hfe::ai::BotSpawner::findSuitableKit [assigned-squad equipment]"); + // ELF 0x35E3C0..0x35E6F4: the members' current vehicles are counted (strength types + // 1/2/4 vehicles, damaged below 0.5f health; 0 infantry, health read and discarded), + // then the enemies around the assigned area (rectangle centre - 2 (pos - centre), + // the object arm uses 3), then the same kit ladder as the object arm with an integer + // infantry comparison and a vehicle-repair test against kitCounts[4]. + int friendlyVehicles = 0, damagedFriendlyVehicles = 0, friendlyInfantry = 0; + for (int i = 0; i < members; ++i) + { + IAIObject* const vehicle = squad->getSquadMember(i)->getPlayer()->getCurrentVehicle(); + if (!vehicle) + continue; + Information* const entry = informationManager->getInformation(vehicle->getInformation(side)); + if (!entry || !entry->getUnit()) + continue; + IPIPhysical* const physical = entry->getPhysical(); + switch (physical->getStrengthType()) + { + case 1: case 2: case 4: + ++friendlyVehicles; + if (physical->getHealth() < 0.5f) + ++damagedFriendlyVehicles; + break; + case 0: + ++friendlyInfantry; + physical->getHealth(); // shipped discarded call + break; + } + } + AIStrategicObject* const area = AIStrategicObjectManager::getInstance()->getStrategicObject( + squad->getSquadStrategicAreaAssignment()->getIndex()); + Vec2 minimum = static_cast(area)->m_centre; + const Vec2 position = area->getPosition(side); + const double dx = static_cast(position.x) - minimum.x; + const double dy = static_cast(position.y) - minimum.y; + minimum.x = static_cast(static_cast(minimum.x) - dx * 2.0f); + minimum.y = static_cast(static_cast(minimum.y) - dy * 2.0f); + Vec2 maximum = {}; + maximum = getBoxMaxCorner(minimum, position, maximum); + IAIInformationEnvironment* const environment = + static_cast(AISingletonServer::m_iaiInformationEnvironment); + environment->getObjectsWithinRectangle(information, minimum, maximum, side, true, 0); + int enemyVehicles = 0, enemyInfantry = 0; + const int enemySide = (side == 1) + 1; + std::vector::const_iterator end = information.end(); + for (std::vector::const_iterator it = information.begin(); it != end; ++it) + { + Information* const entry = informationManager->getInformation(*it); + if (!entry) + continue; + IPIPhysical* const physical = entry->getPhysical(); + if (vehicleOccupied(*it, side) && entry->getSide() == enemySide) + { + switch (physical->getStrengthType()) + { + case 0: ++enemyInfantry; break; + case 1: case 2: case 4: ++enemyVehicles; break; + } + } + end = information.end(); // ELF refreshes after every nonnull record + } + if (enemyVehicles > friendlyVehicles + kitCounts[6] && templates[6]) + return 6; + if (enemyInfantry > friendlyInfantry) + { + AIRandom* const random = AIRandom::m_instance; + if (static_cast(random->m_index) >= AIRandom::kStateSize) + random->generateNumbers(); + const double draw = static_cast(random->next()) * (1.0 / 4294967296.0); + if (draw > 0.85f && templates[0]) + return 0; + if (draw > 0.55f && templates[2]) + return 2; + if (draw > 0.25f && templates[3]) + return 3; + if (templates[4]) + return 4; + } + else if (damagedFriendlyVehicles + friendlyVehicles > kitCounts[4] * 2 && templates[4]) + { + return 4; + } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h index 2de4422de..1d7e157eb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h @@ -5,6 +5,8 @@ #include +#include "../../../../Math/Vec3.h" + namespace dice { namespace hfe { enum KitType : int; namespace ai { @@ -26,6 +28,15 @@ struct SpawnChoice float weight; }; +// Element of BotSpawner::m_kitWeightVector. Only the 8-byte, trivially destructible element is +// attested (the teardown at ELF 0x35EE90 steps by 8 and frees capacity * 8); nothing in the image +// reads or writes the vector. The name and fields are [INFERRED]. +struct KitWeight +{ + int kit; + float weight; +}; + // These static contracts imply no instance layout, lifecycle or factory. class BotSpawner { @@ -33,15 +44,20 @@ class BotSpawner static bool findSuitableSpawnGroup(float* enemyStrengths, float* enemyCounts, float* friendlyStrengths, float* friendlyCounts, int strategicObjectId, Bot* bot); + // Return type bool as in the sibling overload [INFERRED]; the only caller discards it. + static bool findSuitableSpawnGroup(const Vec3& position, Bot* bot); static int findSuitableSpawnGroup(int side, AIStrategicObject*& object, Bot* bot); static int findSuitableKit(const float* enemyStrengths, const float* enemyCounts, const float* friendlyStrengths, const float* friendlyCounts, AIStrategicObject* object, int side, Bot* bot); static KitType GetRandomKit(SquadMember* member); + static void sqrDistAndExcess(float* values, int* counts, float& sqrDist, float& excess); + static bool isAllowedKit(SquadMember* member, KitType kit); // Shared static vector. Ordinary // static construction/destruction; retained capacity across selector calls. // Public access is [CHOSEN, not recovered], not an instance-layout claim. + static std::vector m_kitWeightVector; static std::vector m_pointWeightVector; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp new file mode 100644 index 000000000..86202a165 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp @@ -0,0 +1,377 @@ +// Strategic grid map. Evidence: libaidll.so (ia-32) 0x35FD10..0x364544, the TU named by the +// anonymous-namespace symbols AI_AIDLL_AI_AIStrategicMap_SAIMap.cpp. + +#include "SAIMap.h" + +#include +// 's ios_base::Init object and defaultModifiers are this TU's static initialisation +// (ELF 0x364330, __tcf_0 0x3644C0, _GLOBAL__I 0x3644F0). +#include + +#include "SAIMapSquare.h" +#include "ScalarMap.h" +#include "TemperatureTreeModifiers.h" +#include "../AIKnowledge/AIInformationGrid.h" +#include "../AIKnowledge/BFInformationEnvironment.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIStrategic/SAI.h" +#include "../AIStrategic/StatusMap.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF: the modifiers a SAIMap uses when constructed without any. +TemperatureTreeModifiers* defaultModifiers = checkPointer(new TemperatureTreeModifiers()); + +// ELF 0x364510 (weak; vtable 0x4BF808, one slot): information whose security is below 0.1. +class SecurityPredicate : public IAIInformationGridPredicate +{ +public: + bool includeInformation(Information* information) const override + { + return 0.1f > information->getSecurity(); + } +}; + +} // namespace + +// ELF 0x35FD10 (C2; C1 0x3618D0). Every allocation goes through checkPointer. The square sizes +// divide by the dimension arguments; the half-diagonal of a square is the bounding radius. Only +// buffer 0 of each layer is initialised. +0x24, +0x3C, +0x6C's values and the update state's +// index are left unwritten, as shipped. +SAIMap::SAIMap(int side, int dimX, int dimY, Vec2 min, Vec2 max, TemperatureTreeModifiers* modifiers) + : m_side(side) + , m_dimX(dimX) + , m_dimY(dimY) + , m_min(min) + , m_max(max) + , m_currentBuffer(0) + , m_modifiers(modifiers) +{ + m_layer44[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer44[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer4C[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer4C[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer54[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer54[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer5C[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer5C[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer64[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer64[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer6C = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_statusMaps[0] = checkPointer(new StatusMap(m_dimX, m_dimY)); + m_statusMaps[1] = checkPointer(new StatusMap(m_dimX, m_dimY)); + m_squares[0] = checkPointer(new SAIMapSquare[m_dimX * m_dimY]); + m_squares[1] = checkPointer(new SAIMapSquare[m_dimX * m_dimY]); + m_layer80[0] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + m_layer80[1] = checkPointer(new ScalarMap(m_dimX, m_dimY)); + + m_squareXSize = (max.x - min.x) / static_cast(dimX); + m_squareYSize = (max.y - min.y) / static_cast(dimY); + Vec2 half; + half.x = m_squareXSize * 0.5f; + half.y = m_squareYSize * 0.5f; + m_squareBoundingCircleRadius = sqrtf(half.x * half.x + half.y * half.y); + + m_updateState = checkPointer(new UpdateState); + m_updateState->m_state = 0; + + m_stateA = checkPointer(new float[44]); + m_stateB = checkPointer(new float[44]); + m_stateC = checkPointer(new float[44]); + m_stateD = checkPointer(new float[44]); + clearStates(m_stateA, m_stateC); + clearStates(m_stateB, m_stateD); + + for (int x = 0; x < m_dimX; ++x) + { + for (int y = 0; y < m_dimY; ++y) + { + ScalarMap* map = m_layer44[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer4C[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer54[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer5C[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + map = m_layer64[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 0.0f; + StatusMap* const status = m_statusMaps[m_currentBuffer]; + status->m_statuses[y * status->m_width + x] = StatusMap::Neutral; + map = m_layer80[m_currentBuffer]; + map->m_values[y * map->m_width + x] = 1.0f; + } + } + + if (!m_modifiers) + m_modifiers = defaultModifiers; +} + +// ELF 0x363490 (D2; D1 0x363790): the layers in member order except that +0x80/+0x84 go before +// the square arrays, then the update state and the four state rows. The modifiers are borrowed. +SAIMap::~SAIMap() +{ + if (m_layer44[0]) delete m_layer44[0]; + if (m_layer44[1]) delete m_layer44[1]; + if (m_layer4C[0]) delete m_layer4C[0]; + if (m_layer4C[1]) delete m_layer4C[1]; + if (m_layer54[0]) delete m_layer54[0]; + if (m_layer54[1]) delete m_layer54[1]; + if (m_layer5C[0]) delete m_layer5C[0]; + if (m_layer5C[1]) delete m_layer5C[1]; + if (m_layer64[0]) delete m_layer64[0]; + if (m_layer64[1]) delete m_layer64[1]; + if (m_layer6C) delete m_layer6C; + if (m_statusMaps[0]) delete m_statusMaps[0]; + if (m_statusMaps[1]) delete m_statusMaps[1]; + if (m_layer80[0]) delete m_layer80[0]; + if (m_layer80[1]) delete m_layer80[1]; + if (m_squares[0]) delete[] m_squares[0]; + if (m_squares[1]) delete[] m_squares[1]; + if (m_updateState) delete m_updateState; + if (m_stateA) delete[] m_stateA; + if (m_stateB) delete[] m_stateB; + if (m_stateC) delete[] m_stateC; + if (m_stateD) delete[] m_stateD; +} + +// ELF 0x363A90. A jump table over the update state (0..24): 0-3 collect every information id +// of both kinds, 4 add the side's insecure ones (SecurityPredicate as the second predicate), +// 5-7 visit the collected ids (resumable at m_index), 8-23 only advance, 24 flips the buffers +// and answers true. Each step checks the update-time deadline (timer read once) first; other +// states answer false. +bool SAIMap::update(SAI* sai, double budget) +{ + const int buffer = m_currentBuffer == 0; + IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const double deadline = timer->getUpdateTime() + budget; + IAIInformationEnvironment* environment; + switch (m_updateState->m_state) + { + case 0: case 1: case 2: case 3: + environment = static_cast(AISingletonServer::m_iaiInformationEnvironment); + environment->getAllInformation(m_updateState->m_ids, 0, true, 0, 0); + environment->getAllInformation(m_updateState->m_ids, 0, false, 0, 0); + m_updateState->m_state = 4; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 4: + { + environment = static_cast(AISingletonServer::m_iaiInformationEnvironment); + SecurityPredicate insecure; + environment->getAllInformation(m_updateState->m_ids, m_side, true, 0, &insecure); + environment->getAllInformation(m_updateState->m_ids, m_side, false, 0, &insecure); + m_updateState->m_state = 5; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + } + // fall through + case 5: case 6: case 7: + for (unsigned int index = m_updateState->m_index; index < m_updateState->m_ids.size(); ++index) + { + if (timer->getUpdateTime() >= deadline) + { + m_updateState->m_index = index; + return false; + } + Information* information = informationManager->getInformation(m_updateState->m_ids[index]); + if (!information || (information->getObjectTypeFlags() & 0x800000)) + continue; + if (information->getSecurity() == 0.0f) + continue; + updateInformation(information, sai, buffer); + int it; + for (Information* secondary = informationManager->getInformation(information->getFirstSecondaryObject(it, m_side)); + secondary; + secondary = informationManager->getInformation(information->getSecondaryObject(it, m_side))) + { + if (!(secondary->getObjectTypeFlags() & 0x800000) && secondary->getSecurity() > 0.0f) + updateInformation(secondary, sai, buffer); + } + } + m_updateState->m_state = 8; + m_updateState->m_index = 0; + m_updateState->m_ids.resize(0); + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: + m_updateState->m_state = 16; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: + m_updateState->m_state = 24; + m_updateState->m_index = 0; + if (timer->getUpdateTime() >= deadline) + return false; + // fall through + case 24: + m_updateState->m_state = 0; + m_currentBuffer = buffer; + return true; + default: + return false; + } +} + +// ELF 0x363FA0. +int SAIMap::getSide() const +{ + return m_side; +} + +// ELF 0x363FB0. +int SAIMap::getMapDimensionX() const +{ + return m_dimX; +} + +// ELF 0x363FC0. +int SAIMap::getMapDimensionY() const +{ + return m_dimY; +} + +// ELF 0x363FD0. +TemperatureTreeModifiers* SAIMap::getTemperatureTreeModifiers() const +{ + return m_modifiers; +} + +// ELF 0x363FE0. +void SAIMap::setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers) +{ + m_modifiers = modifiers; +} + +// ELF 0x364000. +float SAIMap::getSquareArea() const +{ + return m_squareArea; +} + +// ELF 0x364010. +float SAIMap::getSquareBoundingCircleRadius() const +{ + return m_squareBoundingCircleRadius; +} + +// ELF 0x364020. +float SAIMap::getSquareXSize() const +{ + return m_squareXSize; +} + +// ELF 0x364030. +float SAIMap::getSquareYSize() const +{ + return m_squareYSize; +} + +// ELF 0x364040. +Vec2 SAIMap::getCoordFromSquareId(int id) +{ + Vec2 coord; + coord.x = static_cast(id % m_dimX) * m_squareXSize + m_min.x + m_squareXSize * 0.5f; + coord.y = static_cast(id / m_dimX) * m_squareYSize + m_min.y + m_squareYSize * 0.5f; + return coord; +} + +// ELF 0x3640C0: empty. +void SAIMap::setMapDimensionX(int) +{ +} + +// ELF 0x3640D0: empty. +void SAIMap::setMapDimensionY(int) +{ +} + +// ELF 0x3640E0: the relative position is formed in float and truncated after the scale. +bool SAIMap::getSquareId(int& x, int& y, const Vec3& position) const +{ + Vec2 relative; + relative.x = (position.x - m_min.x) / (m_max.x - m_min.x); + relative.y = (position.z - m_min.y) / (m_max.y - m_min.y); + x = static_cast(relative.x * static_cast(m_dimX)); + y = static_cast(relative.y * static_cast(m_dimY)); + return x >= 0 && x < m_dimX && y >= 0 && y < m_dimY; +} + +// ELF 0x364180: both 44-element rows to zero, the last element of each to one. +void SAIMap::clearStates(float* a, float* b) +{ + for (int i = 0; i <= 43; ++i) + { + a[i] = 0.0f; + b[i] = 0.0f; + } + a[43] = 1.0f; + b[43] = 1.0f; +} + +// ELF 0x3641D0. +float SAIMap::setFastThreshold(float threshold) +{ + return m_fastThreshold = threshold; +} + +// ELF 0x3641E0. +float SAIMap::getFastThreshold() +{ + return m_fastThreshold; +} + +// ELF 0x3641F0. Only the square test and the final strength copy (+0x14 into +0x10) have an +// effect: the side classification, the occupancy query and the clamped strength sum are +// computed and unused, as shipped (the sum is never negative, so the early return never fires). +void SAIMap::updateInformation(Information* information, SAI* sai, int) +{ + int x; + int y; + if (!getSquareId(x, y, information->getPosition())) + return; + IPIUnit* const unit = information->getUnit(); + float total = 0.0f; + float strengths[6]; + const bool isFriend = sai->isFriend(information->getSide()); + const bool isEnemy = sai->isEnemy(information->getSide()); + bool neutral = false; + if (!isFriend && !isEnemy) + neutral = true; + else if (unit) + unit->isOccupied(); + (void)neutral; + if (unit) + { + for (int i = 0; i <= 5; ++i) + { + float strength = i < unit->getNBattleStrengths() ? unit->getBattleStrengths()[i] : 0.0f; + if (!(strength > 0.0f)) + strength = 0.0f; + strengths[i] = strength; + total += strength; + } + if (0.0f > total) + return; + } + information->setStrength(information->getBasicTemp()); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h new file mode 100644 index 000000000..8d612921f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.h @@ -0,0 +1,99 @@ +// A grid view of one side's strategic situation: per-square scalar layers, status layers and +// temperature trees, double-buffered (the update writes the buffer that is not current and flips +// at the end), and a resumable update that collects the information ids it will visit. +// Evidence: libaidll.so (ia-32) SAIMap.cpp 0x35FD10..0x364544. Nothing in the image constructs a +// SAIMap. Offsets are ELF; layer names are [UNRESOLVED] where no accessor names them. + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SAIMAP_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_SAIMAP_H + +#include + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Information; +class SAI; +class SAIMapSquare; +class ScalarMap; +class StatusMap; +class TemperatureTreeModifiers; + +class SAIMap +{ +public: + // ELF: a 28-byte record owned at +0x88. Only the state, the resume index and the id vector + // are touched; the last eight bytes are [UNRESOLVED]. Names [INFERRED]. + struct UpdateState + { + /* +0x00 */ int m_state; + /* +0x04 */ int m_index; + /* +0x08 */ std::vector m_ids; + /* +0x14 */ unsigned char m_unresolved14[8]; + }; + + // Allocates every layer at dimX * dimY; a null modifiers pointer selects the TU's defaults. + SAIMap(int side, int dimX, int dimY, Vec2 min, Vec2 max, TemperatureTreeModifiers* modifiers); + ~SAIMap(); + + // Runs the resumable update until the update-time budget is spent (false) or a full pass + // completed and the buffers flipped (true). + bool update(SAI* sai, double budget); + int getSide() const; + int getMapDimensionX() const; + int getMapDimensionY() const; + TemperatureTreeModifiers* getTemperatureTreeModifiers() const; + void setTemperatureTreeModifiers(TemperatureTreeModifiers* modifiers); + float getSquareArea() const; // +0x24 is never written in the image + float getSquareBoundingCircleRadius() const; + float getSquareXSize() const; + float getSquareYSize() const; + // The centre of the square, x = id % dimX and y = id / dimX. + Vec2 getCoordFromSquareId(int id); + void setMapDimensionX(int x); // empty + void setMapDimensionY(int y); // empty + // The square containing position (x, z); false outside the map. + bool getSquareId(int& x, int& y, const Vec3& position) const; + void clearStates(float* a, float* b); + float setFastThreshold(float threshold); // fsts: the value stays in st0 + float getFastThreshold(); + void updateInformation(Information* information, SAI* sai, int buffer); + +private: + /* +0x00 */ int m_side; + /* +0x04 */ int m_dimX; + /* +0x08 */ int m_dimY; + /* +0x0C */ Vec2 m_min; + /* +0x14 */ Vec2 m_max; + /* +0x1C */ float m_squareXSize; + /* +0x20 */ float m_squareYSize; + /* +0x24 */ float m_squareArea; // not constructed + /* +0x28 */ float m_squareBoundingCircleRadius; + // Four 44-float state rows, paired by clearStates as (A, C) and (B, D). + /* +0x2C */ float* m_stateA; + /* +0x30 */ float* m_stateB; + /* +0x34 */ float* m_stateC; + /* +0x38 */ float* m_stateD; + /* +0x3C */ float m_fastThreshold; // not constructed + /* +0x40 */ int m_currentBuffer; // 0 or 1; layers below are indexed by it + /* +0x44 */ ScalarMap* m_layer44[2]; // [UNRESOLVED] role; zeroed + /* +0x4C */ ScalarMap* m_layer4C[2]; // [UNRESOLVED] role; zeroed + /* +0x54 */ ScalarMap* m_layer54[2]; // [UNRESOLVED] role; zeroed + /* +0x5C */ ScalarMap* m_layer5C[2]; // [UNRESOLVED] role; zeroed + /* +0x64 */ ScalarMap* m_layer64[2]; // [UNRESOLVED] role; zeroed + /* +0x6C */ ScalarMap* m_layer6C; // [UNRESOLVED] role; not initialised + /* +0x70 */ StatusMap* m_statusMaps[2]; // Neutral + /* +0x78 */ SAIMapSquare* m_squares[2]; + /* +0x80 */ ScalarMap* m_layer80[2]; // [UNRESOLVED] role; one + /* +0x88 */ UpdateState* m_updateState; + /* +0x8C */ TemperatureTreeModifiers* m_modifiers; // borrowed +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SAIMAP_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp new file mode 100644 index 000000000..4f4581258 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp @@ -0,0 +1,34 @@ +// SAIMapRenderUtil. The FILE symbol attests the basename; directory placement is [INFERRED]. +#include "SAIMapRenderUtil.h" + +// static init: ELF 0x364590, 0x3645F0, 0x364620 (iostream Init and teardown only). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x364550; amd-64 0x39BF80 also clears eax and returns. +SAIMapRendInfo* SAIMapRenderUtil::createRenderInfo(SAIMap*, SAIMapRenderType) +{ + return 0; +} + +// ELF 0x364560; amd-64 0x39BF90 is also empty. +void SAIMapRenderUtil::update(SAIMapRendInfo*) +{ +} + +// ELF 0x364570; amd-64 0x39BFA0 is also empty. +void SAIMapRenderUtil::render(SAIMapRendInfo*) +{ +} + +// ELF 0x364580; amd-64 0x39BFB0 is also empty, including no deletion. +void SAIMapRenderUtil::releaseRenderInfo(SAIMapRendInfo*) +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.h new file mode 100644 index 000000000..8e4a6ae1d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.h @@ -0,0 +1,31 @@ +// Strategic-map rendering hooks. The parameter names are attested by the ELF symbols; +// [CHOSEN, not recovered] a static utility class spells the otherwise ambiguous scope. +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPRENDERUTIL_H +#define AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPRENDERUTIL_H + +namespace dice { +namespace hfe { +namespace ai { + +class SAIMap; +class SAIMapRendInfo; +// [CHOSEN, not recovered] int permits an opaque enum declaration. Neither image reads +// this argument or attests enumerators or signedness; no values are introduced here. +enum SAIMapRenderType : int; + +class SAIMapRenderUtil +{ +public: + // The shipped AI image provides no rendering information and always returns null. + static SAIMapRendInfo* createRenderInfo(SAIMap* map, SAIMapRenderType type); + // These shipped hooks leave the supplied opaque information untouched. + static void update(SAIMapRendInfo* info); + static void render(SAIMapRendInfo* info); + static void releaseRenderInfo(SAIMapRendInfo* info); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPRENDERUTIL_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp new file mode 100644 index 000000000..e8e5e7198 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp @@ -0,0 +1,26 @@ +// Strategic grid square. Evidence: libaidll.so (ia-32) 0x3663F0..0x366508. + +#include "SAIMapSquare.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x366460, __tcf_0 0x3664C0, _GLOBAL__I 0x3664F0). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3663F0 (C2; C1 0x366420): only the tree is constructed. +SAIMapSquare::SAIMapSquare() +{ +} + +// ELF 0x366450. +const TemperatureTree& SAIMapSquare::getTemperatureTree() const +{ + return m_temperatureTree; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h new file mode 100644 index 000000000..eb63f1a6b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.h @@ -0,0 +1,28 @@ +// One square of the strategic grid map: its temperature tree. Evidence: libaidll.so (ia-32) +// 0x3663F0..0x366458; sizeof 40 (SAIMap allocates count * 0x28 bytes, no array cookie). + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPSQUARE_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPSQUARE_H + +#include "TemperatureTree.h" + +namespace dice { +namespace hfe { +namespace ai { + +class SAIMapSquare +{ +public: + SAIMapSquare(); + + // The image answers the square's own address; the reference spelling is [INFERRED]. + const TemperatureTree& getTemperatureTree() const; + + /* +0x00 */ TemperatureTree m_temperatureTree; // [INFERRED] name +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SAIMAPSQUARE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp new file mode 100644 index 000000000..be03f843f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp @@ -0,0 +1,203 @@ +// Scalar grid smoothing and ranking. Evidence: libaidll.so (ia-32) 0x364640..0x365FF8; the +// smoothing error names AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp. The TU has no static +// initialisation in the image. + +#include "ScalarMap.h" + +#include +#include + +#include "../AIUtils/checkPointer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Core/Debug.h" + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// ELF: 8-byte heap element {index, value}. std::less (the instantiated comparator) orders +// by descending value, so the priority queue's top is the smallest kept value. +struct PQElem +{ + PQElem(int index, float value) : m_index(index), m_value(value) {} + bool operator<(const PQElem& other) const { return m_value > other.m_value; } + + int m_index; + float m_value; +}; + +} // namespace + +// ELF 0x364640 (C2; C1 0x3647A0). +ScalarMap::ScalarMap(int width, int height) + : m_width(width) + , m_height(height) +{ + m_values = checkPointer(new float[width * height]); +} + +// ELF 0x364900 (D2; D1 0x364930). +ScalarMap::~ScalarMap() +{ + if (m_values) + delete[] m_values; +} + +// ELF 0x364960. The result is indexed with its own width for the row and this map's width for the +// right column, as shipped. The update-time timer is read once. +bool ScalarMap::smooth(ScalarMap& result, double deadline, int& row) const +{ + if (m_height * m_width == 1) + return true; + + Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp", 45, "") << "Does not work"; + + IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + const float* const v = m_values; + if (row >= 0) + { + int y = row ? row : 1; + for (; y < m_height - 1; ++y) + { + if (timer->getUpdateTime() >= deadline) + { + row = y; + return false; + } + for (int x = 1; x < m_width - 1; ++x) + { + float& out = result.m_values[y * result.m_width + x]; + out = v[(y - 1) * m_width + x - 1]; + out += v[y * m_width + x - 1]; + out += v[(y + 1) * m_width + x - 1]; + out += v[(y - 1) * m_width + x]; + out += v[y * m_width + x]; + out += v[(y + 1) * m_width + x]; + out += v[(y - 1) * m_width + x + 1]; + out += v[y * m_width + x + 1]; + out += v[(y + 1) * m_width + x + 1]; + out *= 0.11111111f; + } + } + row = -1; + if (timer->getUpdateTime() >= deadline) + return false; + } + + // Top row. + for (int x = 1; x < m_width - 1; ++x) + { + float& out = result.m_values[x]; + out = v[x - 1]; + out += v[m_width + x - 1]; + out += v[x]; + out += v[m_width + x]; + out += v[x + 1]; + out += v[m_width + x + 1]; + out *= 0.16666667f; + } + // Bottom row. + for (int x = 1; x < m_width - 1; ++x) + { + float& out = result.m_values[(m_height - 1) * result.m_width + x]; + out = v[(m_height - 2) * m_width + x - 1]; + out += v[(m_height - 1) * m_width + x - 1]; + out += v[(m_height - 2) * m_width + x]; + out += v[(m_height - 1) * m_width + x]; + out += v[(m_height - 2) * m_width + x + 1]; + out += v[(m_height - 1) * m_width + x + 1]; + out *= 0.16666667f; + } + // Left column. + for (int y = 1; y < m_height - 1; ++y) + { + float& out = result.m_values[y * result.m_width]; + out = v[(y - 1) * m_width]; + out += v[y * m_width]; + out += v[(y + 1) * m_width]; + out += v[(y - 1) * m_width + 1]; + out += v[y * m_width + 1]; + out += v[(y + 1) * m_width + 1]; + out *= 0.16666667f; + } + // Right column. + for (int y = 1; y < m_height - 1; ++y) + { + float& out = result.m_values[y * result.m_width + m_width - 1]; + out = v[(y - 1) * m_width + m_width - 2]; + out += v[y * m_width + m_width - 2]; + out += v[(y + 1) * m_width + m_width - 2]; + out += v[(y - 1) * m_width + m_width - 1]; + out += v[y * m_width + m_width - 1]; + out += v[(y + 1) * m_width + m_width - 1]; + out *= 0.16666667f; + } + // Corners. + { + float& out = result.m_values[0]; + out = v[0]; + out += v[m_width]; + out += v[1]; + out += v[m_width + 1]; + out *= 0.25f; + } + { + float& out = result.m_values[m_width - 1]; + out = v[m_width - 2]; + out += v[2 * m_width - 2]; + out += v[m_width - 1]; + out += v[2 * m_width - 1]; + out *= 0.25f; + } + { + float& out = result.m_values[(m_height - 1) * result.m_width]; + out = v[(m_height - 2) * m_width]; + out += v[(m_height - 1) * m_width]; + out += v[(m_height - 2) * m_width + 1]; + out += v[(m_height - 1) * m_width + 1]; + out *= 0.25f; + } + { + float& out = result.m_values[(m_height - 1) * result.m_width + m_width - 1]; + out = v[(m_height - 2) * m_width + m_width - 2]; + out += v[(m_height - 1) * m_width + m_width - 2]; + out += v[(m_height - 2) * m_width + m_width - 1]; + out += v[(m_height - 1) * m_width + m_width - 1]; + out *= 0.25f; + } + return true; +} + +// ELF 0x365890. The queue starts with count placeholders {-1, -1e20}; a value above the smallest +// kept one replaces it. The queue is then emptied smallest first from the back of indices. +void ScalarMap::sortLargest(int count, int* indices) const +{ + std::priority_queue queue; + PQElem element(-1, -1e20f); + float threshold = -1e20f; + for (int i = 0; i < count; ++i) + queue.push(element); + for (int i = 0; i < m_width * m_height; ++i) + { + if (m_values[i] > threshold) + { + queue.pop(); + element.m_index = i; + element.m_value = m_values[i]; + queue.push(element); + threshold = queue.top().m_value; + } + } + for (int i = count - 1; i >= 0; --i) + { + indices[i] = queue.top().m_index; + queue.pop(); + } +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.h new file mode 100644 index 000000000..739413862 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/ScalarMap.h @@ -0,0 +1,37 @@ +// A row-major grid of floats over the strategic map. Evidence: libaidll.so (ia-32) +// 0x364640..0x365FF8; sizeof 12 (width, height, the owned array). Member names [INFERRED]. + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_SCALARMAP_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_SCALARMAP_H + +namespace dice { +namespace hfe { +namespace ai { + +class ScalarMap +{ +public: + // Allocates width * height uninitialised values (checkPointer reports a failed allocation). + ScalarMap(int width, int height); + ~ScalarMap(); + + // Writes the 3x3 (edges 2x3, corners 2x2) box average of this map into result, which must + // have this map's size. Interior rows are resumable: row is the row to continue at (0 starts + // at the first interior row, -1 skips them); when the update-time budget (IBFTimer + // getUpdateTime() >= deadline) runs out the next row is stored and false returned. A 1x1 map + // answers true at once; any other size reports the shipped "Does not work" error first. + bool smooth(ScalarMap& result, double deadline, int& row) const; + // indices[0..count) receive the indices of the count largest values, largest last; with fewer + // candidates above -1e20 the remaining entries are -1. + void sortLargest(int count, int* indices) const; + + /* +0x0 */ int m_width; + /* +0x4 */ int m_height; + /* +0x8 */ float* m_values; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_SCALARMAP_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp new file mode 100644 index 000000000..2445d936b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp @@ -0,0 +1,39 @@ +// Strategic status grid. Evidence: libaidll.so (ia-32) 0x366000..0x3663E8, a TU of its own +// without static initialisation between ScalarMap.cpp and SAIMapSquare.cpp. Its placement in +// AIStrategicMap is [INFERRED] from that address range; the header stays in AIStrategic. + +#include "../AIStrategic/StatusMap.h" + +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x366000 (C2; C1 0x366160). +StatusMap::StatusMap(int width, int height) + : m_width(width) + , m_height(height) +{ + m_statuses = checkPointer(new Status[width * height]); +} + +// ELF 0x3662C0 (D2; D1 0x3662F0). +StatusMap::~StatusMap() +{ + if (m_statuses) + delete[] m_statuses; +} + +// ELF 0x366320. +void StatusMap::getOwnedSquares(std::vector& squares) const +{ + for (int y = 0; y < m_height; ++y) + for (int x = 0; x < m_width; ++x) + if (m_statuses[y * m_width + x] == Owned) + squares.push_back(x + y * m_width); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp new file mode 100644 index 000000000..29ea0de46 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp @@ -0,0 +1,107 @@ +// Strategic temperature tree. Evidence: libaidll.so (ia-32) 0x366510..0x366A55. The TU has no +// static initialisation in the image. Placement next to TemperatureTreeModifiers is [INFERRED] +// from the address range. + +#include "TemperatureTree.h" + +#include "TemperatureTreeModifiers.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x366510 (C2; C1 0x366540). +TemperatureTree::TemperatureTree() +{ + reset(); +} + +// ELF 0x366570 (C2; C1 0x3665C0): the ten words in order. The memberwise spelling is [INFERRED]. +TemperatureTree::TemperatureTree(const TemperatureTree& other) +{ + *this = other; +} + +// ELF 0x366610. +void TemperatureTree::reset() +{ + for (int i = 0; i <= 4; ++i) + { + m_temperatures[i] = 0.0f; + m_weights[i] = 1.0f; + } +} + +// ELF 0x366650. +void TemperatureTree::addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight) +{ + propagateToParents(modifiers, node, temperature, weight); +} + +// ELF 0x3666A0. +void TemperatureTree::addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float weight) +{ + float temperature = 0.0f; + for (int i = 0; i <= 5; ++i) + temperature += strengths[i] * modifiers->m_combatStrengthModifiers[node][i]; + propagateToParents(modifiers, node, temperature, weight); +} + +// ELF 0x366720. +void TemperatureTree::addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float scale, float weight) +{ + float temperature = 0.0f; + for (int i = 0; i <= 5; ++i) + temperature += strengths[i] * modifiers->m_combatStrengthModifiers[node][i]; + propagateToParents(modifiers, node, temperature * scale, weight); +} + +// ELF 0x3667A0. +void TemperatureTree::addTemperature(const TemperatureTree& other) +{ + for (int i = 0; i <= 4; ++i) + m_temperatures[i] += other.m_temperatures[i]; +} + +// ELF 0x3667D0: a jump table over the 41 nodes; the image turns the parent calls into a loop. +// Nodes 0..4 are stored (temperature += t * modifier, weight *= w); every node except the root +// passes t * its modifier on to its parent. Nodes above 40 are ignored. +// [CHOSEN, not recovered] each level's product is rounded to float; the ELF keeps it in x87. +void TemperatureTree::propagateToParents(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight) +{ + const float* const m = modifiers->m_nodeModifiers; + int parent; + switch (static_cast(node)) + { + case 0: + m_temperatures[0] += temperature * m[0]; + m_weights[0] *= weight; + return; + case 1: case 2: case 3: case 4: + m_temperatures[node] += temperature * m[node]; + m_weights[node] *= weight; + parent = (node <= 2) ? 0 : 1; + break; + case 5: case 6: parent = 2; break; + case 7: case 9: case 13: parent = 3; break; + case 8: case 10: case 15: parent = 4; break; + case 29: case 30: case 31: case 32: parent = 5; break; + case 33: case 34: case 35: case 36: case 37: case 38: parent = 6; break; + case 11: case 12: parent = 7; break; + case 14: case 16: parent = 8; break; + case 17: case 18: parent = 11; break; + case 19: case 20: parent = 12; break; + case 21: case 22: parent = 13; break; + case 23: case 24: parent = 14; break; + case 27: case 28: parent = 15; break; + case 25: case 26: parent = 16; break; + case 39: case 40: parent = 38; break; + default: + return; + } + propagateToParents(modifiers, static_cast(parent), temperature * m[node], weight); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.h new file mode 100644 index 000000000..ff6c73676 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTree.h @@ -0,0 +1,44 @@ +// Per-square strategic temperature: five top-level tree nodes, each with an accumulated +// temperature and a multiplicative weight. Deeper nodes of the 41-node TemperatureTreeNode tree +// only scale a contribution on its way up to one of the five. Evidence: libaidll.so (ia-32) +// 0x366510..0x366A55; sizeof 40 (the copy constructor copies ten words). Member names [INFERRED]. + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREE_H // [INFERRED] guard style +#define AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREE_H + +namespace dice { +namespace hfe { +namespace ai { + +class TemperatureTreeModifiers; +enum TemperatureTreeNode : int; // index 0..40 + +class TemperatureTree +{ +public: + TemperatureTree(); + TemperatureTree(const TemperatureTree& other); + + // Every temperature to 0, every weight to 1. + void reset(); + // Adds temperature at node (scaled by the modifiers up the tree) and multiplies the weight of + // every top-level node on the way by weight. + void addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight); + // As above with the temperature formed from six combat strengths and the node's per-strength + // modifiers. + void addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float weight); + // As above with the strength sum multiplied by scale first. + void addTemperature(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float* strengths, float scale, float weight); + // Adds the other tree's temperatures; the weights are untouched. + void addTemperature(const TemperatureTree& other); + void propagateToParents(TemperatureTreeModifiers* modifiers, TemperatureTreeNode node, float temperature, float weight); + + /* +0x00 */ float m_temperatures[5]; + /* +0x14 */ float m_weights[5]; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp new file mode 100644 index 000000000..dab0cb98f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp @@ -0,0 +1,26 @@ +// Temperature-tree modifiers. Evidence: libaidll.so (ia-32) 0x366A60..0x366B20. + +#include "TemperatureTreeModifiers.h" + +namespace dice { +namespace hfe { +namespace ai { + +TemperatureTreeModifiers::TemperatureTreeModifiers() +{ + reset(); +} + +// ELF 0x366AC0. +void TemperatureTreeModifiers::reset() +{ + for (unsigned int node = 0; node <= 40; ++node) + m_nodeModifiers[node] = 1.0f; + for (unsigned int node = 0; node <= 55; ++node) + for (unsigned int type = 0; type <= 5; ++type) + m_combatStrengthModifiers[node][type] = 1.0f; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.h b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.h new file mode 100644 index 000000000..955b6c35f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.h @@ -0,0 +1,28 @@ +// Per-strategy multipliers for the strategic temperature tree: one per tree node and one per +// (node, combat-strength type). Evidence: libaidll.so (ia-32) 0x366A60..0x366B20 (constructor, +// reset) and Strategy's accessors (0x333930..0x333A80); operator new(0x5E4) in Strategy's +// constructor. Source file attested as TemperatureTreeModifiers.cpp (AIStrategicMap link block). + +#ifndef AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREEMODIFIERS_H +#define AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREEMODIFIERS_H + +namespace dice { +namespace hfe { +namespace ai { + +class TemperatureTreeModifiers +{ +public: + TemperatureTreeModifiers(); + void reset(); // every multiplier to 1.0f + + /* +0x000 */ float m_nodeModifiers[41]; // TemperatureTreeNode 0..40 + /* +0x0A4 */ float m_combatStrengthModifiers[56][6]; // [node][CombatStrengthType]; reset + // covers 56 rows, setters only 0..40 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AISTRATEGICMAP_TEMPERATURETREEMODIFIERS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp new file mode 100644 index 000000000..fdb1de108 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.cpp @@ -0,0 +1,103 @@ +// Free vector helpers of the AI image. See AIVectorMath.h for the placement note. + +#include "AIVectorMath.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x3679F0, __tcf_0 0x367A50, _GLOBAL__I 0x367A80). +#include + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x367500. +float distancePointLineSqr(const Vec3& point, const Vec3& linePoint, const Vec3& direction) +{ + const float dx = point.x - linePoint.x; + const float dy = point.y - linePoint.y; + const float dz = point.z - linePoint.z; + const float cx = direction.z * dy - direction.y * dz; + const float cy = dz * direction.x - direction.z * dx; + const float cz = dx * direction.y - dy * direction.x; + return (cx * cx + cy * cy + cz * cz) + / (direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); +} + +// objFireLineDist - libaidll.so (ia-32) 0x367590, 687 B (objdump listing and Ghidra, 2026-11-02). +// The segment direction is normalised by multiplying with 1/length; the projection parameter +// is the dot product of that direction with point - from. Below zero the start is nearest, +// beyond the length the end; an unordered parameter takes the projection branch, as compiled. +float objFireLineDist(const Vec3& point, const Vec3& from, const Vec3& to) +{ + float result = 0.0f; + const float sx = to.x - from.x; + const float sy = to.y - from.y; + const float sz = to.z - from.z; + const float length = std::sqrt(sx * sx + sy * sy + sz * sz); + if (length < 0.001f) + return result; + + const float inv = 1.0f / length; + const float dirX = sx * inv; + const float dirY = sy * inv; + const float dirZ = sz * inv; + float dx = point.x - from.x; + float dy = point.y - from.y; + float dz = point.z - from.z; + const float t = dirX * dx + dirY * dy + dirZ * dz; + if (!(t < 0.0f)) + { + if (t > length) + { + dx = point.x - to.x; + dy = point.y - to.y; + dz = point.z - to.z; + } + else + { + dx -= dirX * t; + dy -= dirY * t; + dz -= dirZ * t; + } + } + result = std::sqrt(dx * dx + dy * dy + dz * dz); + return result; +} + +// ELF 0x367840. Row 2 is saved, row 1 set to `up`; row 0 takes the third axis of (row 1, row 2) +// (which rewrites rows 1 and 2), row 2 is put back, and row 1 takes the third axis of +// (row 2, row 0). +void makeTransOrthonormalUp(Mat4& transformation, const Vec3& up) +{ + Vec3& right = *reinterpret_cast(&transformation.m[0]); + Vec3& upRow = *reinterpret_cast(&transformation.m[4]); + Vec3& forward = *reinterpret_cast(&transformation.m[8]); + const Vec3 savedForward = forward; + upRow = up; + right.makeOrthonormalBasis(upRow, forward); + forward = savedForward; + upRow.makeOrthonormalBasis(forward, right); +} + +// ELF 0x3678D0. A zeroed matrix (the shipped Mat4 construction) set to identity; row 2 becomes +// `direction`; then row 1 takes the third axis of (row 2, row 0) and row 0 that of (row 1, row 2). +Mat4 getDofTransformation(const Vec3& direction) +{ + Mat4 transformation; + for (int i = 0; i < 16; ++i) + transformation.m[i] = 0.0f; + transformation = Mat4::getIdentity(); + Vec3& right = *reinterpret_cast(&transformation.m[0]); + Vec3& up = *reinterpret_cast(&transformation.m[4]); + Vec3& forward = *reinterpret_cast(&transformation.m[8]); + forward = direction; + up.makeOrthonormalBasis(forward, right); + right.makeOrthonormalBasis(up, forward); + return transformation; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h new file mode 100644 index 000000000..328c1faa1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AIVectorMath.h @@ -0,0 +1,38 @@ +// Free vector helpers of the AI image (namespace dice::hfe::ai). +// [INFERRED] Source placement and file name: libaidll.so keeps these in one translation unit with +// its own static initializer (ELF 0x367500..0x367A9F: distancePointLineSqr, objFireLineDist, +// makeTransOrthonormalUp, getDofTransformation); no __FILE__ string attests the path. + +#ifndef AI_AIDLL_AI_AIUTILS_AIVECTORMATH_H +#define AI_AIDLL_AI_AIUTILS_AIVECTORMATH_H + +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// Squared distance from `point` to the infinite line through `linePoint` along `direction` +// (|(point - linePoint) x direction|^2 / |direction|^2). A zero direction divides by zero. +// No caller in libaidll.so. +float distancePointLineSqr(const Vec3& point, const Vec3& linePoint, const Vec3& direction); + +// Distance from `point` to the segment from `from` to `to`: the perpendicular distance where the +// projection falls inside the segment, otherwise the distance to the nearer end. A segment +// shorter than 0.001 answers 0. +float objFireLineDist(const Vec3& point, const Vec3& from, const Vec3& to); + +// Re-orthonormalises `transformation` around `up`: row 1 becomes `up`, then the rows are rebuilt +// keeping row 2's direction (the forward vector). No caller in libaidll.so. +void makeTransOrthonormalUp(Mat4& transformation, const Vec3& up); + +// An orthonormal transformation whose row 2 points along `direction`, no translation. No caller +// in libaidll.so. +Mat4 getDofTransformation(const Vec3& direction); + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_AIVECTORMATH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp new file mode 100644 index 000000000..bd9ce8ba3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp @@ -0,0 +1,75 @@ +// Ballistic arc helper. [INFERRED] Source placement. + +// static init: ELF 0x2EA8B0 (__tcf_0 0x2EA910, _GLOBAL__I 0x2EA940): 's Init object only. +#include + +#include "AimerHelper.h" + +#include "checkPointer.h" +#include "../AIBot/Aimer.h" +#include "../Main/CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EA2D0 (C1; C2 0x2EA160). +AimerHelper::AimerHelper() : m_aimer(checkPointer(new Aimer())) +{ +} + +// ELF 0x2EA4A0 (D1; D2 0x2EA440, D0 0x2EA500). +AimerHelper::~AimerHelper() +{ + if (m_aimer) + delete m_aimer; +} + +// ELF 0x2EA570 (amd-64 0x335D50). +bool AimerHelper::hasIndirectLineOfFire(float speed, const float& drag, const float& gravity, + const Vec3& relativePosition, const Vec3& origin, Vec3& predictedTarget, Vec3& velocity, Vec3& apex) +{ + m_aimer->m_speed = speed; + m_aimer->m_drag = drag; + m_aimer->m_inverseDrag = drag != 0.0f ? 1.0f / drag : 0.0f; + m_aimer->m_gravity = gravity; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + static Vec3 zero = {0.0f, 0.0f, 0.0f}; + const Vec3 shooterVelocity = {0.0f, 0.0f, 0.0f}; + m_aimer->setTargetData(relativePosition, zero, shooterVelocity, 0, now); + if (!m_aimer->getFiringDirection(now, 0.5f, true, velocity, predictedTarget, 0)) + return false; + const float lengthSqr = velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z; + if (!(std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f)) + { + if (std::fabs(lengthSqr) < 1.1920929e-07f) + velocity.x = velocity.y = velocity.z = 0.0f; + else + { + const float inverse = 1.0f / std::sqrt(lengthSqr); + velocity.x *= inverse; + velocity.y *= inverse; + velocity.z *= inverse; + } + } + velocity.x *= speed; + velocity.y *= speed; + velocity.z *= speed; + const double extreme = m_aimer->getVerticalExtreme(); + const float time = static_cast(extreme); + const float halfTimeSquared = static_cast(extreme * extreme * 0.5); + const Vec3 displacement = {time * velocity.x, time * velocity.y, time * velocity.z}; + const Vec3 position = {displacement.x + origin.x, displacement.y + origin.y, displacement.z + origin.z}; + // Preserve the zero acceleration terms as well: zero times an infinite time is NaN. + const Vec3 fall = {halfTimeSquared * 0.0f, halfTimeSquared * gravity, halfTimeSquared * 0.0f}; + const Vec3 result = {position.x + fall.x, position.y + fall.y, position.z + fall.z}; + apex = result; + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h new file mode 100644 index 000000000..e82432db9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.h @@ -0,0 +1,34 @@ +// Owns a ballistic aimer; the inherited slot remains pure. [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_AIUTILS_AIMERHELPER_H +#define AI_AIDLL_AI_AIUTILS_AIMERHELPER_H + +#include "IAimerHelper.h" + +namespace dice { +namespace hfe { +namespace ai { + +class Aimer; + +class AimerHelper : public IAimerHelper +{ +public: + AimerHelper(); + virtual ~AimerHelper(); + + // Finds a high arc, returning its predicted target, initial velocity and apex. + // ELF 0x2EA570: a new slot 3 (+0x0C ia-32, +0x18 amd-64), not a slot-2 override. + virtual bool hasIndirectLineOfFire(float speed, const float& drag, const float& gravity, + const Vec3& relativePosition, const Vec3& origin, Vec3& predictedTarget, + Vec3& velocity, Vec3& apex); + +private: + /* +0x04 (amd-64 +0x08) */ Aimer* m_aimer; // owned +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp index 452573279..2296868fd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp @@ -1,15 +1,36 @@ // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIRenderUtil operations. + +// static init: ELF 0x3BA330 (__tcf_0 0x3BA390, _GLOBAL__I 0x3BA3C0): 's Init object only. +#include +#include // drawArrow's length +#include // setCoordinate, renderStrategies #include "AIRenderUtil.h" +#include "../../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain::getTerrainAltitude +#include "../../AIStrategic/SAI.h" +#include "../../AIStrategic/Strategy.h" +#include "../../AIStrategicEntity/CoverPosition/CoverPosition.h" +#include "../../AIStrategicEntity/CoverPosition/CoverPositionManager.h" +#include "../../Main/AIMain.h" // IAIMain::m_instance->getSAI +#include "../../Main/AIPathfinding.h" +#include "../../Main/AIPathfindingSearchTypes.h" // QTPath, ClusterNodePath +#include "../AIVectorMath.h" +#include "../../AIStrategicEntity/GuardPosition.h" +#include "../../AIStrategicEntity/PatrolPath.h" +#include "../checkPointer.h" +#include "../../AIStrategicEntity/AILandingZone.h" #include "../../AIStrategicEntity/AILandingZoneManager.h" #include "../../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../../AIStrategicEntity/AIStrategicArea.h" #include "../../DrawPrimitives/DPManager.h" +#include "../../DrawPrimitives/DPStaticCircle.h" +#include "../../DrawPrimitives/DPStaticLine.h" #include "../../Main/AIConsole.h" #include "../../Main/AIDllFrontier.h" #include "../../Main/AISettingsInterfaces.h" #include "../../Main/BotManager.h" +#include "../../AIBot/BotMain.h" // Bot::getBotId #include "../../Main/CommonSingletonServer.h" namespace dice { @@ -48,6 +69,13 @@ AIRenderUtil::BotPrimitives::BotPrimitives(DrawPrimitive* line0, DrawPrimitive* // declared and empty on purpose - see the header. Removing it would change which temporaries get // a destructor call in the emitted code. +// ELF 0x3B44B0 / 0x3B44F0. Copies the seven borrowed primitive handles. +AIRenderUtil::BotPrimitives::BotPrimitives(const BotPrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_circle0(other.m_circle0), + m_circle1(other.m_circle1), m_line2(other.m_line2), m_line3(other.m_line3), m_text3d(other.m_text3d) +{ +} + AIRenderUtil::BotPrimitives::~BotPrimitives() { } @@ -65,15 +93,32 @@ void AIRenderUtil::BotPrimitives::deletePrimitives() manager->delete3dText(m_text3d); } +// ELF 0x3B3790 / 0x3B3860. AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives() : m_line0(0) , m_line1(0) , m_circle0(0) , m_circle1(0) , m_text3d(0) +{ + m_circles.resize(2, static_cast(0)); +} + +// ELF 0x3B3930 / 0x3B3B00. Copies both vectors before resizing the circle vector. +AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives(const StrategicAreaPrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_lines(other.m_lines), + m_circle0(other.m_circle0), m_circle1(other.m_circle1), m_text3d(other.m_text3d), + m_circles(other.m_circles) +{ + m_circles.resize(2, static_cast(0)); +} + +// ELF 0x3B4050 / 0x3B40C0. Only the vectors' storage is released; handles are borrowed here. +AIRenderUtil::StrategicAreaPrimitives::~StrategicAreaPrimitives() { } +// ELF 0x3B3CD0 / 0x3B3E90. AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives( DrawPrimitive* line0, DrawPrimitive* line1, const std::vector& lines, DrawPrimitive* circle0, DrawPrimitive* circle1, DrawPrimitive* text3d, @@ -86,6 +131,7 @@ AIRenderUtil::StrategicAreaPrimitives::StrategicAreaPrimitives( , m_text3d(text3d) , m_circles(circles) { + m_circles.resize(2, static_cast(0)); } void AIRenderUtil::StrategicAreaPrimitives::deletePrimitives() @@ -131,6 +177,13 @@ AIRenderUtil::LandingZonePrimitives::LandingZonePrimitives(DrawPrimitive* line0, { } +// ELF 0x3B4350 / 0x3B4380. +AIRenderUtil::LandingZonePrimitives::LandingZonePrimitives(const LandingZonePrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_line2(other.m_line2), + m_line3(other.m_line3), m_text3d(other.m_text3d) +{ +} + void AIRenderUtil::LandingZonePrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -155,6 +208,12 @@ AIRenderUtil::PatrolPathPrimitives::PatrolPathPrimitives( { } +// ELF 0x3B46C0 / 0x3B4760. +AIRenderUtil::PatrolPathPrimitives::PatrolPathPrimitives(const PatrolPathPrimitives& other) + : m_segments(other.m_segments), m_text3d(other.m_text3d) +{ +} + void AIRenderUtil::PatrolPathPrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -184,6 +243,12 @@ AIRenderUtil::GuardPositionPrimitives::GuardPositionPrimitives( { } +// ELF 0x3B4A70 / 0x3B4A90. +AIRenderUtil::GuardPositionPrimitives::GuardPositionPrimitives(const GuardPositionPrimitives& other) + : m_marker(other.m_marker), m_text3d(other.m_text3d) +{ +} + void AIRenderUtil::GuardPositionPrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -210,6 +275,13 @@ AIRenderUtil::CoverPositionPrimitives::CoverPositionPrimitives( { } +// ELF 0x3B4C10 / 0x3B4E10. +AIRenderUtil::CoverPositionPrimitives::CoverPositionPrimitives(const CoverPositionPrimitives& other) + : m_line0(other.m_line0), m_line1(other.m_line1), m_linesA(other.m_linesA), + m_linesB(other.m_linesB), m_linesC(other.m_linesC) +{ +} + void AIRenderUtil::CoverPositionPrimitives::deletePrimitives() { IDPManager* const manager = static_cast(CommonSingletonServer::m_iDPManager); @@ -389,26 +461,33 @@ void AIRenderUtil::unrenderAll() AIConsole::m_instance->removeCameraText(); } -// [FRONTIER] Bot primitive cleanup requires the remaining bot rendering contract. -// [RETIRE-WHEN: botmain-bases] Complete and validate the corresponding AIRenderUtil operation. -void AIRenderUtil::unrenderBot(Bot*) +// ELF 0x3B7410: the bot's id (+0xE8 getBotId) indexes the primitive records unchecked. +void AIRenderUtil::unrenderBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::unrenderBot (Bot::getBotId, botmain-bases)"); + m_botPrimitives[bot->getBotId()].deletePrimitives(); } -// [FRONTIER] Releases every bot's debug primitives once the required bot interfaces are available. -// [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x3B7460: with a bot manager, every index below getBotCount (+0x08) goes through +// getBotFromId (+0x18) to unrenderBot. The count is read once. void AIRenderUtil::unrenderAllBots() { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::unrenderAllBots (IBotManager, botmanager-bases)"); + IBotManager* const bots = IBotManager::instance; + if (!bots) + return; + const int count = bots->getBotCount(); + for (int i = 0; i < count; ++i) + unrenderBot(bots->getBotFromId(static_cast(i))); } -// [FRONTIER] Area primitive cleanup requires its validated primitive index. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIRenderUtil operation. -void AIRenderUtil::unrenderStrategicArea(AIStrategicArea*) +// ELF 0x3B7FD0: the area's index (+0xF0, AIStrategicObject::m_index) selects its primitive +// record, then each landing zone's id (AILandingZone::getId) selects a landing-zone record. The +// zone vector is fetched again for every end() comparison. +void AIRenderUtil::unrenderStrategicArea(AIStrategicArea* area) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::unrenderStrategicArea (AIStrategicArea layout)"); + m_strategicAreaPrimitives[area->getIndex()].deletePrimitives(); + for (std::vector::iterator zone = area->getLandingZones().begin(); + zone != area->getLandingZones().end(); ++zone) + m_landingZonePrimitives[(*zone)->getId()].deletePrimitives(); } // Copies the strategic-area map before iterating it to remove debug rendering. @@ -537,47 +616,450 @@ void AIRenderUtil::updateNumberOfLandingZones() m_landingZonePrimitives.resize(count); } -// [FRONTIER] Remaining console-driven rendering operations stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIRenderUtil operation. - -void AIRenderUtil::setCoordinate(const Vec3&) +// ELF 0x3B65C0. Replaces the text lines with one "x/y/z" line for `position` and shows them as +// the white 2D text at the screen origin, creating m_text2dA on first use and updating it after. +// [INFERRED] The three '/'-separated inserts may be an inlined Vec3 stream operator. +void AIRenderUtil::setCoordinate(const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::setCoordinate"); + m_text.resize(0); + std::stringstream stream; + stream << position.x << '/' << position.y << '/' << position.z; + m_text.push_back(stream.str()); + + if (m_text2dA) + { + const Vec2 origin = {0.0f, 0.0f}; + static_cast(CommonSingletonServer::m_iDPManager) + ->set2dTextAttributes(m_text2dA, 1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } + else + { + const Vec2 origin = {0.0f, 0.0f}; + m_text2dA = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic2dText(1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } } +// ELF 0x3B6C10. Replaces the text lines with the active strategy of SAI sides 1 and 2, each as +// "name a b c" with the three values getActiveStrategy reports, and shows them as white 2D text +// twelve units down (m_text2dB). The strategy pointers are used unchecked (shipped). void AIRenderUtil::renderStrategies() { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderStrategies"); + m_text.resize(0); + std::stringstream stream; + SAI* const side1 = IAIMain::m_instance->getSAI(1); + SAI* const side2 = IAIMain::m_instance->getSAI(2); + float a = 0.0f; + float b = 0.0f; + float c = 0.0f; + + stream << side1->getActiveStrategy(a, b, c)->getName() << " " << a << " " << b << " " << c; + m_text.push_back(stream.str()); + stream.str(""); + + stream << side2->getActiveStrategy(a, b, c)->getName() << " " << a << " " << b << " " << c; + m_text.push_back(stream.str()); + + if (m_text2dB) + { + const Vec2 origin = {0.0f, 12.0f}; + static_cast(CommonSingletonServer::m_iDPManager) + ->set2dTextAttributes(m_text2dB, 1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } + else + { + const Vec2 origin = {0.0f, 12.0f}; + m_text2dB = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic2dText(1.0e9f, 0xFFFFFFFFu, origin, m_text, 0, + static_cast(0), static_cast(0)); + } } -void AIRenderUtil::drawArrow(float, unsigned int, const Vec3&, const Vec3&) +// ELF 0x3B7670. One static polyline in m_sensingLine: from `position` to the tip +// (`position` + `direction`), then over three barbs back to the tip. The barbs sit at 70% of the +// length, offset by a tenth of the length along the frame's first row, a twentieth along its +// second row, and a tenth against the first row. The line is 3% of the length wide. The frame is +// getDofTransformation's (third row forward), as in drawAxisPoint. The ia-32 build forms +// 1 - 0.3 at run time, so the three fractions were locals in the source. +void AIRenderUtil::drawArrow(float lifeTime, unsigned int colour, const Vec3& position, + const Vec3& direction) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::drawArrow"); + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + + direction.z * direction.z); + const Mat4 frame = getDofTransformation(direction); + Vec3 point = {0.0f, 0.0f, 0.0f}; + const float barbWidth = 0.1f; + const float barbLength = 0.3f; + const float barbHeight = 0.05f; + + m_sensingLine.resize(0, point); + m_sensingLine.push_back(position); + + // the tip + point.x = position.x + length * frame.m[8]; + point.y = position.y + length * frame.m[9]; + point.z = position.z + length * frame.m[10]; + m_sensingLine.push_back(point); + + // first barb: back along forward, out along the first row + point.x = position.x + length * frame.m[8] * (1.0f - barbLength) + length * frame.m[0] * barbWidth; + point.y = position.y + length * frame.m[9] * (1.0f - barbLength) + length * frame.m[1] * barbWidth; + point.z = position.z + length * frame.m[10] * (1.0f - barbLength) + length * frame.m[2] * barbWidth; + m_sensingLine.push_back(point); + + // second barb: out along the second row + point.x = position.x + length * frame.m[8] * (1.0f - barbLength) + length * frame.m[4] * barbHeight; + point.y = position.y + length * frame.m[9] * (1.0f - barbLength) + length * frame.m[5] * barbHeight; + point.z = position.z + length * frame.m[10] * (1.0f - barbLength) + length * frame.m[6] * barbHeight; + m_sensingLine.push_back(point); + + // third barb: against the first row + point.x = position.x + length * frame.m[8] * (1.0f - barbLength) - length * frame.m[0] * barbWidth; + point.y = position.y + length * frame.m[9] * (1.0f - barbLength) - length * frame.m[1] * barbWidth; + point.z = position.z + length * frame.m[10] * (1.0f - barbLength) - length * frame.m[2] * barbWidth; + m_sensingLine.push_back(point); + + // back to the tip + point.x = position.x + length * frame.m[8]; + point.y = position.y + length * frame.m[9]; + point.z = position.z + length * frame.m[10]; + m_sensingLine.push_back(point); + + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, m_sensingLine, length * 0.03f); } -void AIRenderUtil::drawAxisPoint(float, unsigned int, const Vec3&, const Vec3&, float) +// ELF 0x3B7DD0. Three static lines through `position`, one per axis of the frame +// getDofTransformation builds from `direction` (third row, then second, then first), each from +// position - axis to position + axis and a quarter of `size` wide. +void AIRenderUtil::drawAxisPoint(float lifeTime, unsigned int colour, const Vec3& position, + const Vec3& direction, float size) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::drawAxisPoint"); + const Mat4 frame = getDofTransformation(direction); + Vec3 end; + Vec3 start; + size = size * 0.25f; + + end.x = position.x + frame.m[8]; + end.y = position.y + frame.m[9]; + end.z = position.z + frame.m[10]; + start.x = position.x - frame.m[8]; + start.y = position.y - frame.m[9]; + start.z = position.z - frame.m[10]; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, start, end, size); + + end.x = position.x + frame.m[4]; + end.y = position.y + frame.m[5]; + end.z = position.z + frame.m[6]; + start.x = position.x - frame.m[4]; + start.y = position.y - frame.m[5]; + start.z = position.z - frame.m[6]; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, start, end, size); + + end.x = position.x + frame.m[0]; + end.y = position.y + frame.m[1]; + end.z = position.z + frame.m[2]; + start.x = position.x - frame.m[0]; + start.y = position.y - frame.m[1]; + start.z = position.z - frame.m[2]; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(lifeTime, colour, start, end, size); } -void AIRenderUtil::renderPatrolPath(const std::string&, PatrolPath*) +// ELF 0x3B83E0. Once per patrol path: for every waypoint a short vertical post (built in +// m_sensingLine, which serves as the scratch point list) and a unit circle, recorded as a +// (line, circle) segment; then the name five units above the first waypoint. The text handle is +// not stored (shipped, kept). The path is fetched again for every end() comparison. +void AIRenderUtil::renderPatrolPath(const std::string& name, PatrolPath* path) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderPatrolPath"); + if (m_patrolPathPrimitives.find(path) != m_patrolPathPrimitives.end()) + return; + PatrolPathPrimitives* const primitives = checkPointer(new PatrolPathPrimitives()); + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + + for (std::vector::const_iterator waypoint = path->getPath().begin(); + waypoint != path->getPath().end(); ++waypoint) + { + const Vec3 point = *waypoint; + Vec3 vertex = {0.0f, 0.0f, 0.0f}; + m_sensingLine.resize(0, vertex); + vertex.x = point.x; + vertex.y = point.y - 2.5f; + vertex.z = point.z + 0.1f; + m_sensingLine.push_back(vertex); + vertex.x = point.x; + vertex.y = 2.5f + point.y; + vertex.z = point.z - 0.1f; + m_sensingLine.push_back(vertex); + DrawPrimitive* const line = creator->createStaticLine(1.0e9f, 0xFF4422u, m_sensingLine, 0.2f); + + vertex.x = 0.0f; + vertex.y = 1.0f; + vertex.z = 0.0f; + DrawPrimitive* const circle + = creator->createStaticCircle(1.0e9f, 0xFF4422u, *waypoint, 1.0f, vertex, false, 255); + primitives->m_segments.push_back(std::make_pair(line, circle)); + } + + const Vec3& first = path->getPath()[0]; + Vec3 textPosition; + textPosition.x = first.x; + textPosition.y = first.y + 5.0f; + textPosition.z = first.z; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic3dText(1.0e9f, 0xFFFFFFFFu, textPosition, name, 0, + static_cast(0), static_cast(0)); + m_patrolPathPrimitives.insert(std::make_pair(path, primitives)); } -void AIRenderUtil::renderGuardPosition(const std::string&, GuardPosition*) +// ELF 0x3B8BC0. Once per guard position: a circle of the minimum distance one unit above it, the +// name four units higher, and a line below the name. The text handle is not stored (the record's +// m_text3d stays at its default), and the line's upper end subtracts the circle height rather than +// an offset, so it ends near world height 4 (both shipped, kept). +void AIRenderUtil::renderGuardPosition(const std::string& name, GuardPosition* guardPosition) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderGuardPosition"); + if (m_guardPositionPrimitives.find(guardPosition) != m_guardPositionPrimitives.end()) + return; + GuardPositionPrimitives* const primitives = checkPointer(new GuardPositionPrimitives()); + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + + Vec3 position = guardPosition->getPosition(); + position.y = position.y + 1.0f; + const float circleHeight = position.y; + const Vec3 up = {0.0f, 1.0f, 0.0f}; + primitives->m_marker.first = creator->createStaticCircle( + 1.0e9f, 0x117799u, position, guardPosition->getMinDistance(), up, false, 255); + + position.y = 4.0f + position.y; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStatic3dText(1.0e9f, 0xFFFFFFFFu, position, name, 0, + static_cast(0), static_cast(0)); + m_guardPositionPrimitives.insert(std::make_pair(guardPosition, primitives)); + + Vec3 start; + start.x = position.x - 0.0f; + start.y = position.y - circleHeight; + start.z = position.z - 0.0f; + Vec3 end; + end.x = position.x - 0.0f; + end.y = position.y - 5.0f; + end.z = position.z - 0.0f; + primitives->m_marker.second = creator->createStaticLine(1.0e9f, 0x117799u, start, end, 0.1f); } -void AIRenderUtil::renderCoverPosition(int) +// ELF 0x3B9130. Once per cover position (the record's first line is the marker): its box as a +// closed outline half a unit above the terrain, a post at its centre, and one line from the +// centre to each linked position, five units higher per link kind: move neighbours (linesA, to +// the other box's first corner plus half a unit, grey), attackable links (linesB, to the first +// corner, coloured by the link type) and defendable links (linesC, likewise). The record vector +// grows to fit the index; a negative index is not caught (shipped). The first loop fetches the +// creator singleton again; the other calls use the copy taken on entry. +void AIRenderUtil::renderCoverPosition(int index) { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::renderCoverPosition"); + CoverPositionManager* const manager = CoverPositionManager::m_instance; + CoverPosition* const cover = manager->m_coverPositions[index]; + if (!cover) + return; + + if (index >= static_cast(m_coverPositionPrimitives.size())) + m_coverPositionPrimitives.resize(index + 1); + CoverPositionPrimitives& primitives = m_coverPositionPrimitives[index]; + if (primitives.m_line0) + return; + + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + const IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + + const Vec3 corner0 = {cover->m_min.x, + terrain->getTerrainAltitude(cover->m_min.x, cover->m_min.y) + 0.5f, + cover->m_min.y}; + const Vec3 corner1 = {cover->m_max.x, + terrain->getTerrainAltitude(cover->m_max.x, cover->m_min.y) + 0.5f, + cover->m_min.y}; + const Vec3 corner2 = {cover->m_max.x, + terrain->getTerrainAltitude(cover->m_max.x, cover->m_max.y) + 0.5f, + cover->m_max.y}; + const Vec3 corner3 = {cover->m_min.x, + terrain->getTerrainAltitude(cover->m_min.x, cover->m_max.y) + 0.5f, + cover->m_max.y}; + + const Vec3 zero = {0.0f, 0.0f, 0.0f}; + m_sensingLine.resize(0, zero); + m_sensingLine.push_back(corner0); + m_sensingLine.push_back(corner1); + m_sensingLine.push_back(corner2); + m_sensingLine.push_back(corner3); + m_sensingLine.push_back(corner0); + primitives.m_line0 = creator->createStaticLine(1.0e9f, 0x77777777u, m_sensingLine, 0.2f); + + Vec3 centre = {0.0f, 0.0f, 0.0f}; + centre.x = cover->m_min.x + (cover->m_max.x - cover->m_min.x) * 0.5f; + centre.z = cover->m_min.y + (cover->m_max.y - cover->m_min.y) * 0.5f; + centre.y = terrain->getTerrainAltitude(centre.x, centre.z); + + Vec3 top; + top.x = centre.x + 0.0f; + top.y = centre.y + 15.0f; + top.z = centre.z + 0.0f; + Vec3 foot; + foot.x = centre.x + 0.1f; + foot.y = centre.y + 0.0f; + foot.z = centre.z + 0.1f; + primitives.m_line1 = creator->createStaticLine(1.0e9f, 0x77777777u, foot, top, 0.2f); + + centre.y = centre.y + 5.0f; + Vec3 end = {0.0f, 0.0f, 0.0f}; + for (std::set::const_iterator it = cover->m_moveNeighbours.begin(); + it != cover->m_moveNeighbours.end(); ++it) + { + const CoverPosition* const other = manager->m_coverPositions[*it]; + if (!other) + continue; + end.x = other->m_min.x + 0.5f; + end.z = other->m_min.y + 0.5f; + end.y = terrain->getTerrainAltitude(end.x, end.z) + 5.0f; + primitives.m_linesA.push_back( + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(1.0e9f, 0xAAAAAAAAu, centre, end, 0.1f)); + } + + centre.y = centre.y + 5.0f; + for (std::map::const_iterator it = cover->m_attackable.begin(); + it != cover->m_attackable.end(); ++it) + { + const CoverPosition* const other = manager->m_coverPositions[it->first]; + if (!other) + continue; + unsigned int colour; + switch (it->second.m_type) + { + case ConnectionType::kPartial: colour = 0xBBBB00u; break; + case ConnectionType::kBlocked: colour = 0xBB0000u; break; + case ConnectionType::kVisible: colour = 0x00BB00u; break; + default: colour = 0; break; + } + end.x = other->m_min.x; + end.z = other->m_min.y; + end.y = terrain->getTerrainAltitude(end.x, end.z) + 10.0f; + primitives.m_linesB.push_back(creator->createStaticLine(1.0e9f, colour, centre, end, 0.1f)); + } + + centre.y = centre.y + 5.0f; + for (std::map::const_iterator it = cover->m_defendable.begin(); + it != cover->m_defendable.end(); ++it) + { + const CoverPosition* const other = manager->m_coverPositions[it->first]; + if (!other) + continue; + unsigned int colour; + switch (it->second.m_type) + { + case ConnectionType::kPartial: colour = 0xBBBB00u; break; + case ConnectionType::kBlocked: colour = 0xBB0000u; break; + case ConnectionType::kVisible: colour = 0x00BB00u; break; + default: colour = 0; break; + } + end.x = other->m_min.x; + end.z = other->m_min.y; + end.y = terrain->getTerrainAltitude(end.x, end.z) + 15.0f; + primitives.m_linesC.push_back(creator->createStaticLine(1.0e9f, colour, centre, end, 0.1f)); + } } +// ELF 0x3B9D00 (dice's spelling, "redender"). The pathfinding debug tool's markers: the found +// path as one line (m_pathLine) once both search points are set, and a circle at each set search +// point (m_pathCircleA, m_pathCircleB), each created on first use and updated after. Setting the +// first point again deletes the line, and an unset point deletes its circle. The plain path is +// read through its own step cursor, which this advances; a cursor that does not start at zero +// runs off the end and copies through a null position (shipped). The cluster path skips its +// start step and ignores getPoint's answer. void AIRenderUtil::redenderPathfindingDebug() { - BF2_AI_FRONTIER("dice::hfe::ai::AIRenderUtil::redenderPathfindingDebug"); + AIPathfinding* const pathfinding = static_cast(IAIPathfinding::instance); + + if (m_pathLine) + { + if (pathfinding->getSearchPointToSet() == 1) + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteLine(m_pathLine); + m_pathLine = 0; + } + } + else if (pathfinding->getSearchPointToSet() == 2) + { + const bool cluster = pathfinding->getClusterSearch(); + const unsigned int colour = cluster ? 0xFF00FF44u : 0xFFFF8800u; + IDPStaticCreator* const creator = static_cast(CommonSingletonServer::m_iDPStaticCreator); + std::vector points; + + if (!cluster) + { + QTPath* const path = pathfinding->getDebugPath(); + for (unsigned int i = 0; i < path->m_nodes.size(); ++i) + { + // [INFERRED] an inlined QTPath step accessor (unsigned compare, post-increment of + // the cursor); no out-of-line copy exists to name it. + const Vec3* position = 0; + if (static_cast(path->m_i0) < path->m_nodes.size()) + position = &path->m_nodes[path->m_i0++].third; + points.push_back(*position); + } + } + else + { + const ClusterNodePath* const path = pathfinding->getDebugClusterPath(); + Vec3 point = {0.0f, 0.0f, 0.0f}; + unsigned int polygon; + for (unsigned int i = 1; i < path->m_nodes.size(); ++i) + { + path->getPoint(point, polygon, i); + points.push_back(point); + } + } + + m_pathLine = creator->createStaticLine(1.0e9f, colour, points, 0.3f); + } + + if (pathfinding->getSearchPointToSet() > 0) + { + const Vec3 up = {0.0f, 1.0f, 0.0f}; + if (m_pathCircleA) + static_cast(CommonSingletonServer::m_iDPManager) + ->setCircleAttributes(m_pathCircleA, 1.0e9f, 0xFFFF8800u, + *pathfinding->getSearchPoint(0), 1.0f, up, false, 255); + else + m_pathCircleA = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(1.0e9f, 0xFFFF8800u, *pathfinding->getSearchPoint(0), 1.0f, up, + false, 255); + } + else + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteCircle(m_pathCircleA); + m_pathCircleA = 0; + } + + if (pathfinding->getSearchPointToSet() == 2) + { + const Vec3 up = {0.0f, 1.0f, 0.0f}; + if (m_pathCircleB) + static_cast(CommonSingletonServer::m_iDPManager) + ->setCircleAttributes(m_pathCircleB, 1.0e9f, 0xFFFF8800u, + *pathfinding->getSearchPoint(1), 1.0f, up, false, 255); + else + m_pathCircleB = static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticCircle(1.0e9f, 0xFFFF8800u, *pathfinding->getSearchPoint(1), 1.0f, up, + false, 255); + } + else + { + static_cast(CommonSingletonServer::m_iDPManager)->deleteCircle(m_pathCircleB); + m_pathCircleB = 0; + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h index e6f7ad824..2f9a8bf71 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.h @@ -1,7 +1,5 @@ // Owns AI debug-drawing handles allocated by the primitive manager. // The dedicated build leaves per-frame render operations empty; console-driven operations remain active. -// [FRONTIER] Remaining render methods stop until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate the remaining rendering operations. // [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. @@ -40,6 +38,7 @@ class AIRenderUtil struct BotPrimitives { BotPrimitives(); + BotPrimitives(const BotPrimitives&); BotPrimitives(DrawPrimitive* line0, DrawPrimitive* line1, DrawPrimitive* circle0, DrawPrimitive* circle1, DrawPrimitive* line2, DrawPrimitive* line3, DrawPrimitive* text3d); @@ -61,6 +60,9 @@ class AIRenderUtil struct StrategicAreaPrimitives { StrategicAreaPrimitives(); + // Every constructor resizes the circle vector to exactly two entries after copying it. + StrategicAreaPrimitives(const StrategicAreaPrimitives&); + ~StrategicAreaPrimitives(); StrategicAreaPrimitives(DrawPrimitive* line0, DrawPrimitive* line1, const std::vector& lines, DrawPrimitive* circle0, DrawPrimitive* circle1, DrawPrimitive* text3d, @@ -80,6 +82,7 @@ class AIRenderUtil struct LandingZonePrimitives { LandingZonePrimitives(); + LandingZonePrimitives(const LandingZonePrimitives&); LandingZonePrimitives(DrawPrimitive* line0, DrawPrimitive* line1, DrawPrimitive* line2, DrawPrimitive* line3, DrawPrimitive* text3d); @@ -95,6 +98,7 @@ class AIRenderUtil struct PatrolPathPrimitives { PatrolPathPrimitives(); + PatrolPathPrimitives(const PatrolPathPrimitives&); // the text comes first here and last in memory - see the header block. PatrolPathPrimitives(DrawPrimitive* text3d, const std::vector >& segments); @@ -108,6 +112,7 @@ class AIRenderUtil struct GuardPositionPrimitives { GuardPositionPrimitives(); + GuardPositionPrimitives(const GuardPositionPrimitives&); // Same inversion as PatrolPathPrimitives. GuardPositionPrimitives(DrawPrimitive* text3d, const std::pair& marker); @@ -121,6 +126,7 @@ class AIRenderUtil struct CoverPositionPrimitives { CoverPositionPrimitives(); + CoverPositionPrimitives(const CoverPositionPrimitives&); CoverPositionPrimitives(DrawPrimitive* line0, DrawPrimitive* line1, const std::vector& linesA, const std::vector& linesB, @@ -142,13 +148,13 @@ class AIRenderUtil void exit(); // - empty in retail // the render half. Every one of these with a five-byte body is empty in retail. - void setCoordinate(const Vec3& position); // [FRONTIER] - void renderStrategies(); // [FRONTIER] + void setCoordinate(const Vec3& position); + void renderStrategies(); void renderBot(BotMain*, const std::pair&, const std::pair&, float, const std::pair&); // - empty void addSensingLine(const Vec3& from, const Vec3& to, int side, bool visible); - void drawArrow(float, unsigned int, const Vec3&, const Vec3&); // [FRONTIER] - void drawAxisPoint(float, unsigned int, const Vec3&, const Vec3&, float); // [FRONTIER] + void drawArrow(float lifeTime, unsigned int colour, const Vec3& position, const Vec3& direction); + void drawAxisPoint(float, unsigned int, const Vec3&, const Vec3&, float); void renderPath(int, bool, const std::vector&, unsigned int); // - empty void renderWaypointList(BotMain*); // - empty void renderPathFinding(BotMain*); // - empty @@ -158,21 +164,21 @@ class AIRenderUtil void renderBotStats(BotMain*, const std::pair&, const std::pair&, float, const std::pair&); // - empty void renderBehaviourStats(BotMain*, std::vector&); // - empty - void renderPatrolPath(const std::string&, PatrolPath*); // [FRONTIER] - void renderGuardPosition(const std::string&, GuardPosition*); // [FRONTIER] - void renderCoverPosition(int); // [FRONTIER] - void redenderPathfindingDebug(); // [FRONTIER] + void renderPatrolPath(const std::string&, PatrolPath*); + void renderGuardPosition(const std::string&, GuardPosition*); + void renderCoverPosition(int); + void redenderPathfindingDebug(); // dice's spelling void renderObstacleInfo(Bot*); // - empty void initAIMeshRendering(); // - empty void cleanUpAIMeshRendering(); // - empty void renderAIMeshes(); // - empty - // the unrender half. All written except the two blocked on a missing type. + // the unrender half. void unrenderAll(); - void unrenderBot(Bot*); // [FRONTIER] + void unrenderBot(Bot*); void unrenderAllBots(); - void unrenderStrategicArea(AIStrategicArea*); // [FRONTIER] + void unrenderStrategicArea(AIStrategicArea*); void unrenderAllStrategicAreas(); void unrenderPatrolPath(PatrolPath*); void unrenderAllPatrolPaths(); @@ -192,8 +198,8 @@ class AIRenderUtil private: /* +0x00 */ std::vector m_sensingLine; // rebuilt from scratch by every addSensingLine - /* +0x0C */ std::vector m_text; // [UNRESOLVED] role - only the destructor - // which releases each string, proves the type + /* +0x0C */ std::vector m_text; // the 2D text lines setCoordinate and + // renderStrategies rebuild /* +0x18 */ std::vector m_botPrimitives; // indexed by Bot::getBotId /* +0x24 */ std::vector m_strategicAreaPrimitives; /* +0x30 */ std::vector m_landingZonePrimitives; @@ -202,8 +208,8 @@ class AIRenderUtil /* +0x54 */ std::vector m_coverPositionPrimitives; // The five loose handles, named by the delete slot each goes to. - /* +0x60 */ DrawPrimitive* m_text2dA; // delete2dText, from unrenderAll - /* +0x64 */ DrawPrimitive* m_text2dB; // delete2dText, from unrenderAll + /* +0x60 */ DrawPrimitive* m_text2dA; // setCoordinate's text; delete2dText, from unrenderAll + /* +0x64 */ DrawPrimitive* m_text2dB; // renderStrategies' text; delete2dText, from unrenderAll /* +0x68 */ DrawPrimitive* m_pathCircleA; // deleteCircle, from unrendenderPathfindingDebug /* +0x6C */ DrawPrimitive* m_pathCircleB; // deleteCircle, from unrendenderPathfindingDebug /* +0x70 */ DrawPrimitive* m_pathLine; // deleteLine, from unrendenderPathfindingDebug diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp new file mode 100644 index 000000000..4c182f110 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp @@ -0,0 +1,96 @@ +// World-space debug text meant to follow an AI object. Evidence: libaidll.so (ia-32) +// 0x36F5C0..0x36FB1F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x36FB20, __tcf_0 0x36FB80, _GLOBAL__I 0x36FBB0; the _GLOBAL__I symbol names this TU's +// DPAIObject3dText constructor, although the ledger files the three rows under CustomCurve.cpp). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../AIKnowledge/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x36F5C0 (C2; C1 0x36F640). m_bot is left unwritten. +DPAIObject3dText::DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x36F6C0 (C2; C1 0x36F740). m_bot is left unwritten. +DPAIObject3dText::DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x36F7C0 (D2; D1 0x36F800, D0 0x36F840). +DPAIObject3dText::~DPAIObject3dText() +{ +} + +// ELF 0x36F880. The position comes from the information's IAIObject, the type-3 transformation +// from the information itself (as DPDynamic3dText, translation added twice). +// shipped defect: the information is resolved through the unwritten m_bot. +bool DPAIObject3dText::draw(IDebugRenderer* renderer) +{ + Information* const information = informationManager->getInformation(m_bot->getCurrentEquipment()); + if (!information) + return false; + const Vec3& offset = information->getAIObject()->getPosition(); + Vec3 position; + position.x = m_position.x + offset.x; + position.y = m_position.y + offset.y; + position.z = m_position.z + offset.z; + switch (m_type) + { + case 0: + case 1: + case 2: + break; + case 3: + { + const Mat4& transformation = information->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + transformed.x = position.x * transformation.m[0] + position.y * transformation.m[4] + + position.z * transformation.m[8] + transformation.m[12]; + transformed.y = position.x * transformation.m[1] + position.y * transformation.m[5] + + position.z * transformation.m[9] + transformation.m[13]; + transformed.z = position.x * transformation.m[2] + position.y * transformation.m[6] + + position.z * transformation.m[10] + transformation.m[14]; + position = transformed; + position.x += transformation.m[12]; + position.y += transformation.m[13]; + position.z += transformation.m[14]; + break; + } + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp", 97, "") + << "Invalid type."; + break; + } + renderer->draw3dText(position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp new file mode 100644 index 000000000..a0bc09816 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp @@ -0,0 +1,96 @@ +// Debug circle that follows an AI object. Evidence: libaidll.so (ia-32) +// 0x36FBD0..0x37012F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x370080, __tcf_0 0x3700E0, _GLOBAL__I 0x370110). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../AIKnowledge/Information.h" +#include "../../AIKnowledge/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x36FBD0 (C2; C1 0x36FC40). +DPAIObjectCircle::DPAIObjectCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, DPDynamicTypes /*type*/, + const Vec3& normal, bool filled, int segments) + : DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments) + , m_information(information) +{ +} + +// ELF 0x36FCB0 (D2; D1 0x36FCF0, D0 0x36FD30). +DPAIObjectCircle::~DPAIObjectCircle() +{ +} + +// ELF 0x36FD70. DPDynamicCircle::draw over the information's IAIObject: the circle sits at +// m_position offset by the object's position; types 0 and 1 +// keep m_normal, 2 takes the transformation's third row and 3 its second row. An unknown type +// reports and draws with the zero centre and normal. +bool DPAIObjectCircle::draw(IDebugRenderer* renderer) +{ + Information* const information = informationManager->getInformation(m_information); + if (!information) + return false; + IAIObject* const object = information->getAIObject(); + + Vec3 normal = {0.0f, 0.0f, 0.0f}; + Vec3 centre = {0.0f, 0.0f, 0.0f}; + switch (m_type) + { + case 0: + case 1: + { + const Vec3& position = object->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + normal = m_normal; + break; + } + case 2: + { + const Vec3& position = object->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = object->getTransformation(); + normal.x = transformation.m[8]; + normal.y = transformation.m[9]; + normal.z = transformation.m[10]; + break; + } + case 3: + { + const Vec3& position = object->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = object->getTransformation(); + normal.x = transformation.m[4]; + normal.y = transformation.m[5]; + normal.z = transformation.m[6]; + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp", 73, "") + << "Invalid type."; + break; + } + renderer->drawCircle(normal, centre, m_radius, m_colour, m_filled, m_segments); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp new file mode 100644 index 000000000..6d737c986 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp @@ -0,0 +1,140 @@ +// Debug polyline that follows an AI object. Evidence: libaidll.so (ia-32) +// 0x370130..0x370C1F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x370B70, __tcf_0 0x370BD0, _GLOBAL__I 0x370C00). +#include + +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../AIKnowledge/Information.h" +#include "../../AIKnowledge/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x370130 (C2; C1 0x3701B0). +DPAIObjectLine::DPAIObjectLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, start, end, width) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x370230 (C2; C1 0x3702B0). +DPAIObjectLine::DPAIObjectLine(float lifeTime, unsigned int colour, const std::vector& points, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, points, width) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x370330 (D2; D1 0x3703B0, D0 0x370430). +DPAIObjectLine::~DPAIObjectLine() +{ +} + +// ELF 0x3704B0. DPDynamicLine::draw over the information's IAIObject (its position and +// transformation slots) instead of the information itself. Type 2 derives a yaw from the transformation's third row (x and z normalised by +// their absolute sum, acos of the clamped x, +-pi when z is negative) and rotates every point by +// it before adding the translation. Type 3 transforms every point and then adds the translation a +// second time (shipped defect, kept). An unknown type reports and draws the empty point list. +bool DPAIObjectLine::draw(IDebugRenderer* renderer) +{ + m_drawPoints.resize(0); + Information* const information = informationManager->getInformation(m_information); + if (!information) + return false; + IAIObject* const object = information->getAIObject(); + + switch (m_type) + { + case 0: + { + const Vec3& position = object->getPosition(); + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + Vec3 placed; + placed.x = point->x + position.x; + placed.y = point->y + position.y; + placed.z = point->z + position.z; + m_drawPoints.push_back(placed); + } + break; + } + case 1: + m_drawPoints.push_back(object->getPosition()); + m_drawPoints.insert(m_drawPoints.end(), m_points.begin(), m_points.end()); + break; + case 2: + { + const Mat4& transformation = object->getTransformation(); + Vec3 rotated = {0.0f, 0.0f, 0.0f}; + const float scale = 1.0f / (std::fabs(transformation.m[8]) + std::fabs(transformation.m[10])); + float x = transformation.m[8] * scale; + const float z = transformation.m[10] * scale; + if (x < -1.0f) + x = -1.0f; + else if (x > 1.0f) + x = 1.0f; + float angle = std::acos(x); + if (z < 0.0f) + { + if (angle < 0.0f) + angle -= 3.14159265f; + else + angle += 3.14159265f; + } + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + rotateXZ(*point, rotated, angle); + Vec3 placed; + placed.x = rotated.x + transformation.m[12]; + placed.y = rotated.y + transformation.m[13]; + placed.z = rotated.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 3: + { + const Mat4& transformation = object->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + transformed.x = point->x * transformation.m[0] + point->y * transformation.m[4] + + point->z * transformation.m[8] + transformation.m[12]; + transformed.y = point->x * transformation.m[1] + point->y * transformation.m[5] + + point->z * transformation.m[9] + transformation.m[13]; + transformed.z = point->x * transformation.m[2] + point->y * transformation.m[6] + + point->z * transformation.m[10] + transformation.m[14]; + Vec3 placed; + placed.x = transformed.x + transformation.m[12]; + placed.y = transformed.y + transformation.m[13]; + placed.z = transformed.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp", 124, "") + << "Invalid type."; + break; + } + renderer->drawLine(m_drawPoints, m_colour, m_width); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp new file mode 100644 index 000000000..f39c47626 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp @@ -0,0 +1,118 @@ +// World-space debug text that follows a bot's equipment or an information. Evidence: libaidll.so +// (ia-32) 0x371500..0x371D3F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x371C90, __tcf_0 0x371CF0, _GLOBAL__I 0x371D20). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../AIKnowledge/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x371500 (C2; C1 0x371580). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, Bot* bot, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x371600 (C2; C1 0x371680). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, Bot* bot, DPDynamicTypes type, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x371700 (C2; C1 0x371780). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x371800 (C2; C1 0x371880). +DPDynamic3dText::DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x371900 (D2; D1 0x371940, D0 0x371980). +DPDynamic3dText::~DPDynamic3dText() +{ +} + +// ELF 0x3719C0. The text sits at m_position offset by the information's position; types 0-2 use +// that directly, type 3 transforms it and then adds the translation a second time (shipped +// defect, kept). A negative or larger type reports and still draws. +bool DPDynamic3dText::draw(IDebugRenderer* renderer) +{ + Information* const information + = informationManager->getInformation(m_bot ? m_bot->getCurrentEquipment() : m_information); + // shipped defect: no null test before the virtual call. + const Vec3& offset = information->getPosition(); + Vec3 position; + position.x = m_position.x + offset.x; + position.y = m_position.y + offset.y; + position.z = m_position.z + offset.z; + switch (m_type) + { + case 0: + case 1: + case 2: + break; + case 3: + { + const Mat4& transformation = information->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + transformed.x = position.x * transformation.m[0] + position.y * transformation.m[4] + + position.z * transformation.m[8] + transformation.m[12]; + transformed.y = position.x * transformation.m[1] + position.y * transformation.m[5] + + position.z * transformation.m[9] + transformation.m[13]; + transformed.z = position.x * transformation.m[2] + position.y * transformation.m[6] + + position.z * transformation.m[10] + transformation.m[14]; + position = transformed; + position.x += transformation.m[12]; + position.y += transformation.m[13]; + position.z += transformation.m[14]; + break; + } + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp", 141, "") + << "Invalid type."; + break; + } + renderer->draw3dText(position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp new file mode 100644 index 000000000..fff96db50 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp @@ -0,0 +1,106 @@ +// Debug circle that follows a bot's equipment or an information. Evidence: libaidll.so (ia-32) +// 0x371D40..0x3723DF. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x372330, __tcf_0 0x372390, _GLOBAL__I 0x3723C0). +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../AIKnowledge/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x371D40 (C2; C1 0x371DC0). +DPDynamicCircle::DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, Bot* bot, DPDynamicTypes /*type*/, const Vec3& normal, + bool filled, int segments) + : DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments) + , m_bot(bot) + , m_information(0xFFFFFFFFu) +{ +} + +// ELF 0x371E40 (C2; C1 0x371EC0). +DPDynamicCircle::DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, DPDynamicTypes /*type*/, + const Vec3& normal, bool filled, int segments) + : DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments) + , m_bot(0) + , m_information(information) +{ +} + +// ELF 0x371F40 (D2; D1 0x371F80, D0 0x371FC0). +DPDynamicCircle::~DPDynamicCircle() +{ +} + +// ELF 0x372000. The circle sits at m_position offset by the information's position; types 0 and 1 +// keep m_normal, 2 takes the transformation's third row and 3 its second row. An unknown type +// reports and draws with the zero centre and normal. +bool DPDynamicCircle::draw(IDebugRenderer* renderer) +{ + Information* const information + = informationManager->getInformation(m_bot ? m_bot->getCurrentEquipment() : m_information); + if (!information) + return false; + + Vec3 normal = {0.0f, 0.0f, 0.0f}; + Vec3 centre = {0.0f, 0.0f, 0.0f}; + switch (m_type) + { + case 0: + case 1: + { + const Vec3& position = information->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + normal = m_normal; + break; + } + case 2: + { + const Vec3& position = information->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = information->getTransformation(); + normal.x = transformation.m[8]; + normal.y = transformation.m[9]; + normal.z = transformation.m[10]; + break; + } + case 3: + { + const Vec3& position = information->getPosition(); + centre.x = m_position.x + position.x; + centre.y = m_position.y + position.y; + centre.z = m_position.z + position.z; + const Mat4& transformation = information->getTransformation(); + normal.x = transformation.m[4]; + normal.y = transformation.m[5]; + normal.z = transformation.m[6]; + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp", 97, "") + << "Invalid type."; + break; + } + renderer->drawCircle(normal, centre, m_radius, m_colour, m_filled, m_segments); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp new file mode 100644 index 000000000..235508ae2 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp @@ -0,0 +1,161 @@ +// Debug polyline that follows a bot's equipment or an information. Evidence: libaidll.so (ia-32) +// 0x3723E0..0x37312F. Placement attested by the __FILE__ string +// "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp". + +#include "DPDynamicPrimitives.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x373080, __tcf_0 0x3730E0, _GLOBAL__I 0x373110). +#include + +#include + +#include "../../../../../Core/Debug.h" +#include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../../AIBot/BotMain.h" +#include "../../AIKnowledge/Information.h" +#include "../../AIKnowledge/InformationManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3723E0 (C2; C1 0x372470). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, Bot* bot, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, start, end, width) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x372600 (C2; C1 0x372690). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, start, end, width) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x372500 (C2; C1 0x372580). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, + float width, Bot* bot, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, points, width) + , m_bot(bot) + , m_information(0xFFFFFFFFu) + , m_type(type) +{ +} + +// ELF 0x372720 (C2; C1 0x3727A0). +DPDynamicLine::DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, + float width, unsigned int information, DPDynamicTypes type) + : DPStaticLine(lifeTime, colour, points, width) + , m_bot(0) + , m_information(information) + , m_type(type) +{ +} + +// ELF 0x372820 (D2; D1 0x3728A0, D0 0x372920). +DPDynamicLine::~DPDynamicLine() +{ +} + +// ELF 0x3729A0. Type 2 derives a yaw from the transformation's third row (x and z normalised by +// their absolute sum, acos of the clamped x, +-pi when z is negative) and rotates every point by +// it before adding the translation. Type 3 transforms every point and then adds the translation a +// second time (shipped defect, kept). An unknown type reports and draws the empty point list. +bool DPDynamicLine::draw(IDebugRenderer* renderer) +{ + m_drawPoints.resize(0); + Information* const information + = informationManager->getInformation(m_bot ? m_bot->getCurrentEquipment() : m_information); + if (!information) + return false; + + switch (m_type) + { + case 0: + { + const Vec3& position = information->getPosition(); + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + Vec3 placed; + placed.x = point->x + position.x; + placed.y = point->y + position.y; + placed.z = point->z + position.z; + m_drawPoints.push_back(placed); + } + break; + } + case 1: + m_drawPoints.push_back(information->getPosition()); + m_drawPoints.insert(m_drawPoints.end(), m_points.begin(), m_points.end()); + break; + case 2: + { + const Mat4& transformation = information->getTransformation(); + Vec3 rotated = {0.0f, 0.0f, 0.0f}; + const float scale = 1.0f / (std::fabs(transformation.m[8]) + std::fabs(transformation.m[10])); + float x = transformation.m[8] * scale; + const float z = transformation.m[10] * scale; + if (x < -1.0f) + x = -1.0f; + else if (x > 1.0f) + x = 1.0f; + float angle = std::acos(x); + if (z < 0.0f) + { + if (angle < 0.0f) + angle -= 3.14159265f; + else + angle += 3.14159265f; + } + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + rotateXZ(*point, rotated, angle); + Vec3 placed; + placed.x = rotated.x + transformation.m[12]; + placed.y = rotated.y + transformation.m[13]; + placed.z = rotated.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 3: + { + const Mat4& transformation = information->getTransformation(); + Vec3 transformed = {0.0f, 0.0f, 0.0f}; + for (std::vector::const_iterator point = m_points.begin(); point != m_points.end(); ++point) + { + transformed.x = point->x * transformation.m[0] + point->y * transformation.m[4] + + point->z * transformation.m[8] + transformation.m[12]; + transformed.y = point->x * transformation.m[1] + point->y * transformation.m[5] + + point->z * transformation.m[9] + transformation.m[13]; + transformed.z = point->x * transformation.m[2] + point->y * transformation.m[6] + + point->z * transformation.m[10] + transformation.m[14]; + Vec3 placed; + placed.x = transformed.x + transformation.m[12]; + placed.y = transformed.y + transformation.m[13]; + placed.z = transformed.z + transformation.m[14]; + m_drawPoints.push_back(placed); + } + break; + } + case 4: // [INFERRED] the jump table has a fifth entry that shares the default target + default: + Debug(DebugTypeError, "AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp", 160, "") + << "Invalid type."; + break; + } + renderer->drawLine(m_drawPoints, m_colour, m_width); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicPrimitives.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicPrimitives.h new file mode 100644 index 000000000..094734529 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicPrimitives.h @@ -0,0 +1,160 @@ +// Debug primitives that follow a bot's equipment or an AI object, drawn relative to it. +// Placement: each class's TU path is attested by its __FILE__ string +// (AI/AIDLL/AI/AIUtils/DebugRendering/DP*.cpp); this shared header name is [INFERRED]. + +#ifndef AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPDYNAMICPRIMITIVES_H +#define AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPDYNAMICPRIMITIVES_H + +#include +#include + +#include "../../DrawPrimitives/DPStatic3dText.h" +#include "../../DrawPrimitives/DPStaticCircle.h" +#include "../../DrawPrimitives/DPStaticLine.h" +#include "../../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// The DPDynamic* primitives resolve their information either through Bot::getCurrentEquipment +// (when constructed with a bot) or through a stored information handle (bot null). The +// DPAIObject* primitives resolve a stored information handle and use its IAIObject. The +// [UNRESOLVED] DPDynamicTypes values select how the stored geometry is placed: +// 0 offset by the position, 1 (line: prefix the position), 2 yaw-rotated about the +// transformation (circle: normal = third matrix row), 3 fully transformed (circle: second row). + +// sizeof == 0x44 on ia-32. +class DPDynamicCircle : public DPStaticCircle +{ +public: + // shipped defect: neither constructor stores `type`, so m_type is never initialised. + DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, Bot* bot, + DPDynamicTypes type, const Vec3& normal, bool filled, int segments); + DPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, + unsigned int information, DPDynamicTypes type, const Vec3& normal, bool filled, + int segments); + virtual ~DPDynamicCircle(); + + // Returns false once the information no longer resolves. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ Bot* m_bot; + /* +0x3C */ unsigned int m_information; + /* +0x40 */ DPDynamicTypes m_type; +}; + +// sizeof == 0x3C on ia-32. +class DPDynamicLine : public DPStaticLine +{ +public: + DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, float width, + Bot* bot, DPDynamicTypes type); + DPDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, float width, + unsigned int information, DPDynamicTypes type); + DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, float width, + Bot* bot, DPDynamicTypes type); + DPDynamicLine(float lifeTime, unsigned int colour, const std::vector& points, float width, + unsigned int information, DPDynamicTypes type); + virtual ~DPDynamicLine(); + + // Rebuilds m_drawPoints from m_points; returns false once the information no longer resolves. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x24 */ Bot* m_bot; + /* +0x28 */ unsigned int m_information; + /* +0x2C */ DPDynamicTypes m_type; + /* +0x30 */ std::vector m_drawPoints; +}; + +// sizeof == 0x44 on ia-32. +class DPDynamic3dText : public DPStatic3dText +{ +public: + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, + Bot* bot, DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, Bot* bot, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, + unsigned int information, DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + DPDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, AITextAlignmentY alignY); + virtual ~DPDynamic3dText(); + + // shipped defect: the information is not null-tested, so an unresolved one is dereferenced. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ Bot* m_bot; + /* +0x3C */ unsigned int m_information; + /* +0x40 */ DPDynamicTypes m_type; +}; + +// sizeof == 0x40 on ia-32. +class DPAIObjectCircle : public DPStaticCircle +{ +public: + // shipped defect: `type` is not stored, so m_type is never initialised. + DPAIObjectCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, + unsigned int information, DPDynamicTypes type, const Vec3& normal, bool filled, + int segments); + virtual ~DPAIObjectCircle(); + + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ unsigned int m_information; + /* +0x3C */ DPDynamicTypes m_type; +}; + +// sizeof == 0x38 on ia-32. +class DPAIObjectLine : public DPStaticLine +{ +public: + DPAIObjectLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width, unsigned int information, DPDynamicTypes type); + DPAIObjectLine(float lifeTime, unsigned int colour, const std::vector& points, float width, + unsigned int information, DPDynamicTypes type); + virtual ~DPAIObjectLine(); + + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x24 */ unsigned int m_information; + /* +0x28 */ DPDynamicTypes m_type; + /* +0x2C */ std::vector m_drawPoints; +}; + +// sizeof == 0x44 on ia-32. +class DPAIObject3dText : public DPStatic3dText +{ +public: + DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, + unsigned int information, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, AITextAlignmentY alignY); + virtual ~DPAIObject3dText(); + + // shipped defect: resolves its information through m_bot, which no constructor writes; + // m_information is stored but never read. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x38 */ Bot* m_bot; + /* +0x3C */ unsigned int m_information; + /* +0x40 */ DPDynamicTypes m_type; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPDYNAMICPRIMITIVES_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp new file mode 100644 index 000000000..70783d14a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp @@ -0,0 +1,84 @@ +// Debug graph primitive. Evidence: libaidll.so (ia-32) 0x373130..0x37348F. +// [INFERRED] Source placement. + +#include "DPGraph.h" + +#include "IBFGraph.h" + +#include "../../../../AIInterface/BFKnowledge/BFGraphCreator.h" +#include "../../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x373130 (C2; C1 0x373190). Colour 0. +DPGraph::DPGraph(float lifeTime) + : DrawPrimitive(lifeTime, 0) +{ + m_graph = static_cast(CommonSingletonServer::m_iBFGraphCreator)->createGraph(); +} + +// ELF 0x3731F0 (D2; D1 0x373240, D0 0x373290). +DPGraph::~DPGraph() +{ + static_cast(CommonSingletonServer::m_iBFGraphCreator)->destroyGraph(m_graph); +} + +// ELF 0x3732F0. +bool DPGraph::draw(IDebugRenderer* /*renderer*/) +{ + return true; +} + +// ELF 0x373300: m_graph slot 2 (BFGraph::setNumberOfSamples(int)). +void DPGraph::setNumberOfSamples(int samples) +{ + m_graph->setNumberOfSamples(samples); +} + +// ELF 0x373330: m_graph slot 3 (BFGraph::setDimensions(float, float, float, float)). +void DPGraph::setDimensions(float x, float y, float width, float height) +{ + m_graph->setDimensions(x, y, width, height); +} + +// ELF 0x373370: m_graph slot 4 (BFGraph::setColours(unsigned int, unsigned int, unsigned int)). +void DPGraph::setColours(unsigned int first, unsigned int second, unsigned int third) +{ + m_graph->setColours(first, second, third); +} + +// ELF 0x3733A0: m_graph slot 5 (BFGraph::setThresholds(float, float)). +void DPGraph::setThresholds(float low, float high) +{ + m_graph->setThresholds(low, high); +} + +// ELF 0x3733D0: m_graph slot 6 (BFGraph::setMinMaxY(float, float)). +void DPGraph::setMinMaxY(float minimum, float maximum) +{ + m_graph->setMinMaxY(minimum, maximum); +} + +// ELF 0x373400: m_graph slot 9 (BFGraph::addSample(float)). +void DPGraph::addSample(float sample) +{ + m_graph->addSample(sample); +} + +// ELF 0x373430: m_graph slot 7 (BFGraph::setCurrentSampleEnding(std::string const&)). +void DPGraph::setCurrentSampleEnding(const std::string& ending) +{ + m_graph->setCurrentSampleEnding(ending); +} + +// ELF 0x373460: m_graph slot 8 (BFGraph::setCurrentSampleOffset(int, int)). +void DPGraph::setCurrentSampleOffset(int x, int y) +{ + m_graph->setCurrentSampleOffset(x, y); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.h new file mode 100644 index 000000000..661ba8e47 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.h @@ -0,0 +1,45 @@ +// A timed debug graph backed by an engine IBFGraph. +// [INFERRED] Source placement (the TU is DPGraph.cpp; it links between the attested +// AIUtils/DebugRendering/DPDynamicLine.cpp and DPManager.cpp). + +#ifndef AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPGRAPH_H +#define AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPGRAPH_H + +#include + +#include "../../DrawPrimitives/DrawPrimitive.h" +#include "../../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x18 on ia-32. The graph is created through IBFGraphCreator in the constructor and +// destroyed through it in the destructor; every setter forwards to it. +class DPGraph : public DrawPrimitive +{ +public: + explicit DPGraph(float lifeTime); + virtual ~DPGraph(); + + // The engine graph draws itself; this only reports the primitive alive. + virtual bool draw(IDebugRenderer* renderer); + + void setNumberOfSamples(int samples); + void setDimensions(float x, float y, float width, float height); + void setColours(unsigned int first, unsigned int second, unsigned int third); + void setThresholds(float low, float high); + void setMinMaxY(float minimum, float maximum); + void addSample(float sample); + void setCurrentSampleEnding(const std::string& ending); + void setCurrentSampleOffset(int x, int y); + +protected: + /* +0x14 */ IBFGraph* m_graph; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_DPGRAPH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h new file mode 100644 index 000000000..7acea1c3e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h @@ -0,0 +1,37 @@ +// Engine debug-graph interface, as the AI DLL calls it through DPGraph. +// [CHOSEN, not recovered] Declared AIDLL-side because the engine-side AIInterface tree has no +// declaration yet; move it next to BFGraphCreator.h once that tree adds one. +// Evidence: bf2 (ia-32) vtable for dice::hfe::ai::BFGraph at 0x88DB320 (slots below, D1/D0 first) +// and IBFGraph at 0x88DB440 (all eight pure); names and parameter types from the BFGraph symbols. +// Return types [INFERRED] void: the engine bodies only forward to an inner object, and every DLL +// call site (DPGraph's setters) discards the result register. + +#ifndef AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_IBFGRAPH_H +#define AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_IBFGRAPH_H + +#include + +namespace dice { +namespace hfe { +namespace ai { + +class IBFGraph +{ +public: + virtual ~IBFGraph() {} + + virtual void setNumberOfSamples(int samples) = 0; // slot 2 + virtual void setDimensions(float x, float y, float width, float height) = 0; // slot 3 + virtual void setColours(unsigned int first, unsigned int second, unsigned int third) = 0; // 4 + virtual void setThresholds(float low, float high) = 0; // slot 5 + virtual void setMinMaxY(float minimum, float maximum) = 0; // slot 6 + virtual void setCurrentSampleEnding(const std::string& ending) = 0; // slot 7 + virtual void setCurrentSampleOffset(int x, int y) = 0; // slot 8 + virtual void addSample(float sample) = 0; // slot 9 +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_DEBUGRENDERING_IBFGRAPH_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp new file mode 100644 index 000000000..3a801c4ca --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.cpp @@ -0,0 +1,32 @@ +// Aimer singleton registration. [INFERRED] Source placement. + +#include "IAimerHelper.h" + +#include "../../../../Core/ClassManager.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { + +extern ClassManager* classManager; + +namespace ai { + +// ELF 0x2EAA00 (C1; C2 0x2EA960). +IAimerHelper::IAimerHelper() +{ + // shipped defect: the cached singleton is looked up as "AimerHelper", not this name. + if (!CommonSingletonServer::m_iAimerHelper) + classManager->registerSimpleSingleton("IAimerHelper", this); +} + +// ELF 0x2EAB30 (D1; D2 0x2EAAA0, D0 0x2EABC0). +IAimerHelper::~IAimerHelper() +{ + if (CommonSingletonServer::m_iAimerHelper == this) + classManager->unregisterSimpleSingleton("IAimerHelper"); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h new file mode 100644 index 000000000..8b711b8f7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IAimerHelper.h @@ -0,0 +1,35 @@ +// Abstract registered aimer interface. [INFERRED] Source placement beside AimerHelper. + +#ifndef AI_AIDLL_AI_AIUTILS_IAIMERHELPER_H +#define AI_AIDLL_AI_AIUTILS_IAIMERHELPER_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class IAimerHelper +{ +public: + IAimerHelper(); + virtual ~IAimerHelper(); + + // [CHOSEN, not recovered] Name, pointer spellings/constness and byte return under + // the unimplemented-slot exception. Pure in IAimerHelper/AimerHelper vtables + // ia-32 ELF 0x4BE8E8/0x4BE8C0, amd-64 0x61D160/0x61D120, slot 2 (+0x08/+0x10). + // The sole caller is engine BFObjectEnvironment::hasIndirectLineOfFire: + // ia-32 0x8402408 passes stack this, &exitVelocity, &drag, &scaledGravity, + // &delta, &weaponPosition, &target, &velocity, &apex, then tests al at 0x840240D. + // amd-64 0x771752: rdi=this; rsi/rdx/rcx/r8/r9 are the first five addresses, + // the three output addresses are on the stack; al is tested at 0x771757. + // No AI-image call or concrete override exists. This is not the by-value-float slot 3. + virtual unsigned char unimplementedAimerSlot2(const float*, const float*, const float*, + const Vec3*, const Vec3*, Vec3*, Vec3*, Vec3*) = 0; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp new file mode 100644 index 000000000..84c8496cd --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp @@ -0,0 +1,33 @@ +// Recovered from libaidll.so 1.5.3153 (0x2EA000..0x2EA0A1). + +#include "IgnoreListPredicate.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x2EA0B0, __tcf_0 0x2EA110, _GLOBAL__I 0x2EA140). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x2EA000 / 0x2EA030: the vptr, then the list's address at +4. +IgnoreListPredicate::IgnoreListPredicate(std::vector& ignore) + : m_ignore(&ignore) +{ +} + +// ELF 0x2EA060. Index walk; the size is read once, the data pointer on every step. +bool IgnoreListPredicate::predicate(IAIObject* object) +{ + const unsigned int count = static_cast(m_ignore->size()); + for (unsigned int i = 0; i < count; ++i) + { + if (object == (*m_ignore)[i]) + return false; + } + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h new file mode 100644 index 000000000..902233b99 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/IgnoreListPredicate.h @@ -0,0 +1,31 @@ +// Object predicate that rejects the objects of a borrowed ignore list (line-of-fire and aiming +// traces). ELF: vtable 0x4BE8A8 (base AIObjectPredicate, one slot), ctor C1/C2 0x2EA000/0x2EA030, +// predicate 0x2EA060; attested FILE symbol IgnoreListPredicate.cpp (directory [INFERRED]). +#ifndef AI_AIDLL_AI_AIUTILS_IGNORELISTPREDICATE_H +#define AI_AIDLL_AI_AIUTILS_IGNORELISTPREDICATE_H + +#include + +#include "../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate + +namespace dice { +namespace hfe { +namespace ai { + +class IgnoreListPredicate : public AIObjectPredicate +{ +public: + explicit IgnoreListPredicate(std::vector& ignore); + + // False for an object in the list, true otherwise. + virtual bool predicate(IAIObject* object); + +private: + /* +0x04 */ std::vector* m_ignore; // borrowed; the constructor stores the address +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp new file mode 100644 index 000000000..dd07ba62f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.cpp @@ -0,0 +1,153 @@ +// Opening visibility queries. [INFERRED] Source placement. + +// static init: ELF 0x3686D0 (__tcf_0 0x368730, _GLOBAL__I 0x368760): 's Init object only. +#include + +#include "Opening.h" + +#include "../../../AIInterface/BFKnowledge/PlanePolygon.h" + +#include +#include +#include + +namespace dice { +namespace hfe { +namespace ai { + +namespace { + +// [CHOSEN, not recovered] Local factoring of the inline Vec2 normalization at ELF 0x368574..0x3685C3. +void normalizeOpeningNormal(Vec2& normal) +{ + const float lengthSqr = normal.x * normal.x + normal.y * normal.y; + if (std::fabs(lengthSqr - 1.0f) < 1.1920929e-07f) + return; + if (std::fabs(lengthSqr) < 1.4210855e-14f) + { + normal.x = normal.y = 0.0f; + return; + } + const float inverse = 1.0f / std::sqrt(lengthSqr); + normal.x *= inverse; + normal.y *= inverse; +} + +} // namespace + +// ELF 0x367AA0 (amd-64 0x39EF90). +bool Opening::spot(Vec2& origin, Vec2& towards, std::list* path, + std::list* openings, IPlanePolygon& polygon, Vec3& targetPosition) +{ + Vec2 position = {0.0f, 0.0f}; + Vec2 unused = {0.0f, 0.0f}; + Vec2 clipped = {0.0f, 0.0f}; + vec3ToVec2XZ(m_position, position); + const Vec3 delta = {targetPosition.x - m_position.x, targetPosition.y - m_position.y, + targetPosition.z - m_position.z}; + vec3ToVec2XZ(delta, unused); + for (std::list::iterator it = openings->begin(); it != openings->end(); ++it) + { + if ((*it)->isInside(origin, towards, clipped)) + { + // shipped defect: searches the same list being traversed, rather than path. + if (std::find(openings->begin(), openings->end(), *it) != openings->end()) + return true; + } + else + { + if (!polygon.intersects(clipped, position)) + return false; + bool rejected = false; + for (std::list::iterator p = path->begin(); p != path->end(); ++p) + { + // shipped defect: repeatedly tests *it, never the path entry *p. + if (!(*it)->isInside(origin, towards, clipped)) + { + rejected = true; + break; + } + } + if (rejected) + continue; + } + path->insert(path->begin(), *it); + if ((*it)->spot(origin, towards, path, openings, polygon, targetPosition)) + return true; + path->erase(path->begin()); + } + return false; +} + +// ELF 0x367EE0 (amd-64 0x39F1F0). +std::list* Opening::spotAll(Vec2& origin, Vec2& first, Vec2& second, + std::list* path, std::list* openings, IPlanePolygon& polygon, Vec3& targetPosition) +{ + Vec2 position = {0.0f, 0.0f}; + Vec2 unused = {0.0f, 0.0f}; + Vec2 clippedFirst = {0.0f, 0.0f}; + Vec2 clippedSecond = {0.0f, 0.0f}; + vec3ToVec2XZ(m_position, position); + std::list* const result = new std::list(); + const Vec3 delta = {targetPosition.x - m_position.x, targetPosition.y - m_position.y, + targetPosition.z - m_position.z}; + vec3ToVec2XZ(delta, unused); + for (std::list::iterator it = openings->begin(); it != openings->end(); ++it) + { + const bool firstInside = (*it)->isInside(origin, first, clippedFirst); + const bool secondInside = (*it)->isInside(origin, second, clippedSecond); + if (!firstInside) + { + if (!polygon.intersects(clippedFirst, position)) + return result; + for (std::list::iterator p = path->begin(); p != path->end(); ++p) + { + // shipped defect: tests the current opening instead of the path entry. + if (!(*it)->isInside(origin, first, clippedFirst)) + return result; + } + } + else + clippedFirst = first; + if (secondInside) + clippedSecond = second; + // shipped defect: searches openings, not path, just as spot does. + if (std::find(openings->begin(), openings->end(), *it) != openings->end()) + { + result->insert(result->end(), clippedFirst); + result->insert(result->end(), clippedSecond); + } + else + { + path->insert(path->begin(), *it); + std::list* const child = (*it)->spotAll(origin, clippedFirst, clippedSecond, + path, openings, polygon, targetPosition); + std::copy(child->begin(), child->end(), std::inserter(*result, result->begin())); + // shipped defect: the recursive result list and its nodes are not deleted. + path->erase(path->begin()); + } + } + return result; +} + +// ELF 0x368510 (amd-64 0x39EDC0). +bool Opening::isInside(Vec2& origin, Vec2& towards, Vec2& clipped) +{ + const Vec2 delta = {towards.x - origin.x, towards.y - origin.y}; + Vec2 normal = {-delta.y, delta.x}; + normalizeOpeningNormal(normal); + // The endpoints are dotted directly; origin is not subtracted from them. + const float firstDot = normal.x * m_first.x + normal.y * m_first.y; + const float secondDot = normal.x * m_second.x + normal.y * m_second.y; + if ((firstDot >= 0.0f && secondDot < 0.0f) || (firstDot < 0.0f && secondDot > 0.0f)) + { + clipped = towards; + return true; + } + clipped = firstDot > secondDot ? m_second : m_first; + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h new file mode 100644 index 000000000..e0bd164fa --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/Opening.h @@ -0,0 +1,63 @@ +// Opening visibility queries. [INFERRED] Source placement; no construction path is emitted. + +#ifndef AI_AIDLL_AI_AIUTILS_OPENING_H +#define AI_AIDLL_AI_AIUTILS_OPENING_H + +#include "../../../../Math/Vec3.h" + +#include +#include +#include + +namespace dice { +namespace hfe { + +class IPlanePolygon; + +namespace ai { + +class Opening +{ +public: + bool spot(Vec2& origin, Vec2& towards, std::list* path, std::list* openings, + IPlanePolygon& polygon, Vec3& targetPosition); + // Returns a newly allocated list owned by the caller; recursive intermediate lists leak as shipped. + std::list* spotAll(Vec2& origin, Vec2& first, Vec2& second, std::list* path, + std::list* openings, IPlanePolygon& polygon, Vec3& targetPosition); + bool isInside(Vec2& origin, Vec2& towards, Vec2& clipped); + + // [CHOSEN, not recovered] Unaccessed storage under AGENTS.md's member exception. + // No vtable/constructor/writer exists in either ELF. Only spot 0x367AA0 / amd-64 + // 0x39EF90, spotAll 0x367EE0 / 0x39F1F0 and isInside 0x368510 / 0x39EDC0 + // access this type; their object reads start at endpoints +0x04/+0x0C and position +0x1C. + // Their outputs and list nodes are distinct from the object prefix. Neighbouring Vec2 + // floats establish four-byte field alignment; no source-level prefix type is attested. + alignas(float) unsigned char m_unaccessedPrefix[4]; +#if INTPTR_MAX == INT64_MAX + // [PLATFORM] [UNRESOLVED] amd-64's unaccessed prefix is sixteen bytes, not four. + // [CHOSEN, not recovered] Extra native storage preserves its observed field offsets; + // it does not guess a container, pointer or original member type/alignment. + unsigned char m_nativeUnresolvedPrefix[12]; +#endif + /* +0x04 */ Vec2 m_first; // [INFERRED] endpoint names; amd-64 +0x10 + /* +0x0C */ Vec2 m_second; // amd-64 +0x18 + // [CHOSEN, not recovered] The eight bytes between endpoints and position are also unaccessed. + /* +0x14 */ unsigned char m_unaccessedBetween[8]; // amd-64 +0x20 + /* +0x1C */ Vec3 m_position; // [INFERRED] name; amd-64 +0x28 +}; + +#if INTPTR_MAX == INT32_MAX +static_assert(offsetof(Opening, m_first) == 0x04, "Opening ia-32 first endpoint"); +static_assert(offsetof(Opening, m_second) == 0x0C, "Opening ia-32 second endpoint"); +static_assert(offsetof(Opening, m_position) == 0x1C, "Opening ia-32 position"); +#elif INTPTR_MAX == INT64_MAX +static_assert(offsetof(Opening, m_first) == 0x10, "Opening native first endpoint"); +static_assert(offsetof(Opening, m_second) == 0x18, "Opening native second endpoint"); +static_assert(offsetof(Opening, m_position) == 0x28, "Opening native position"); +#endif + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp new file mode 100644 index 000000000..78087f7dc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.cpp @@ -0,0 +1,43 @@ +// Pathfinding trace helpers. Evidence: libaidll.so 1.5.3153 (ia-32), see TraceUtils.h. + +#include "TraceUtils.h" + +#include "../Main/IAIPathfinding.h" + +#include + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x36AD90, __tcf_0 0x36ADF0, _GLOBAL__I 0x36AE20). +#include + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x36AC90. The circle point is centre + rotated * radius with +// rotated = (d.x * cos - d.y * sin, 0, d.z * cos + d.z * sin) +// as compiled: the y component stays at its zero initialisation and the x/z terms do not form a +// rotation about Y (shipped defect, kept). The trace runs on map `map` from `from` to that point +// (IAIPathfinding +0x88: arguments 1, -1, 0.0f, 0, null; the polygon out-value is discarded). +// [PLATFORM] retail keeps the products and sums in x87 extended precision. +bool TraceUtils::tracePointOnCircle(const Vec3& direction, const Vec3& centre, const Vec3& from, int map, + float angle, float radius, Vec3& point) +{ + Vec3 target; + target.x = 0.0f; + target.y = 0.0f; + target.z = 0.0f; + const float sine = std::sin(angle); + const float cosine = std::cos(angle); + const float rotatedX = direction.x * cosine - direction.y * sine; + const float rotatedZ = direction.z * cosine + direction.z * sine; + target.x = rotatedX * radius + centre.x; + target.y = radius * target.y + centre.y; + target.z = rotatedZ * radius + centre.z; + unsigned int polygon; + return IAIPathfinding::instance->trace(map, from, target, point, polygon, 1, -1, 0.0f, 0, 0); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h new file mode 100644 index 000000000..0ecc1bdc7 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/TraceUtils.h @@ -0,0 +1,29 @@ +// Pathfinding trace helpers of the AI image. +// Evidence: libaidll.so 1.5.3153 (ia-32), FILE symbol TraceUtils.cpp; the AIUtils directory and +// the class form of TraceUtils (the mangled name fits a class with static members as well as a +// namespace) are [INFERRED]. + +#ifndef AI_AIDLL_AI_AIUTILS_TRACEUTILS_H // [INFERRED] guard style +#define AI_AIDLL_AI_AIUTILS_TRACEUTILS_H + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +class TraceUtils +{ +public: + // Rotates `direction` by `angle` (see the body for the shipped formula), scales it by `radius` + // around `centre` and traces the pathfinding map `map` from `from` to that point; `point` + // receives the trace's end. Returns the trace's answer. + static bool tracePointOnCircle(const Vec3& direction, const Vec3& centre, const Vec3& from, int map, + float angle, float radius, Vec3& point); +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_TRACEUTILS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp index 3332f4efd..e46d325c0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp @@ -1,9 +1,15 @@ // [INFERRED] path/name; see VehicleOccupancy.h. Full instructions read from // libaidll.so and AIDLL_w32ded.dll . #include "VehicleOccupancy.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x36CE90, __tcf_0 0x36CEF0, _GLOBAL__I 0x36CF20). +#include #include "../AIKnowledge/Information.h" #include "../AIKnowledge/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" namespace dice { namespace hfe { namespace ai { @@ -68,4 +74,97 @@ bool vehicleOccupied(unsigned int handle, int side) return false; } +// ELF 0x36CAB0: a primary occupation/booking decides immediately; otherwise inspect the +// secondary objects until a squad match. The resolved primary is deliberately unchecked. +int vehicleOccupiedBySquadMember(unsigned int handle, SquadMember* member, int side) +{ + int result = -1; + SquadManager* const squads = SquadManager::m_instance; + Information* const original = informationManager->getInformation(handle); + if (!original) + return result; + Information* primary = original; + if (!original->isPrimary()) + { + InformationManager* const manager = informationManager; + const unsigned int primaryHandle = original->getPrimaryObject(side); + primary = manager->getInformation(primaryHandle); + } + IPIUnit* unit = primary->getUnit(); + if (!unit) + return result; + if (unit->isOccupied()) + { + const unsigned int occupierHandle = unit->getOccupier(side); + Information* const occupier = informationManager->getInformation(occupierHandle); + if (occupier && occupier->getSide() == side) + { + const int playerId = unit->getOccupyingPlayerId(side); + SquadMember* const occupyingMember = squads->getSquadMember(playerId, side); + if (!occupyingMember) + return 0; + const int ownPlayerId = member->getPlayerId(); + if (ownPlayerId != occupyingMember->getPlayerId()) + { + const int ownSquadId = member->getSquadId(); + return ownSquadId == occupyingMember->getSquadId() ? 1 : 0; + } + } + } + else if (original->isBooked()) + { + const int playerId = original->getBookingPlayerId(); + SquadMember* const bookingMember = squads->getSquadMember(playerId, side); + if (bookingMember) + { + const int ownSquadId = member->getSquadId(); + return ownSquadId == bookingMember->getSquadId() ? 1 : 0; + } + } + + int iterator; + InformationManager* manager = informationManager; + const unsigned int firstHandle = primary->getFirstSecondaryObject(iterator, side); + Information* secondary = manager->getInformation(firstHandle); + while (secondary && result != 1) + { + unit = secondary->getUnit(); + if (unit && unit->isOccupied()) + { + const unsigned int occupierHandle = unit->getOccupier(side); + Information* const occupier = informationManager->getInformation(occupierHandle); + if (occupier && occupier->getSide() == side) + { + const int playerId = unit->getOccupyingPlayerId(side); + SquadMember* const occupyingMember = squads->getSquadMember(playerId, side); + if (!occupyingMember) + result = 0; + else + { + const int ownPlayerId = member->getPlayerId(); + if (ownPlayerId != occupyingMember->getPlayerId()) + { + const int ownSquadId = member->getSquadId(); + result = ownSquadId == occupyingMember->getSquadId() ? 1 : 0; + } + } + } + } + else if (secondary->isBooked()) + { + const int playerId = secondary->getBookingPlayerId(); + SquadMember* const bookingMember = squads->getSquadMember(playerId, side); + if (bookingMember) + { + const int ownSquadId = member->getSquadId(); + result = ownSquadId == bookingMember->getSquadId() ? 1 : 0; + } + } + manager = informationManager; + const unsigned int nextHandle = primary->getSecondaryObject(iterator, side); + secondary = manager->getInformation(nextHandle); + } + return result; +} + } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h index 2cf7d859f..a06f4045a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h @@ -6,8 +6,14 @@ namespace dice { namespace hfe { namespace ai { +class SquadMember; + // Parameter types/namespace from the ELF mangled name; Boolean materialized in both ports. bool vehicleOccupied(unsigned int handle, int side); +// Returns 1 for another member of the same squad, 0 for another squad or an unassigned +// occupier, and -1 when no qualifying occupation or booking was found. +int vehicleOccupiedBySquadMember(unsigned int handle, SquadMember* member, int side); + } } } #endif diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp index 651742134..2dc4cdd36 100644 --- a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp @@ -1,12 +1,30 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining DPManager operations. - #include "DPManager.h" +// 's ios_base::Init object is the static initialisation and teardown of DPManager.cpp +// (ELF 0x3797D0, __tcf_0 0x379830, _GLOBAL__I 0x379860). The four interface constructors below +// were separate TUs in retail (file symbols IDPAIObjectCreator.cpp, IDPDynamicCreator.cpp, +// IDPManager.cpp, IDPStaticCreator.cpp), each with the same Init object: 0x381640/0x3816A0/ +// 0x3816D0, 0x3819F0/0x381A50/0x381A80, 0x381DA0/0x381E00/0x381E30, 0x382150/0x3821B0/0x3821E0. +// [INFERRED] keeping them in this TU. +#include + #include #include "../../../../Core/ClassManager.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIMain.h" #include "../Main/CommonSingletonServer.h" #include "../Main/AIDllFrontier.h" +#include "../AIUtils/DebugRendering/DPDynamicPrimitives.h" +#include "DPStatic2dText.h" +#include "DPStatic3dText.h" +#include "DPStaticCircle.h" +#include "DPStaticLine.h" +#include "DPStaticMesh.h" +#include "DPStaticPolygon.h" +#include "DPStaticTriangle.h" namespace dice { namespace hfe { @@ -82,264 +100,693 @@ DPManager::~DPManager() { } -int DPManager::deleteCircle(DrawPrimitive *&) +// The delete*, get*Attributes and set*Attributes slots share one shape: the handle is looked up in +// that kind's map with find(); an unknown handle answers 0 (or does nothing in the void slots). + +// ELF 0x374260. A known handle deletes the value through its deleting destructor (null-tested), +// erases the node, nulls the caller's handle and answers 1. +int DPManager::deleteCircle(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteCircle"); + std::map::iterator found = m_circles.find(primitive); + if (found == m_circles.end()) + return 0; + delete found->second; + m_circles.erase(found); + primitive = 0; + return 1; } -int DPManager::getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) +// ELF 0x374320. +int DPManager::getCircleAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + Vec3 & position, float & radius, Vec3 & normal, bool & filled, + int & segments) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getCircleAttributes"); + std::map::const_iterator found = m_circles.find(primitive); + if (found == m_circles.end()) + return 0; + found->second->getAttributes(lifeTime, colour, position, radius, normal, filled, segments); + return 1; } -int DPManager::setCircleAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, float, const Vec3&, bool, int) +// ELF 0x3743C0. DPStaticCircle::setAttributes takes the position by value; the copy is made here. +int DPManager::setCircleAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const Vec3& position, float radius, const Vec3& normal, + bool filled, int segments) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setCircleAttributes"); + std::map::iterator found = m_circles.find(primitive); + if (found == m_circles.end()) + return 0; + found->second->setAttributes(lifeTime, colour, position, radius, normal, filled, segments); + return 1; } -int DPManager::deleteLine(DrawPrimitive *&) +// ELF 0x374480. +int DPManager::deleteLine(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteLine"); + std::map::iterator found = m_lines.find(primitive); + if (found == m_lines.end()) + return 0; + delete found->second; + m_lines.erase(found); + primitive = 0; + return 1; } -int DPManager::getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) +// ELF 0x374540. +int DPManager::getLineAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + std::vector & points, float & width) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getLineAttributes"); + std::map::const_iterator found = m_lines.find(primitive); + if (found == m_lines.end()) + return 0; + found->second->getAttributes(lifeTime, colour, points, width); + return 1; } -int DPManager::setLineAttributes(DrawPrimitive *, float, unsigned int, const std::vector&, float) +// ELF 0x3745C0. DPStaticLine::setAttributes takes references, so the by-value arguments are passed +// by address. +int DPManager::setLineAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const std::vector& points, float width) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setLineAttributes"); + std::map::iterator found = m_lines.find(primitive); + if (found == m_lines.end()) + return 0; + found->second->setAttributes(lifeTime, colour, points, width); + return 1; } -int DPManager::delete2dText(DrawPrimitive *&) +// ELF 0x374640. +int DPManager::delete2dText(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::delete2dText"); + std::map::iterator found = m_text2d.find(primitive); + if (found == m_text2d.end()) + return 0; + delete found->second; + m_text2d.erase(found); + primitive = 0; + return 1; } -int DPManager::get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) +// ELF 0x374700. +int DPManager::get2dTextAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + Vec2 & position, std::vector & lines, int & size, + AITextAlignmentX & alignX, AITextAlignmentY & alignY) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::get2dTextAttributes"); + std::map::const_iterator found = m_text2d.find(primitive); + if (found == m_text2d.end()) + return 0; + found->second->getAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::set2dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x3747A0. +int DPManager::set2dTextAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const Vec2& position, const std::vector& lines, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::set2dTextAttributes"); + std::map::iterator found = m_text2d.find(primitive); + if (found == m_text2d.end()) + return 0; + found->second->setAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::delete3dText(DrawPrimitive *&) +// ELF 0x374840. +int DPManager::delete3dText(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::delete3dText"); + std::map::iterator found = m_text3d.find(primitive); + if (found == m_text3d.end()) + return 0; + delete found->second; + m_text3d.erase(found); + primitive = 0; + return 1; } -int DPManager::get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) +// ELF 0x374900. +int DPManager::get3dTextAttributes(DrawPrimitive * primitive, float & lifeTime, unsigned int & colour, + Vec3 & position, std::vector & lines, int & size, + AITextAlignmentX & alignX, AITextAlignmentY & alignY) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::get3dTextAttributes"); + std::map::const_iterator found = m_text3d.find(primitive); + if (found == m_text3d.end()) + return 0; + found->second->getAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::set3dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x3749A0. +int DPManager::set3dTextAttributes(DrawPrimitive * primitive, float lifeTime, unsigned int colour, + const Vec3& position, const std::vector& lines, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::set3dTextAttributes"); + std::map::iterator found = m_text3d.find(primitive); + if (found == m_text3d.end()) + return 0; + found->second->setAttributes(lifeTime, colour, position, lines, size, alignX, alignY); + return 1; } -int DPManager::deleteTriangle(DrawPrimitive *&) +// ELF 0x374A40. +int DPManager::deleteTriangle(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteTriangle"); + std::map::iterator found = m_triangles.find(primitive); + if (found == m_triangles.end()) + return 0; + delete found->second; + m_triangles.erase(found); + primitive = 0; + return 1; } -int DPManager::getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) +// ELF 0x374B00. No result register is written on either path. +void DPManager::getTriangleAttributes(DrawPrimitive * primitive, float & lifeTime, + std::vector & vertices, + std::vector& colours, bool & filled) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getTriangleAttributes"); + std::map::const_iterator found = m_triangles.find(primitive); + if (found != m_triangles.end()) + found->second->getAttributes(lifeTime, vertices, colours, filled); } -int DPManager::setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &) +// ELF 0x374B80. +void DPManager::setTriangleAttributes(DrawPrimitive * primitive, float & lifeTime, + const std::vector& vertices, + const std::vector& colours, bool & filled) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setTriangleAttributes"); + std::map::iterator found = m_triangles.find(primitive); + if (found != m_triangles.end()) + found->second->setAttributes(lifeTime, vertices, colours, filled); } -int DPManager::deletePolygon(DrawPrimitive *&) +// ELF 0x374C00. +int DPManager::deletePolygon(DrawPrimitive *& primitive) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deletePolygon"); + std::map::iterator found = m_polygons.find(primitive); + if (found == m_polygons.end()) + return 0; + delete found->second; + m_polygons.erase(found); + primitive = 0; + return 1; } -int DPManager::getPolygonAttributes(DrawPrimitive *, float &, bool &) +// ELF 0x374CC0. +void DPManager::getPolygonAttributes(DrawPrimitive * primitive, float & lifeTime, bool & filled) const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getPolygonAttributes"); + std::map::const_iterator found = m_polygons.find(primitive); + if (found != m_polygons.end()) + found->second->getAttributes(lifeTime, filled); } -int DPManager::setPolygonAttributes(DrawPrimitive *, float &, bool &) +// ELF 0x374D30. +void DPManager::setPolygonAttributes(DrawPrimitive * primitive, float & lifeTime, bool & filled) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setPolygonAttributes"); + std::map::iterator found = m_polygons.find(primitive); + if (found != m_polygons.end()) + found->second->setAttributes(lifeTime, filled); } -// Deletes a known mesh and clears the caller's handle. An unknown handle returns false. -// [FRONTIER] Known mesh deletion requires DPStaticMesh destruction. +// ELF 0x374DA0. Deletes a known mesh and clears the caller's handle; an unknown handle returns false. bool DPManager::deleteMesh(DrawPrimitive *& primitive) { - const std::map::iterator found = m_meshes.find(primitive); + std::map::iterator found = m_meshes.find(primitive); if (found == m_meshes.end()) return false; - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteMesh [DPStaticMesh's destructor]"); + delete found->second; + m_meshes.erase(found); + primitive = 0; + return true; } -void DPManager::setTextGamma(float) +// ELF 0x374E60 +void DPManager::setTextGamma(float gamma) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::setTextGamma"); + m_textGamma = gamma; } -float DPManager::getTextGamma() +// ELF 0x374E70 +float DPManager::getTextGamma() const { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::getTextGamma"); + return m_textGamma; } -void DPManager::drawAll() -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::drawAll"); -} +namespace { -void DPManager::nodrawUpdate() +// [CHOSEN, not recovered] Helper names for the loops drawAll, nodrawUpdate and deleteAll repeat +// once per map; each instantiation is inlined into its caller as the shipped bodies show. +// A primitive goes when it has expired, or (when drawing) when draw() answers false. +template +inline void drawMap(Map& primitives, double now, IDebugRenderer* renderer) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::nodrawUpdate"); + for (typename Map::iterator it = primitives.begin(); it != primitives.end();) + { + if (it->second->expired(now) || !it->second->draw(renderer)) + { + delete it->second; + primitives.erase(it++); + } + else + ++it; + } } -int DPManager::deleteAll() +template +inline void updateMap(Map& primitives, double now) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::deleteAll"); + for (typename Map::iterator it = primitives.begin(); it != primitives.end();) + { + if (it->second->expired(now)) + { + delete it->second; + primitives.erase(it++); + } + else + ++it; + } } -DPStaticCircle * DPManager::createStaticCircle(float, unsigned int, const Vec3&, float, const Vec3&, bool, int) +template +inline void deleteMap(Map& primitives) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticCircle"); + for (typename Map::iterator it = primitives.begin(); it != primitives.end();) + { + delete it->second; + primitives.erase(it++); + } } -DPStaticLine * DPManager::createStaticLine(float, unsigned int, const Vec3&, const Vec3&, float) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticLine"); -} +} // namespace -int DPManager::createStaticLine(float, unsigned int, const std::vector&, float) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticLine"); -} - -DrawPrimitive * DPManager::createStatic2dText(float, unsigned int, const Vec2&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic2dText"); -} - -DrawPrimitive * DPManager::createStatic2dText(float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic2dText"); -} - -int DPManager::createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic3dText"); -} - -int DPManager::createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStatic3dText"); -} - -int DPManager::createStaticTriangle(float, const std::vector&, const std::vector&, bool) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticTriangle"); -} - -int DPManager::createStaticPolygon(float, const std::vector&, const std::vector&, bool) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticPolygon"); -} - -DPStaticMesh * DPManager::createStaticMesh(float, unsigned int *, Vec3 *, unsigned int *, int, bool) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticMesh"); -} - -int DPManager::createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool) +// ELF 0x374E80. Does nothing without an AI main. The renderer is read before the game time; the +// maps are walked circles, 2D text, 3D text, triangles, polygons, meshes, lines. +void DPManager::drawAll() { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createStaticMesh"); + if (!IAIMain::m_instance) + return; + IDebugRenderer* const renderer = static_cast(CommonSingletonServer::m_iDebugRenderer); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + drawMap(m_circles, now, renderer); + drawMap(m_text2d, now, renderer); + drawMap(m_text3d, now, renderer); + drawMap(m_triangles, now, renderer); + drawMap(m_polygons, now, renderer); + drawMap(m_meshes, now, renderer); + drawMap(m_lines, now, renderer); } -int DPManager::testStatics(Mat4 &) +// ELF 0x375550. drawAll's expiry sweep without drawing, in the same map order. +void DPManager::nodrawUpdate() { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::testStatics"); + if (!IAIMain::m_instance) + return; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + updateMap(m_circles, now); + updateMap(m_text2d, now); + updateMap(m_text3d, now); + updateMap(m_triangles, now); + updateMap(m_polygons, now); + updateMap(m_meshes, now); + updateMap(m_lines, now); } -DPStaticCircle * DPManager::createDPDynamicCircle(float, unsigned int, const Vec3&, float, Bot *, DPDynamicTypes, const Vec3&, bool, int) +// ELF 0x375B00. Every map is drained in this order - circles, 2D text, 3D text, triangles, +// polygons, meshes, lines - deleting each value and erasing its node. +void DPManager::deleteAll() { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDPDynamicCircle"); + deleteMap(m_circles); + deleteMap(m_text2d); + deleteMap(m_text3d); + deleteMap(m_triangles); + deleteMap(m_polygons); + deleteMap(m_meshes); + deleteMap(m_lines); } -DPStaticCircle * DPManager::createDPDynamicCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDPDynamicCircle"); -} +// The create* slots share one shape: operator new of the concrete primitive, checkPointer (the +// AIUtils/checkPointer.h report on a null result), insert (primitive, primitive) into that kind's +// map, return the primitive. A null result is still inserted; the insert follows the report. -DPStaticLine * DPManager::createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, Bot *, DPDynamicTypes) +// ELF 0x375F30 (sizeof 0x38). +DPStaticCircle * DPManager::createStaticCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, const Vec3& normal, bool filled, int segments) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStaticCircle* const circle = checkPointer( + new DPStaticCircle(lifeTime, colour, position, radius, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; } -DPStaticLine * DPManager::createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) +// ELF 0x376100 (sizeof 0x24). +DPStaticLine * DPManager::createStaticLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStaticLine* const line = checkPointer(new DPStaticLine(lifeTime, colour, start, end, width)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes) +// ELF 0x3762B0 (sizeof 0x24). +DrawPrimitive* DPManager::createStaticLine(float lifeTime, unsigned int colour, + const std::vector& points, float width) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStaticLine* const line = checkPointer(new DPStaticLine(lifeTime, colour, points, width)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) +// ELF 0x376450 (sizeof 0x34). +DrawPrimitive * DPManager::createStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamicLine"); + DPStatic2dText* const primitive = checkPointer( + new DPStatic2dText(lifeTime, colour, position, text, size, alignX, alignY)); + m_text2d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x376610 (sizeof 0x34). +DrawPrimitive * DPManager::createStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPStatic2dText* const primitive = checkPointer( + new DPStatic2dText(lifeTime, colour, position, lines, size, alignX, alignY)); + m_text2d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x3767D0 (sizeof 0x38). +DrawPrimitive* DPManager::createStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + DPStatic3dText* const primitive = checkPointer( + new DPStatic3dText(lifeTime, colour, position, text, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376990 (sizeof 0x38). +DrawPrimitive* DPManager::createStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + DPStatic3dText* const primitive = checkPointer( + new DPStatic3dText(lifeTime, colour, position, lines, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376B50 (sizeof 0x30). +DrawPrimitive* DPManager::createStaticTriangle(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) +{ + DPStaticTriangle* const primitive = checkPointer( + new DPStaticTriangle(lifeTime, vertices, colours, filled)); + m_triangles.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376D00 (sizeof 0x30). +DrawPrimitive* DPManager::createStaticPolygon(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) +{ + DPStaticPolygon* const primitive = checkPointer( + new DPStaticPolygon(lifeTime, vertices, colours, filled)); + m_polygons.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x376EB0 (sizeof 0x2C). +DPStaticMesh * DPManager::createStaticMesh(float lifeTime, unsigned int * colours, Vec3 * vertices, + unsigned int * indices, int count, bool filled) +{ + DPStaticMesh* const mesh = checkPointer( + new DPStaticMesh(lifeTime, colours, vertices, indices, count, filled)); + m_meshes.insert(std::make_pair(mesh, mesh)); + return mesh; +} + +// ELF 0x377070 (sizeof 0x2C). +DPStaticMesh * DPManager::createStaticMesh(float lifeTime, unsigned int * colours, Polygon * polygons, + Vec3 * vertices, unsigned int * indices, int count, + bool filled) +{ + DPStaticMesh* const mesh = checkPointer( + new DPStaticMesh(lifeTime, colours, polygons, vertices, indices, count, filled)); + m_meshes.insert(std::make_pair(mesh, mesh)); + return mesh; +} + +// ELF 0x377240. A demo of every static primitive kind at `transform`'s position, a tenth of a +// second each: a filled and an outlined circle of radius 5 facing up, a small circle 10 units +// along the third row facing along it, a line along the third row, the same line shifted a +// quarter unit along the first row as a point list (its end point pushed twice, shipped), and +// 2D and 3D text in both the line-list and single-string forms. Every call goes through this +// object's own virtual creators. Nothing is returned: the ia-32 body leaves eax unset, so the +// slot is void [INFERRED]. +void DPManager::testStatics(Mat4& transform) +{ + const float lifeTime = 0.1f; + float size = 10.0f; + const float width = 0.05f; + const Vec3& position = *reinterpret_cast(&transform.m[12]); + + Vec3 normal = {0.0f, 1.0f, 0.0f}; + const float radius = size * 0.5f; + createStaticCircle(lifeTime, 0xFF00FF00u, position, radius, normal, true, 255); + createStaticCircle(lifeTime, 0xFF00FF00u, position, radius, normal, false, 5); + + normal.x = transform.m[8]; + normal.y = transform.m[9]; + normal.z = transform.m[10]; + Vec3 end; + end.x = normal.x * size + position.x; + end.y = normal.y * size + position.y; + end.z = normal.z * size + position.z; + createStaticCircle(lifeTime, 0xFF00FF00u, end, radius / 20.0f, normal, false, 255); + + Vec3 start = position; + end.x = size * transform.m[8] + position.x; + end.y = size * transform.m[9] + position.y; + end.z = size * transform.m[10] + position.z; + createStaticLine(lifeTime, 0xFFFF0000u, start, end, width); + + std::vector points; + const float shiftX = width * transform.m[0] * 5.0f; + const float shiftY = width * transform.m[1] * 5.0f; + const float shiftZ = width * transform.m[2] * 5.0f; + start.x = start.x + shiftX; + start.y = start.y + shiftY; + start.z = start.z + shiftZ; + end.x = shiftX + end.x; + end.y = shiftY + end.y; + end.z = shiftZ + end.z; + points.push_back(start); + points.push_back(end); + points.push_back(end); + createStaticLine(lifeTime, 0xFFFF0000u, points, width + width); + + std::vector lines2d; + lines2d.push_back(std::string("Static 2D Text Demo")); + lines2d.push_back(std::string("Line 2")); + Vec2 screenPosition = {10.0f, 10.0f}; + createStatic2dText(lifeTime, 0xFFFFFF00u, screenPosition, lines2d, 5, + static_cast(0), static_cast(1)); + screenPosition.x = 40.0f; + screenPosition.y = 10.0f; + createStatic2dText(lifeTime, 0xFFFFFF00u, screenPosition, std::string("PureString"), 5, + static_cast(0), static_cast(1)); + + std::vector lines3d; + lines3d.push_back(std::string("Static 3D Text Demo")); + lines3d.push_back(std::string("Line 2")); + createStatic3dText(lifeTime, 0xFFFF00FFu, position, lines3d, 5, + static_cast(0), static_cast(1)); + const std::string pureString("PureString"); + size = size * 0.2f; + Vec3 textPosition; + textPosition.x = position.x; + textPosition.y = size + position.y; + textPosition.z = position.z; + createStatic3dText(lifeTime, 0xFFFF00FFu, textPosition, pureString, 5, + static_cast(0), static_cast(1)); +} + +// The dynamic and AI-object creators follow the static shape and file their primitive in the map +// of the static base: circles, lines or 3D text. + +// ELF 0x377D00 (sizeof 0x44). +DPStaticCircle * DPManager::createDPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, Bot * bot, DPDynamicTypes type, + const Vec3& normal, bool filled, int segments) +{ + DPDynamicCircle* const circle = checkPointer(new DPDynamicCircle( + lifeTime, colour, position, radius, bot, type, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; +} + +// ELF 0x377EE0 (sizeof 0x44). +DPStaticCircle * DPManager::createDPDynamicCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, + DPDynamicTypes type, const Vec3& normal, bool filled, + int segments) +{ + DPDynamicCircle* const circle = checkPointer(new DPDynamicCircle( + lifeTime, colour, position, radius, information, type, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; +} + +// ELF 0x3780C0 (sizeof 0x3C). +DPStaticLine * DPManager::createDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width, Bot * bot, DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, start, end, width, bot, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x378280 (sizeof 0x3C). +DPStaticLine * DPManager::createDynamicLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width, unsigned int information, + DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, start, end, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x378440 (sizeof 0x3C). +DrawPrimitive* DPManager::createDynamicLine(float lifeTime, unsigned int colour, + const std::vector& points, float width, Bot * bot, + DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, points, width, bot, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x3785F0 (sizeof 0x3C). +DrawPrimitive* DPManager::createDynamicLine(float lifeTime, unsigned int colour, + const std::vector& points, float width, + unsigned int information, DPDynamicTypes type) +{ + DPDynamicLine* const line = checkPointer( + new DPDynamicLine(lifeTime, colour, points, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; +} + +// ELF 0x3787A0 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, Bot * bot, DPDynamicTypes type, + int size, AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, text, bot, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; +} + +// ELF 0x378970 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, Bot * bot, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, lines, bot, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x378B40 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, text, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x378D10 (sizeof 0x44). +DrawPrimitive* DPManager::createDynamic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, + unsigned int information, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDynamic3dText"); + DPDynamic3dText* const primitive = checkPointer(new DPDynamic3dText( + lifeTime, colour, position, lines, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -DPStaticCircle * DPManager::createDPAIObjectCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) +// ELF 0x378EE0 (sizeof 0x40). +DPStaticCircle * DPManager::createDPAIObjectCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, unsigned int information, + DPDynamicTypes type, const Vec3& normal, bool filled, + int segments) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createDPAIObjectCircle"); + DPAIObjectCircle* const circle = checkPointer(new DPAIObjectCircle( + lifeTime, colour, position, radius, information, type, normal, filled, segments)); + m_circles.insert(std::make_pair(circle, circle)); + return circle; } -DPStaticLine * DPManager::createAIObjectLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) +// ELF 0x3790C0 (sizeof 0x38). +DPStaticLine * DPManager::createAIObjectLine(float lifeTime, unsigned int colour, const Vec3& start, + const Vec3& end, float width, unsigned int information, + DPDynamicTypes type) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObjectLine"); + DPAIObjectLine* const line = checkPointer( + new DPAIObjectLine(lifeTime, colour, start, end, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) +// ELF 0x379280 (sizeof 0x38). +DrawPrimitive* DPManager::createAIObjectLine(float lifeTime, unsigned int colour, + const std::vector& points, float width, + unsigned int information, DPDynamicTypes type) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObjectLine"); + DPAIObjectLine* const line = checkPointer( + new DPAIObjectLine(lifeTime, colour, points, width, information, type)); + m_lines.insert(std::make_pair(line, line)); + return line; } -int DPManager::createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x379430 (sizeof 0x44). +DrawPrimitive* DPManager::createAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, unsigned int information, + DPDynamicTypes type, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObject3dText"); + DPAIObject3dText* const primitive = checkPointer(new DPAIObject3dText( + lifeTime, colour, position, text, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } -int DPManager::createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) +// ELF 0x379600 (sizeof 0x44). +DrawPrimitive* DPManager::createAIObject3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, + unsigned int information, DPDynamicTypes type, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) { - BF2_AI_FRONTIER("dice::hfe::ai::DPManager::createAIObject3dText"); + DPAIObject3dText* const primitive = checkPointer(new DPAIObject3dText( + lifeTime, colour, position, lines, information, type, size, alignX, alignY)); + m_text3d.insert(std::make_pair(primitive, primitive)); + return primitive; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h index 0a8a9ccaa..b5161bd10 100644 --- a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPManager.h @@ -18,6 +18,11 @@ namespace dice { namespace hfe { namespace ai { +class DPStatic2dText; +class DPStatic3dText; +class DPStaticTriangle; +class DPStaticPolygon; + // Draw-manager interface. Registration guards the roster static, which may remain // stale until updateStaticMethods refreshes it. class IDPManager @@ -26,30 +31,30 @@ class IDPManager IDPManager(); virtual ~IDPManager(); virtual int deleteCircle(DrawPrimitive *&) = 0; - virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) = 0; + virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) const = 0; virtual int setCircleAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, float, const Vec3&, bool, int) = 0; virtual int deleteLine(DrawPrimitive *&) = 0; - virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) = 0; + virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) const = 0; virtual int setLineAttributes(DrawPrimitive *, float, unsigned int, const std::vector&, float) = 0; virtual int delete2dText(DrawPrimitive *&) = 0; - virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) = 0; + virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const = 0; virtual int set2dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; virtual int delete3dText(DrawPrimitive *&) = 0; - virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) = 0; + virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const = 0; virtual int set3dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; virtual int deleteTriangle(DrawPrimitive *&) = 0; - virtual int getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) = 0; - virtual int setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &) = 0; + virtual void getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) const = 0; + virtual void setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &) = 0; virtual int deletePolygon(DrawPrimitive *&) = 0; - virtual int getPolygonAttributes(DrawPrimitive *, float &, bool &) = 0; - virtual int setPolygonAttributes(DrawPrimitive *, float &, bool &) = 0; + virtual void getPolygonAttributes(DrawPrimitive *, float &, bool &) const = 0; + virtual void setPolygonAttributes(DrawPrimitive *, float &, bool &) = 0; // bool virtual bool deleteMesh(DrawPrimitive *&) = 0; virtual void setTextGamma(float) = 0; - virtual float getTextGamma() = 0; + virtual float getTextGamma() const = 0; virtual void drawAll() = 0; virtual void nodrawUpdate() = 0; - virtual int deleteAll() = 0; + virtual void deleteAll() = 0; }; // IDPStaticCreator - 14 vtable slots. @@ -61,16 +66,19 @@ class IDPStaticCreator virtual ~IDPStaticCreator(); virtual DPStaticCircle * createStaticCircle(float, unsigned int, const Vec3&, float, const Vec3&, bool, int) = 0; virtual DPStaticLine * createStaticLine(float, unsigned int, const Vec3&, const Vec3&, float) = 0; - virtual int createStaticLine(float, unsigned int, const std::vector&, float) = 0; + virtual DrawPrimitive* createStaticLine(float, unsigned int, const std::vector&, float) = 0; virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) = 0; virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createStaticTriangle(float, const std::vector&, const std::vector&, bool) = 0; - virtual int createStaticPolygon(float, const std::vector&, const std::vector&, bool) = 0; + // ELF 0x3767D0 returns the allocated text pointer; QuadTreeManager stores the handle. + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createStaticTriangle(float, const std::vector&, const std::vector&, bool) = 0; + virtual DrawPrimitive* createStaticPolygon(float, const std::vector&, const std::vector&, bool) = 0; virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Vec3 *, unsigned int *, int, bool) = 0; - virtual int createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool) = 0; - virtual int testStatics(Mat4 &) = 0; + // Returns the new DPStaticMesh (DPManager::createStaticMesh 0x377070; QuadTree::draw stores it). + virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool) = 0; + // void [INFERRED]: no caller exists and the ia-32 body (0x377240) leaves eax unset. + virtual void testStatics(Mat4 &) = 0; }; // IDPDynamicCreator - 12 vtable slots. @@ -84,12 +92,12 @@ class IDPDynamicCreator virtual DPStaticCircle * createDPDynamicCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) = 0; virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, Bot *, DPDynamicTypes) = 0; virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes) = 0; - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes) = 0; + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; }; // IDPAIObjectCreator - 7 vtable slots. @@ -101,9 +109,9 @@ class IDPAIObjectCreator virtual ~IDPAIObjectCreator(); virtual DPStaticCircle * createDPAIObjectCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int) = 0; virtual DPStaticLine * createAIObjectLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes) = 0; + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY) = 0; }; // DPManager - sizeof == 104, from BF2AI::init step 7. @@ -115,75 +123,76 @@ class DPManager : public IDPManager, public IDPStaticCreator, public IDPDynamicC // IDPManager virtual int deleteCircle(DrawPrimitive *&); - virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &); + virtual int getCircleAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, float &, Vec3 &, bool &, int &) const; virtual int setCircleAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, float, const Vec3&, bool, int); virtual int deleteLine(DrawPrimitive *&); - virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &); + virtual int getLineAttributes(DrawPrimitive *, float &, unsigned int &, std::vector &, float &) const; virtual int setLineAttributes(DrawPrimitive *, float, unsigned int, const std::vector&, float); virtual int delete2dText(DrawPrimitive *&); - virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &); + virtual int get2dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec2 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const; virtual int set2dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); virtual int delete3dText(DrawPrimitive *&); - virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &); + virtual int get3dTextAttributes(DrawPrimitive *, float &, unsigned int &, Vec3 &, std::vector &, int &, AITextAlignmentX &, AITextAlignmentY &) const; virtual int set3dTextAttributes(DrawPrimitive *, float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); virtual int deleteTriangle(DrawPrimitive *&); - virtual int getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &); - virtual int setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &); + virtual void getTriangleAttributes(DrawPrimitive *, float &, std::vector &, std::vector&, bool &) const; + virtual void setTriangleAttributes(DrawPrimitive *, float &, const std::vector&, const std::vector&, bool &); virtual int deletePolygon(DrawPrimitive *&); - virtual int getPolygonAttributes(DrawPrimitive *, float &, bool &); - virtual int setPolygonAttributes(DrawPrimitive *, float &, bool &); + virtual void getPolygonAttributes(DrawPrimitive *, float &, bool &) const; + virtual void setPolygonAttributes(DrawPrimitive *, float &, bool &); virtual bool deleteMesh(DrawPrimitive *&); virtual void setTextGamma(float); - virtual float getTextGamma(); + virtual float getTextGamma() const; virtual void drawAll(); virtual void nodrawUpdate(); - virtual int deleteAll(); + virtual void deleteAll(); // IDPStaticCreator virtual DPStaticCircle * createStaticCircle(float, unsigned int, const Vec3&, float, const Vec3&, bool, int); virtual DPStaticLine * createStaticLine(float, unsigned int, const Vec3&, const Vec3&, float); - virtual int createStaticLine(float, unsigned int, const std::vector&, float); + virtual DrawPrimitive* createStaticLine(float, unsigned int, const std::vector&, float); virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::string&, int, AITextAlignmentX, AITextAlignmentY); virtual DrawPrimitive * createStatic2dText(float, unsigned int, const Vec2&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY); - virtual int createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); - virtual int createStaticTriangle(float, const std::vector&, const std::vector&, bool); - virtual int createStaticPolygon(float, const std::vector&, const std::vector&, bool); + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::string&, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createStatic3dText(float, unsigned int, const Vec3&, const std::vector&, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createStaticTriangle(float, const std::vector&, const std::vector&, bool); + virtual DrawPrimitive* createStaticPolygon(float, const std::vector&, const std::vector&, bool); virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Vec3 *, unsigned int *, int, bool); - virtual int createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool); - virtual int testStatics(Mat4 &); + virtual DPStaticMesh * createStaticMesh(float, unsigned int *, Polygon *, Vec3 *, unsigned int *, int, bool); + virtual void testStatics(Mat4 &); // IDPDynamicCreator virtual DPStaticCircle * createDPDynamicCircle(float, unsigned int, const Vec3&, float, Bot *, DPDynamicTypes, const Vec3&, bool, int); virtual DPStaticCircle * createDPDynamicCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int); virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, Bot *, DPDynamicTypes); virtual DPStaticLine * createDynamicLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes); - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes); - virtual int createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, Bot *, DPDynamicTypes); + virtual DrawPrimitive* createDynamicLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, Bot *, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createDynamic3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); // IDPAIObjectCreator virtual DPStaticCircle * createDPAIObjectCircle(float, unsigned int, const Vec3&, float, unsigned int, DPDynamicTypes, const Vec3&, bool, int); virtual DPStaticLine * createAIObjectLine(float, unsigned int, const Vec3&, const Vec3&, float, unsigned int, DPDynamicTypes); - virtual int createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); - virtual int createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createAIObjectLine(float, unsigned int, const std::vector&, float, unsigned int, DPDynamicTypes); + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::string&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); + virtual DrawPrimitive* createAIObject3dText(float, unsigned int, const Vec3&, const std::vector&, unsigned int, DPDynamicTypes, int, AITextAlignmentX, AITextAlignmentY); private: - // Seven _Rb_trees, one per primitive kind, in the constructor's order. Element types are - // [FRONTIER] - the trees are only ever walked by the unwritten bodies. [UNRESOLVED] key type. - /* +0x10 */ std::set m_circles; - /* +0x1C */ std::set m_lines; - /* +0x28 */ std::set m_text2d; - /* +0x34 */ std::set m_text3d; - /* +0x40 */ std::set m_triangles; - /* +0x4C */ std::set m_polygons; - // Maps debug-primitive handles to their static meshes. The preceding six containers - // still have placeholder element types. - /* +0x58 */ std::map m_meshes; + // Seven maps from the caller's primitive handle to the owned static primitive, in the + // constructor's order. Key/value types are the ELF instantiations + // (_Rb_tree>); the offsets come from + // the delete* bodies: deleteLine +0x10, deleteCircle +0x1C, delete2dText +0x28, + // delete3dText +0x34, deleteTriangle +0x40, deletePolygon +0x4C, deleteMesh +0x58. + /* +0x10 */ std::map m_lines; + /* +0x1C */ std::map m_circles; + /* +0x28 */ std::map m_text2d; + /* +0x34 */ std::map m_text3d; + /* +0x40 */ std::map m_triangles; + /* +0x4C */ std::map m_polygons; + /* +0x58 */ std::map m_meshes; /* +0x64 */ float m_textGamma; // = 1.0f }; diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp new file mode 100644 index 000000000..484d5a27c --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp @@ -0,0 +1,84 @@ +// Timed screen-space debug text. Evidence: libaidll.so (ia-32) 0x37B590..0x37BD6F. +// [INFERRED] Source placement. + +#include "DPStatic2dText.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37BCC0, __tcf_0 0x37BD20, _GLOBAL__I 0x37BD50). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37B590 (C2; C1 0x37B700). The line vector is built with the fill constructor, one copy of `text`. +DPStatic2dText::DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::string& text, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(1, text) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37B7B0 (C2; C1 0x37B880). +DPStatic2dText::DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(lines) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37B950 (D2; D1 0x37BA10, D0 0x37BAD0). +DPStatic2dText::~DPStatic2dText() +{ +} + +// ELF 0x37BC70. IDebugRenderer slot 6 (drawScreenText). +bool DPStatic2dText::draw(IDebugRenderer* renderer) +{ + renderer->drawScreenText(m_position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +// ELF 0x37BB90. +void DPStatic2dText::getAttributes(float& lifeTime, unsigned int& colour, Vec2& position, + std::vector& lines, int& size, + AITextAlignmentX& alignX, AITextAlignmentY& alignY) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + position = m_position; + lines = m_lines; + size = m_size; + alignX = m_alignX; + alignY = m_alignY; +} + +// ELF 0x37BC00. +void DPStatic2dText::setAttributes(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_position = position; + m_lines = lines; + m_size = size; + m_alignX = alignX; + m_alignY = alignY; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.h new file mode 100644 index 000000000..1d8f17af5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.h @@ -0,0 +1,53 @@ +// A timed block of screen-space debug text. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC2DTEXT_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC2DTEXT_H + +#include +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x34 on ia-32 (DPManager::createStatic2dText allocates 0x34). +class DPStatic2dText : public DrawPrimitive +{ +public: + // One line of text. + DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPStatic2dText(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + virtual ~DPStatic2dText(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies every attribute except the creation time. + void getAttributes(float& lifeTime, unsigned int& colour, Vec2& position, + std::vector& lines, int& size, AITextAlignmentX& alignX, + AITextAlignmentY& alignY) const; + // Replaces every attribute except the creation time. + void setAttributes(float lifeTime, unsigned int colour, const Vec2& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + +protected: + /* +0x14 */ Vec2 m_position; + /* +0x1C */ std::vector m_lines; + /* +0x28 */ int m_size; + /* +0x2C */ AITextAlignmentX m_alignX; + /* +0x30 */ AITextAlignmentY m_alignY; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC2DTEXT_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp new file mode 100644 index 000000000..2f834c060 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp @@ -0,0 +1,84 @@ +// Timed world-space debug text. Evidence: libaidll.so (ia-32) 0x37C040..0x37C8DF. +// [INFERRED] Source placement. + +#include "DPStatic3dText.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37C830, __tcf_0 0x37C890, _GLOBAL__I 0x37C8C0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37C040 (C2; C1 0x37C1C0). The line vector is built with the fill constructor, one copy of `text`. +DPStatic3dText::DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::string& text, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(1, text) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37C2A0 (C2; C1 0x37C3A0). +DPStatic3dText::DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_lines(lines) + , m_size(size) + , m_alignX(alignX) + , m_alignY(alignY) +{ +} + +// ELF 0x37C4A0 (D2; D1 0x37C560, D0 0x37C620). +DPStatic3dText::~DPStatic3dText() +{ +} + +// ELF 0x37C7E0. IDebugRenderer slot 7 (draw3dText). +bool DPStatic3dText::draw(IDebugRenderer* renderer) +{ + renderer->draw3dText(m_position, m_lines, m_size, m_colour, m_alignX, m_alignY); + return true; +} + +// ELF 0x37C6E0. +void DPStatic3dText::getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, + std::vector& lines, int& size, + AITextAlignmentX& alignX, AITextAlignmentY& alignY) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + position = m_position; + lines = m_lines; + size = m_size; + alignX = m_alignX; + alignY = m_alignY; +} + +// ELF 0x37C760. +void DPStatic3dText::setAttributes(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_position = position; + m_lines = lines; + m_size = size; + m_alignX = alignX; + m_alignY = alignY; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.h new file mode 100644 index 000000000..6183a50b3 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.h @@ -0,0 +1,53 @@ +// A timed block of world-space debug text. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC3DTEXT_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC3DTEXT_H + +#include +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x38 on ia-32 (DPManager::createStatic3dText allocates 0x38). +class DPStatic3dText : public DrawPrimitive +{ +public: + // One line of text. + DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, const std::string& text, int size, + AITextAlignmentX alignX, AITextAlignmentY alignY); + DPStatic3dText(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + virtual ~DPStatic3dText(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies every attribute except the creation time. + void getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, + std::vector& lines, int& size, AITextAlignmentX& alignX, + AITextAlignmentY& alignY) const; + // Replaces every attribute except the creation time. + void setAttributes(float lifeTime, unsigned int colour, const Vec3& position, + const std::vector& lines, int size, AITextAlignmentX alignX, + AITextAlignmentY alignY); + +protected: + /* +0x14 */ Vec3 m_position; + /* +0x20 */ std::vector m_lines; + /* +0x2C */ int m_size; + /* +0x30 */ AITextAlignmentX m_alignX; + /* +0x34 */ AITextAlignmentY m_alignY; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATIC3DTEXT_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCircle.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCircle.h new file mode 100644 index 000000000..2edbd887d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCircle.h @@ -0,0 +1,45 @@ +// A timed debug circle in world space. +// [INFERRED] Source placement and header name (the TU is attested as DPStaticCirlce.cpp). + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICCIRCLE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICCIRCLE_H + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x38 (DPManager::createStaticCircle allocates 0x38). The renderer receives the normal +// as drawCircle's first vector and the position as its second. +class DPStaticCircle : public DrawPrimitive +{ +public: + DPStaticCircle(float lifeTime, unsigned int colour, const Vec3& position, float radius, + const Vec3& normal, bool filled, int segments); + virtual ~DPStaticCircle(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies every attribute except the creation time. + void getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, float& radius, + Vec3& normal, bool& filled, int& segments) const; + // Replaces every attribute except the creation time. + void setAttributes(float lifeTime, unsigned int colour, Vec3 position, float radius, + const Vec3& normal, bool filled, int segments); + +protected: + /* +0x14 */ Vec3 m_position; + /* +0x20 */ float m_radius; + /* +0x24 */ Vec3 m_normal; + /* +0x30 */ bool m_filled; + /* +0x34 */ int m_segments; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICCIRCLE_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp new file mode 100644 index 000000000..a3139586e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp @@ -0,0 +1,68 @@ +// Timed debug circle. Evidence: libaidll.so (ia-32) 0x37C8E0..0x37CCDF. The translation unit's +// file symbol is DPStaticCirlce.cpp (sic); the directory is [INFERRED]. + +#include "DPStaticCircle.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37CC30, __tcf_0 0x37CC90, _GLOBAL__I 0x37CCC0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37C8E0 (C2; C1 0x37C990). +DPStaticCircle::DPStaticCircle(float lifeTime, unsigned int colour, const Vec3& position, + float radius, const Vec3& normal, bool filled, int segments) + : DrawPrimitive(lifeTime, colour) + , m_position(position) + , m_radius(radius) + , m_normal(normal) + , m_filled(filled) + , m_segments(segments) +{ +} + +// ELF 0x37CA40 (D2; D1 0x37CA80, D0 0x37CAC0). +DPStaticCircle::~DPStaticCircle() +{ +} + +// ELF 0x37CB00. IDebugRenderer slot 5 (drawCircle) takes the normal first. +bool DPStaticCircle::draw(IDebugRenderer* renderer) +{ + renderer->drawCircle(m_normal, m_position, m_radius, m_colour, m_filled, m_segments); + return true; +} + +// ELF 0x37CB50. +void DPStaticCircle::getAttributes(float& lifeTime, unsigned int& colour, Vec3& position, + float& radius, Vec3& normal, bool& filled, int& segments) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + position = m_position; + radius = m_radius; + normal = m_normal; + filled = m_filled; + segments = m_segments; +} + +// ELF 0x37CBC0. +void DPStaticCircle::setAttributes(float lifeTime, unsigned int colour, Vec3 position, + float radius, const Vec3& normal, bool filled, int segments) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_position = position; + m_radius = radius; + m_normal = normal; + m_filled = filled; + m_segments = segments; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp new file mode 100644 index 000000000..3337d97cc --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp @@ -0,0 +1,74 @@ +// Timed debug polyline. Evidence: libaidll.so (ia-32) 0x37CCE0..0x37D4BF. +// [INFERRED] Source placement. + +#include "DPStaticLine.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37D410, __tcf_0 0x37D470, _GLOBAL__I 0x37D4A0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37CCE0 (C2; C1 0x37CDF0). Three push_backs: the start point, then the end point twice. +// shipped defect: the end point is stored twice, so the renderer receives a degenerate last segment. +DPStaticLine::DPStaticLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, + float width) + : DrawPrimitive(lifeTime, colour) + , m_width(width) +{ + m_points.push_back(start); + m_points.push_back(end); + m_points.push_back(end); +} + +// ELF 0x37CF00 (C2; C1 0x37CFE0). +DPStaticLine::DPStaticLine(float lifeTime, unsigned int colour, const std::vector& points, + float width) + : DrawPrimitive(lifeTime, colour) + , m_points(points) + , m_width(width) +{ +} + +// ELF 0x37D0C0 (D2; D1 0x37D140, D0 0x37D1C0). +DPStaticLine::~DPStaticLine() +{ +} + +// ELF 0x37D240. IDebugRenderer slot 4 (drawLine). +bool DPStaticLine::draw(IDebugRenderer* renderer) +{ + renderer->drawLine(m_points, m_colour, m_width); + return true; +} + +// ELF 0x37D280. resize(0) then a range insert at the end, as the listing's erase/_M_fill_insert +// pair followed by _M_range_insert shows. +void DPStaticLine::getAttributes(float& lifeTime, unsigned int& colour, std::vector& points, + float& width) const +{ + lifeTime = m_lifeTime; + colour = m_colour; + width = m_width; + points.resize(0); + points.insert(points.end(), m_points.begin(), m_points.end()); +} + +// ELF 0x37D340. +void DPStaticLine::setAttributes(float& lifeTime, unsigned int& colour, + const std::vector& points, float& width) +{ + m_lifeTime = lifeTime; + m_colour = colour; + m_width = width; + m_points.resize(0); + m_points.insert(m_points.end(), points.begin(), points.end()); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h new file mode 100644 index 000000000..c760a575b --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticLine.h @@ -0,0 +1,42 @@ +// A timed debug polyline in world space. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICLINE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICLINE_H + +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x24 on ia-32 (DPManager::createStaticLine allocates 0x24). +class DPStaticLine : public DrawPrimitive +{ +public: + // A two-point line. The shipped constructor stores the end point twice (see the body). + DPStaticLine(float lifeTime, unsigned int colour, const Vec3& start, const Vec3& end, float width); + DPStaticLine(float lifeTime, unsigned int colour, const std::vector& points, float width); + virtual ~DPStaticLine(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies lifetime, colour, points and width; `points` is replaced, not appended to. + void getAttributes(float& lifeTime, unsigned int& colour, std::vector& points, float& width) const; + // Replaces lifetime, colour, points and width; the creation time is kept. + void setAttributes(float& lifeTime, unsigned int& colour, const std::vector& points, float& width); + +protected: + /* +0x14 */ std::vector m_points; + /* +0x20 */ float m_width; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICLINE_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp new file mode 100644 index 000000000..ee6ac88b5 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp @@ -0,0 +1,82 @@ +// Timed debug mesh. Evidence: libaidll.so (ia-32) 0x37D850..0x37E61F. +// [INFERRED] Source placement. + +#include "DPStaticMesh.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37E570, __tcf_0 0x37E5D0, _GLOBAL__I 0x37E600). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" +#include "../AIUtils/checkPointer.h" +#include "../Main/AIRandom.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37D850 (C2; C1 0x37DB20). The random base is drawn before the loop whether or not +// `colours` is given; the low-bit term is drawn per entry only on the null-`colours` path. +DPStaticMesh::DPStaticMesh(float lifeTime, unsigned int* colours, Vec3* vertices, + unsigned int* indices, int count, bool filled) + : DrawPrimitive(lifeTime, colours ? colours[0] : 0xFFFFFFFFu) + , m_vertices(vertices) + , m_indices(indices) + , m_count(count) + , m_filled(filled) +{ + m_colours = checkPointer(new unsigned int[m_count]); + m_ownsArrays = false; + const unsigned int base = AIRandom::m_instance->next() & 0xE0E0E0E0u; + for (int i = 0; i < m_count; ++i) + { + if (colours) + m_colours[i] = colours[i]; + else + m_colours[i] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } +} + +// ELF 0x37DDF0 (C2; C1 0x37E0C0). Identical to the overload above apart from the ignored +// polygon pointer. +DPStaticMesh::DPStaticMesh(float lifeTime, unsigned int* colours, Polygon* /*polygons*/, + Vec3* vertices, unsigned int* indices, int count, bool filled) + : DrawPrimitive(lifeTime, colours ? colours[0] : 0xFFFFFFFFu) + , m_vertices(vertices) + , m_indices(indices) + , m_count(count) + , m_filled(filled) +{ + m_colours = checkPointer(new unsigned int[m_count]); + m_ownsArrays = false; + const unsigned int base = AIRandom::m_instance->next() & 0xE0E0E0E0u; + for (int i = 0; i < m_count; ++i) + { + if (colours) + m_colours[i] = colours[i]; + else + m_colours[i] = (AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base; + } +} + +// ELF 0x37E390 (D2; D1 0x37E410, D0 0x37E490). +DPStaticMesh::~DPStaticMesh() +{ + delete[] m_colours; + if (m_ownsArrays) + { + delete[] m_vertices; + delete[] m_indices; + } +} + +// ELF 0x37E520. IDebugRenderer slot 9 (drawMesh). +bool DPStaticMesh::draw(IDebugRenderer* renderer) +{ + renderer->drawMesh(m_vertices, m_indices, m_count, m_colours, m_filled); + return true; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h new file mode 100644 index 000000000..1ff18c0c1 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.h @@ -0,0 +1,45 @@ +// A timed debug mesh over caller-owned vertex and index arrays. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICMESH_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICMESH_H + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x2C on ia-32 (DPManager::createStaticMesh allocates 0x2C). +class DPStaticMesh : public DrawPrimitive +{ +public: + // Keeps `vertices` and `indices` by pointer (not owned) and copies `count` colours into an + // owned array. A null `colours` gives the primitive colour 0xFFFFFFFF and random per-entry + // colours: one high-bit base (& 0xE0E0E0E0) plus a fresh low-bit term (& 0x1F1F1F1F) each. + DPStaticMesh(float lifeTime, unsigned int* colours, Vec3* vertices, unsigned int* indices, + int count, bool filled); + // As above; the polygon pointer is accepted and ignored. + DPStaticMesh(float lifeTime, unsigned int* colours, Polygon* polygons, Vec3* vertices, + unsigned int* indices, int count, bool filled); + virtual ~DPStaticMesh(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + +protected: + /* +0x14 */ Vec3* m_vertices; + /* +0x18 */ unsigned int* m_indices; + /* +0x1C */ int m_count; + /* +0x20 */ bool m_filled; + /* +0x24 */ unsigned int* m_colours; + // [INFERRED] name. Always false here; when set, the destructor also frees the two arrays. + /* +0x28 */ bool m_ownsArrays; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICMESH_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp new file mode 100644 index 000000000..dbd68601f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp @@ -0,0 +1,68 @@ +// Timed debug polygon. Evidence: libaidll.so (ia-32) 0x37E620..0x37F4CF. +// [INFERRED] Source placement. + +#include "DPStaticPolygon.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x37F420, __tcf_0 0x37F480, _GLOBAL__I 0x37F4B0). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x37E620 (C2; C1 0x37EAC0). Both outer vectors are resized to size - 2 (an unsigned count, +// so fewer than two vertices wraps), then each fan triangle receives v0, vi, vi+1 with its colours +// interleaved in that order. +DPStaticPolygon::DPStaticPolygon(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) + : DrawPrimitive(lifeTime, colours[0]) + , m_filled(filled) +{ + const unsigned int count = vertices.size(); + m_triangles.resize(count - 2); + m_colours.resize(count - 2); + for (unsigned int i = 1; i < count - 1; ++i) + { + m_triangles[i - 1].push_back(vertices[0]); + m_colours[i - 1].push_back(colours[0]); + m_triangles[i - 1].push_back(vertices[i]); + m_colours[i - 1].push_back(colours[i]); + m_triangles[i - 1].push_back(vertices[i + 1]); + m_colours[i - 1].push_back(colours[i + 1]); + } +} + +// ELF 0x37EF60 (D2; D1 0x37F0B0, D0 0x37F200). +DPStaticPolygon::~DPStaticPolygon() +{ +} + +// ELF 0x37F350. The triangle count is read once before the loop. +bool DPStaticPolygon::draw(IDebugRenderer* renderer) +{ + const unsigned int count = m_triangles.size(); + for (unsigned int i = 0; i < count; ++i) + renderer->drawTriangle(m_triangles[i], m_colours[i], m_filled); + return true; +} + +// ELF 0x37F3E0. +void DPStaticPolygon::getAttributes(float& lifeTime, bool& filled) const +{ + lifeTime = m_lifeTime; + filled = m_filled; +} + +// ELF 0x37F400. +void DPStaticPolygon::setAttributes(float& lifeTime, bool& filled) +{ + m_lifeTime = lifeTime; + m_filled = filled; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.h new file mode 100644 index 000000000..61420e4d6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.h @@ -0,0 +1,43 @@ +// A timed debug polygon, fan-triangulated at construction. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICPOLYGON_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICPOLYGON_H + +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x30 on ia-32 (DPManager::createStaticPolygon allocates 0x30). +class DPStaticPolygon : public DrawPrimitive +{ +public: + // Splits the outline into the fan (v0, vi, vi+1); `colours` runs parallel to `vertices` and + // its first entry becomes the primitive colour. Needs at least one vertex and one colour. + DPStaticPolygon(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled); + virtual ~DPStaticPolygon(); + + // Draws every fan triangle and returns true. + virtual bool draw(IDebugRenderer* renderer); + + void getAttributes(float& lifeTime, bool& filled) const; + // Replaces the lifetime and the fill flag; the triangles are kept. + void setAttributes(float& lifeTime, bool& filled); + +protected: + /* +0x14 */ std::vector > m_triangles; + /* +0x20 */ std::vector > m_colours; + /* +0x2C */ bool m_filled; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICPOLYGON_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp new file mode 100644 index 000000000..6f13741c4 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp @@ -0,0 +1,64 @@ +// Timed debug triangles. Evidence: libaidll.so (ia-32) 0x380730..0x380F8F. +// [INFERRED] Source placement. + +#include "DPStaticTriangle.h" + +// 's ios_base::Init object is this TU's static initialisation and teardown (ELF +// 0x380EE0, __tcf_0 0x380F40, _GLOBAL__I 0x380F70). +#include + +#include "../../../AIInterface/BFKnowledge/DebugRenderer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x380730 (C2; C1 0x3808A0). Reads colours[0] unchecked. +DPStaticTriangle::DPStaticTriangle(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled) + : DrawPrimitive(lifeTime, colours[0]) + , m_vertices(vertices) + , m_colours(colours) + , m_filled(filled) +{ +} + +// ELF 0x380A10 (D2; D1 0x380AB0, D0 0x380B50). +DPStaticTriangle::~DPStaticTriangle() +{ +} + +// ELF 0x380BF0. IDebugRenderer slot 8 (drawTriangle). +bool DPStaticTriangle::draw(IDebugRenderer* renderer) +{ + renderer->drawTriangle(m_vertices, m_colours, m_filled); + return true; +} + +// ELF 0x380C30. +void DPStaticTriangle::getAttributes(float& lifeTime, std::vector& vertices, + std::vector& colours, bool& filled) const +{ + lifeTime = m_lifeTime; + vertices.resize(0); + vertices.insert(vertices.end(), m_vertices.begin(), m_vertices.end()); + colours.resize(0); + colours.insert(colours.end(), m_colours.begin(), m_colours.end()); + filled = m_filled; +} + +// ELF 0x380D70. +void DPStaticTriangle::setAttributes(float& lifeTime, const std::vector& vertices, + const std::vector& colours, bool& filled) +{ + m_lifeTime = lifeTime; + m_vertices.resize(0); + m_vertices.insert(m_vertices.end(), vertices.begin(), vertices.end()); + m_colours.resize(0); + m_colours.insert(m_colours.end(), colours.begin(), colours.end()); + m_filled = filled; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.h new file mode 100644 index 000000000..f17e0128a --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.h @@ -0,0 +1,45 @@ +// A timed set of debug triangles given as a vertex list and per-vertex colours. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICTRIANGLE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICTRIANGLE_H + +#include + +#include "DrawPrimitive.h" +#include "../Main/AIDllTypes.h" + +namespace dice { +namespace hfe { +namespace ai { + +// sizeof == 0x30 on ia-32 (DPManager::createStaticTriangle allocates 0x30). +class DPStaticTriangle : public DrawPrimitive +{ +public: + // The primitive colour is the first entry of `colours`, which must not be empty. + DPStaticTriangle(float lifeTime, const std::vector& vertices, + const std::vector& colours, bool filled); + virtual ~DPStaticTriangle(); + + // Always draws and returns true. + virtual bool draw(IDebugRenderer* renderer); + + // Copies lifetime, vertices, colours and the fill flag; the vectors are replaced. + void getAttributes(float& lifeTime, std::vector& vertices, + std::vector& colours, bool& filled) const; + // Replaces lifetime, vertices, colours and the fill flag; the primitive colour is kept. + void setAttributes(float& lifeTime, const std::vector& vertices, + const std::vector& colours, bool& filled); + +protected: + /* +0x14 */ std::vector m_vertices; + /* +0x20 */ std::vector m_colours; + /* +0x2C */ bool m_filled; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DPSTATICTRIANGLE_H diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp new file mode 100644 index 000000000..ea853bf4d --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp @@ -0,0 +1,41 @@ +// AI debug primitive base. Evidence: libaidll.so (ia-32) 0x3811C0..0x38133C. +// [INFERRED] Source placement. + +#include "DrawPrimitive.h" + +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../Main/CommonSingletonServer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// ELF 0x3811C0 (C2; C1 0x381210). +DrawPrimitive::DrawPrimitive(float lifeTime, unsigned int colour) + : m_creationTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()) + , m_lifeTime(lifeTime) + , m_colour(colour) +{ +} + +// ELF 0x381260 (D2; D1 0x381280, D0 0x3812A0). +DrawPrimitive::~DrawPrimitive() +{ +} + +// ELF 0x381320. The sum creation + lifetime is formed in x87 precision from the double and the +// float, then compared unsigned-above against `time`. +bool DrawPrimitive::expired(double time) const +{ + return time > m_creationTime + m_lifeTime; +} + +// ELF 0x3812E0. Calls the out-of-line overload through the PLT. +bool DrawPrimitive::expired() const +{ + return expired(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.h b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.h new file mode 100644 index 000000000..992b83d2e --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.h @@ -0,0 +1,40 @@ +// Base of every AI debug primitive: a lifetime, a colour and one draw slot. +// [INFERRED] Source placement (the TU is DrawPrimitive.cpp; the directory is not attested). + +#ifndef AI_AIDLL_AI_DRAWPRIMITIVES_DRAWPRIMITIVE_H +#define AI_AIDLL_AI_DRAWPRIMITIVES_DRAWPRIMITIVE_H + +namespace dice { +namespace hfe { +namespace ai { + +class IDebugRenderer; + +// A timed debug primitive. The creation time is taken from the game timer when the primitive is +// constructed; DPManager deletes it once expired() reports true or draw() returns false. +class DrawPrimitive +{ +public: + DrawPrimitive(float lifeTime, unsigned int colour); + virtual ~DrawPrimitive(); + + // Draws the primitive through the renderer. Returns false when the primitive should be + // discarded (the dynamic primitives do so once their object is gone). + virtual bool draw(IDebugRenderer* renderer) = 0; + + // True once `time` lies strictly beyond creation time plus lifetime. + bool expired(double time) const; + // expired() against the current game time. + bool expired() const; + +protected: + /* +0x04 */ double m_creationTime; // ia-32: 4-byte aligned, so the double sits at +4 + /* +0x0C */ float m_lifeTime; + /* +0x10 */ unsigned int m_colour; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_DRAWPRIMITIVES_DRAWPRIMITIVE_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp index c550177e1..ff72736b4 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp @@ -1,4 +1,8 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AICollisionHandler operations. +// Bridges engine projectile events to the bots. libaidll.so (ia-32) 1.5.3153; every body carries +// its ELF address. [INFERRED] Source placement (one TU in the image, static initializer 0x383440). + +// static init: ELF 0x3833B0 (__tcf_0 0x383410, _GLOBAL__I 0x383440): 's Init object only. +#include #include "AICollisionHandler.h" @@ -6,7 +10,28 @@ #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" -#include "AIDllFrontier.h" +#include "IBotManager.h" +#include "../AIBot/BotMain.h" // Bot +0x94 / +0xD0 / +0xE0 +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // IAIObject +0xB8 +#include "../AIBot/BotNavigation.h" +#include "../AIBot/SensedObject.h" +#include "../AIBot/SquadManager.h" +#include "../AIKnowledge/FireObject.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIArmament.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/IPIUnit.h" +#include "../AIKnowledge/WeaponInfo.h" +#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/AIVectorMath.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFCollisionHandler.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../../Math/Mat4.h" + +#include namespace dice { namespace hfe { @@ -15,7 +40,9 @@ extern ClassManager* classManager; namespace ai { + // IAICollisionHandler +// libaidll.so 0x3E5F80 (C2) / 0x3E6020 (C1). IAICollisionHandler::IAICollisionHandler() { // the guard reads the roster static, not the registry. Reproduced. @@ -23,6 +50,7 @@ IAICollisionHandler::IAICollisionHandler() classManager->registerSimpleSingleton("IAICollisionHandler", this); } +// libaidll.so 0x3E60C0 (D2) / 0x3E6150 (D1) / 0x3E61E0 (D0). IAICollisionHandler::~IAICollisionHandler() { if (CommonSingletonServer::m_iAICollisionHandler == this) @@ -30,53 +58,324 @@ IAICollisionHandler::~IAICollisionHandler() } // Stateless collision adapter; construction requires only the base-class initialization. +// libaidll.so 0x382200 (C2) / 0x382240 (C1). AICollisionHandler::AICollisionHandler() { } // The vptr reset and the base call, which again is what C++ emits. +// libaidll.so 0x382280 (D2) / 0x3822C0 (D1) / 0x382300 (D0). AICollisionHandler::~AICollisionHandler() { } -void AICollisionHandler::handleProjectileFire(const Vec3&, world::IObject *, const Mat4&, int, IAIObject *, int, int) +namespace { + +inline IBFTimer* bfTimer() +{ + return static_cast(CommonSingletonServer::m_iBFTimer); +} + +inline IAIPlayerFactory* aiPlayerFactory() +{ + return static_cast(CommonSingletonServer::m_iaiPlayerFactory); +} + +} // namespace + +// handleProjectileFire - libaidll.so (ia-32) 0x382340, 689 B (objdump listing, 2026-11-02; Ghidra +// drops `this` here, so its parameters are shifted by one). `from` is the round's start point, +// `projectile` the round, `objectId` its object id, `shooter` the AI object of the shooter's root +// and `playerId` the shooter's player id; the transformation and the team are not read. A live +// bot books a fire correction for the round (BotMain::event_firing answers whether it may and the +// record's predicted target) and hands it to the engine collision handler. A thrown or launched +// explosive without guidance stamps the grenade time. Last, the firing target's information is +// resolved to its primary object and, when the bot senses it, the physical plug-in is asked its +// strength type; the answer is discarded, as compiled. +void AICollisionHandler::handleProjectileFire(const Vec3& from, world::IObject* projectile, const Mat4&, + int objectId, IAIObject* shooter, int playerId, int) +{ + if (!shooter) + return; + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + if (!bot || bot->isDeactivated()) // +0xD0 + return; + if (projectile) + { + bool corrected; + const Vec3& target = static_cast(bot)->event_firing(corrected, objectId, from); // +0x2A8 + if (corrected) + static_cast(CommonSingletonServer::m_iBFCollisionHandler) + ->addBotProjectile(bot->getBotId(), projectile, target); // +0xE8, +0x3C + } + + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); // +0xD8 + IPIArmament* const armament = equipment ? equipment->getArmament() : 0; + const int activeWeapon = armament ? armament->getActiveWeapon() : -1; // +0x14 + if (activeWeapon == -1 || !armament) + return; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(activeWeapon)); // +0x1C + if (!weapon) + return; + if (weapon->getExplosionRadius() > 0.0f && weapon->getWeaponGuidanceType() == 0) + bot->setTimeOfLastGrenadeThrown(bfTimer()->getGameTime()); // +0xF4 + + unsigned int target = bot->getFiringTarget(); // +0x80 + Information* targetInfo = informationManager->getInformation(target); + if (targetInfo && !targetInfo->isPrimary()) + { + target = targetInfo->getPrimaryObject(bot->getSide()); // +0xE0 + targetInfo = informationManager->getInformation(target); + } + IPIPhysical* const physical = targetInfo ? targetInfo->getPhysical() : 0; + SensedObject* const sensed = bot->getSensedObjectFromHandle(target); // +0x94 + if (targetInfo && physical && sensed) + physical->getStrengthType(); // +0x44 +} + +// handleIndirectProjectileHit - libaidll.so 0x382600, 52 B: the bots near the round's flight line +// are told about it. The team, object id and last argument are not read. +// [CHOSEN, not recovered] the return value: the image returns whatever the void helper left in +// EAX; the only caller (BFCollisionHandler, bf2 0x83FDDC0) passes it on and its callers discard it. +int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject* shooter, int, const Vec3& position, int) +{ + updateBotsOnProjectile(shooter, position); + return 0; +} + +// handleIndirectProjectileHit - libaidll.so 0x382640, 52 B: as above, without the object id. +// [CHOSEN, not recovered] the return value, as above (caller bf2 0x83FDC70). +int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject* shooter, const Vec3& position, int) +{ + updateBotsOnProjectile(shooter, position); + return 0; +} + +// handleProjectileDamage - libaidll.so (ia-32) 0x392680, 128 B (read with rea, 2026-11-01). Only a +// shooting bot that is not deactivated reacts: it looks the victim up among its sensed objects by +// the victim's information handle for the bot's side (result discarded, as compiled). The +// strength and weapon index are not read. +// [CHOSEN, not recovered] the return value: the image sets none (EAX keeps the last call's result) +// and the only caller, BFCollisionHandler::handleProjectileDamage (bf2 0x83FE410), discards it. +int AICollisionHandler::handleProjectileDamage(IAIObject* shooter, IAIObject* victim, const int&, int) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileFire"); + Bot* const bot = IBotManager::instance->getBot(shooter); // +0x24 + if (bot && !bot->isDeactivated()) // +0xD0 + bot->getSensedObjectFromHandle(victim->getInformation(bot->getSide())); // +0x94 / +0xB8 / +0xE0 + return 0; } -int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject *, int, const Vec3&, int) +// handleProjectileMiss - libaidll.so 0x382710, 136 B. GameLogicCollision's terrain hit through +// BFCollisionHandler (bf2 0x83FE6A0): a live shooting bot records the miss of the round +// (event_shotMissed +0x174), then every bot near the flight line is told about it. +// [CHOSEN, not recovered] the return value: EAX is the void helper's leftover; the caller discards it. +int AICollisionHandler::handleProjectileMiss(IAIObject* shooter, int playerId, int objectId, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleIndirectProjectileHit"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + if (bot && !bot->isDeactivated()) // +0xD0 + bot->event_shotMissed(objectId, position); // +0x174 + updateBotsOnProjectile(shooter, position); + return 0; } -int AICollisionHandler::handleIndirectProjectileHit(int, IAIObject *, const Vec3&, int) +// victimUpdate - libaidll.so 0x3827A0, 966 B (objdump listing, Ghidra cross-check). Called by +// BFCollisionHandler::handleCollision (bf2 0x83FD5C0) when a round hits a player's object; it +// answers 1 when the victim is a live bot that was told about the shot. +// First the squads: when the shooter's information (as seen by the victim's side) and the +// victim's current vehicle are on different sides and the shooter does not carry C4, the +// victim's squad learns it was fired at; a human occupying the shooter's unit is booked the +// other way round. Then a live victim bot that is not hit by C4 receives the shot as incoming +// fire: a FireObject from the shooter's position to the hit point with the unit's battle +// strengths, direct, decay 1. The victim-side information is not null-tested before setTime, +// as compiled. `objectId` is not read. +int AICollisionHandler::victimUpdate(int victimPlayerId, int, const Vec3& position, IAIObject* victim, + IAIObject* shooter) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleIndirectProjectileHit"); + IAIPlayer* const victimPlayer = aiPlayerFactory()->getPlayerFromId(victimPlayerId); // +0x20 + if (victimPlayer && shooter) + { + const unsigned int shooterHandle = + shooter->forceGetInformation(victimPlayer->getSide(), true); // +0x6C, +0xB4 + Information* const shooterInfo = informationManager->getInformation(shooterHandle); + IAIObject* const vehicle = shooterInfo ? victimPlayer->getCurrentVehicle() : 0; // +0x54 + if (vehicle) + { + Information* const vehicleInfo = + informationManager->getInformation(vehicle->getInformation(victimPlayer->getSide())); // +0xB8 + if (!isC4(shooter) && vehicleInfo && vehicleInfo->getSide() != shooterInfo->getSide()) // +0x44 + { + SquadManager* const squads = SquadManager::m_instance; + squads->shotsFired(victimPlayerId, victimPlayer->getSide(), shooterHandle); + if (IPIUnit* const unit = shooterInfo->getUnit()) + { + const int occupant = unit->getOccupyingPlayerId(shooterInfo->getSide()); + if (occupant != -1) + { + IAIPlayer* const occupantPlayer = aiPlayerFactory()->getPlayerFromId(occupant); + if (occupantPlayer && !occupantPlayer->getIsAIPlayer()) // +0x88 + squads->shotsFired(occupant, shooterInfo->getSide(), + victim->forceGetInformation(shooterInfo->getSide(), true)); + } + } + } + } + } + + Bot* const bot = IBotManager::instance->getBotFromPlayerId(victimPlayerId); // +0x1C + if (!bot || bot->isDeactivated() || isC4(shooter)) + return 0; + const unsigned int handle = shooter->forceGetInformation(bot->getSide(), true); + Information* const info = informationManager->getInformation(handle); + info->setTime(bfTimer()->getGameTime()); // +0x0C + IPIUnit* const unit = info->getUnit(); + if (!unit) + return 0; + FireObject* const fire = new FireObject(shooter->getPosition(), position, unit->getBattleStrengths(), + true, bfTimer()->getGameTime(), 1.0f); // +0xD4 + bot->event_projectile(fire, handle); // +0x16C + return 1; } -int AICollisionHandler::handleProjectileDamage(IAIObject *, IAIObject *, const int&, int) +// shooterUpdate - libaidll.so 0x382B70, 168 B. After victimUpdate answered 1: a live shooting bot +// counts one more hit in its sensed record of the victim (+0x48) and reports the hit of the round. +// [CHOSEN, not recovered] the return value: the image sets none; the caller discards it. +int AICollisionHandler::shooterUpdate(int playerId, int objectId, world::IObject* hitObject, IAIObject* victim, + const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileDamage"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + if (!bot || bot->isDeactivated()) + return 0; + if (SensedObject* const sensed = bot->getSensedObjectFromHandle(victim->getInformation(bot->getSide()))) + ++sensed->m_fireRating; + bot->event_shotHit(objectId, hitObject, position); // +0x170 + return 0; } -int AICollisionHandler::handleProjectileMiss(IAIObject *, int, int, const Vec3&) +// handleProjectileTimeout - libaidll.so 0x382C20, 223 B. A round's reset or detonation through +// BFCollisionHandler (bf2 0x83FDA30): a live owning bot drops its fire correction for the round +// (event_shotTimeOut +0x2A4), the bots near the line from the owner's current vehicle are told, +// and a sticky round of a live bot that has C4 placed removes the C4. +// [CHOSEN, not recovered] the return value: the image sets none; both callers discard it. +int AICollisionHandler::handleProjectileTimeout(int objectId, int playerId, const Vec3& position, bool sticky) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileMiss"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); // +0x1C + bool liveBot = false; + if (bot && !bot->isDeactivated()) + { + liveBot = true; + static_cast(bot)->event_shotTimeOut(objectId); // +0x2A4 + } + IAIPlayer* const player = aiPlayerFactory()->getPlayerFromId(playerId); // +0x20 + if (player) + updateBotsOnProjectile(player->getCurrentVehicle(), position); // +0x54 + if (liveBot && player && sticky && bot->isC4Placed()) // +0x150 + bot->removeC4(); // +0x154 + return 0; } -int AICollisionHandler::victimUpdate(int, int, const Vec3&, IAIObject *, IAIObject *) +// checkIfGrenade - libaidll.so 0x382D00, 728 B (objdump listing, Ghidra cross-check). A thrown +// explosive that lands within 10 m of the bot (and not on it) warns the bot's navigation: always +// within 5 m, otherwise only when it lies ahead of the bot (positive dot product with the +// equipment's forward axis, the third matrix row). The warning carries the weapon's firing time +// and whether it is the flashbang ("nshgr_flashbang"). The weapon name is copied, as compiled. +void AICollisionHandler::checkIfGrenade(Bot* bot, IAIObject* projectile, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::victimUpdate"); + Information* const projectileInfo = + informationManager->getInformation(projectile->getInformation(projectile->getSide())); // +0x12C, +0xB8 + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!projectileInfo || !equipment) + return; + IPIArmament* const armament = projectileInfo->getArmament(); + if (!armament || armament->getActiveWeapon() == -1) + return; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon || !weapon->getIsThrown() || !(weapon->getExplosionRadius() > 0.0f)) + return; + + const std::string name = weapon->getName(); + const Vec3& botPosition = equipment->getPosition(); // +0x30 + float dx = position.x - botPosition.x; + float dy = position.y - botPosition.y; + float dz = position.z - botPosition.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + if (!(distance < 10.0f) || !(distance > 1e-05f)) + return; + const float inv = 1.0f / distance; + dx *= inv; + dy *= inv; + dz = inv * dz; + bool warn = distance < 5.0f; + if (!warn) + { + const Mat4& transformation = equipment->getTransformation(); // +0x3C + warn = dx * transformation.m[8] + dy * transformation.m[9] + dz * transformation.m[10] > 0.0f; + } + if (warn) + { + const bool flashbang = name.compare("nshgr_flashbang") == 0; + const double time = weapon->getTimeOfFiring(); // +0x20 + bot->getBotNavigation()->setGrenadeWarning(position, time, flashbang); // +0xFC + } } -int AICollisionHandler::shooterUpdate(int, int, world::IObject *, IAIObject *, const Vec3&) +// isC4 - libaidll.so 0x382FE0, 201 B: the object's own information has an active weapon of +// weapon type 4. +bool AICollisionHandler::isC4(IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::shooterUpdate"); + Information* const info = informationManager->getInformation(object->getInformation(object->getSide())); + if (!info) + return false; + IPIArmament* const armament = info->getArmament(); + if (!armament) + return false; + if (armament->getActiveWeapon() == -1) + return false; + WeaponInfo* const weapon = + WeaponInfoManager::m_instance->getInformation(armament->getWeapon(armament->getActiveWeapon())); + if (!weapon) + return false; + return weapon->getWeaponType() == 4; } -int AICollisionHandler::handleProjectileTimeout(int, int, const Vec3&, bool) +// updateBotsOnProjectile - libaidll.so 0x3830B0, 763 B (objdump listing). Every active bot that is +// neither dead nor man-down is first checked for a grenade warning. A bot of another side than +// the round's object, not facing C4, whose equipment lies within 10 m of the line from that +// object to `position` (objFireLineDist), receives the round as indirect incoming fire: a +// FireObject from the object's position to `position` with the unit's battle strengths, not +// direct, decay 0.1. The bot count is re-read every pass; neither the bot, the information +// nor its unit plug-in is null-tested, as compiled. +void AICollisionHandler::updateBotsOnProjectile(IAIObject* projectile, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::AICollisionHandler::handleProjectileTimeout"); + if (!projectile) + return; + const Vec3& origin = projectile->getPosition(); // +0xD4 + const int side = projectile->getSide(); // +0x12C + IBotManager* const bots = IBotManager::instance; + for (unsigned int i = 0; i < static_cast(bots->getBotCount()); ++i) // +0x08 + { + Bot* const bot = bots->getBot(i); // +0x14 + if (bot->isDeactivated() || bot->isDead() || bot->getManDown()) // +0xD0, +0xC4, +0x1B0 + continue; + checkIfGrenade(bot, projectile, position); + if (bot->getPlayer()->getSide() == side) // +0xBC, +0x6C + continue; + if (isC4(projectile)) + continue; + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (!equipment) + continue; + if (!(objFireLineDist(equipment->getAIObject()->getPosition(), origin, position) < 10.0f)) + continue; + Information* const info = informationManager->getInformation( + projectile->forceGetInformation(bot->getSide(), true)); // +0xB4 + info->setTime(bfTimer()->getGameTime()); + IPIUnit* const unit = info->getUnit(); + FireObject* const fire = new FireObject(projectile->getPosition(), position, unit->getBattleStrengths(), + false, bfTimer()->getGameTime(), 0.1f); + bot->event_projectile(fire, projectile->getInformation(bot->getSide())); // +0x16C + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h index 73f95b33e..64cb63344 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.h @@ -1,6 +1,8 @@ // Handles collisions in the AI module. -// Preserve virtual declaration order. [INFERRED] Return types require validation where implementations remain incomplete. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// Preserve virtual declaration order. Parameter types are attested by the libaidll.so mangled +// names. [INFERRED] the int return types: the shipped bodies of handleIndirectProjectileHit, +// handleProjectileMiss, shooterUpdate and handleProjectileTimeout set no return value and +// every engine caller discards it; victimUpdate answers 0/1 and BFCollisionHandler tests it. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_AICOLLISIONHANDLER_H @@ -52,6 +54,11 @@ class AICollisionHandler : public IAICollisionHandler virtual int shooterUpdate(int, int, world::IObject *, IAIObject *, const Vec3&); virtual int handleProjectileTimeout(int, int, const Vec3&, bool); + // Non-virtual helpers (mangled names in libaidll.so; [INFERRED] access and return spelling: + // checkIfGrenade and updateBotsOnProjectile set no return value, isC4 materialises a bool). + void checkIfGrenade(Bot* bot, IAIObject* projectile, const Vec3& position); // 0x382D00 + bool isC4(IAIObject* object); // 0x382FE0 + void updateBotsOnProjectile(IAIObject* projectile, const Vec3& position); // 0x3830B0 }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp index a3e466f82..be9954e10 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp @@ -1,4 +1,5 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIConsole operations. +// static init: ELF 0x3969C0 (__tcf_0 0x396A20, _GLOBAL__I 0x396A50): 's Init object only. +#include #include "AIConsole.h" @@ -6,10 +7,45 @@ #include "../AIBot/SquadManager.h" // init's second allocation #include "../AIUtils/checkPointer.h" // init's two dead null checks #include "../AIPlanInterpreter/BAPEntries.h" // the 42 registered primitives -#include "AIDllFrontier.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/BotOrder.h" +#include "../AIBot/SensingAgent.h" +#include "../AIBot/WPMoveTo.h" +#include "../AIBot/WPAltitudeMoveTo.h" +#include "../AIBot/WPPatrol.h" +#include "../AIBot/WPAltitudePatrol.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIPathFinding/NavMesh/MapProperties.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFGameEffector.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../Core/Debug.h" +#include "../../../../Core/StringUtil.h" +#include "../../../../IO/File/File.h" +#include "../../../../Math/Mat4.h" +#include "IBotManager.h" +#include "AILODManager.h" +#include "IAIPathfinding.h" +#include +#include +#include +#include #include "AIMain.h" // IAIMain::m_instance -#include "../../../../Core/ConsoleObjectMacro.h" // the ai.init binding at the tail #include "CommonSingletonServer.h" +#include "AISettings.h" // IAISettings / IAISettingsModifier +#include "AIStreamOperators.h" // the script-vocabulary extractors +#include "../AIBotBehaviour/BotBehaviour.h" // setVehicleBehaviour's result +#include "BotBehaviourManager.h" // the behaviour commands +#include "StrategyManager.h" // the aiStrategy bindings +#include "../AIStrategic/SAI.h" // addSAIStrategy +#include "../AIStrategic/Strategy.h" namespace dice { namespace hfe { @@ -17,10 +53,9 @@ namespace ai { AIConsole* AIConsole::m_instance = 0; -// Registers Bot Action Plan primitives. -// [FRONTIER] Missing primitive implementations stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x383470 / 0x389360. Registers Bot Action Plan primitives and sensing patterns. AIConsole::AIConsole() + : m_activeBehaviourModifiers(), m_gap44() { // Publishes this console as the active singleton. m_instance = this; @@ -74,42 +109,94 @@ AIConsole::AIConsole() m_sensingAgentPatterns["MouseFreeLook"] = new SensingAgentMouseFreeLookPattern(); m_sensingAgentPatterns["Soldier"] = new SensingAgentSoldierPattern(); m_sensingAgentPatterns["Null"] = new SensingAgentNullPattern(); + + m_activeBehaviourModifiers = m_behaviourModifiers.end(); + m_aiMain = 0; + // shipped defect: this allocation is never stored or released. + MapProperties* const properties = new MapProperties(); + properties->setMaxSlope(0.36651915311813354f); } -// [FRONTIER] Destruction requires cleanup of owned plan entries, behavior entries and squad state. +// ELF 0x38F5C0 (D1, 1047 B; recovered on the client track, docs/macos-c-singleplayer.md). +// reset, then the SquadManager singleton is deleted and this singleton zeroed unconditionally. +// The BAP entries are deleted through their virtual deleting destructor (+4) and erased one by +// one; the modifier arrays are freed with delete[] but their nodes stay (only the cursor is +// moved to end). The sensing-pattern loop advances twice per pass - `++it` in the loop header on +// top of `erase(it++)` - so it deletes the 1st and 3rd of the four patterns and leaves the 2nd +// and 4th to the map's own destructor, which frees their nodes without deleting them. Shipped +// (0x38F774 and 0x38F7DF are both _M_increment); with the four patterns the constructor +// registers, the iterator never passes end(). AIConsole::~AIConsole() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::~AIConsole"); + reset(); + if (SquadManager::m_instance) + delete SquadManager::m_instance; + m_instance = 0; + + std::map::iterator entry = m_bapEntries.begin(); + while (entry != m_bapEntries.end()) + { + delete entry->second; // virtual, slot +4 + m_bapEntries.erase(entry++); + } + + for (std::map::iterator modifier = m_behaviourModifiers.begin(); + modifier != m_behaviourModifiers.end(); ++modifier) + delete[] modifier->second; + m_activeBehaviourModifiers = m_behaviourModifiers.end(); // +0x10 + + for (std::map::iterator pattern = m_sensingAgentPatterns.begin(); + pattern != m_sensingAgentPatterns.end(); ++pattern) + { + delete pattern->second; // virtual, slot +4 + m_sensingAgentPatterns.erase(pattern++); + } } -// [FRONTIER] Reset must delete behavior-modifier arrays and Strategy objects and return -// true, while retaining plan-entry and sensing-pattern registries. Ordered cleanup is unimplemented. +// ELF 0x395F60 (528 B; recovered on the client track). Frees every behaviour-modifier array +// (delete[]) and erases its node, then deletes every Strategy (nonvirtual D1 + operator delete) +// and erases its node. The BAP and sensing registries and the modifier cursor are left alone. +// Returns 1. bool AIConsole::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::reset"); + std::map::iterator modifier = m_behaviourModifiers.begin(); + while (modifier != m_behaviourModifiers.end()) + { + delete[] modifier->second; + m_behaviourModifiers.erase(modifier++); + } + std::map::iterator strategy = m_strategies.begin(); + while (strategy != m_strategies.end()) + { + delete strategy->second; + m_strategies.erase(strategy++); + } + return true; } -// Dedicated-server console behavior: no single-player instance, no debug/camera-text -// action, and zero camera position and rotation. +// ELF 0x383460. The dedicated image has no single-player instance. AIConsole* AIConsole::getSinglePlayerInstance() { return 0; } +// ELF 0x38F9E0. IAIMain* AIConsole::getActiveAIMain() { return IAIMain::m_instance; } +// ELF 0x396170. Empty in the dedicated image. void AIConsole::debug() { } +// ELF 0x3934B0. Empty in the dedicated image. void AIConsole::removeCameraText() { } -// A zeroed Vec3, by value. Three immediate zero stores into the return slot and nothing else. +// ELF 0x392B40. A zeroed Vec3, by value. Vec3 AIConsole::getRendCameraPosition() { Vec3 position; @@ -119,6 +206,7 @@ Vec3 AIConsole::getRendCameraPosition() return position; } +// ELF 0x392B70. Vec3 AIConsole::getRendCameraRotation() { Vec3 rotation; @@ -128,19 +216,20 @@ Vec3 AIConsole::getRendCameraRotation() return rotation; } -// [FRONTIER] Remaining bot, behavior and interpreter commands require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -BAPEntry* AIConsole::getBAPEntryFromName(std::string) +// ELF 0x392610: `m_bapEntries[name]` (lower_bound + insert_unique: an unknown name is inserted +// null, case-sensitive). +BAPEntry* AIConsole::getBAPEntryFromName(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBAPEntryFromName"); + return m_bapEntries[name]; } -ISensingAgentPattern* AIConsole::getSensingAgentPatternFromName(std::string) +// ELF 0x3927B0: `m_sensingAgentPatterns[name]` (operator[]: an unknown name is inserted null). +ISensingAgentPattern* AIConsole::getSensingAgentPatternFromName(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getSensingAgentPatternFromName"); + return m_sensingAgentPatterns[name]; } -// Initializes AI from a level script. Returns immediately when an active AI runtime already exists. +// ELF 0x38FA00. Initializes AI from a level script, unless a runtime already exists. void AIConsole::init(int n) { if (getActiveAIMain()) @@ -161,254 +250,807 @@ void AIConsole::init(int n) (void)squadManager; } -void AIConsole::addBot(std::string, int, std::string, std::string) +// ELF 0x38FCF0. Unknown modifier names are inserted with a null value. +int AIConsole::addBot(std::string name, int side, std::string modifiers, std::string equipment) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addBot"); + if (!IAIMain::m_instance || static_cast(side) > 2) + return -1; + IAIObject* object = 0; + if (equipment != "NoEquipment") + { + object = static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getObjectFromName(equipment); + if (!object) + return -1; + } + const int playerId = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerIdFromName(name); + if (playerId == -1) + return -1; + float* const weights = m_behaviourModifiers[modifiers]; + if (!weights || !static_cast(IAIMain::m_instance)->addBot(playerId, side, weights, object)) + return -1; + return IBotManager::instance->getBotCount() - 1; } -void AIConsole::addUnspawnedBot(std::string, int, std::string) +// ELF 0x38FF90. The shipped command refuses the operation with an Error diagnostic. +int AIConsole::addUnspawnedBot(std::string, int, std::string) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addUnspawnedBot"); + Debug(DebugTypeError, "AI/AIDLL/AI/Main/AIConsole.cpp", 363, "") << "Does not work"; + return -1; } -void AIConsole::updateBot(int) +// ELF 0x3900A0. +void AIConsole::updateBot(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::updateBot"); + if (!getActiveAIMain()) + return; + Bot* const bot = getBotFromId(id); + if (bot) + bot->updateBot(); } -void AIConsole::killBotName(const std::string&) +// ELF 0x390100. The effector call is respawnBot, despite the command's name. +std::string AIConsole::killBotName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::killBotName"); + std::stringstream out; + if (!IBotManager::instance) + { + out << "No active BotManager found."; + return out.str(); + } + Bot* const bot = IBotManager::instance->getBotFromName(name); + if (!bot) + out << "Failed to find bot with name: " << name << ". Check caps."; + else if (!bot->isDead()) + { + static_cast(CommonSingletonServer::m_iaiGameEffector)->respawnBot(bot->getPlayer()); + out << "Bot " << name << " id: " << bot->getBotId() << " has been killed."; + } + else + out << "Failed to kill bot " << name << " id: " << bot->getBotId() << "."; + return out.str(); } -void AIConsole::killBotId(int) +// ELF 0x390760. +std::string AIConsole::killBotId(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::killBotId"); + std::stringstream out; + if (!IBotManager::instance) + { + out << "No active BotManager found."; + return out.str(); + } + Bot* const bot = IBotManager::instance->getBotFromId(id); + if (!bot) + out << "Failed to find bot with id: " << id << "."; + else if (!bot->isDead()) + { + static_cast(CommonSingletonServer::m_iaiGameEffector)->respawnBot(bot->getPlayer()); + const std::string& name = bot->getPlayer()->getName(); + out << "Bot " << name << " id: " << id << " has been killed."; + } + else + { + const std::string& name = bot->getPlayer()->getName(); + out << "Failed to kill bot " << name << " id: " << id << "."; + } + return out.str(); } +// ELF 0x390CB0. Count is captured once; null entries are skipped. void AIConsole::killAllBots() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::killAllBots"); + IBotManager* const manager = IBotManager::instance; + if (!manager) + return; + const int count = manager->getBotCount(); + for (int i = 0; i < count; ++i) + { + Bot* const bot = manager->getBot(i); + if (bot) + static_cast(CommonSingletonServer::m_iaiGameEffector)->respawnBot(bot->getPlayer()); + } } -void* AIConsole::getBotFromId(int) +// ELF 0x392950. +Bot* AIConsole::getBotFromId(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBotFromId"); + return IBotManager::instance ? IBotManager::instance->getBotFromId(id) : 0; } -void AIConsole::botMoveTo(float, Vec3, int) +// ELF 0x391D40. +void AIConsole::botMoveTo(float radius, Vec3 position, int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botMoveTo"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + positions.push_back(position); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + WaypointList* waypoints; + if (equipment && (equipment->getObjectTypeFlags() & 0x10)) + waypoints = new WPAltitudeMoveTo(radius, radius, radius, 1, positions); + else + waypoints = new WPMoveTo(radius, 60.0f, 1, positions, -1); + bot->setWaypoints(waypoints); } -void AIConsole::botFlyTo(int, float, float, float, Vec3) +// ELF 0x391EE0. +void AIConsole::botFlyTo(int id, float first, float second, float third, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botFlyTo"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + positions.push_back(position); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (equipment && (equipment->getObjectTypeFlags() & 0x10)) + bot->setWaypoints(new WPAltitudeMoveTo(first, second, third, 1, positions)); } -void AIConsole::botSetWaypoints_Patrol(int, float, int, Vec3, Vec3, Vec3) +// ELF 0x392040. The flags retain count + 1 even when count exceeds the three supplied points. +void AIConsole::botSetWaypoints_Patrol(int id, float radius, int count, Vec3 a, Vec3 b, Vec3 c) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botSetWaypoints_Patrol"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + if (count > 0) positions.push_back(a); + if (count > 1) positions.push_back(b); + if (count > 2) positions.push_back(c); + bot->setWaypoints(new WPPatrol(radius, static_cast(count) + 1, positions)); } -void AIConsole::botSetWaypoints_Patrol3d(int, float, int, Vec3, Vec3, Vec3) +// ELF 0x3921D0. +void AIConsole::botSetWaypoints_Patrol3d(int id, float radius, int count, Vec3 a, Vec3 b, Vec3 c) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botSetWaypoints_Patrol3d"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + std::list positions; + if (count > 0) positions.push_back(a); + if (count > 1) positions.push_back(b); + if (count > 2) positions.push_back(c); + bot->setWaypoints(new WPAltitudePatrol(radius, 10.0f, 100.0f, + static_cast(count) + 1, positions)); } -void AIConsole::botGiveOrder(int, std::string, std::string) +// ELF 0x392380. +void AIConsole::botGiveOrder(int id, std::string behaviour, std::string modifiers) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::botGiveOrder"); + Bot* const bot = getBotFromId(id); + if (!bot) + return; + const int behaviourId = BotBehaviourManager::m_instance->getBehaviourId(behaviour); + if (behaviourId == -1) + return; + float* const weights = m_behaviourModifiers[modifiers]; + if (weights) + bot->recieveOrder(new BotOrder(weights, static_cast(behaviourId))); } -void AIConsole::setBehaviour(int, std::string) +// ELF 0x390D50: names behaviour `id` (while AI settings exist). +void AIConsole::setBehaviour(int id, std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setBehaviour"); + if (CommonSingletonServer::m_iaiSettings) + BotBehaviourManager::m_instance->setBehaviourName(id, name); } -std::string AIConsole::getBehaviour(int) +// ELF 0x390DE0. +std::string AIConsole::getBehaviour(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBehaviour"); + return CommonSingletonServer::m_iaiSettings ? BotBehaviourManager::m_instance->getBehaviourName(id) : ""; } -void AIConsole::setVehicleDefaultBehaviour(std::string&, std::string&) +// ELF 0x390E60: nothing while the bot limit is unset (IAISettings slot 0 getMaxNBots() == -1) +// or for an unknown vehicle (+0x54 getVehicle) or behaviour; otherwise IAISettingsModifier +0x18. +void AIConsole::setVehicleDefaultBehaviour(std::string& vehicleName, std::string& behaviourName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setVehicleDefaultBehaviour"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + if (settings->getMaxNBots() == -1) + return; + const int vehicle = settings->getVehicle(vehicleName); + if (vehicle == -1) + return; + const int behaviour = BotBehaviourManager::m_instance->getBehaviourId(behaviourName); + if (behaviour == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setDefaultBehaviour(vehicle, behaviour); } -void AIConsole::setVehicleBehaviour(std::string, std::string, std::string, std::string, int, - std::string, std::string) +// ELF 0x390F50 (761 bytes): the same two guards, then the named modifier set must exist. The +// behaviour "NULL" registers a null behaviour under getBehaviourId("NULL"); any other name goes +// through BotBehaviourManager::create, and only a non-null result is registered +// (IAISettingsModifier +0x14 addBehaviour). The create message is built and dropped. +void AIConsole::setVehicleBehaviour(std::string vehicleName, std::string behaviourName, + std::string createFunctionName, std::string patternName, + int mode, std::string urgeCurveName, std::string modifiersName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setVehicleBehaviour"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + if (settings->getMaxNBots() == -1) + return; + const int vehicle = settings->getVehicle(vehicleName); + if (vehicle == -1) + return; + const std::map::iterator modifiers = m_behaviourModifiers.find(modifiersName); + if (modifiers == m_behaviourModifiers.end()) + return; + + std::string message; + BotBehaviour* behaviour = 0; + if (behaviourName.compare("NULL") != 0) + { + behaviour = BotBehaviourManager::m_instance->create(behaviourName, createFunctionName, + patternName, mode, urgeCurveName, + modifiers->second, message); + if (!behaviour) + return; + } + const int id = BotBehaviourManager::m_instance->getBehaviourId(behaviourName); + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addBehaviour(vehicle, id, behaviour); } -void AIConsole::setBasicBotWeights(std::string) +// ELF 0x391500: `m_behaviourModifiers[name]` (operator[]: an unknown name is inserted with a +// null set); a non-null set becomes the bots' basic weights (IAISettingsModifier +0x30). +void AIConsole::setBasicBotWeights(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setBasicBotWeights"); + float* const weights = m_behaviourModifiers[name]; + if (weights) + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBasicBotWeights(weights); } -void AIConsole::createBehaviourModifiers(std::string) +// ELF 0x3916E0: a new set of getNumberOfBehaviours() zero weights (the count is re-read every +// iteration) under an unused name, which becomes the active set. An existing name does nothing. +void AIConsole::createBehaviourModifiers(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::createBehaviourModifiers"); + if (m_behaviourModifiers.find(name) != m_behaviourModifiers.end()) + return; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + float* const weights = new float[settings->getNumberOfBehaviours()]; + for (int i = 0; i < settings->getNumberOfBehaviours(); ++i) + weights[i] = 0.0f; + m_behaviourModifiers.insert(std::pair(name, weights)); + m_activeBehaviourModifiers = m_behaviourModifiers.find(name); } -void AIConsole::setActiveBehaviourModifiers(std::string) +// ELF 0x3918C0. A missing name leaves the current selection unchanged. +void AIConsole::setActiveBehaviourModifiers(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setActiveBehaviourModifiers"); + const std::map::iterator it = m_behaviourModifiers.find(name); + if (it != m_behaviourModifiers.end()) + m_activeBehaviourModifiers = it; } +// ELF 0x391920. std::string AIConsole::getActiveBehaviourModifiers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getActiveBehaviourModifiers"); + return m_activeBehaviourModifiers == m_behaviourModifiers.end() ? "" : m_activeBehaviourModifiers->first; } -float AIConsole::getBehaviourModifier(std::string) +// ELF 0x391990. +float AIConsole::getBehaviourModifier(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getBehaviourModifier"); + if (m_activeBehaviourModifiers == m_behaviourModifiers.end()) + return 0.0f; + const int id = BotBehaviourManager::m_instance->getBehaviourId(name); + return id == -1 ? 0.0f : m_activeBehaviourModifiers->second[id]; } -void AIConsole::setBehaviourModifier(std::string, float) +// ELF 0x391A50: one weight of the active set, by behaviour name; an unknown name or no active +// set does nothing. +void AIConsole::setBehaviourModifier(std::string name, float value) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setBehaviourModifier"); + if (m_activeBehaviourModifiers == m_behaviourModifiers.end()) + return; + const int id = BotBehaviourManager::m_instance->getBehaviourId(name); + if (id == -1) + return; + m_activeBehaviourModifiers->second[id] = value; } -void AIConsole::listBehaviourModifiers() +// ELF 0x391B00. Names are looked up twice per row, as shipped. +std::string AIConsole::listBehaviourModifiers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::listBehaviourModifiers"); + if (m_activeBehaviourModifiers == m_behaviourModifiers.end()) + return ""; + std::string result; + char value[256]; + for (int i = 0; i < static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfBehaviours(); ++i) + { + result += BotBehaviourManager::m_instance->getBehaviourName(i); + result += " = "; + std::sprintf(value, "%f\n", getBehaviourModifier(BotBehaviourManager::m_instance->getBehaviourName(i))); + result += value; + } + return result; } -void AIConsole::addInterpreterEntry(std::string, std::string) +// ELF 0x391250: the entry is looked up first (an unknown name is inserted null and ignored), +// then the vehicle (IAISettings +0x54); IAISettingsModifier +0x1C. +void AIConsole::addInterpreterEntry(std::string vehicleName, std::string entryName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addInterpreterEntry"); + BAPEntry* const entry = getBAPEntryFromName(entryName); + if (!entry) + return; + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addInterpreterEntry(vehicle, entry); } -void AIConsole::addInterpreterEntry(std::string, std::string, BotLodLevel) +// ELF 0x391310: as above, IAISettingsModifier +0x20. +void AIConsole::addInterpreterEntry(std::string vehicleName, std::string entryName, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addInterpreterEntry"); + BAPEntry* const entry = getBAPEntryFromName(entryName); + if (!entry) + return; + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addInterpreterEntry(vehicle, lod, entry); } -void AIConsole::removeInterpreterEntry(std::string, std::string, BotLodLevel) +// ELF 0x3913D0: as above, IAISettingsModifier +0x24. +void AIConsole::removeInterpreterEntry(std::string vehicleName, std::string entryName, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::removeInterpreterEntry"); + BAPEntry* const entry = getBAPEntryFromName(entryName); + if (!entry) + return; + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->removeInterpreterEntry(vehicle, lod, entry); } -void AIConsole::activateDefaultInterpreter(std::string, BAPStatementType, BotLodLevel) +// ELF 0x391490: a known vehicle gets IAISettingsModifier +0x28. +void AIConsole::activateDefaultInterpreter(std::string vehicleName, BAPStatementType type, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::activateDefaultInterpreter"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + if (vehicle == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->activateDefaultInterpreter(vehicle, type, lod); } -void AIConsole::addSAIStrategy(int, std::string) +// ELF 0x392990: the side's SAI (IAIMain +0x3C) gets the named strategy (ISAI +0x08 +// addStrategy); an absent AI main, SAI or strategy does nothing. +void AIConsole::addSAIStrategy(int side, std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addSAIStrategy"); + if (!getActiveAIMain()) + return; + SAI* const sai = getActiveAIMain()->getSAI(side); + if (!sai) + return; + Strategy* const strategy = StrategyManager::getInstance()->getStrategy(name); + if (strategy) + sai->addStrategy(strategy); } -void AIConsole::addSensingAgentPattern(const std::string&, const std::string&) +// ELF 0x3967A0: a known pattern for a known vehicle (IAISettings +0x54 getVehicle) is added +// through IAISettingsModifier +0x80. +void AIConsole::addSensingAgentPattern(const std::string& vehicle, const std::string& patternName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addSensingAgentPattern"); + ISensingAgentPattern* const pattern = getSensingAgentPatternFromName(patternName); + if (!pattern) + return; + const int id = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicle); + if (id == -1) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->addSensingAgentPattern(id, pattern); } -void AIConsole::setSensingAgentPatternName(const std::string&) +// ELF 0x396860: IAISettingsModifier +0x78. +void AIConsole::setSensingAgentPatternName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setSensingAgentPatternName"); + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setSensingAgentPatternName(name); } -void AIConsole::setSensingAgentNullPattern(const std::string&) +// ELF 0x3968A0: IAISettingsModifier +0x7C with the named pattern (null when unknown). +void AIConsole::setSensingAgentNullPattern(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setSensingAgentNullPattern"); + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setSensingAgentNullPattern(getSensingAgentPatternFromName(name)); } +// ELF 0x396930. Stops at the first absent bot id, rather than scanning the manager's count. void AIConsole::sensingAgentDebug() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::sensingAgentDebug"); + int id = 0; + while (Bot* bot = IBotManager::instance->getBotFromId(id)) + { + ++id; + bot->getSensingAgent()->m_flag134 = true; + } + if (id) + { + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setDraw(true); + static_cast(IAIMain::m_instance)->showAll(false); + } } -void AIConsole::addAllowedUnit(const std::string&) +// ELF 0x395E40. The vehicle lookup's -1 result is passed on unchecked. +void AIConsole::addAllowedUnit(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addAllowedUnit"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(name); + AIStrategicObjectManager::getInstance()->getActiveArea()->addAllowedUnit(vehicle); } -void AIConsole::addExpelledUnit(const std::string&) +// ELF 0x395EA0. +void AIConsole::addExpelledUnit(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addExpelledUnit"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(name); + AIStrategicObjectManager::getInstance()->getActiveArea()->addExpelledUnit(vehicle); } -void AIConsole::addLandingZoneUnit(const std::string&) +// ELF 0x395F00. +void AIConsole::addLandingZoneUnit(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::addLandingZoneUnit"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(name); + AIStrategicObjectManager::getInstance()->getActiveArea()->addToLandingZoneUsers(vehicle); } -void AIConsole::setVehicleMods(const std::string&, const std::string&) +// ELF 0x396690: the vehicle id is taken unchecked (-1 is passed on); a known modifier set goes to +// IAISettingsModifier +0x10 setVehicleMods. +void AIConsole::setVehicleMods(const std::string& vehicleName, const std::string& modifiersName) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setVehicleMods"); + const int vehicle = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicleName); + const std::map::iterator it = m_behaviourModifiers.find(modifiersName); + if (it == m_behaviourModifiers.end()) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setVehicleMods(vehicle, it->second); } -void AIConsole::setStandardPersonality(const std::string&, int) +// ELF 0x396720: a known modifier set becomes the side's standard personality +// (IAISettingsModifier +0x50). The ELF answers the low byte of that void call's EAX; the console +// class (297) is void and drops it. +void AIConsole::setStandardPersonality(const std::string& name, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setStandardPersonality"); + const std::map::iterator it = m_behaviourModifiers.find(name); + if (it == m_behaviourModifiers.end()) + return; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setStandardPersonality(it->second, side); } +// ELF 0x392AE0. The SAI lookup is discarded; the result is always -1. float AIConsole::getFastThreshold() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getFastThreshold"); + if (getActiveAIMain()) + getActiveAIMain()->getSAI(1); + return -1.0f; } +// ELF 0x392A70. The argument is unused and neither SAI is modified. void AIConsole::setFastThreshold(float) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::setFastThreshold"); + if (getActiveAIMain()) + { + getActiveAIMain()->getSAI(1); + getActiveAIMain()->getSAI(2); + } } +// ELF 0x392BA0. The three diagnostic strings are constructed, then discarded. void AIConsole::freeCameraFire() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::freeCameraFire"); + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + Mat4 camera = {}; + camera.m[0] = camera.m[5] = camera.m[10] = camera.m[15] = 1.0f; + environment->getLocalPlayerCameraTransformation(camera); + const Vec3 start = { camera.m[12], camera.m[13], camera.m[14] }; + const Vec3 end = { start.x + 1000.0f * camera.m[8], + start.y + 1000.0f * camera.m[9], + start.z + 1000.0f * camera.m[10] }; + Vec3 hit = {}; + if (environment->collideLineWithWorld(start, end, 0, &hit)) + { + std::stringstream out; + std::vector text; + out << "Start: " << start.x << '/' << start.y << '/' << start.z; + text.push_back(out.str()); + out.str(""); + out << "End: " << hit.x << '/' << hit.y << '/' << hit.z; + text.push_back(out.str()); + out.str(""); + const Vec3 difference = { hit.x - start.x, hit.y - start.y, hit.z - start.z }; + out << "Distance: " << std::sqrt(difference.x * difference.x + difference.y * difference.y + + difference.z * difference.z) << "m"; + text.push_back(out.str()); + } } -void AIConsole::showAISettings() +// ELF 0x3934C0. The shipped report leaves each vehicle's opening brace unmatched. +std::string AIConsole::showAISettings() { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::showAISettings"); + std::stringstream out; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + out << "Number of vehicle types: " << settings->getNumberOfVehicles() << std::endl; + out << "Maximum number of bots: " << settings->getMaxNBots() << std::endl; + out << "Number of behaviours: " << settings->getNumberOfBehaviours() << std::endl; + out << "World size (x,z): (" + << static_cast(CommonSingletonServer::m_iaiTerrain)->getWorldSizeX() << ", " + << static_cast(CommonSingletonServer::m_iaiTerrain)->getWorldSizeZ() << ")" << std::endl; + for (int vehicle = 0; vehicle < settings->getNumberOfVehicles(); ++vehicle) + { + out << "Vehicle '" << static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(vehicle) + << "'" << std::endl; + out << "{" << std::endl; + for (int behaviour = 0; behaviour < settings->getNumberOfBehaviours(); ++behaviour) + { + out << " " << BotBehaviourManager::m_instance->getBehaviourName(behaviour) << ", "; + out << (settings->getPlanGenerator(vehicle, behaviour) ? "HasGenerator=TRUE" : "HasGenerator=FALSE") + << std::endl; + } + } + return out.str(); } -void AIConsole::createLODManager(float, float) +// ELF 0x393B50. ConsoleClass315 discards this string result. +std::string AIConsole::createLODManager(float distance, float speedScale) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::createLODManager"); + std::stringstream out; + if (!AILODManager::m_instance) + { + new AILODManager(distance, speedScale); + out << "LODManager created."; + } + else + out << "LODManager already created."; + return out.str(); } -void AIConsole::saveAll(const std::string&, const std::string&) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::saveAll"); -} +namespace { -float AIConsole::getCurrentPitchAngle() +// ELF 0x393E10. Tokenization deliberately uses the copied string's buffer. +bool checkLayerStrList(const std::string& list, int layer) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getCurrentPitchAngle"); + std::string copy = list; + const std::string wanted = formatString("%d", layer); + char* token = std::strtok(const_cast(copy.c_str()), "|"); + while (token) + { + if (std::string(token) == wanted) + return true; + token = std::strtok(0, "|"); + } + return false; } -float AIConsole::getCurrentYawAngle() +} // namespace + +// ELF 0x394070. Writes the seven sections in retail order; write results are discarded. +bool AIConsole::saveAll(const std::string& directory, const std::string& layers) { - BF2_AI_FRONTIER("dice::hfe::ai::AIConsole::getCurrentYawAngle"); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + const std::string filename = directory + "/AI/StrategicAreas.ai"; + const int groups = settings->getNumberOfVehicleGroups(); + io::File file; + if (!file.open(filename, static_cast(0), io::FILEACCESS_2, 0)) + return false; + + std::ostringstream areas, assignments, landingZones, vehicleGroups, vehicles, categories; + if (groups > 0) + { + vehicleGroups << "rem *** Create vehicle groups ***\n\n"; + for (int i = 0; i < groups; ++i) + { + const std::string& name = settings->getVehicleGroupName(i); + vehicleGroups << "aiSettings.createVehicleGroup " << name << "\n"; + } + vehicleGroups << "\n"; + vehicles << "rem * add vehicles to the groups *\n\n"; + for (int i = 0; i < settings->getNumberOfVehicles(); ++i) + { + const int group = settings->getVehicleGroup(i); + const std::string& name = settings->getVehicleGroupName(group); + vehicles << "aiSettings.addVehicleToVehicleGroup " << i << " " << name << "\n"; + } + vehicles << "\n\n"; + // shipped defect: categories are emitted only when there are vehicle groups. + categories << "rem *** Create categories ***\n\n"; + for (int i = 0; i < manager->getNumberOfCategories(); ++i) + { + const std::string& name = manager->getCategoryName(i); + categories << "aiStrategicArea.createNewCategory " << name << "\n"; + } + categories << "\n"; + } + + areas << "rem *** Create strategic areas ***\n"; + for (std::map::const_iterator it = manager->getStrategicAreas().begin(); + it != manager->getStrategicAreas().end(); ++it) + { + AIStrategicArea* const area = it->second; + if (!layers.empty() && !checkLayerStrList(layers, area->m_i400)) + continue; + const std::string name = it->first; + if (area->m_fromControlPoint) + areas << "aiStrategicArea.createFromControlPoint " << name << " " + << area->m_controlPointId << " " << area->m_size[0]; + else + { + areas << "aiStrategicArea.create " << name << " " << area->m_centre.x << '/' + << area->m_centre.y << " "; + const Vec2& position = area->getPosition(1); + areas << position.x << '/' << position.y << " " << area->m_f148 << " " << area->m_size[0]; + } + if (manager->getNumberOfCategories() > 0) + { + const std::string& category = manager->getCategoryName(area->m_category); + areas << " " << category; + } + areas << "\n"; + areas << "aiStrategicArea.layer " << area->m_i400 << "\n\n"; + assignments << "aiStrategicArea.setActive " << name << "\n"; + + IAISettings* const currentSettings = static_cast(CommonSingletonServer::m_iaiSettings); + const int groupCount = currentSettings->getNumberOfVehicleGroups(); + const int allowed = area->getAllowedVehicleGroups(); + if (allowed != -1) + { + for (int i = 0; i < groupCount; ++i) + if ((allowed >> (i & 31)) & 1) + { + const std::string& group = currentSettings->getVehicleGroupName(i); + assignments << "AIStrategicArea.addAllowedVehicleGroup " << group << "\n"; + } + } + const int expelled = area->getExpelledVehicleTypes(); + const int vehicleCount = currentSettings->getNumberOfVehicles(); + if (expelled) + { + for (int i = 0; i < vehicleCount; ++i) + if ((expelled >> (i & 31)) & 1) + { + const std::string& vehicle = currentSettings->getVehicle(i); + assignments << "AIStrategicArea.addExpelledUnit " << vehicle << "\n"; + } + } + const int landingZoneVehicles = currentSettings->getNumberOfVehicles(); + for (int i = 0; i < landingZoneVehicles; ++i) + if (area->isLandingZoneUser(i)) + { + const std::string& vehicle = currentSettings->getVehicle(i); + assignments << "AIStrategicArea.addLandingZoneUnit " << vehicle << "\n"; + } + + const std::vector zones = area->getLandingZones(); + for (std::vector::const_iterator zone = zones.begin(); zone != zones.end(); ++zone) + { + if (!*zone) + continue; + const LandingZoneDirection beach = (*zone)->getBeachDirection(); + landingZones << "AILandingZone.createLandingZone " << (*zone)->getName() << " "; + const Vec2& minimum = (*zone)->getMinCorner(); + landingZones << minimum.x << '/' << minimum.y << " "; + const Vec2& maximum = (*zone)->getMaxCorner(); + landingZones << maximum.x << '/' << maximum.y << " " << beach << "\n\n"; + assignments << "AIStrategicArea.attachLandingZone " << (*zone)->getName() << "\n"; + } + if (!zones.empty() && landingZoneVehicles < 1) + assignments << "AIStrategicArea.addLandingZoneUnit LandingCraft\n"; + + const std::vector neighbours = area->m_neighbours; + for (std::vector::const_iterator neighbour = neighbours.begin(); + neighbour != neighbours.end(); ++neighbour) + assignments << "AIStrategicArea.addNeighbour " + << static_cast(*neighbour)->m_name << "\n"; + const int flags = area->getObjectTypeFlags(); + for (int i = 1; i < 21; ++i) + if ((flags >> i) & 1) + assignments << "aiStrategicArea.addObjectTypeFlag " + << static_cast(i) << "\n"; + for (int i = 0; i < IAIPathfinding::instance->getNumberOfMaps(); ++i) + if (IAIPathfinding::instance->isMapUsed(i)) + { + const std::string& map = IAIPathfinding::instance->getMapNameFromId(i); + assignments << "AIStrategicArea.setOrderPosition " << map << " "; + const Vec3 position = area->getOrderPos(i, 1); + assignments << position.x << '/' << position.y << '/' << position.z << "\n"; + } + assignments << "aiStrategicArea.setSide " << area->getSide() << "\n"; + if (std::fabs(area->m_f396 - area->m_size[0]) > 0.25f) + assignments << "aiStrategicArea.vehicleSearchRadius " << area->m_f396 << "\n"; + if (!area->m_sideEnabled[0]) + assignments << "aiStrategicArea.setTakeable 1 0\n"; + if (!area->m_sideEnabled[1]) + assignments << "aiStrategicArea.setTakeable 2 0\n"; + assignments << "\n"; + } + + std::ostringstream waypoints; + manager->streamWaypoints(waypoints, layers); + file.write(vehicleGroups); + file.write(vehicles); + file.write(categories); + file.write(areas); + file.write(landingZones); + file.write(assignments); + file.write(waypoints); + file.close(); + return true; } -// Console binding for ai.init. Calls may reach named stops in dependent subsystems. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -namespace { - -const char* const kAiConsoleTag = "ai"; - -void consoleAiInit(int n) +// ELF 0x396180. Projects both forward directions onto XZ before comparing them. +float AIConsole::getCurrentPitchAngle() const { - // Requires AIConsole initialization before level scripts invoke this command. - AIConsole::m_instance->init(n); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromLocalHumanPlayer(); + if (!player) + return -1.0f; + const Mat4& camera = *static_cast(player->getCameraTransformation()); + Vec3 first = { camera.m[8], 0.0f, camera.m[10] }; + const auto normalize = [](Vec3& v) { + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (!(std::fabs(lengthSqr - 1.0f) < 1.1920928955078125e-7f)) + { + if (std::fabs(lengthSqr) < 1.1920928955078125e-7f) + v = Vec3(); + else + { + const float scale = 1.0f / std::sqrt(lengthSqr); + v.x *= scale; v.y *= scale; v.z *= scale; + } + } + }; + normalize(first); + IAIObject* const vehicle = player->getCurrentVehicle(); + Vec3 second; + second.x = vehicle->getTransformation().m[8]; + second.y = 0.0f; + second.z = vehicle->getTransformation().m[10]; + normalize(second); + float dot = second.x * first.x + second.y * first.y + second.z * first.z; + if (dot < -1.0f) dot = -1.0f; + if (dot > 1.0f) dot = 1.0f; + return std::acos(dot) * 57.2957763671875f; } -} // anonymous namespace - -BF2_CONSOLE_OBJECT("ai", 2, 0) -BF2_CONSOLE_METHOD_1(init, consoleAiInit, int, kAiConsoleTag) - -// Handed to the console registry by AIModule::init. -ConsoleObjectList& aiConsoleObjects() +// ELF 0x396410. Projects onto YZ, retaining the shipped pitch/yaw naming. +float AIConsole::getCurrentYawAngle() const { - return consoleBindingList(kAiConsoleTag); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromLocalHumanPlayer(); + if (!player) + return -1.0f; + const Mat4& camera = *static_cast(player->getCameraTransformation()); + Vec3 first = { 0.0f, camera.m[9], camera.m[10] }; + const auto normalize = [](Vec3& v) { + const float lengthSqr = v.x * v.x + v.y * v.y + v.z * v.z; + if (!(std::fabs(lengthSqr - 1.0f) < 1.1920928955078125e-7f)) + { + if (std::fabs(lengthSqr) < 1.1920928955078125e-7f) + v = Vec3(); + else + { + const float scale = 1.0f / std::sqrt(lengthSqr); + v.x *= scale; v.y *= scale; v.z *= scale; + } + } + }; + normalize(first); + IAIObject* const vehicle = player->getCurrentVehicle(); + Vec3 second; + second.x = 0.0f; + second.y = vehicle->getTransformation().m[9]; + second.z = vehicle->getTransformation().m[10]; + normalize(second); + float dot = second.x * first.x + second.y * first.y + second.z * first.z; + if (dot < -1.0f) dot = -1.0f; + if (dot > 1.0f) dot = 1.0f; + return std::acos(dot) * 57.2957763671875f; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h index 215f5e452..1f1e741cb 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.h @@ -1,7 +1,5 @@ // Bot Action Plan registry and AI commands, recovered from the symbolized libaidll.so. // AI/Main/AIConsole.cpp is attested; this header path is [INFERRED]. -// frontier: the constructor omits MapProperties; teardown, reset and most commands remain unwritten. -// [RETIRE-WHEN: aidll-02-skeleton] Complete those bodies and the missing constructor state. #ifndef AI_AIDLL_AI_MAIN_AICONSOLE_H #define AI_AIDLL_AI_MAIN_AICONSOLE_H @@ -16,6 +14,7 @@ namespace hfe { namespace ai { class BAPEntry; +class Bot; class IAIMain; class ISensingAgentPattern; class MapProperties; @@ -49,17 +48,18 @@ class AIConsole // constructs SquadManager. It returns void: the binding emits no result // and the two exits do not materialize a common return value. void init(int); - void addBot(std::string, int, std::string, std::string); - void addUnspawnedBot(std::string, int, std::string); + int addBot(std::string, int, std::string, std::string); // ConsoleClass186 stores the int + int addUnspawnedBot(std::string, int, std::string); // ConsoleClass187 stores the int void updateBot(int); - void killBotName(const std::string&); - void killBotId(int); + std::string killBotName(const std::string&); // ConsoleClass191 assigns the string + std::string killBotId(int); // ConsoleClass190 assigns the string void killAllBots(); - void* getBotFromId(int); + Bot* getBotFromId(int); void botMoveTo(float, Vec3, int); void botFlyTo(int, float, float, float, Vec3); - void botSetWaypoints_Patrol(int, float, int, Vec3, Vec3, Vec3); - void botSetWaypoints_Patrol3d(int, float, int, Vec3, Vec3, Vec3); + // ConsoleClass196/197 pass a zero Vec3 for an omitted sixth argument [INFERRED spelling: value-initialised]. + void botSetWaypoints_Patrol(int, float, int, Vec3, Vec3, Vec3 = Vec3()); + void botSetWaypoints_Patrol3d(int, float, int, Vec3, Vec3, Vec3 = Vec3()); void botGiveOrder(int, std::string, std::string); // Behaviors and modifier weights. @@ -74,7 +74,7 @@ class AIConsole std::string getActiveBehaviourModifiers(); float getBehaviourModifier(std::string); void setBehaviourModifier(std::string, float); - void listBehaviourModifiers(); + std::string listBehaviourModifiers(); // ConsoleClass310 assigns the string // Plan interpreter. void addInterpreterEntry(std::string, std::string); @@ -101,12 +101,12 @@ class AIConsole Vec3 getRendCameraRotation(); // ; retail returns zero void freeCameraFire(); void removeCameraText(); // ; retail no-op - void showAISettings(); - void createLODManager(float, float); - void saveAll(const std::string&, const std::string&); + std::string showAISettings(); // ConsoleClass311 assigns the string + std::string createLODManager(float, float); // ConsoleClass315 discards the string + bool saveAll(const std::string&, const std::string&); // ConsoleClass476 stores the bool void debug(); // ; retail no-op - float getCurrentPitchAngle(); - float getCurrentYawAngle(); + float getCurrentPitchAngle() const; + float getCurrentYawAngle() const; // Neither body uses this. Keep member declarations: getFastThreshold calls through an object; // identical-code folding prevents establishing staticness from these bodies alone. @@ -121,14 +121,13 @@ class AIConsole /* +16 */ std::map::iterator m_activeBehaviourModifiers; // [INFERRED] /* +20 */ std::map m_bapEntries; // 42 owned primitives /* +32 */ std::map m_strategies; // [INFERRED] name - /* +44 */ char m_gap44[4]; // [UNRESOLVED] + /* +44 */ char m_gap44[4]; // [UNRESOLVED]; constructor zeroes this word /* +48 */ std::map m_sensingAgentPatterns; // 4 owned patterns - // Retail construction allocates MapProperties and calls setMaxSlope. Its destination is - // [UNRESOLVED], so that allocation is not implemented here. + // Retail construction allocates MapProperties and calls setMaxSlope, then loses the pointer. // init writes +60; getActiveAIMain reads the static instance instead. Other readers of this // cached pointer are [UNRESOLVED]; do not assume it is dead. /* +60 */ AIMain* m_aiMain; - /* +64 */ char m_gap64[4]; // [UNRESOLVED]; this is the one that may be the MapProperties* + /* +64 */ char m_gap64[4]; // [UNRESOLVED]; unwritten by the constructor // Published by the constructor ( via GOT ), cleared by retail teardown. // BF2AI::clear deletes through this pointer. diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp index 79377ee7e..662adb64d 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp @@ -1,4 +1,5 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIEventCourier operations. +// static init: ELF 0x3998D0 (__tcf_0 0x399930, _GLOBAL__I 0x399960): 's Init object only. +#include #include "AIEventCourier.h" @@ -7,11 +8,26 @@ #include "../../../../Core/ClassManager.h" #include "../../../../Core/Debug.h" // the map-part events' fatal Debugs #include "CommonSingletonServer.h" -#include "AIDllFrontier.h" #include "IAIPathfinding.h" // IAIPathfindingSetup::initMaps #include "../AIStrategicEntity/AIStrategicObjectManager.h" // postLoadInitAreas #include "AIMain.h" // IAIMain::spawnBots -#include "../AIBot/SquadManager.h" // squad notification forwarders +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" // squad notification forwarders +#include "../AIUtils/DebugRendering/AIRenderUtil.h" // event_worldReset +#include "../DrawPrimitives/DPManager.h" // event_worldReset +#include "CommunicationHub.h" // event_worldReset +#include "IBotManager.h" // the bot-state forwarders +#include "AILODManager.h" // eventPlayerDisconnect +#include "AIConsole.h" // event_freeCameraFire +#include "../AIBot/BotMain.h" // event_isRepaired +#include "../AIStrategic/SAI.h" // the commander and request events +#include "../AIKnowledge/Information.h" // eventManDown +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit - eventMissileLock +#include "../../../AIInterface/BFKnowledge/BFGame.h" // eventDrawDebug +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" // event_incomingArtillery namespace dice { namespace hfe { @@ -20,172 +36,259 @@ extern ClassManager* classManager; namespace ai { -// IAIEventCourier +// ELF 0x3E6280 / 0x3E6390. IAIEventCourier::IAIEventCourier() { if (!classManager->getSimpleSingleton("IAIEventCourier")) classManager->registerSimpleSingleton("IAIEventCourier", this); } +// ELF 0x3E64A0 / 0x3E6590 / 0x3E6680. IAIEventCourier::~IAIEventCourier() { if (classManager->getSimpleSingleton("IAIEventCourier") == this) classManager->unregisterSimpleSingleton("IAIEventCourier"); } -// Stateless event courier; construction requires only the base-class initialization. +// ELF 0x398570 / 0x3985B0. Stateless; construction only initializes the base. AIEventCourier::AIEventCourier() { } -// The vptr reset and the base call, which again is what C++ emits. +// ELF 0x3985F0 / 0x398630 / 0x398670. Member and base teardown only. AIEventCourier::~AIEventCourier() { } -void AIEventCourier::eventMissileLock(IAIObject *, world::MissileLockMessage *) +// ELF 0x3986B0: the locked object's unit plug-in (IAIObject +0x98 getUnit) gets +// IAIObjectUnit +0x78 setMissileLockStatus(1). The message pointer is not read. +void AIEventCourier::eventMissileLock(IAIObject* object, world::MissileLockMessage*) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventMissileLock"); + if (object) + { + IAIObjectUnit* const unit = object->getUnit(); + if (unit) + unit->setMissileLockStatus(1); + } } -int AIEventCourier::eventPlayerSpawned(int) +// ELF 0x3986F0: IBotManager +0x38 setBotIsAlive, unguarded. +void AIEventCourier::eventPlayerSpawned(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerSpawned"); + IBotManager::instance->setBotIsAlive(playerId); } -void AIEventCourier::eventPlayerKilled(int, int) +// ELF 0x398780: IBotManager +0x34 setBotIsDead (unguarded), then the guarded squad member's +// squadMemberKilled. The second argument is the side the squad lookup uses. +void AIEventCourier::eventPlayerKilled(int playerId, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerKilled"); + IBotManager::instance->setBotIsDead(playerId); + if (SquadManager::m_instance) + { + SquadMember* const member = SquadManager::m_instance->getSquadMember(playerId, side); + if (member) + member->squadMemberKilled(); + } } -// Notifies the active AI runtime that a player was created, if the runtime exists. +// ELF 0x398740. Notifies the active AI runtime, when present, of player creation. void AIEventCourier::eventPlayerCreated(bool isAI) { if (IAIMain::m_instance) IAIMain::m_instance->newPlayerCreated(isAI); // IAIMain vtable +0x20 } +// ELF 0x398730 is a bare `ret`: the kit change is not forwarded. void AIEventCourier::eventChangedKit(KitType) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventChangedKit"); } -void AIEventCourier::eventPlayerDisconnect(int) +// ELF 0x3987F0: the LOD manager drops the player (when it exists). With an AI main, a leaving +// bot is deactivated (IAIMain +0x1C); for anyone else IAIMain +0x24 reactivateBot runs, which +// refills the bot population. +void AIEventCourier::eventPlayerDisconnect(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerDisconnect"); + if (AILODManager::m_instance) + AILODManager::m_instance->removePlayer(playerId); + if (IAIMain::m_instance) + { + if (IBotManager::instance->getBotFromPlayerId(playerId)) + IAIMain::m_instance->deactivateBot(playerId); + else + IAIMain::m_instance->reactivateBot(playerId); + } } -int AIEventCourier::eventPlayerEnterVehicle(int, IAIObject *, IAIObject *) +// ELF 0x398880: IBotManager +0x30 setBotChangedVehicle(player, first object); the second +// object is not read. +void AIEventCourier::eventPlayerEnterVehicle(int playerId, IAIObject* vehicle, IAIObject*) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerEnterVehicle"); + IBotManager::instance->setBotChangedVehicle(playerId, vehicle); } -int AIEventCourier::eventPlayerExitVehicle(IAIObject *, int) +// ELF 0x3988C0: IAIMain +0x60 setPlayerExitedVehicle, unguarded. +void AIEventCourier::eventPlayerExitVehicle(IAIObject* vehicle, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventPlayerExitVehicle"); + IAIMain::m_instance->setPlayerExitedVehicle(vehicle, playerId); } +// ELF 0x398900: draws only while the game is playing (IAIGame +0x60 isPlaying). void AIEventCourier::eventDrawDebug() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventDrawDebug"); + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + if (game && game->isPlaying()) + IAIMain::m_instance->draw(); } -// Starts bot spawning when the game-start event arrives. -// [CHOSEN, not recovered] Returns zero; the original scalar return contract is unverified. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -int AIEventCourier::eventGameStart() +// ELF 0x398950. Starts bot spawning without producing a scalar result. +void AIEventCourier::eventGameStart() { IAIMain::m_instance->spawnBots(); // IAIMain vtable +0x54 - - return 0; // [CHOSEN, not recovered] - see above } +// ELF 0x398980 is a bare `ret`. void AIEventCourier::event_roundEnd() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_roundEnd"); } +// ELF 0x398990: four guarded resets, in this order. AIRenderUtil and CommunicationHub are +// direct calls; the DP manager is reached through its singleton interface (+0x64 deleteAll, +// result dropped) and the AI main through IAIMain +0x4C resetLevel. void AIEventCourier::event_worldReset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_worldReset"); + if (AIRenderUtil::m_instance) + AIRenderUtil::m_instance->unrenderAll(); + if (CommonSingletonServer::m_iDPManager) + static_cast(CommonSingletonServer::m_iDPManager)->deleteAll(); + if (IAIMain::m_instance) + IAIMain::m_instance->resetLevel(); + if (CommunicationHub::m_instance) + CommunicationHub::m_instance->reset(); } -int AIEventCourier::eventManDown(int, IAIObject *) +// ELF 0x398A00: IBotManager +0x3C setBotIsManDown; then, for a sided object, the opposing +// side's information about it (IAIObject +0xB8 getInformation(side == 1 ? 2 : 1), resolved +// inline through the information pool) has its physical plug-in's health set to 0 +// (IPIPhysical +0x18 setHealth, the 0.0f constant at ELF 0x49CB34). +void AIEventCourier::eventManDown(int playerId, IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventManDown"); + IBotManager::instance->setBotIsManDown(playerId, object); + const int side = object->getSide(); + if (side) + { + Information* const information = + informationManager->getInformation(object->getInformation((side == 1) + 1)); + if (information) + information->getPhysical()->setHealth(0.0f); + } } -int AIEventCourier::eventRevived(int, IAIObject *) +// ELF 0x398AC0: IBotManager +0x40 setBotIsRevived, unguarded. +void AIEventCourier::eventRevived(int playerId, IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventRevived"); + IBotManager::instance->setBotIsRevived(playerId, object); } -int AIEventCourier::eventRadioMessage(const AIRadioMessageSettings&, int, int) +// ELF 0x398B00: the hub filters and delivers the message; the fourth argument is false. +void AIEventCourier::eventRadioMessage(const AIRadioMessageSettings& settings, int a, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::eventRadioMessage"); + CommunicationHub::m_instance->filterAndReceiveAIRadioMessage(settings, a, b, false); } -int AIEventCourier::event_mineRemoved(unsigned int) +// ELF 0x398ED0: IBotManager +0x6C removeMineTarget, unguarded. +void AIEventCourier::event_mineRemoved(unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_mineRemoved"); + IBotManager::instance->removeMineTarget(handle); } -int AIEventCourier::event_enemySpotted(IAIObject *, unsigned char) +// ELF 0x398F10: forwarded to the hub unchanged. +void AIEventCourier::event_enemySpotted(IAIObject* object, unsigned char value) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_enemySpotted"); + CommunicationHub::m_instance->enemySpottedByHuman(object, value); } -int AIEventCourier::event_isRepaired(int) +// ELF 0x398F50: a bot player's BotMain +0x1E0 setIsRepaired(true). The slot lies past the +// Bot interface's last declared one (+0x1DC); BotMain is the only Bot in the image. +void AIEventCourier::event_isRepaired(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_isRepaired"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (bot) + static_cast(bot)->setIsRepaired(true); } -void AIEventCourier::event_requestNewOrders(int, int) +// ELF 0x3991A0: guarded SquadManager::repeatOrder with the two arguments swapped. +void AIEventCourier::event_requestNewOrders(int a, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_requestNewOrders"); + if (SquadManager::m_instance) + SquadManager::m_instance->repeatOrder(b, a); // ELF 0x3991D1 } -void AIEventCourier::event_recievedAttackCommanderOrder(int) +// ELF 0x398B90: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 0, squad, true). +void AIEventCourier::event_recievedAttackCommanderOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedAttackCommanderOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderAttack, squadId, true); } -void AIEventCourier::event_recievedDefendCommanderOrder(int) +// ELF 0x398BE0: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 1, squad, true). +void AIEventCourier::event_recievedDefendCommanderOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedDefendCommanderOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderDefend, squadId, true); } -void AIEventCourier::event_recievedMoveCommanderOrder(int) +// ELF 0x398C30: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 2, squad, true). +void AIEventCourier::event_recievedMoveCommanderOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedMoveCommanderOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderMove, squadId, true); } -void AIEventCourier::event_incomingArtillery(int, Vec2) +// ELF 0x398C80: guarded; the 2D position gets the terrain altitude (IAITerrain +0x14 +// getTerrainAltitude(x, z)) as its y, and SquadManager::incomingArtillery(Vec3, side) follows. +void AIEventCourier::event_incomingArtillery(int side, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_incomingArtillery"); + if (SquadManager::m_instance) + { + const float height = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getTerrainAltitude(position.x, position.y); + Vec3 impact; + impact.x = position.x; + impact.y = height; + impact.z = position.y; + SquadManager::m_instance->incomingArtillery(impact, side); + } } -int AIEventCourier::event_receivedArtilleryRequest(int, int, Vec3) +// ELF 0x398D10: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x54 playerRequestsArtillery(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedArtilleryRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedArtilleryRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsArtillery(playerId, position); } -int AIEventCourier::event_receivedUavRequest(int, int, Vec3) +// ELF 0x398D80: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x58 playerRequestsUav(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedUavRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedUavRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsUav(playerId, position); } -int AIEventCourier::event_receivedSupplyRequest(int, int, Vec3) +// ELF 0x398DF0: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x5C playerRequestsSupply(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedSupplyRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedSupplyRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsSupply(playerId, position); } -int AIEventCourier::event_receivedVehicleDropRequest(int, int, Vec3) +// ELF 0x398E60: the side's SAI (IAIMain +0x3C getSAI) gets SAI +0x60 playerRequestsVehicleDrop(player, position). +// The ELF returns the SAI's bool in EAX unchanged. +int AIEventCourier::event_receivedVehicleDropRequest(int side, int playerId, Vec3 position) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedVehicleDropRequest"); + return IAIMain::m_instance->getSAI(side)->playerRequestsVehicleDrop(playerId, position); } -// Both guard the singleton and forward the +// ELF 0x398FA0. Guards the singleton and forwards the // unchanged squad id through IAIMain +0x68 / +0x64. The concrete AIMain callback is empty // in both images ; this courier still performs the virtual call. void AIEventCourier::event_commanderOrderAccepted(int squadId) @@ -194,27 +297,33 @@ void AIEventCourier::event_commanderOrderAccepted(int squadId) IAIMain::m_instance->commanderOrderAccepted(squadId); } -void AIEventCourier::event_commanderOrderRejected(int) +// ELF 0x398FE0: guarded IAIMain +0x6C, the same shape as event_commanderOrderAccepted. +void AIEventCourier::event_commanderOrderRejected(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_commanderOrderRejected"); + if (IAIMain::m_instance) + IAIMain::m_instance->commanderOrderRejected(squadId); } -int AIEventCourier::event_appliedForCommander(int) +// ELF 0x399020: IAIMain +0x70, unguarded. +void AIEventCourier::event_appliedForCommander(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_appliedForCommander"); + IAIMain::m_instance->appliedForCommander(playerId); } -int AIEventCourier::event_acceptedCommander(int, int) +// ELF 0x399060: the second argument's SAI gets SAI +0x4C setPlayerIsCommander(true), unguarded. +void AIEventCourier::event_acceptedCommander(int, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_acceptedCommander"); + IAIMain::m_instance->getSAI(side)->setPlayerIsCommander(true); } -void AIEventCourier::event_resignAsCommander(int, int) +// ELF 0x3990B0: guarded; setPlayerIsCommander(false) on the second argument's SAI. +void AIEventCourier::event_resignAsCommander(int, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_resignAsCommander"); + if (IAIMain::m_instance) + IAIMain::m_instance->getSAI(side)->setPlayerIsCommander(false); } -// Only the SquadManager singleton is guarded; +// ELF 0x398B50. Only the SquadManager singleton is guarded; // the manager receives the original one-based side and squad id without validation here. void AIEventCourier::eventNewSquadLeader(int side, int squadId) { @@ -222,7 +331,7 @@ void AIEventCourier::eventNewSquadLeader(int side, int squadId) SquadManager::m_instance->newSquadLeader(side, squadId); } -// The order is player id, squad id, side. +// ELF 0x399100. The order is player id, squad id, side. // Both images pass all three integers unchanged after testing the manager singleton. void AIEventCourier::event_joinedSquad(int playerId, int squadId, int side) { @@ -230,67 +339,82 @@ void AIEventCourier::event_joinedSquad(int playerId, int squadId, int side) SquadManager::m_instance->playerJoinsSquad(playerId, squadId, side); } -void AIEventCourier::event_removedFromSquad(int, int, int) +// ELF 0x399150: forwarded unchanged to the squad manager when it exists. +void AIEventCourier::event_removedFromSquad(int playerId, int squadId, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_removedFromSquad"); + if (SquadManager::m_instance) + SquadManager::m_instance->playerRemovedFromSquad(playerId, squadId, side); } -void AIEventCourier::event_recievedAttackSquadOrder(int) +// ELF 0x3991E0: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 0, squad, false). +void AIEventCourier::event_recievedAttackSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedAttackSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderAttack, squadId, false); } -void AIEventCourier::event_recievedDefendSquadOrder(int) +// ELF 0x399230: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 1, squad, false). +void AIEventCourier::event_recievedDefendSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedDefendSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderDefend, squadId, false); } -void AIEventCourier::event_recievedMoveSquadOrder(int) +// ELF 0x399280: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 2, squad, false). +void AIEventCourier::event_recievedMoveSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_recievedMoveSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(BotSquad::OrderMove, squadId, false); } -void AIEventCourier::event_receivedRepairSquadOrder(int) +// ELF 0x3992D0: guarded SquadManager::setSquadReceivedOrder(BotSquad::OrderType 3, squad, false). +void AIEventCourier::event_receivedRepairSquadOrder(int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_receivedRepairSquadOrder"); + if (SquadManager::m_instance) + SquadManager::m_instance->setSquadReceivedOrder(static_cast(3), squadId, false); } +// ELF 0x399320 and 0x399330 are bare `ret`s. void AIEventCourier::event_squadOrderAccepted(int, int) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_squadOrderAccepted"); } void AIEventCourier::event_squadOrderRejected(int, int) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_squadOrderRejected"); } -int AIEventCourier::event_botTeamKilled(int, int) +// ELF 0x399340: IBotManager +0x60 setBotTeamKilled, unguarded. +void AIEventCourier::event_botTeamKilled(int a, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_botTeamKilled"); + IBotManager::instance->setBotTeamKilled(a, b); } -int AIEventCourier::event_freeCameraFire(bool) +// ELF 0x399380: IAIPathfinding +0xF0 searchPointSelected(!fire), then the console's +// freeCameraFire. Neither singleton is tested. +void AIEventCourier::event_freeCameraFire(bool fire) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_freeCameraFire"); + IAIPathfinding::instance->searchPointSelected(!fire); + AIConsole::m_instance->freeCameraFire(); } +// ELF 0x399780: guarded SquadManager::removeAllSquads. void AIEventCourier::event_removeAllSquadMembers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_removeAllSquadMembers"); + if (SquadManager::m_instance) + SquadManager::m_instance->removeAllSquads(); } -// Forwards destroyable-map and bridge events to pathfinding and strategic owners. +// ELF 0x3993D0. Forwards map-part initialization unchanged, including the bool argument. // Requires initialized owners; negative map-part IDs emit an error diagnostic. -int AIEventCourier::event_retrievePathfindingMapId(int& mapPartId, bool walkable, const Vec3& minCorner, +void AIEventCourier::event_retrievePathfindingMapId(int& mapPartId, bool walkable, const Vec3& minCorner, const Vec3& maxCorner, const Mat4& transformation) { IAIPathfinding::instance->initializeDestroyableMapPart(mapPartId, walkable, minCorner, maxCorner, transformation); // +0xE0 / PE +0xDC - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_pathfindingMapIdDestroyed(int mapPartId, IAIObject* object) +// ELF 0x399430. +void AIEventCourier::event_pathfindingMapIdDestroyed(int mapPartId, IAIObject* object) { if (mapPartId < 0) { @@ -303,16 +427,16 @@ int AIEventCourier::event_pathfindingMapIdDestroyed(int mapPartId, IAIObject* ob if (object) AIStrategicObjectManager::getInstance()->removeBridgeSegment(object); } - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_pathfindingMapIdRestored(int mapPartId) +// ELF 0x399580. +void AIEventCourier::event_pathfindingMapIdRestored(int mapPartId) { IAIPathfinding::instance->restoreMapPart(mapPartId); // +0xE8 / PE +0xE4 - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_pathfindingMapIdRestoreOriginalMaterials(int mapPartId, IAIObject* object) +// ELF 0x3995C0. +void AIEventCourier::event_pathfindingMapIdRestoreOriginalMaterials(int mapPartId, IAIObject* object) { if (mapPartId < 0) { @@ -325,49 +449,47 @@ int AIEventCourier::event_pathfindingMapIdRestoreOriginalMaterials(int mapPartId if (object) AIStrategicObjectManager::getInstance()->removeBridgeSegment(object); } - return 0; // [CHOSEN, not recovered] - see above } -// The int lands in the segment's +4, [UNRESOLVED] (see AIStrategicObjectManager::BridgeSegment). -int AIEventCourier::event_bridgeDestroyed(IAIObject* object, int value) +// ELF 0x399710. The int lands in the segment's +4, [UNRESOLVED] (see AIStrategicObjectManager::BridgeSegment). +void AIEventCourier::event_bridgeDestroyed(IAIObject* object, int value) { AIStrategicObjectManager::getInstance()->bridgeSegmentDestroyed(object, value); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_bridgeRepaired(IAIObject* object) +// ELF 0x399750. +void AIEventCourier::event_bridgeRepaired(IAIObject* object) { AIStrategicObjectManager::getInstance()->bridgeSegmentRepaired(object); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_bridgeCreated(IAIObject* object) +// ELF 0x3997B0. +void AIEventCourier::event_bridgeCreated(IAIObject* object) { AIStrategicObjectManager::getInstance()->createBridgeSegment(object); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_bridgeRemoved(IAIObject* object) +// ELF 0x3997E0. +void AIEventCourier::event_bridgeRemoved(IAIObject* object) { AIStrategicObjectManager::getInstance()->removeBridgeSegment(object); - return 0; // [CHOSEN, not recovered] - see above } -// Initializes strategic areas, then pathfinding maps after level loading. -int AIEventCourier::event_levelLoaded() +// ELF 0x399810. Initializes strategic areas before pathfinding maps. +void AIEventCourier::event_levelLoaded() { AIStrategicObjectManager::getInstance()->postLoadInitAreas(); IAIPathfindingSetup::instance->initMaps(); - return 0; // [CHOSEN, not recovered] - see above } -int AIEventCourier::event_botSwitchSides(int) +// ELF 0x399850: IAIMain +0x28 switchSides(int), unguarded. +void AIEventCourier::event_botSwitchSides(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIEventCourier::event_botSwitchSides"); + IAIMain::m_instance->switchSides(playerId); } -// Forwards a side switch when the IAIMain singleton exists. +// ELF 0x399890. Forwards a side switch when the IAIMain singleton exists. void AIEventCourier::event_playerSwitchSides(int side, int playerId) { if (IAIMain::m_instance) diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h index 540a2b978..b436d5e6c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.h @@ -1,6 +1,5 @@ // Routes game events into the AI module. -// Preserve virtual declaration order. [INFERRED] Return types require validation where implementations remain incomplete. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// Preserve virtual declaration order. Notification callbacks forward without a scalar result. #ifndef AI_AIDLL_AI_MAIN_AIEVENTCOURIER_H #define AI_AIDLL_AI_MAIN_AIEVENTCOURIER_H @@ -25,23 +24,23 @@ class IAIEventCourier IAIEventCourier(); virtual ~IAIEventCourier(); virtual void eventMissileLock(IAIObject *, world::MissileLockMessage *) = 0; - virtual int eventPlayerSpawned(int) = 0; + virtual void eventPlayerSpawned(int) = 0; virtual void eventPlayerKilled(int, int) = 0; virtual void eventPlayerCreated(bool) = 0; virtual void eventChangedKit(KitType) = 0; virtual void eventPlayerDisconnect(int) = 0; - virtual int eventPlayerEnterVehicle(int, IAIObject *, IAIObject *) = 0; - virtual int eventPlayerExitVehicle(IAIObject *, int) = 0; + virtual void eventPlayerEnterVehicle(int, IAIObject *, IAIObject *) = 0; + virtual void eventPlayerExitVehicle(IAIObject *, int) = 0; virtual void eventDrawDebug() = 0; - virtual int eventGameStart() = 0; + virtual void eventGameStart() = 0; virtual void event_roundEnd() = 0; virtual void event_worldReset() = 0; - virtual int eventManDown(int, IAIObject *) = 0; - virtual int eventRevived(int, IAIObject *) = 0; - virtual int eventRadioMessage(const AIRadioMessageSettings&, int, int) = 0; - virtual int event_mineRemoved(unsigned int) = 0; - virtual int event_enemySpotted(IAIObject *, unsigned char) = 0; - virtual int event_isRepaired(int) = 0; + virtual void eventManDown(int, IAIObject *) = 0; + virtual void eventRevived(int, IAIObject *) = 0; + virtual void eventRadioMessage(const AIRadioMessageSettings&, int, int) = 0; + virtual void event_mineRemoved(unsigned int) = 0; + virtual void event_enemySpotted(IAIObject *, unsigned char) = 0; + virtual void event_isRepaired(int) = 0; virtual void event_requestNewOrders(int, int) = 0; virtual void event_recievedAttackCommanderOrder(int) = 0; virtual void event_recievedDefendCommanderOrder(int) = 0; @@ -53,8 +52,8 @@ class IAIEventCourier virtual int event_receivedVehicleDropRequest(int, int, Vec3) = 0; virtual void event_commanderOrderAccepted(int) = 0; virtual void event_commanderOrderRejected(int) = 0; - virtual int event_appliedForCommander(int) = 0; - virtual int event_acceptedCommander(int, int) = 0; + virtual void event_appliedForCommander(int) = 0; + virtual void event_acceptedCommander(int, int) = 0; virtual void event_resignAsCommander(int, int) = 0; virtual void eventNewSquadLeader(int, int) = 0; virtual void event_joinedSquad(int, int, int) = 0; @@ -65,19 +64,19 @@ class IAIEventCourier virtual void event_receivedRepairSquadOrder(int) = 0; virtual void event_squadOrderAccepted(int, int) = 0; virtual void event_squadOrderRejected(int, int) = 0; - virtual int event_botTeamKilled(int, int) = 0; - virtual int event_freeCameraFire(bool) = 0; + virtual void event_botTeamKilled(int, int) = 0; + virtual void event_freeCameraFire(bool) = 0; virtual void event_removeAllSquadMembers() = 0; - virtual int event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&) = 0; - virtual int event_pathfindingMapIdDestroyed(int, IAIObject *) = 0; - virtual int event_pathfindingMapIdRestored(int) = 0; - virtual int event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *) = 0; - virtual int event_bridgeDestroyed(IAIObject *, int) = 0; - virtual int event_bridgeRepaired(IAIObject *) = 0; - virtual int event_bridgeCreated(IAIObject *) = 0; - virtual int event_bridgeRemoved(IAIObject *) = 0; - virtual int event_levelLoaded() = 0; - virtual int event_botSwitchSides(int) = 0; + virtual void event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&) = 0; + virtual void event_pathfindingMapIdDestroyed(int, IAIObject *) = 0; + virtual void event_pathfindingMapIdRestored(int) = 0; + virtual void event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *) = 0; + virtual void event_bridgeDestroyed(IAIObject *, int) = 0; + virtual void event_bridgeRepaired(IAIObject *) = 0; + virtual void event_bridgeCreated(IAIObject *) = 0; + virtual void event_bridgeRemoved(IAIObject *) = 0; + virtual void event_levelLoaded() = 0; + virtual void event_botSwitchSides(int) = 0; virtual void event_playerSwitchSides(int, int) = 0; }; @@ -90,23 +89,23 @@ class AIEventCourier : public IAIEventCourier // IAIEventCourier virtual void eventMissileLock(IAIObject *, world::MissileLockMessage *); - virtual int eventPlayerSpawned(int); + virtual void eventPlayerSpawned(int); virtual void eventPlayerKilled(int, int); virtual void eventPlayerCreated(bool); virtual void eventChangedKit(KitType); virtual void eventPlayerDisconnect(int); - virtual int eventPlayerEnterVehicle(int, IAIObject *, IAIObject *); - virtual int eventPlayerExitVehicle(IAIObject *, int); + virtual void eventPlayerEnterVehicle(int, IAIObject *, IAIObject *); + virtual void eventPlayerExitVehicle(IAIObject *, int); virtual void eventDrawDebug(); - virtual int eventGameStart(); + virtual void eventGameStart(); virtual void event_roundEnd(); virtual void event_worldReset(); - virtual int eventManDown(int, IAIObject *); - virtual int eventRevived(int, IAIObject *); - virtual int eventRadioMessage(const AIRadioMessageSettings&, int, int); - virtual int event_mineRemoved(unsigned int); - virtual int event_enemySpotted(IAIObject *, unsigned char); - virtual int event_isRepaired(int); + virtual void eventManDown(int, IAIObject *); + virtual void eventRevived(int, IAIObject *); + virtual void eventRadioMessage(const AIRadioMessageSettings&, int, int); + virtual void event_mineRemoved(unsigned int); + virtual void event_enemySpotted(IAIObject *, unsigned char); + virtual void event_isRepaired(int); virtual void event_requestNewOrders(int, int); virtual void event_recievedAttackCommanderOrder(int); virtual void event_recievedDefendCommanderOrder(int); @@ -118,8 +117,8 @@ class AIEventCourier : public IAIEventCourier virtual int event_receivedVehicleDropRequest(int, int, Vec3); virtual void event_commanderOrderAccepted(int); // guarded IAIMain forward virtual void event_commanderOrderRejected(int); - virtual int event_appliedForCommander(int); - virtual int event_acceptedCommander(int, int); + virtual void event_appliedForCommander(int); + virtual void event_acceptedCommander(int, int); virtual void event_resignAsCommander(int, int); virtual void eventNewSquadLeader(int, int); // side then squad id virtual void event_joinedSquad(int, int, int); // player id, squad id, side @@ -130,20 +129,20 @@ class AIEventCourier : public IAIEventCourier virtual void event_receivedRepairSquadOrder(int); virtual void event_squadOrderAccepted(int, int); virtual void event_squadOrderRejected(int, int); - virtual int event_botTeamKilled(int, int); - virtual int event_freeCameraFire(bool); + virtual void event_botTeamKilled(int, int); + virtual void event_freeCameraFire(bool); virtual void event_removeAllSquadMembers(); // the eight below: / - virtual int event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&); // IAIPathfinding forward - virtual int event_pathfindingMapIdDestroyed(int, IAIObject *); // Debug(Error) if < 0, line 508 - virtual int event_pathfindingMapIdRestored(int); // IAIPathfinding forward - virtual int event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *); // Debug(Error) if < 0, line 532 - virtual int event_bridgeDestroyed(IAIObject *, int); // AIStrategicObjectManager forwards - virtual int event_bridgeRepaired(IAIObject *); // no singleton test - virtual int event_bridgeCreated(IAIObject *); - virtual int event_bridgeRemoved(IAIObject *); - virtual int event_levelLoaded(); - virtual int event_botSwitchSides(int); + virtual void event_retrievePathfindingMapId(int &, bool, const Vec3&, const Vec3&, const Mat4&); // IAIPathfinding forward + virtual void event_pathfindingMapIdDestroyed(int, IAIObject *); // Debug(Error) if < 0, line 508 + virtual void event_pathfindingMapIdRestored(int); // IAIPathfinding forward + virtual void event_pathfindingMapIdRestoreOriginalMaterials(int, IAIObject *); // Debug(Error) if < 0, line 532 + virtual void event_bridgeDestroyed(IAIObject *, int); // AIStrategicObjectManager forwards + virtual void event_bridgeRepaired(IAIObject *); // no singleton test + virtual void event_bridgeCreated(IAIObject *); + virtual void event_bridgeRemoved(IAIObject *); + virtual void event_levelLoaded(); + virtual void event_botSwitchSides(int); virtual void event_playerSwitchSides(int, int); }; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp index ca9fce5f0..9a3268cbf 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp @@ -1,9 +1,23 @@ // [INFERRED] Source placement. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AILODManager operations. + +// static init: ELF 0x39C180 (__tcf_0 0x39C1E0, _GLOBAL__I 0x39C210): 's Init object only. +#include #include "AILODManager.h" -#include "AIDllFrontier.h" +#include +#include "CommonSingletonServer.h" +#include "IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" +#include "../../../../Math/Mat4.h" namespace dice { namespace hfe { @@ -11,17 +25,56 @@ namespace ai { AILODManager* AILODManager::m_instance = 0; -// Seeds both LOD distance fields from the same value and updates players before +// ELF 0x39B0D0 / 0x39B100. +PlayerLODStats::PlayerLODStats() : m_position(), m_player(0), m_lodDistance(0.0f) {} + +// ELF 0x39B130 / 0x39B160. +PlayerLODStats::PlayerLODStats(IAIPlayer* player) + : m_position(), m_player(player), m_lodDistance(0.0f) {} + +// ELF 0x39B190 / 0x39B1D0. +PlayerLODStats::PlayerLODStats(const PlayerLODStats& other) + : m_position(other.m_position), m_player(other.m_player), m_lodDistance(other.m_lodDistance) {} + +// ELF 0x39B210 / 0x39B220. Does not own the player. +PlayerLODStats::~PlayerLODStats() {} + +// ELF 0x39B230. Dead players, or those without a vehicle, use the camera position. +void PlayerLODStats::update(float basicDistance, float speedScale) +{ + float speed = 0.0f; + IAIObject* vehicle = 0; + if (m_player->getIsAlive()) + vehicle = m_player->getCurrentVehicle(); + if (vehicle) + { + m_position = vehicle->getPosition(); + if (vehicle->isMobile()) + speed = vehicle->getMobile()->getSpeedMagnitude(); + } + else + { + const Mat4* const camera = static_cast(m_player->getCameraTransformation()); + m_position.x = camera->m[12]; + m_position.y = camera->m[13]; + m_position.z = camera->m[14]; + } + speedScale *= speed; + m_lodDistance = basicDistance + speedScale; + m_lodDistance *= m_player->getFieldOfViewModifier(); +} + +// ELF 0x39B320 / 0x39B4C0. Seeds both distances equally and updates players before // publishing the singleton. Player initialization must work before publication. AILODManager::AILODManager(float basicLODDistance, float f36) : m_playerStats() - , m_set16() + , m_updatedPlayerIds() , m_basicLODDistance(basicLODDistance) , m_maxLODDistance(basicLODDistance) , m_f36(f36) , m_lodEnable(true) - , m_i44(-1) - , m_i48(0) + , m_playerCursor(-1) + , m_botCursor(0) { updateAllPlayers(); @@ -29,77 +82,203 @@ AILODManager::AILODManager(float basicLODDistance, float f36) m_instance = this; } -// [FRONTIER] LOD-manager teardown remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when ordered destruction is recovered. +// ELF 0x39B690 (D1, 240 B; recovered on the client track, docs/macos-c-singleplayer.md): the +// singleton is zeroed when it is this one; the set and the stats map go as members. AILODManager::~AILODManager() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::~AILODManager"); + if (m_instance == this) + m_instance = 0; } -// Updates players, clears their statistics, and enables LOD regardless of its previous setting. -void AILODManager::reset() +// ELF 0x39C090. Updates players, clears their statistics, and enables LOD. +bool AILODManager::reset() { updatePlayers(); m_playerStats.clear(); m_lodEnable = true; + return true; } -// - one store. `AISettings::setViewDistance` is its only caller in the image. +// ELF 0x39C170. `AISettings::setViewDistance` is its only caller in the image. void AILODManager::setBasicLODDistance(float distance) { m_basicLODDistance = distance; } // Setter and getter intentionally share the lodEnable name. -void AILODManager::lodEnable(bool enable) +// ELF 0x39C060: stores the byte and returns it (movzbl of the argument). +bool AILODManager::lodEnable(bool enable) { m_lodEnable = enable; + return enable; } -bool AILODManager::lodEnable() const +// ELF 0x39C080. Nonconst by the mangled symbol. +bool AILODManager::lodEnable() { return m_lodEnable; } -// [FRONTIER] Player LOD updates remain unimplemented; construction reaches updateAllPlayers. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when its corresponding update behavior is recovered. - +// ELF 0x39B780. void AILODManager::updateAllPlayers() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updateAllPlayers"); + if (!m_lodEnable) + return; + const std::vector& players = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment)->getActivePlayerIds(); + m_updatedPlayerIds.clear(); + for (std::vector::const_iterator it = players.begin(); it != players.end(); ++it) + updatePlayer(*it); + updatePlayerMap(); + m_updatedPlayerIds.clear(); } +// ELF 0x39B880. A completed sweep prunes stale entries before clearing its ID set. void AILODManager::updatePlayers() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updatePlayers"); + IAIObjectEnvironment* const environment = static_cast( + CommonSingletonServer::m_iaiObjectEnvironment); + const std::vector& players = environment->getActivePlayerIds(); + if (environment->isValidPlayerId(m_playerCursor)) + { + updatePlayer(m_playerCursor); + m_playerCursor = environment->getNextPlayerId(m_playerCursor); + } + else + { + if (!players.empty()) + { + m_playerCursor = players.front(); + updatePlayerMap(); + } + m_updatedPlayerIds.clear(); + } } -void AILODManager::updatePlayer(int) +// ELF 0x39B970. Disabled LOD still answers true without touching player state. +bool AILODManager::updatePlayer(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updatePlayer"); + if (m_lodEnable) + { + std::map::iterator it = m_playerStats.find(playerId); + if (it == m_playerStats.end()) + { + IAIPlayer* const player = static_cast( + CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(playerId); + it = m_playerStats.insert(std::pair( + playerId, PlayerLODStats(player))).first; + } + it->second.update(m_basicLODDistance, m_f36); + m_updatedPlayerIds.insert(it->first); + } + return true; } +// ELF 0x39BB80. Equal container sizes skip the scan, even if their keys differ. void AILODManager::updatePlayerMap() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updatePlayerMap"); + if (m_updatedPlayerIds.size() == m_playerStats.size()) + return; + std::map::iterator it = m_playerStats.begin(); + while (it != m_playerStats.end()) + { + if (m_updatedPlayerIds.find(it->first) == m_updatedPlayerIds.end()) + m_playerStats.erase(it++); + else + ++it; + } } +// ELF 0x39BC90. Limits each enabled pass to four successful updates, retaining the cursor. void AILODManager::updateBots() { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updateBots"); + IBotManager* const manager = IBotManager::instance; + if (!manager || manager->getBotCount() == 0) + return; + int updated = 0; + Bot* const first = manager->getBot(static_cast(m_botCursor)); + ++m_botCursor; + if (!m_lodEnable) + first->setLodLevel(BotLodFull); + else + { + if (updateBot(first)) + updated = 1; + while (updated < 4 && m_botCursor < manager->getBotCount()) + { + Bot* const bot = manager->getBot(static_cast(m_botCursor)); + const bool success = updateBot(bot); + ++m_botCursor; + if (success) + ++updated; + } + } + if (m_botCursor >= manager->getBotCount()) + m_botCursor = 0; } -void AILODManager::updateBot(Bot*) +// ELF 0x39BD70. Hysteresis depends on the old level; each pass begins at light detail. +bool AILODManager::updateBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::updateBot"); + const BotLodLevel oldLevel = bot->getLodLevel(); + bot->setLodLevel(BotLodLight); + if (bot->isDead()) + return false; + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information) + return false; + IAIObject* const object = information->getAIObject(); + const Vec3& position = information->getPosition(); + float fullThreshold = 1.0f; + float mediumThreshold = 1.425f; + if (oldLevel == BotLodFull) + { + fullThreshold = 1.05f; + mediumThreshold = 1.5f; + } + else if (oldLevel == BotLodMedium) + { + fullThreshold = 0.95f; + mediumThreshold = 1.575f; + } + float speed = 0.0f; + IPIMobile* const mobile = information->getMobile(); + if (mobile) + speed = mobile->getSpeedMagnitude(); + for (std::map::iterator it = m_playerStats.begin(); + it != m_playerStats.end(); ++it) + { + const float x = it->second.m_position.x - position.x; + const float y = it->second.m_position.y - position.y; + const float z = it->second.m_position.z - position.z; + float distance = std::sqrt(x * x + y * y + z * z) - speed * m_f36; + if (it->second.m_lodDistance > 1.0e-7f) + distance /= it->second.m_lodDistance; + if (distance < fullThreshold) + { + bot->setLodLevel(BotLodFull); + if (oldLevel != BotLodFull && object->isMobile() && object->isPhysical()) + { + IAIObjectPhysical* const physical = object->getPhysical(); + if (!physical->hasPhysicsEnabled()) + physical->enablePhysics(bot->getSide()); + } + break; + } + if (bot->getLodLevel() > BotLodMedium && distance < mediumThreshold) + bot->setLodLevel(BotLodMedium); + } + return true; } -void AILODManager::removePlayer(int) +// ELF 0x39C110. +void AILODManager::removePlayer(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AILODManager::removePlayer"); + if (m_playerCursor == playerId) + m_playerCursor = -1; + m_playerStats.erase(playerId); + m_updatedPlayerIds.erase(playerId); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h index 1fe481295..43653e801 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.h @@ -1,5 +1,4 @@ // Controls AI level of detail and update budgets. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_AILODMANAGER_H // [INFERRED] guard style @@ -7,56 +6,63 @@ #include #include +#include "../../../../Math/Vec3.h" namespace dice { namespace hfe { namespace ai { class Bot; +class IAIPlayer; -// Per-player LOD record. [CHOSEN, not recovered] Five words preserve its known 20-byte -// size; field meanings remain unknown. +// Per-player position and distance used when selecting bot detail levels. class PlayerLODStats { public: - int m_words[5]; + PlayerLODStats(); + explicit PlayerLODStats(IAIPlayer* player); + PlayerLODStats(const PlayerLODStats& other); + ~PlayerLODStats(); + void update(float basicDistance, float speedScale); + + // ELF offsets; names are [INFERRED]. The player is borrowed. + /* +0x00 */ Vec3 m_position; + /* +0x0C */ IAIPlayer* m_player; + /* +0x10 */ float m_lodDistance; }; class AILODManager { public: AILODManager(float basicLODDistance, float f36); - ~AILODManager(); // , [FRONTIER] + ~AILODManager(); // ELF 0x39B690 // The whole vtable. See the header note. - virtual void reset(); + virtual bool reset(); void setBasicLODDistance(float distance); - void lodEnable(bool enable); - bool lodEnable() const; + bool lodEnable(bool enable); // ELF 0x39C060 answers the stored value (ConsoleClass293 keeps it) + bool lodEnable(); - // the seven that are not written - // Each is a named stop; `updateAllPlayers` is reached from the constructor and the rest from - // `reset` or from the console, so none of them runs on a path this tree exercises. - void updateAllPlayers(); // [FRONTIER] - void updatePlayers(); // [FRONTIER] - void updatePlayer(int playerId); // [FRONTIER] - void updatePlayerMap(); // [FRONTIER] - void updateBots(); // [FRONTIER] - void updateBot(Bot* bot); // [FRONTIER] - void removePlayer(int playerId); // [FRONTIER] + void updateAllPlayers(); + void updatePlayers(); + bool updatePlayer(int playerId); // [INFERRED] bool: every exit returns 1 + void updatePlayerMap(); + void updateBots(); + bool updateBot(Bot* bot); + void removePlayer(int playerId); static AILODManager* m_instance; // layout, on the ELF, read store by store out of the constructor /* +4 */ std::map m_playerStats; // `reset` clears it - /* +16 */ std::set m_set16; // [UNRESOLVED] - a 4-byte element + /* +16 */ std::set m_updatedPlayerIds; // [INFERRED] IDs seen in the current sweep /* +28 */ float m_basicLODDistance; // = the first argument; `setBasicLODDistance` writes it /* +32 */ float m_maxLODDistance; // = the first argument too - see the header note [INFERRED] - /* +36 */ float m_f36; // = the second argument [UNRESOLVED] + /* +36 */ float m_f36; // speed scale; second constructor argument /* +40 */ bool m_lodEnable; // = true; the `lodEnable` pair, and `reset` raises it again - /* +44 */ int m_i44; // = -1 [UNRESOLVED] - /* +48 */ int m_i48; // = 0 [UNRESOLVED] + /* +44 */ int m_playerCursor; // = -1; next player ID [INFERRED] + /* +48 */ int m_botCursor; // = 0; next bot index [INFERRED] }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp index b370b581f..3c58a5fd7 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp @@ -1,11 +1,14 @@ // AI runtime lifecycle, population management and simulation updates. +// static init: ELF 0x39F580 (__tcf_0 0x39F5E0, _GLOBAL__I 0x39F610): 's Init object only. +#include + #include "AIMain.h" #include // std::min - spawnBots' bot budget +#include #include -#include "AIDllFrontier.h" // the twenty named stops below #include "../AIUtils/checkPointer.h" // the ctor's dead null check #include "../AIBotBehaviour/CustomCurve.h" // SCurve / JCurve / DecleiningSlopeCurve #include "../../../AIInterface/Module/BFConsole.h" // IBFModuleCourier::aiMainInit @@ -30,7 +33,10 @@ #include "../../../AIInterface/BFKnowledge/BFTimer.h" // action's three timer methods #include "../../../AIInterface/BFKnowledge/BFCollisionHandler.h" // updateBotProjectiles #include "../AIBot/SquadManager.h" // update(double) -#include "AIMineManager.h" // IAIMineManager::update +#include "AIMineManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // updateAIObject, vehicle changes +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit +#include "CommunicationHub.h" // resetLevel // IAIMineManager::update namespace dice { namespace hfe { @@ -41,11 +47,13 @@ IAIMain* IAIMain::m_instance = 0; // Construction replaces the active IAIMain pointer. Destruction clears it unconditionally. // Only one IAIMain may be alive when callers use this singleton. +// ELF 0x3E6790 / 0x3E67C0 IAIMain::IAIMain() { m_instance = this; } +// ELF 0x3E67F0 / 0x3E6820 / 0x3E6850 IAIMain::~IAIMain() { m_instance = 0; @@ -53,6 +61,7 @@ IAIMain::~IAIMain() // Returns whether initialization has completed. [INFERRED] State-field name. +// ELF 0x39F9F0 bool AIMain::isInitialised() { return m_initialised; @@ -63,38 +72,46 @@ bool AIMain::isInitialised() // The AI's debug rendering entry point - inert on a dedicated server build, which is the // only build this pair comes from. So none of the ~20 show*/render* console switches this class // exposes can produce any output here; they set flags that only a client-side AIMain would read. +// ELF 0x39DD60 void AIMain::draw() { } // The sound-event hook is empty, so it never fills the sound queue. // [UNRESOLVED] SoundEffect members cannot be established from this path. +// ELF 0x39EF60 void AIMain::queueSoundEffect(const Vec3& /*pos*/, int /*a*/, int /*b*/) { } // These five commander notifications intentionally do nothing in AIMain. +// ELF 0x39F530 void AIMain::commanderOrderAccepted(int /*a*/) { } +// ELF 0x39F540 void AIMain::commanderOrderRejected(int /*a*/) { } +// ELF 0x39F550 void AIMain::appliedForCommander(int /*a*/) { } +// ELF 0x39F560 void AIMain::acceptedAsCommander(int /*a*/) { } +// ELF 0x39F570 void AIMain::resignedAsCommander(int /*a*/) { } // Creates and activates bots up to the configured population budget when a round starts. +// ELF 0x39F3C0 void AIMain::spawnBots() { IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); @@ -123,41 +140,42 @@ void AIMain::spawnBots() } } -// Constructs and destroys the AI runtime. Remaining dependencies use named frontier stops. +// Constructs the AI runtime and its bot manager. +// ELF 0x39C970 / 0x39CDD0 AIMain::AIMain() // Keep BotManager allocation in the initializer list to preserve its position between // the surrounding container constructions. : m_aiSystemQuotient(0.15f) // the float constant, widened - see AIMain.h - , m_dword12(0.875) + , m_botManagerQuotient(0.875) , m_componentQuotient(0.125) , m_double28(0.0) , m_dword36(0) - , m_double40(3.0) + , m_botStatisticUpdateSpeed(3.0) , m_dword100(0) , m_initialised(false) , m_saiEnabled(false) , m_dword108(0) , m_dword112(0) , m_float120(100.0f) - , m_dword128(1) + , m_renderSide(1) , m_dword132(0) - , m_flag136(false) - , m_flag137(true) - , m_flag138(false) - , m_flag139(true) - , m_flag140(true) - , m_flag141(false) + , m_showBotUrgencies(false) + , m_showStrategies(true) + , m_showSAIStats(false) + , m_showBotStats(true) + , m_showStrategicAreas(true) + , m_showBotSpawnCoord(false) , m_dword144(0) , m_flag148(false) , m_componentCursor(0) - , m_dword168(64) - , m_dword172(64) + , m_saiMapXDimension(64) + , m_saiMapYDimension(64) // FLT_MAX in A double, as the float constant and widened - that is what the binary // stores and the `f` suffix is what reproduces it exactly. A "no value yet" sentinel. , m_double176(-3.4028235e38f) , m_double184(-3.4028235e38f) , m_botManager(checkPointer(new BotManager)) - , m_flag196(false) + , m_validateDataStructuresEnabled(false) , m_botCount(0) , m_humanCount(0) { @@ -180,31 +198,49 @@ AIMain::AIMain() m_sai[2] = 0; } +// ELF 0x39D390 (D1, 538 B; recovered on the client track, docs/macos-c-singleplayer.md). The +// per-side SAIs 1..getNSides() go through their virtual deleting destructor (+4) and are zeroed +// - the side count is asked again on every pass (IAISettings +0x40) - then the bot manager the +// same way. The containers and the IAIMain base follow as members. AIMain::~AIMain() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::~AIMain"); + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + { + if (m_sai[side]) + { + delete m_sai[side]; + m_sai[side] = 0; + } + } + if (m_botManager) + delete m_botManager; } -// The twenty remaining virtual slots, in vtable order. Addresses and sizes are in the [FRONTIER] -// list at the bottom of this file; nothing here adds evidence. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - -void AIMain::addNewPlayer(world::IPlayer* /*player*/) +// ELF 0x39F920 (weak): list insert at end() - the iterator is the list header itself. +void AIMain::addNewPlayer(world::IPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::addNewPlayer"); + m_playerQueue.push_back(player); } -void AIMain::popPlayer() +// ELF 0x39F970 (weak): counts the list (SGI size()), answers null when empty, else erases the +// first node and returns its player. +world::IPlayer* AIMain::popPlayer() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::popPlayer"); + if (m_playerQueue.size() == 0) + return 0; + world::IPlayer* const player = m_playerQueue.front(); + m_playerQueue.erase(m_playerQueue.begin()); + return player; } -void AIMain::registerFreeBot(Bot* /*bot*/) +// ELF 0x39E1B0: list insert at end() of the pending list action() hands to the SAIs. +void AIMain::registerFreeBot(Bot* bot) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::registerFreeBot"); + m_pendingBots.push_back(bot); } // Activates the bot associated with a player ID. +// ELF 0x39E3B0 bool AIMain::activateBot(int playerId, int side, const std::string& name) { IAIObjectEnvironment* const environment = @@ -222,7 +258,27 @@ bool AIMain::activateBot(int playerId, int side, const std::string& name) return addUnspawnedBot(playerId, side, settings->getStandardPersonality(side)); } +// ELF 0x39DDA0 +bool AIMain::addBot(int playerId, int side, float* personality, IAIObject* object) +{ + if (!m_botManager->addBot(playerId, side, personality, object)) + return false; + const int index = m_botManager->getBotCount() - 1; + Bot* const bot = m_botManager->getBot(static_cast(index)); + if (!UserOrderManager::m_instance->recruitBot(bot, side)) + { + if (m_sai[side]) + m_sai[side]->addBot(bot); + } + m_perBot48.push_back(std::pair(0.0f, 0.0f)); + m_perBot60.push_back(std::pair(0.0f, 0.0f)); + m_perBot72.push_back(std::pair(0.0f, 0.0f)); + m_perBot84.push_back(0.0f); + return true; +} + // Adds an unspawned bot to either player-directed orders or its side's strategic AI. +// ELF 0x39DFA0 bool AIMain::addUnspawnedBot(int playerId, int side, float* personality) { const IAISettings* const settings = @@ -251,18 +307,44 @@ bool AIMain::addUnspawnedBot(int playerId, int side, float* personality) return true; } -void AIMain::deactivateBot(int& /*a*/, int /*b*/) +// ELF 0x39E210: the player leaves its squad, a bot of the side is deactivated (-1: the +// player id becomes -1, false), the side's SAI (when set) drops it (SAI +0x1C) and the player +// id becomes the bot's. +bool AIMain::deactivateBot(int& playerId, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::deactivateBot(int&, int)"); + SquadManager::m_instance->removeSquadMember(playerId, side); + const int botId = m_botManager->deactivateBot(side); + if (botId == -1) + { + playerId = -1; + return false; + } + Bot* const bot = m_botManager->getBotFromId(static_cast(botId)); + if (m_sai[side]) + m_sai[side]->removeBot(bot); + playerId = bot->getPlayerId(); + return true; } -void AIMain::deactivateBot(int /*a*/) +// ELF 0x39E2E0: the player's squad member is destroyed, the dead bot of this player is +// deactivated (-1: false) and its side's SAI drops it. +bool AIMain::deactivateBot(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::deactivateBot(int)"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + SquadManager::m_instance->destroySquadMember(playerId, player->getSide()); + const int botId = m_botManager->deactivateBotFromPlayerId(playerId); + if (botId == -1) + return false; + Bot* const bot = m_botManager->getBotFromId(static_cast(botId)); + if (m_sai[bot->getSide()]) + m_sai[bot->getSide()]->removeBot(bot); + return true; } // Updates population counts when a player is created. // A human joining may remove a bot when humans count toward the configured population limit. +// ELF 0x39E7B0 void AIMain::newPlayerCreated(bool isAI) { if (isAI) @@ -338,17 +420,55 @@ void AIMain::newPlayerCreated(bool isAI) } } -void AIMain::reactivateBot(int /*a*/) +// ELF 0x39E460: a leaving human. The human count drops, the player's squad member is +// destroyed, and when humans count toward the limit and the population is below the game's +// maximum, spawnBots refills it (IAIMain +0x54). +void AIMain::reactivateBot(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::reactivateBot"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + if (!player) + return; + --m_humanCount; + SquadManager::m_instance->destroySquadMember(playerId, player->getSide()); + if (!static_cast(CommonSingletonServer::m_iaiSettings)->getmaxBotsIncludeHumans()) + return; + if (m_botCount + m_humanCount < static_cast(CommonSingletonServer::m_iaiGame)->getMaxNumberOfPlayers()) + spawnBots(); } -void AIMain::switchSides(int /*a*/) +// ELF 0x39E510 +void AIMain::switchSides(int side) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::switchSides(int)"); + IAIPlayer* selected = 0; + const std::vector players = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getAllPlayers(); + for (std::vector::const_iterator it = players.begin(); it != players.end(); ++it) + { + IAIPlayer* const player = *it; + if (!player || !player->getIsAIPlayer() || player->getSide() != side) + continue; + if (selected) + { + const int score = player->getScore(); + const int selectedScore = selected->getScore(); + if (score >= selectedScore) + continue; + } + selected = player; + } + if (selected) + { + selected->setSide((side == 1) + 1); + const int playerId = selected->getId(); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + getSAI(side)->removeBot(bot); + getSAI((side == 1) + 1)->addBot(bot); + } } // Moves a bot between sides and updates both strategic AI owners. +// ELF 0x39E6E0 void AIMain::switchSides(int side, int playerId) { Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); @@ -376,6 +496,7 @@ void AIMain::switchSides(int side, int playerId) // Recovered caller: . This retires the entry stop, not the // scheduled callees' individual frontiers (RW-102); no completed tick is implied by linking it. +// ELF 0x39DB90 bool AIMain::action() { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -437,54 +558,144 @@ bool AIMain::action() return true; // Explicit EAX=1 (ELF) / AL=1 (PE), after every scheduled call returns. } +// ELF 0x39EB00: `movzbl 0x69(this)`. bool AIMain::getSAIEnable() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::getSAIEnable"); + return m_saiEnabled; } // an unchecked side-indexed pointer read. +// ELF 0x39EA00 SAI* AIMain::getSAI(int side) { return m_sai[side]; } -void AIMain::updateAIObject(IAIObject* /*o*/) +// ELF 0x39EF40: IAIObject +0x104 positionChanged. +void AIMain::updateAIObject(IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::updateAIObject"); + object->positionChanged(); } -void AIMain::reset() +// ELF 0x39EF70 +bool AIMain::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::reset"); + if (m_initialised) + { + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + { + if (m_sai[side]) + { + delete m_sai[side]; + m_sai[side] = 0; + } + } + m_dword132 = 0; + m_saiMapYDimension = 32; + m_dword144 = 0; + m_aiSystemQuotient = 0.2; + m_renderSide = 1; + m_dword100 = 0; + m_initialised = false; + m_botManagerQuotient = 0.75f; + m_saiMapXDimension = 32; + m_saiEnabled = false; + m_showBotUrgencies = false; + m_componentQuotient = 0.25f; + m_validateDataStructuresEnabled = false; + m_flag148 = false; + m_dword36 = 0; + m_double28 = 0.0f; + m_botStatisticUpdateSpeed = 3.0f; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + const float width = static_cast(terrain->getWorldSizeX()); + const float height = static_cast(terrain->getWorldSizeZ()); + m_float120 = 100.0f; + // [CHOSEN, not recovered] Native libm marks log const; this barrier retains all four shipped calls. + double (*volatile logarithm)(double) = &std::log; + (void)logarithm(static_cast(width)); + (void)logarithm(2.0); + (void)logarithm(static_cast(height)); + (void)logarithm(2.0); + IAIPathfinding::instance->reset(); + IBotManager::instance->reset(); + static_cast(CommonSingletonServer::m_iBFTimer)->reset(); + static_cast(CommonSingletonServer::m_iBFModuleCourier)->reset(); + } + return true; } -void AIMain::resetLevel() +// ELF 0x39F140. The bridges are reset, then the strategic areas (AIStrategicObjectManager +0x04 +// resetAreas); every side's SAI is reset only while all previous resets succeeded (the && chain +// short-circuits). Then the projectiles (IBFCollisionHandler +0x08), the destroyable map parts +// (IAIPathfinding +0x10), the bridges a second time, the communication hub and the mines +// (IAIMineManager +0x0C). Returns the combined strategic reset result. +bool AIMain::resetLevel() { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::resetLevel"); + AIStrategicObjectManager::getInstance()->resetBridges(); + bool ok = AIStrategicObjectManager::getInstance()->resetAreas(); + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + { + if (m_sai[side]) + ok = ok && m_sai[side]->reset(); + } + static_cast(CommonSingletonServer::m_iBFCollisionHandler)->removeAllProjectiles(); + IAIPathfinding::instance->resetDestroyableMapParts(); + AIStrategicObjectManager::getInstance()->resetBridges(); + CommunicationHub::m_instance->reset(); + static_cast(CommonSingletonServer::m_iAIMineManager)->reset(); + return ok; } -void AIMain::setAISystemQuotient(const double& /*q*/) +// ELF 0x39DAE0. The two x87 tests against 0.0f (ELF 0x49CB34) and 1.0f (0x49CB2C) are joined +// with "or": the value is stored unless it is below 0 and above 1 at once, i.e. always (a NaN +// too: its first comparison is unordered and takes the storing branch). +void AIMain::setAISystemQuotient(const double& q) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::setAISystemQuotient"); + if (!(q < 0.0f) || !(q > 1.0f)) + m_aiSystemQuotient = q; } +// ELF 0x39FA00 (weak): `fldl 0x4(this)`. double AIMain::getAISystemQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::getAISystemQuotient"); + return m_aiSystemQuotient; } -void AIMain::setPlayerExitedVehicle(IAIObject* /*o*/, int /*a*/) +// ELF 0x39F230. When a human (IAIPlayer +0x88 getIsAIPlayer false) leaves a unit, the unit +// records the game time as its last possession (IAIObjectUnit +0x64; the unit plug-in is +// fetched before the time) and its primary object is allowed to bots again (+0x9C). +void AIMain::setPlayerExitedVehicle(IAIObject* vehicle, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::setPlayerExitedVehicle"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + if (vehicle && vehicle->isUnit() && player && !player->getIsAIPlayer()) + { + IAIObjectUnit* const unit = vehicle->getUnit(); + unit->setLastPlayerPossesionTime( + static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); + vehicle->getPrimaryObject()->setIsAllowedByBots(true); + } } -void AIMain::setPlayerEnteredVehicle(IAIObject* /*o*/, IAIObject* /*v*/, int /*a*/) +// ELF 0x39F2F0. A human moving between two units with different primary objects leaves the +// first unit's last possession at -1000.0f (ELF 0x49CDC8). The second object is tested first. +void AIMain::setPlayerEnteredVehicle(IAIObject* from, IAIObject* to, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::AIMain::setPlayerEnteredVehicle"); + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + if (to && to->isUnit() && from && from->isUnit() && player && !player->getIsAIPlayer()) + { + IAIObject* const toPrimary = to->getPrimaryObject(); + IAIObject* const fromPrimary = from->getPrimaryObject(); + if (toPrimary && fromPrimary && toPrimary != fromPrimary) + from->getUnit()->setLastPlayerPossesionTime(-1000.0f); + } } // Initializes the AI synchronously from the level script and returns a status message. // The integer argument is unused. +// ELF 0x39D7E0 std::string AIMain::init(int) { // built first, before any work. The message is constructed at the top of the body and @@ -519,11 +730,8 @@ std::string AIMain::init(int) return result; } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] -// The methods below stop until their remaining behavior is implemented and validated. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - // Creates one strategic AI instance for each side. +// ELF 0x39EA20 void AIMain::createSAI() { const IAISettings* const settings = @@ -542,11 +750,12 @@ void AIMain::createSAI() max.x = static_cast(terrain->getWorldSizeX()); max.y = static_cast(terrain->getWorldSizeZ()); - m_sai[side] = ISAI::create(side, m_dword168, m_dword172, min, max); + m_sai[side] = ISAI::create(side, m_saiMapXDimension, m_saiMapYDimension, min, max); } } // Sets the requested state and returns the value accepted, or false when refused. +// ELF 0x39EB10 bool AIMain::setSAIEnable(bool enable) { if (AIStrategicObjectManager::getInstance()->getNumberOfStrategicObjects()) @@ -562,7 +771,117 @@ bool AIMain::setSAIEnable(bool enable) return false; } -// [FRONTIER] The remaining declarations require implementations before use. +// ELF 0x39DB30 +void AIMain::setAISystemComponentsQuotient(unsigned int botManager, unsigned int strategic) +{ + const unsigned int sum = botManager + strategic; + if (sum) + { + m_botManagerQuotient = static_cast(botManager) / sum; + m_componentQuotient = static_cast(strategic) / sum; + } +} + +// ELF 0x39EC60 +void AIMain::setSAIMapXDimension(int n) +{ + m_saiMapXDimension = n; + // Shipped defect: this tests the array address, not whether any SAI exists. + if (m_sai) + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + if (m_sai[side]) + m_sai[side]->setMapXDimension(n); +} + +// ELF 0x39ECE0 +void AIMain::setSAIMapYDimension(int n) +{ + m_saiMapYDimension = n; + // Shipped defect: this tests the array address, not whether any SAI exists. + if (m_sai) + for (int side = 1; side < static_cast(CommonSingletonServer::m_iaiSettings)->getNSides() + 1; ++side) + if (m_sai[side]) + m_sai[side]->setMapYDimension(n); +} + +// ELF 0x39ED60 +int AIMain::getSAIMapXDimension() const { return m_saiMapXDimension; } + +// ELF 0x39ED70 +int AIMain::getSAIMapYDimension() const { return m_saiMapYDimension; } + +// ELF 0x39DD70 +int AIMain::getRenderSide() const { return m_renderSide; } + +// ELF 0x39DD80 +void AIMain::setRenderSide(int side) { m_renderSide = side; } + +// ELF 0x39ED80 +bool AIMain::getValidateDataStructuresEnabled() const { return m_validateDataStructuresEnabled; } + +// ELF 0x39ED90 +void AIMain::setValidateDataStructuresEnabled(bool b) { m_validateDataStructuresEnabled = b; } + +// ELF 0x39EDD0 +bool AIMain::getShowBotUrgencies() const { return m_showBotUrgencies; } + +// ELF 0x39EDB0 +void AIMain::setShowBotUrgencies(bool b) { m_showBotUrgencies = b; } + +// ELF 0x39EE00 +bool AIMain::getShowBotSpawnCoord() const { return m_showBotSpawnCoord; } + +// ELF 0x39EDE0 +void AIMain::setShowBotSpawnCoord(bool b) { m_showBotSpawnCoord = b; } + +// ELF 0x39EE30 +bool AIMain::getShowStrategies() const { return m_showStrategies; } + +// ELF 0x39EE10 +void AIMain::setShowStrategies(bool b) { m_showStrategies = b; } + +// ELF 0x39EE60 +bool AIMain::getShowSAIStats() const { return m_showSAIStats; } + +// ELF 0x39EE40 +void AIMain::setShowSAIStats(bool b) { m_showSAIStats = b; } + +// ELF 0x39EE90 +bool AIMain::getShowBotStats() const { return m_showBotStats; } + +// ELF 0x39EE70 +void AIMain::setShowBotStats(bool b) { m_showBotStats = b; } + +// ELF 0x39EEC0 +bool AIMain::getShowStrategicAreas() const { return m_showStrategicAreas; } + +// ELF 0x39EEA0 +void AIMain::setShowStrategicAreas(bool b) { m_showStrategicAreas = b; } + +// ELF 0x39EED0 +void AIMain::showAll(bool b) +{ + m_showBotUrgencies = b; + m_showStrategies = b; + m_showSAIStats = b; + m_showBotStats = b; + m_showStrategicAreas = b; +} + +// ELF 0x39EF00 +void AIMain::showStrategic(bool b) +{ + m_showStrategies = b; + m_showSAIStats = b; + m_showStrategicAreas = b; +} + +// ELF 0x39EF20 +void AIMain::showBot(bool b) +{ + m_showBotUrgencies = b; + m_showBotStats = b; +} } // namespace ai } // namespace hfe diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMain.h b/Code/BF2/AI/AIDLL/AI/Main/AIMain.h index 1e2df4527..38f487cd2 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMain.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIMain.h @@ -22,7 +22,6 @@ namespace world { class IPlayer; } namespace ai { class Bot; -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. class BotManager; class IAIObject; class SAI; @@ -34,12 +33,12 @@ class IAIMain virtual ~IAIMain(); // +0x00 / +0x04 virtual void addNewPlayer(world::IPlayer* player) = 0; // +0x08 - virtual void popPlayer() = 0; // +0x0C + virtual world::IPlayer* popPlayer() = 0; // +0x0C front of the queue, or null virtual void registerFreeBot(Bot* bot) = 0; // +0x10 // Returns whether the player was activated or queued successfully. virtual bool activateBot(int playerId, int side, const std::string& name) = 0; // +0x14 - virtual void deactivateBot(int& a, int b) = 0; // +0x18 - virtual void deactivateBot(int a) = 0; // +0x1C + virtual bool deactivateBot(int& playerId, int side) = 0; // +0x18 ELF answers 0/1 + virtual bool deactivateBot(int playerId) = 0; // +0x1C ELF answers 0/1 virtual void newPlayerCreated(bool b) = 0; // +0x20 virtual void reactivateBot(int a) = 0; // +0x24 virtual void switchSides(int a) = 0; // +0x28 @@ -52,8 +51,8 @@ class IAIMain virtual SAI* getSAI(int side) = 0; // +0x3C virtual void draw() = 0; // +0x40 virtual void updateAIObject(IAIObject* o) = 0; // +0x44 - virtual void reset() = 0; // +0x48 - virtual void resetLevel() = 0; // +0x4C + virtual bool reset() = 0; // +0x48 + virtual bool resetLevel() = 0; // +0x4C virtual void queueSoundEffect(const Vec3& pos, int a, int b) = 0;// +0x50 virtual void spawnBots() = 0; // +0x54 virtual void setAISystemQuotient(const double& q) = 0; // +0x58 @@ -81,17 +80,18 @@ class AIMain : public IAIMain // IAIMain, in vtable order virtual void addNewPlayer(world::IPlayer* player); - virtual void popPlayer(); + virtual world::IPlayer* popPlayer(); virtual void registerFreeBot(Bot* bot); virtual bool activateBot(int playerId, int side, const std::string& name); - virtual void deactivateBot(int& a, int b); - virtual void deactivateBot(int a); + virtual bool deactivateBot(int& playerId, int side); + virtual bool deactivateBot(int playerId); virtual void newPlayerCreated(bool b); virtual void reactivateBot(int a); // Queues an unspawned bot with its side-specific personality weights. // This nonvirtual AIMain entry is distinct from BotManager::addUnspawnedBot. bool addUnspawnedBot(int playerId, int side, float* personality); + bool addBot(int playerId, int side, float* personality, IAIObject* object); virtual void switchSides(int a); virtual void switchSides(int side, int playerId); virtual bool isInitialised(); @@ -100,8 +100,8 @@ class AIMain : public IAIMain virtual SAI* getSAI(int side); virtual void draw(); // - empty virtual void updateAIObject(IAIObject* o); - virtual void reset(); - virtual void resetLevel(); + virtual bool reset(); + virtual bool resetLevel(); virtual void queueSoundEffect(const Vec3& pos, int a, int b); // - empty virtual void spawnBots(); virtual void setAISystemQuotient(const double& q); @@ -117,7 +117,7 @@ class AIMain : public IAIMain // Initializes AI and returns its status message. The integer parameter is unused. std::string init(int); - void setAISystemComponentsQuotient(unsigned int a, unsigned int b); + void setAISystemComponentsQuotient(unsigned int botManager, unsigned int strategic); // Creates per-side strategic AI. setSAIEnable returns the resulting enabled state, // including false when enabling is refused. @@ -163,19 +163,22 @@ class AIMain : public IAIMain // by accessors. The three leading doubles partition frame time between AI and its subsystems. /* 0 */ // vptr /* 4 */ double m_aiSystemQuotient; // Frame-time share, initialized by widening 0.15f to double. - /* 12 */ double m_dword12; // = 0.875 [UNRESOLVED] + /* 12 */ double m_botManagerQuotient; // = 0.875 /* 20 */ double m_componentQuotient; // = 0.125; fraction of the AI budget // handed to the selected side's SAI // with action's additional 0.95 factor. /* 28 */ double m_double28; // = 0.0 [UNRESOLVED] /* 36 */ int m_dword36; // = 0 - /* 40 */ double m_double40; // = 3.0 [UNRESOLVED] +public: + // [CHOSEN, not recovered] Visibility for the generated inline console property. + /* 40 */ double m_botStatisticUpdateSpeed; // = 3.0; console stores its nonnegative magnitude +private: // Parallel per-bot data arrays, appended together when a bot is admitted. /* 48 */ std::vector > m_perBot48; /* 60 */ std::vector > m_perBot60; /* 72 */ std::vector > m_perBot72; /* 84 */ std::vector m_perBot84; - /* 96 */ std::list m_list96; + /* 96 */ std::list m_playerQueue; // addNewPlayer / popPlayer (ELF 0x39F920 / 0x39F970). Name [INFERRED]. /* 100 */ int m_dword100; // = 0 /* 104 */ bool m_initialised; // Set by init; read by isInitialised. // Gates strategic-AI updates; setSAIEnable controls it and init attempts to enable it. @@ -185,28 +188,28 @@ class AIMain : public IAIMain /* 116 */ char m_gap116[4]; // [UNRESOLVED] - the ctor never writes +116 /* 120 */ float m_float120; // Initially 100.0f; this field is a float. /* 124 */ char m_gap124[4]; // [UNRESOLVED] - never written - /* 128 */ int m_dword128; // = 1 + /* 128 */ int m_renderSide; // = 1 /* 132 */ int m_dword132; // = 0 - /* 136 */ bool m_flag136; // = false ] six adjacent bools, written - /* 137 */ bool m_flag137; // = true ] individually. Almost certainly - /* 138 */ bool m_flag138; // = false ] the show* debug switches, but - /* 139 */ bool m_flag139; // = true ] the setters have not been read - /* 140 */ bool m_flag140; // = true ] yet, so nothing is claimed. - /* 141 */ bool m_flag141; // = false ] [UNRESOLVED] + /* 136 */ bool m_showBotUrgencies; // = false + /* 137 */ bool m_showStrategies; // = true + /* 138 */ bool m_showSAIStats; // = false + /* 139 */ bool m_showBotStats; // = true + /* 140 */ bool m_showStrategicAreas; // = true + /* 141 */ bool m_showBotSpawnCoord; // = false /* 144 */ int m_dword144; // = 0 /* 148 */ bool m_flag148; // = false // One-based SAI array; slot zero remains null. Callers must supply a valid side. // The action cursor wraps modulo the side count, with no zero-count guard. /* 152 */ SAI* m_sai[3]; // 1-based; [0] is never used /* 164 */ unsigned int m_componentCursor; // [CHOSEN] - the round-robin cursor - /* 168 */ int m_dword168; // = 64 - /* 172 */ int m_dword172; // = 64 + /* 168 */ int m_saiMapXDimension; // = 64 + /* 172 */ int m_saiMapYDimension; // = 64 /* 176 */ double m_double176; // = -3.4028235e38 that is -FLT_MAX stored /* 184 */ double m_double184; // = -3.4028235e38 in a double. A "no value // yet" sentinel written with the float // constant. [UNRESOLVED] what they time. /* 192 */ BotManager* m_botManager; // Owned manager; action passes it the remaining time budget. - /* 196 */ bool m_flag196; // = false + /* 196 */ bool m_validateDataStructuresEnabled; // = false /* 200 */ std::list m_soundEffects; // allocate(28) -> 8 + 20; see SoundEffect // [UNRESOLVED] Map key and value types; current declarations preserve the observed storage shape. /* 204 */ std::map m_map204; // +204 node, +208 count, +212 comparator diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp index d942456f1..2bc77c34e 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp @@ -1,4 +1,5 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIMineManager operations. +// static init: ELF 0x2E17C0 (__tcf_0 0x2E1820, _GLOBAL__I 0x2E1850): 's Init object only. +#include #include "AIMineManager.h" @@ -8,7 +9,6 @@ #include "../../../../Core/ClassManager.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment::isAsleep #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime -// AIDllFrontier.h is no longer included - this file has no frontier body left. #include "AIRandom.h" #include "CommonSingletonServer.h" #include "IAIPathfinding.h" @@ -34,6 +34,7 @@ inline const Vec3& translationOf(const Mat4& m) } // anonymous namespace // IAIMineManager +// ELF 0x2E9700 / 0x2E97A0 IAIMineManager::IAIMineManager() { // the guard reads the roster static, not the registry. Reproduced. @@ -41,6 +42,7 @@ IAIMineManager::IAIMineManager() classManager->registerSimpleSingleton("IAIMineManager", this); } +// ELF 0x2E9840 / 0x2E98D0 / 0x2E9960 IAIMineManager::~IAIMineManager() { if (CommonSingletonServer::m_iAIMineManager == this) @@ -48,12 +50,14 @@ IAIMineManager::~IAIMineManager() } // Polygon counter records default to zero and support memberwise copying. +// ELF 0x2DEDD0 / 0x2DEDF0 AIMineManager::PolygonData::PolygonData() : m_mines(0) , m_otherMines(0) { } +// ELF 0x2DEE10 / 0x2DEE30 AIMineManager::PolygonData::PolygonData(const PolygonData& other) : m_mines(other.m_mines) , m_otherMines(other.m_otherMines) @@ -61,6 +65,7 @@ AIMineManager::PolygonData::PolygonData(const PolygonData& other) } // Creates an empty mine record with invalid ID, quad-tree and polygon sentinels. +// ELF 0x2DE2C0 / 0x2DE420 AIMineManager::MineInfo::MineInfo() : m_id(-1) , m_mineType(0) @@ -84,6 +89,7 @@ AIMineManager::MineInfo::MineInfo() } // Creates a circular mine record. mineAtRest() must fill its quad-tree and polygon indices before use. +// ELF 0x2DE4D0 / 0x2DE610 AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& transform, float radius) : m_id(static_cast(id)) @@ -105,6 +111,7 @@ AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& tr // Builds an anti-personnel mine from its triangular footprint. Leaves the quad-tree id, // polygon id, and radius uninitialized; the anti-personnel path does not read radius. +// ELF 0x2DE750 / 0x2DE8B0 AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& transform, const Vec3& corner1, const Vec3& corner2) : m_id(static_cast(id)) @@ -119,13 +126,28 @@ AIMineManager::MineInfo::MineInfo(unsigned int id, MineType type, const Mat4& tr m_corner2 = corner2; } +// ELF 0x2DEA10 / 0x2DEBF0 +AIMineManager::MineInfo::MineInfo(const MineInfo& other) + : m_id(other.m_id) + , m_mineType(other.m_mineType) + , m_quadTree(other.m_quadTree) + , m_polygon(other.m_polygon) + , m_polygons(other.m_polygons) + , m_radius(other.m_radius) +{ + for (int i = 0; i < 16; ++i) + m_transform.m[i] = 0.0f; + m_transform = other.m_transform; + m_corner1 = other.m_corner1; + m_corner2 = other.m_corner2; +} + // Initializes mine tracking with one outer-vector entry for each of the two sides. +// ELF 0x2DEE50 / 0x2DF140 AIMineManager::AIMineManager() : m_nextUpdateTime(-1000000000.0) , m_int60(-1) - , m_int72(0) - , m_int76(0) - , m_int80(0) + , m_missingMinePosition{0.0f, 0.0f, 0.0f} , m_flag84(false) { // Leaves m_gap64 uninitialized. Creates entries for anti-personnel and anti-tank mines; @@ -138,11 +160,13 @@ AIMineManager::AIMineManager() // map, the resting map, then the two nested vectors - and touches none of the six trailing scalars. // That is what proves +72..+83 are three plain ints rather than another vector, and it is all a C++ // destructor does on its own, so the body is empty. +// ELF 0x2DF430 / 0x2DF6D0 / 0x2DF970 AIMineManager::~AIMineManager() { } // Sizes navigation-island tracking for the given mine type. The type must be valid. +// ELF 0x2DFC10 void AIMineManager::init(MineType type, unsigned int islandCount) { m_minedPolygons[type].resize(islandCount); @@ -150,6 +174,7 @@ void AIMineManager::init(MineType type, unsigned int islandCount) } // Resets scheduling and scalar state while retaining both mine maps and polygon indices. +// ELF 0x2DFDE0 void AIMineManager::reset() { m_int60 = -1; @@ -159,30 +184,33 @@ void AIMineManager::reset() // Returns a reference to the indexed polygon set. Both indices must be valid; a later // init that grows the inner vector can invalidate the reference. -const std::set& AIMineManager::getMinedPolygons(MineType type, unsigned int map) +// ELF 0x2E16F0 +const std::set& AIMineManager::getMinedPolygons(MineType type, unsigned int map) const { return m_minedPolygons[type][map]; } -// Writes the latest recorded quad tree and polygon for the mine, or -1 to both outputs when absent. -void AIMineManager::getPathfindingPositionOfMine(unsigned int mineId, MineType /*type*/, - unsigned int& quadTree, unsigned int& polygon) +// Returns the latest recorded mine position and writes its quad tree and polygon; absent mines return the zero fallback. +// ELF 0x2E1720 +const Vec3& AIMineManager::getPathfindingPositionOfMine(unsigned int mineId, MineType /*type*/, + unsigned int& quadTree, unsigned int& polygon) const { const std::map >::const_iterator i = m_mines.find(mineId); if (i == m_mines.end()) { quadTree = 0xFFFFFFFFu; polygon = 0xFFFFFFFFu; - return; + return m_missingMinePosition; } - const MineInfo& info = i->second.back(); - quadTree = info.m_quadTree; - polygon = info.m_polygon; + quadTree = i->second.back().m_quadTree; + polygon = i->second.back().m_polygon; + return translationOf(i->second.back().m_transform); } // Processes pending mine state at two updates per second. // The deadline test is strict: an update runs only when now is greater than m_nextUpdateTime. +// ELF 0x2E0390 void AIMineManager::update() { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -211,6 +239,7 @@ void AIMineManager::update() } // Registers a resting mine as a pathfinding hazard and updates affected polygon counts. +// ELF 0x2E08B0 void AIMineManager::mineAtRest(const MineInfo& info) { MineInfo local(info); @@ -302,6 +331,7 @@ void AIMineManager::mineAtRest(const MineInfo& info) // Probes seven positions along the mine's facing axis, from zero through six metres. // Stops when both polygon and quad-tree ids are valid; returns the final seed otherwise, // which may still be the invalid handle. +// ELF 0x2E04D0 unsigned int AIMineManager::findSeedPolygonForAPMine(MineInfo& info) { unsigned int seed = 0xFFFFFFFFu; @@ -326,6 +356,7 @@ unsigned int AIMineManager::findSeedPolygonForAPMine(MineInfo& info) } // Tries up to fifteen random positions around the mine to find a seed polygon. +// ELF 0x2E05C0 unsigned int AIMineManager::findSeedPolygonForATMine(MineInfo& info) { AIRandom* const random = AIRandom::m_instance; @@ -355,6 +386,7 @@ unsigned int AIMineManager::findSeedPolygonForATMine(MineInfo& info) } // Adds a mine to a polygon's counters. Material changes occur on an existing counter's zero-to-one transition. +// ELF 0x2E1090 void AIMineManager::addNewMineToPolygon(MineType type, unsigned int quadTree, unsigned int polygon) { const std::pair::iterator, bool> result = @@ -372,6 +404,7 @@ void AIMineManager::addNewMineToPolygon(MineType type, unsigned int quadTree, un ++result.first->second.m_mines; } +// ELF 0x2E11D0 void AIMineManager::addNewOtherMineToPolygon(MineType type, unsigned int quadTree, unsigned int polygon) { @@ -391,6 +424,7 @@ void AIMineManager::addNewOtherMineToPolygon(MineType type, unsigned int quadTre } // Removes a mine from an existing polygon entry. The caller must ensure the entry exists. +// ELF 0x2E14B0 void AIMineManager::removeMineFromPolygon(MineType type, unsigned int quadTree, unsigned int polygon) { @@ -407,6 +441,7 @@ void AIMineManager::removeMineFromPolygon(MineType type, unsigned int quadTree, } } +// ELF 0x2E15D0 void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int quadTree, unsigned int polygon) { @@ -423,6 +458,7 @@ void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int quadT } // Queues a newly placed mine for later processing; it does not update navigation polygons immediately. +// ELF 0x2DFF00 void AIMineManager::minePlaced(MineType type, unsigned int id, const Mat4& transform, float radius) { if (type == 1) @@ -455,6 +491,7 @@ void AIMineManager::minePlaced(MineType type, unsigned int id, const Mat4& trans // Removes settling mines first. If absent there, removes a resting mine and releases // its polygon counters. An id must not exist in both maps. +// ELF 0x2DFE10 void AIMineManager::mineRemoved(unsigned int id) { const std::map::iterator settling = m_settlingMines.find(id); @@ -471,6 +508,7 @@ void AIMineManager::mineRemoved(unsigned int id) } // Releases all polygon registrations for a mine and erases its entry. +// ELF 0x2E1310 void AIMineManager::removeMine(std::map >::iterator& entry) { int index = 0; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h b/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h index 58c63215a..905628e33 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h @@ -1,5 +1,4 @@ // Tracks mines by side and updates navigation hazards when mines settle or disappear. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_AIMINEMANAGER_H @@ -35,8 +34,9 @@ class IAIMineManager // Mine notifications do not return a result. virtual void mineRemoved(unsigned int) = 0; virtual void minePlaced(MineType, unsigned int, const Mat4&, float) = 0; - virtual const std::set& getMinedPolygons(MineType, unsigned int) = 0; - virtual void getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&) = 0; + virtual const std::set& getMinedPolygons(MineType, unsigned int) const = 0; + // Returns a borrowed position and writes its navigation indices; unknown mines yield two -1 indices. + virtual const Vec3& getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&) const = 0; }; // Mine tracking and polygon counters. Offsets describe the original 88-byte ELF object; @@ -59,6 +59,7 @@ class AIMineManager : public IAIMineManager struct MineInfo { MineInfo(); + MineInfo(const MineInfo& other); // The anti-tank form: a radius, i.e. a circular danger area. , MineInfo(unsigned int, MineType, const Mat4&, float); @@ -91,8 +92,8 @@ class AIMineManager : public IAIMineManager virtual void update(); virtual void mineRemoved(unsigned int); virtual void minePlaced(MineType, unsigned int, const Mat4&, float); - virtual const std::set& getMinedPolygons(MineType, unsigned int); - virtual void getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&); + virtual const std::set& getMinedPolygons(MineType, unsigned int) const; + virtual const Vec3& getPathfindingPositionOfMine(unsigned int, MineType, unsigned int&, unsigned int&) const; private: // The secondary counter tracks projections of mines onto another navigation map. @@ -124,9 +125,7 @@ class AIMineManager : public IAIMineManager /* 60 */ int m_int60; // = -1 [UNRESOLVED]; reset sets it to -1 as well /* 64 */ char m_gap64[8]; // the constructor never writes these eight bytes - /* 72 */ int m_int72; // = 0 [UNRESOLVED] - /* 76 */ int m_int76; // = 0 [UNRESOLVED] - /* 80 */ int m_int80; // = 0 [UNRESOLVED] + /* 72 */ Vec3 m_missingMinePosition; // Zero fallback returned by getPathfindingPositionOfMine; name [INFERRED]. /* 84 */ bool m_flag84; // = false [UNRESOLVED]; reset clears it as well }; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp index c205a1b44..25945520c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp @@ -3,15 +3,47 @@ #include "AIModule.h" +#include #include +#include +#include #include #include "../../../../Core/ClassManager.h" #include "../../../../Core/ConsoleObjects.h" #include "../../../../Core/DllModule.h" #include "../../../../Core/Ids.h" +#include "../../../../Core/ConsoleObjectBase.h" +#include "../../../../Core/ConsoleObjectMacro.h" // BF2_CC_HEAD_NAMED, BF2_CC_ARG, return/range hooks #include "../AIUtils/checkPointer.h" #include "BF2AI.h" +#include "../AIPathFinding/Material/Material.h" +#include "../AIStrategic/Strategy.h" +#include "../AIStrategic/StrategyCondition.h" +#include "../AIStrategicEntity/AILandingZone.h" +#include "../AIStrategicEntity/AILandingZoneManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" +#include "../AIStrategicEntity/GuardPosition.h" +#include "../AIStrategicEntity/PatrolPath.h" +#include "../AIStrategicMap/AerialHeightMap.h" +#include "../DrawPrimitives/DPManager.h" +#include "AIConsole.h" +#include "AILODManager.h" +#include "AIMain.h" +#include "AIRandom.h" +#include "AISettings.h" +#include "AISettingsInterfaces.h" +#include "AIStreamOperators.h" +#include "BotBehaviourManager.h" +#include "BotPlacementManager.h" +#include "CommonSingletonServer.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "IAIPathfinding.h" +#include "IBotManager.h" +#include "StrategyManager.h" +#include "UserOrderManager.h" namespace dice { namespace hfe { @@ -21,31 +53,117 @@ namespace hfe { extern ClassManager* classManager; extern ConsoleObjects* mainConsoleObjects; -// Module instances allocated during DLL initialization. +// static init: ELF 0x486170 / 0x4861D0. The module pointer is initialized before the console list. IModule* dllmodules[] = { new ai::AIModule, 0 }; +// [INFERRED] The two unsigned spellings the bindings' type strings use ("hfe::uint", "u32"); both +// are extracted by istream::operator>>(unsigned int&) in the image. +typedef unsigned int uint; +typedef unsigned int u32; + namespace ai { +// The receivers of the generated console bindings (ELF 0x3EE940..0x3EEB40): each returns the +// active object of its manager, or null while the manager does not exist. + +// ELF 0x3EE940 +PatrolPath* getActivePatrolPathIfManager() +{ + PatrolPath* path = 0; + if (UserOrderManager::m_instance) + path = UserOrderManager::m_instance->getActivePatrolPath(); + return path; +} + +// ELF 0x3EE980 +GuardPosition* getActiveGuardPositionIfManager() +{ + GuardPosition* position = 0; + if (UserOrderManager::m_instance) + position = UserOrderManager::m_instance->getActiveGuardPosition(); + return position; +} + +// ELF 0x3EE9C0: IAIPathfindingSetup +0x50. +IAIPathfindingSetup::IMapContainer* getActiveMapContainer() +{ + if (!IAIPathfindingSetup::instance) + return 0; + return IAIPathfindingSetup::instance->getActiveMapContainer(); +} + +// ELF 0x3EEA00: getInstance is called twice, once for the test and once for the call. +Strategy* getActiveStrategy() +{ + Strategy* strategy = 0; + if (StrategyManager::getInstance()) + strategy = StrategyManager::getInstance()->getActiveStrategy(); + return strategy; +} + +// ELF 0x3EEA40. The executors call AIMain members on the result non-virtually, so the helper's +// type is AIMain* [INFERRED]; IAIMain is AIMain's only base, the conversion moves no pointer. +AIMain* getActiveAIMain() +{ + AIMain* aiMain = 0; + if (AIConsole::m_instance) + aiMain = static_cast(AIConsole::m_instance->getActiveAIMain()); + return aiMain; +} + +// ELF 0x3EEA80 +StrategyCondition* getActiveCondition() +{ + StrategyCondition* condition = 0; + if (StrategyManager::getInstance()) + condition = StrategyManager::getInstance()->getActiveCondition(); + return condition; +} + +// ELF 0x3EEAC0 +AIStrategicArea* getActiveStrategicArea() +{ + AIStrategicArea* area = 0; + if (AIStrategicObjectManager::getInstance()) + area = AIStrategicObjectManager::getInstance()->getActiveArea(); + return area; +} + +// ELF 0x3EEB00 +AILandingZone* getActiveLandingZone() +{ + AILandingZone* zone = 0; + if (AILandingZoneManager::m_instance) + zone = AILandingZoneManager::m_instance->getActiveZone(); + return zone; +} + +// ELF 0x3EEB40: the settings singleton, unchecked. +IAISettings* getAISettings() +{ + return static_cast(CommonSingletonServer::m_iaiSettings); +} + namespace { -// Console objects registered by module initialization and removed on close. +// static init: ELF 0x3EEE90, _GLOBAL__I 0x40FA70; stream cleanup __tcf_111 0x40A860. +// [CHOSEN, not recovered] Explicit object retains the two merged TUs' initialization order. +std::ios_base::Init consoleStreamInit; -} // anonymous namespace +// The one list every generated binding of this file appends itself to; init registers it. +// static init: ELF 0x3EEE90; list cleanup __tcf_112 0x40A890 releases nodes, not their pointers. +ConsoleObjects::ConsoleObjectList aiList; -// Defined in AIConsole.cpp, beside the binding itself. -ConsoleObjects::ConsoleObjectList& aiConsoleObjects(); -ConsoleObjects::ConsoleObjectList& aiSettingsConsoleObjects(); // AISettings.cpp -// AIStrategicEntity/AIStrategicObjectManager.cpp - `aiStrategicArea.createFromControlPoint`, the -// one command of nine on that object whose whole chain is written. -ConsoleObjects::ConsoleObjectList& aiStrategicAreaConsoleObjects(); -// Pathfinding console commands for navigation meshes, properties, and the trace map. -ConsoleObjects::ConsoleObjectList& aiPathfindingConsoleObjects(); +#include "AIModuleConsole.inc" + +} // anonymous namespace // Two stores and nothing else - the vptr, and a refcount of one. +// ELF 0x4861F0 AIModule::AIModule() : m_refCount(1) { @@ -54,11 +172,13 @@ AIModule::AIModule() // The IBase quartet. Textbook, and reproduced because "textbook" is itself a finding - the AI module // does not do anything unusual with lifetime. +// ELF 0x40FA90 void AIModule::addRef() { ++m_refCount; } +// ELF 0x40FAA0 int AIModule::getRef() { return m_refCount; @@ -66,6 +186,7 @@ int AIModule::getRef() // Decrements the reference count and frees this without a destructor at zero. // Requires a heap-allocated module with no member cleanup. +// ELF 0x40FAB0 int AIModule::release() { const int n = --m_refCount; @@ -75,6 +196,7 @@ int AIModule::release() } // Returns the interface pointer for IBase, IClassServer, or IModule, testing in that order. +// ELF 0x40FAF0 void* AIModule::queryInterface(unsigned int iid) const { if (iid == IID_IBase || iid == IID_IClassServer) @@ -90,40 +212,37 @@ void* AIModule::queryInterface(unsigned int iid) const // class ids and is therefore reachable only as a simple singleton. // - a bare `ret`. +// ELF 0x3EEDD0 void AIModule::getClassList(std::vector& /*out*/) { } // - a bare `ret`. +// ELF 0x3EEDC0 void AIModule::getSingletonList(std::vector& /*out*/) { } // Creates the AI singleton and publishes its console bindings. +// ELF 0x3EEB60 bool AIModule::init() { - std::fflush(stderr); - mainConsoleObjects->registerConsoleObjects(aiConsoleObjects()); - mainConsoleObjects->registerConsoleObjects(aiSettingsConsoleObjects()); - mainConsoleObjects->registerConsoleObjects(aiStrategicAreaConsoleObjects()); - mainConsoleObjects->registerConsoleObjects(aiPathfindingConsoleObjects()); + mainConsoleObjects->registerConsoleObjects(aiList); BF2AI* ai = new BF2AI; // Preserves the explicit allocation check even with throwing operator new. checkPointer(ai); - // true even if the above failed - see the file header. + // Returns true if the allocation diagnostic returns. return true; } // Unregisters console objects and looks up the AI through getSingleton. The original // uses the wrong registry for this simple singleton, leaving the object allocated. +// ELF 0x3EECB0 bool AIModule::close() { - mainConsoleObjects->unregisterConsoleObjects(aiConsoleObjects()); - mainConsoleObjects->unregisterConsoleObjects(aiSettingsConsoleObjects()); - mainConsoleObjects->unregisterConsoleObjects(aiStrategicAreaConsoleObjects()); - mainConsoleObjects->unregisterConsoleObjects(aiPathfindingConsoleObjects()); + mainConsoleObjects->unregisterConsoleObjects(aiList); // getSingleton (+0x4C) searches m_normalSingletons. "AI" was registered into // m_simpleSingletons. This returns null on every run. @@ -134,11 +253,8 @@ bool AIModule::close() if (ai) { - // IAI vtable +0x04 - the deleting destructor , not release. IAI is not an IBase and - // has no refcount to drop. [FRONTIER] to express in C++ until IAI's destructor is declared - // in a way this file can reach; the call is recorded rather than written, because on every - // real run `ai` is null and the arm is dead. - // reinterpret_cast(ai)->~IAI; // conceptually; the slot is , so: delete + // shipped defect: the normal-registry result is treated as IAI despite its IBase type. + delete reinterpret_cast(ai); } return true; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc b/Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc new file mode 100644 index 000000000..a3dbd9d14 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIModuleConsole.inc @@ -0,0 +1,9595 @@ +// GENERATED FILE - do not edit by hand. Regenerate with +// python3 tools/ai-reconstruct/gen_console_bindings.py +// from libaidll.so (Linux 1.5.3153, ia-32, with symbols). Every address is an ELF address. +// +// The AI image's console bindings: 298 generated classes ConsoleClass, all in the +// anonymous namespace of AIModule.cpp (the original __LINE__ is the class number). Emitted here: +// 298; the 0 left out are listed in place with the reason (their commands stay +// unregistered, as before this file existed). Shared shapes recovered from the image: +// - constructor (inlined into AIModule.cpp's static initializer, ELF 0x3EEE90): object name, +// access and category from the SetConsoleClassDefaults in force; function name, m_type, +// min/max argument count, return-type and argument-type strings (the stringized C++ types), +// the +0xA1 flag (1 exactly when getReturnValueAsString formats a value), then the +// needs-conversion flags (`argType != "std::string"`) and `aiList.push_back(this)`. +// - isObjectActive: `receiver != 0`, the receiver being a global or an AIModule.cpp getter. +// - executeObjectMethod: one arm per accepted argument count; m_hasReturnValue is stored before +// the receiver is evaluated; the arm calls receiver->method(arguments) (virtual calls through +// the receiver's static type) and stores the result when the flag is set. Arms that pass fewer +// arguments than the target takes rely on the target's C++ default arguments. +// The verified inline bodies preserve argument copies before that flag, unchecked indices, +// repeated stores and discarded results; see each class's inline-body note and JSON hash. +// - setArgFromString(index): `static T arg; std::istringstream in(value); in >> arg; +// m_args[index - 1] = &arg;` with no fail check (no temporary, unlike Core's BF2_CC_CONVERT). +// - getReturnValueAsString / range hooks: Core/ConsoleObjectMacro.h's BF2_CC_RETURN_AS_STRING, +// BF2_CC_NO_RETURN_AS_STRING and BF2_CC_COMMON_HOOKS (one shape each in the image). +// [INFERRED] The original macro names; the class bodies are spelled out because the shared +// BF2_CONSOLE_* families hard-code a different +0xA1 value and the temp-and-commit conversion. + +#pragma push_macro("BF2_CC_NAME") + +// Converts argument `oneBasedIndex` into its function-local static (one per argument). +#define AIMODULE_CC_EXTRACT(T, oneBasedIndex) \ + if (index == (oneBasedIndex)) \ + { \ + static T arg; \ + std::istringstream in(value); \ + in >> arg; \ + m_args[(oneBasedIndex) - 1] = reinterpret_cast(&arg); \ + } + +// The same, where the image calls a named extractor that overload resolution would not pick. +#define AIMODULE_CC_EXTRACT_WITH(T, oneBasedIndex, extractor) \ + if (index == (oneBasedIndex)) \ + { \ + static T arg; \ + std::istringstream in(value); \ + extractor(in, arg); \ + m_args[(oneBasedIndex) - 1] = reinterpret_cast(&arg); \ + } + +// Closes the constructor BF2_CC_HEAD_NAMED opened: conversion flags, then this file's list. +#define AIMODULE_CC_TAIL(nArgs) \ + for (int i = 0; i < (nArgs); ++i) \ + m_argNeedsConversion[i] = \ + (std::string(m_argTypes[i]) == "std::string") ? 0 : -1; \ + aiList.push_back(this); \ + } + + +SetConsoleClassDefaults IAIfullAccessSetConsoleClassDefaults("IAI", 2, 0); + +SetConsoleClassDefaults AIfullAccessSetConsoleClassDefaults("AI", 2, 0); + +// ConsoleClass161 AI.createHeightMap: method, 0..1 arguments, no result. +// ELF isObjectActive 0x40FF70, executeObjectMethod 0x4102D0, +// setArgFromString 0x410090, getReturnValueAsString 0x40FF30, D1 0x40FF10, D0 0x40FED0. +// argc 0: dice::hfe::ai::AerialHeightMap::createHeightMap(int) (call at 0x41031B; ledger done) +// argc 1: dice::hfe::ai::AerialHeightMap::createHeightMap(int) (call at 0x41031B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass161 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createHeightMap", 0, 0, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AerialHeightMap::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AerialHeightMap::m_instance->createHeightMap(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + AerialHeightMap::m_instance->createHeightMap(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject161; + +// ConsoleClass162 AI.readHeightMapFromFile: method, 0..0 arguments, no result. +// ELF isObjectActive 0x4103E0, executeObjectMethod 0x410510, +// setArgFromString 0x410500, getReturnValueAsString 0x4103A0, D1 0x410380, D0 0x410340. +// argc 0: dice::hfe::ai::AerialHeightMap::readHeightMapFromFile() (call at 0x410549; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass162 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("readHeightMapFromFile", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AerialHeightMap::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AerialHeightMap::m_instance->readHeightMapFromFile(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject162; + +// ConsoleClass165 AI.init: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4105F0, executeObjectMethod 0x410950, +// setArgFromString 0x410710, getReturnValueAsString 0x4105B0, D1 0x410590, D0 0x410550. +// argc 1: dice::hfe::ai::AIConsole::init(int) (call at 0x410991; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass165 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("init", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->init(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject165; + +// ConsoleClass168 AI.debug: method, 0..0 arguments, no result. +// ELF isObjectActive 0x410A40, executeObjectMethod 0x410B70, +// setArgFromString 0x410B60, getReturnValueAsString 0x410A00, D1 0x4109E0, D0 0x4109A0. +// argc 0: dice::hfe::ai::AIConsole::debug() (call at 0x410BA9; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass168 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("debug", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIConsole::m_instance->debug(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject168; + +// ConsoleClass171 AI.writeBotPlans: method, 0..0 arguments, no result. +// ELF isObjectActive 0x410C50, executeObjectMethod 0x410D80, +// setArgFromString 0x410D70, getReturnValueAsString 0x410C10, D1 0x410BF0, D0 0x410BB0. +// argc 0: dice::hfe::ai::BotManager::writeBotPlans() (slot +0x7C at 0x410DBB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass171 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("writeBotPlans", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IBotManager::instance->writeBotPlans(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject171; + +// ConsoleClass174 AI.aiSystemQuotient: property, 0..1 arguments, returns double. +// ELF isObjectActive 0x411060, executeObjectMethod 0x4113D0, +// setArgFromString 0x411190, getReturnValueAsString 0x410E20, D1 0x410E00, D0 0x410DC0. +// argc 0: dice::hfe::ai::AIMain::getAISystemQuotient() const (slot +0x5C at 0x411438; ledger done) +// argc 1: dice::hfe::ai::AIMain::setAISystemQuotient(double const&) (slot +0x58 at 0x411420; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass174 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("aiSystemQuotient", 1, 0, 1, "double", true) + m_argTypes[0] = "double"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getAISystemQuotient(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setAISystemQuotient(BF2_CC_ARG(double, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject174; + +// ConsoleClass175 AI.setAISystemComponentsQuotient: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4114F0, executeObjectMethod 0x411AA0, +// setArgFromString 0x411620, getReturnValueAsString 0x4114B0, D1 0x411490, D0 0x411450. +// argc 2: dice::hfe::ai::AIMain::setAISystemComponentsQuotient(unsigned int, unsigned int) (call at 0x411AF3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass175 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setAISystemComponentsQuotient", 0, 2, 2, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveAIMain()->setAISystemComponentsQuotient(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject175; + +// ConsoleClass176 AI.getBotManagerQuotient: method, 0..0 arguments, double result discarded. +// ELF isObjectActive 0x411BA0, executeObjectMethod 0x411CE0, +// setArgFromString 0x411CD0, getReturnValueAsString 0x411B60, D1 0x411B40, D0 0x411B00. +// argc 0: verified inline body, discarded quotient getter; evaluates only the receiver +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass176 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBotManagerQuotient", 0, 0, 0, "double", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + (void)getActiveAIMain(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject176; + +// ConsoleClass177 AI.getSAIQuotient: method, 0..0 arguments, double result discarded. +// ELF isObjectActive 0x411DC0, executeObjectMethod 0x411F00, +// setArgFromString 0x411EF0, getReturnValueAsString 0x411D80, D1 0x411D60, D0 0x411D20. +// argc 0: verified inline body, discarded quotient getter; evaluates only the receiver +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass177 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSAIQuotient", 0, 0, 0, "double", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + (void)getActiveAIMain(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject177; + +// ConsoleClass178 AI.botStatisticUpdateSpeed: property, 0..1 arguments, returns double. +// ELF isObjectActive 0x4121E0, executeObjectMethod 0x412550, +// setArgFromString 0x412310, getReturnValueAsString 0x411FA0, D1 0x411F80, D0 0x411F40. +// argc 0: verified inline body, statistic speed; ia-32 negates exactly when value < 0 (retains -0 and unordered values) +// argc 1: verified inline body, statistic speed; ia-32 negates exactly when value < 0 (retains -0 and unordered values) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass178 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botStatisticUpdateSpeed", 1, 0, 1, "double", true) + m_argTypes[0] = "double"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->m_botStatisticUpdateSpeed; + } + else if (m_argCount == 1) + { + const double value = BF2_CC_ARG(double, 0); + m_hasReturnValue = false; + AIMain* const object = getActiveAIMain(); + object->m_botStatisticUpdateSpeed = value < 0.0 ? -value : value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject178; + +// ConsoleClass181 AI.getBotCount: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x412870, executeObjectMethod 0x4129A0, +// setArgFromString 0x412990, getReturnValueAsString 0x412630, D1 0x412610, D0 0x4125D0. +// argc 0: dice::hfe::ai::BotManager::getBotCount() const (slot +0x8 at 0x4129D5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass181 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBotCount", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getBotCount(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject181; + +// ConsoleClass182 AI.getNumberOfActiveBots: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x412CA0, executeObjectMethod 0x412DD0, +// setArgFromString 0x412DC0, getReturnValueAsString 0x412A60, D1 0x412A40, D0 0x412A00. +// argc 0: dice::hfe::ai::BotManager::getNumberOfActiveBots() const (slot +0xC at 0x412E05; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass182 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfActiveBots", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getNumberOfActiveBots(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject182; + +// ConsoleClass183 AI.getNumberOfDeactivedBots: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x4130D0, executeObjectMethod 0x413200, +// setArgFromString 0x4131F0, getReturnValueAsString 0x412E90, D1 0x412E70, D0 0x412E30. +// argc 0: dice::hfe::ai::BotManager::getNumberOfDeactivedBots() const (slot +0x10 at 0x413235; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass183 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfDeactivedBots", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getNumberOfDeactivedBots(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject183; + +// ConsoleClass186 AI.addBot: method, 4..4 arguments, returns int. +// ELF isObjectActive 0x413530, executeObjectMethod 0x413FC0, +// setArgFromString 0x413650, getReturnValueAsString 0x4132C0, D1 0x4132A0, D0 0x413260. +// argc 4: dice::hfe::ai::AIConsole::addBot(std::string, int, std::string, std::string) (call at 0x4140AF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass186 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addBot", 0, 4, 4, "int", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->addBot(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject186; + +// ConsoleClass187 AI.addUnspawnedBot: method, 3..3 arguments, returns int. +// ELF isObjectActive 0x4144B0, executeObjectMethod 0x414CE0, +// setArgFromString 0x4145D0, getReturnValueAsString 0x414240, D1 0x414220, D0 0x4141E0. +// argc 3: dice::hfe::ai::AIConsole::addUnspawnedBot(std::string, int, std::string) (call at 0x414D80; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass187 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addUnspawnedBot", 0, 3, 3, "int", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + m_argTypes[2] = "std::string"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->addUnspawnedBot(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1), BF2_CC_ARG(std::string, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject187; + +// ConsoleClass188 AI.deactivateBot: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x4150E0, executeObjectMethod 0x415450, +// setArgFromString 0x415210, getReturnValueAsString 0x414EA0, D1 0x414E80, D0 0x414E40. +// argc 1: dice::hfe::ai::AIMain::deactivateBot(int) (slot +0x1C at 0x41548D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass188 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("deactivateBot", 0, 1, 1, "bool", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->deactivateBot(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject188; + +// ConsoleClass189 AI.updateBot: method, 1..1 arguments, no result. +// ELF isObjectActive 0x415560, executeObjectMethod 0x4158C0, +// setArgFromString 0x415680, getReturnValueAsString 0x415520, D1 0x415500, D0 0x4154C0. +// argc 1: dice::hfe::ai::AIConsole::updateBot(int) (call at 0x415901; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass189 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("updateBot", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->updateBot(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject189; + +// ConsoleClass190 AI.killBotId: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x415C30, executeObjectMethod 0x415F90, +// setArgFromString 0x415D50, getReturnValueAsString 0x4159F0, D1 0x415980, D0 0x415910. +// argc 1: dice::hfe::ai::AIConsole::killBotId(int) (call at 0x415FDB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass190 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("killBotId", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->killBotId(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject190; + +// ConsoleClass191 AI.killBotName: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x416350, executeObjectMethod 0x4166F0, +// setArgFromString 0x416470, getReturnValueAsString 0x416110, D1 0x4160A0, D0 0x416030. +// argc 1: dice::hfe::ai::AIConsole::killBotName(std::string const&) (call at 0x416754; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass191 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("killBotName", 0, 1, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->killBotName(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject191; + +// ConsoleClass192 AI.killAllBots: method, 0..0 arguments, no result. +// ELF isObjectActive 0x416870, executeObjectMethod 0x4169A0, +// setArgFromString 0x416990, getReturnValueAsString 0x416830, D1 0x416810, D0 0x4167D0. +// argc 0: dice::hfe::ai::AIConsole::killAllBots() (call at 0x4169D9; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass192 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("killAllBots", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIConsole::m_instance->killAllBots(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject192; + +// ConsoleClass195 AI.botGiveOrder: method, 3..3 arguments, no result. +// ELF isObjectActive 0x416A80, executeObjectMethod 0x4172B0, +// setArgFromString 0x416BA0, getReturnValueAsString 0x416A40, D1 0x416A20, D0 0x4169E0. +// argc 3: dice::hfe::ai::AIConsole::botGiveOrder(int, std::string, std::string) (call at 0x41735E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass195 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botGiveOrder", 0, 3, 3, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->botGiveOrder(BF2_CC_ARG(int, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject195; + +// ConsoleClass196 AI.botSetWaypoints_Patrol: method, 5..6 arguments, no result. +// ELF isObjectActive 0x417490, executeObjectMethod 0x418570, +// setArgFromString 0x4175B0, getReturnValueAsString 0x417450, D1 0x417430, D0 0x4173F0. +// argc 5: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x418671; ledger stop) +// argc 6: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x418671; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass196 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botSetWaypoints_Patrol", 0, 5, 6, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "float"; + m_argTypes[2] = "int"; + m_argTypes[3] = "hfe::Vec3"; + m_argTypes[4] = "hfe::Vec3"; + m_argTypes[5] = "hfe::Vec3"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4)); + } + else if (m_argCount == 6) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4), BF2_CC_ARG(hfe::Vec3, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(int, 3) + AIMODULE_CC_EXTRACT(hfe::Vec3, 4) + AIMODULE_CC_EXTRACT(hfe::Vec3, 5) + AIMODULE_CC_EXTRACT(hfe::Vec3, 6) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject196; + +// ConsoleClass197 AI.botSetWaypoints_Patrol3d: method, 5..6 arguments, no result. +// ELF isObjectActive 0x4187D0, executeObjectMethod 0x4198B0, +// setArgFromString 0x4188F0, getReturnValueAsString 0x418790, D1 0x418770, D0 0x418730. +// argc 5: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol3d(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x4199B1; ledger stop) +// argc 6: dice::hfe::ai::AIConsole::botSetWaypoints_Patrol3d(int, float, int, dice::hfe::Vec3, dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x4199B1; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass197 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botSetWaypoints_Patrol3d", 0, 5, 6, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "float"; + m_argTypes[2] = "int"; + m_argTypes[3] = "hfe::Vec3"; + m_argTypes[4] = "hfe::Vec3"; + m_argTypes[5] = "hfe::Vec3"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol3d(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4)); + } + else if (m_argCount == 6) + { + m_hasReturnValue = false; + AIConsole::m_instance->botSetWaypoints_Patrol3d(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(int, 2), BF2_CC_ARG(hfe::Vec3, 3), BF2_CC_ARG(hfe::Vec3, 4), BF2_CC_ARG(hfe::Vec3, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(int, 3) + AIMODULE_CC_EXTRACT(hfe::Vec3, 4) + AIMODULE_CC_EXTRACT(hfe::Vec3, 5) + AIMODULE_CC_EXTRACT(hfe::Vec3, 6) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject197; + +// ConsoleClass198 AI.botMoveTo: method, 3..3 arguments, no result. +// ELF isObjectActive 0x419B10, executeObjectMethod 0x41A370, +// setArgFromString 0x419C30, getReturnValueAsString 0x419AD0, D1 0x419AB0, D0 0x419A70. +// argc 3: dice::hfe::ai::AIConsole::botMoveTo(float, dice::hfe::Vec3, int) (call at 0x41A3F0; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass198 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botMoveTo", 0, 3, 3, "void", false) + m_argTypes[0] = "float"; + m_argTypes[1] = "hfe::Vec3"; + m_argTypes[2] = "int"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->botMoveTo(BF2_CC_ARG(float, 0), BF2_CC_ARG(hfe::Vec3, 1), BF2_CC_ARG(int, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + AIMODULE_CC_EXTRACT(hfe::Vec3, 2) + AIMODULE_CC_EXTRACT(int, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject198; + +// ConsoleClass199 AI.botFlyTo: method, 5..5 arguments, no result. +// ELF isObjectActive 0x41A4A0, executeObjectMethod 0x41B150, +// setArgFromString 0x41A5C0, getReturnValueAsString 0x41A460, D1 0x41A440, D0 0x41A400. +// argc 5: dice::hfe::ai::AIConsole::botFlyTo(int, float, float, float, dice::hfe::Vec3) (call at 0x41B1E2; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass199 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("botFlyTo", 0, 5, 5, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "float"; + m_argTypes[2] = "float"; + m_argTypes[3] = "float"; + m_argTypes[4] = "hfe::Vec3"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AIConsole::m_instance->botFlyTo(BF2_CC_ARG(int, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(float, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(hfe::Vec3, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(float, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT(hfe::Vec3, 5) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject199; + +// ConsoleClass202 AI.createSAI: method, 0..0 arguments, no result. +// ELF isObjectActive 0x41B290, executeObjectMethod 0x41B3D0, +// setArgFromString 0x41B3C0, getReturnValueAsString 0x41B250, D1 0x41B230, D0 0x41B1F0. +// argc 0: dice::hfe::ai::AIMain::createSAI() (call at 0x41B406; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass202 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createSAI", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveAIMain()->createSAI(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject202; + +// ConsoleClass203 AI.saiEnable: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41B6B0, executeObjectMethod 0x41BA20, +// setArgFromString 0x41B7E0, getReturnValueAsString 0x41B470, D1 0x41B450, D0 0x41B410. +// argc 0: dice::hfe::ai::AIMain::getSAIEnable() (slot +0x38 at 0x41BA91; ledger done) +// argc 1: dice::hfe::ai::AIMain::setSAIEnable(bool) (call at 0x41BA70; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass203 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saiEnable", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getSAIEnable(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setSAIEnable(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject203; + +// ConsoleClass204 AI.saiMapXDimension: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x41BD80, executeObjectMethod 0x41C0F0, +// setArgFromString 0x41BEB0, getReturnValueAsString 0x41BB10, D1 0x41BAF0, D0 0x41BAB0. +// argc 0: dice::hfe::ai::AIMain::getSAIMapXDimension() const (call at 0x41C156; ledger done) +// argc 1: dice::hfe::ai::AIMain::setSAIMapXDimension(int) (call at 0x41C13E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass204 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saiMapXDimension", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getSAIMapXDimension(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setSAIMapXDimension(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject204; + +// ConsoleClass205 AI.saiMapYDimension: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x41C440, executeObjectMethod 0x41C7B0, +// setArgFromString 0x41C570, getReturnValueAsString 0x41C1D0, D1 0x41C1B0, D0 0x41C170. +// argc 0: dice::hfe::ai::AIMain::getSAIMapYDimension() const (call at 0x41C816; ledger done) +// argc 1: dice::hfe::ai::AIMain::setSAIMapYDimension(int) (call at 0x41C7FE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass205 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saiMapYDimension", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getSAIMapYDimension(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setSAIMapYDimension(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject205; + +// ConsoleClass206 AI.addSAIStrategy: method, 2..2 arguments, no result. +// ELF isObjectActive 0x41C8D0, executeObjectMethod 0x41CEC0, +// setArgFromString 0x41C9F0, getReturnValueAsString 0x41C890, D1 0x41C870, D0 0x41C830. +// argc 2: dice::hfe::ai::AIConsole::addSAIStrategy(int, std::string) (call at 0x41CF40; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass206 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addSAIStrategy", 0, 2, 2, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->addSAIStrategy(BF2_CC_ARG(int, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject206; + +// ConsoleClass209 AI.renderSide: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x41D260, executeObjectMethod 0x41D5D0, +// setArgFromString 0x41D390, getReturnValueAsString 0x41CFF0, D1 0x41CFD0, D0 0x41CF90. +// argc 0: dice::hfe::ai::AIMain::getRenderSide() const (call at 0x41D636; ledger done) +// argc 1: dice::hfe::ai::AIMain::setRenderSide(int) (call at 0x41D61E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass209 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("renderSide", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getRenderSide(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setRenderSide(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject209; + +// ConsoleClass211 AI.validateDataStructuresEnabled: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41D8F0, executeObjectMethod 0x41DC60, +// setArgFromString 0x41DA20, getReturnValueAsString 0x41D6B0, D1 0x41D690, D0 0x41D650. +// argc 0: dice::hfe::ai::AIMain::getValidateDataStructuresEnabled() const (call at 0x41DCCF; ledger done) +// argc 1: dice::hfe::ai::AIMain::setValidateDataStructuresEnabled(bool) (call at 0x41DCB0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass211 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("validateDataStructuresEnabled", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getValidateDataStructuresEnabled(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setValidateDataStructuresEnabled(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject211; + +// ConsoleClass212 AI.showBotUrgencies: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41DF90, executeObjectMethod 0x41E300, +// setArgFromString 0x41E0C0, getReturnValueAsString 0x41DD50, D1 0x41DD30, D0 0x41DCF0. +// argc 0: dice::hfe::ai::AIMain::getShowBotUrgencies() const (call at 0x41E36F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowBotUrgencies(bool) (call at 0x41E350; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass212 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotUrgencies", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowBotUrgencies(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowBotUrgencies(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject212; + +// ConsoleClass213 AI.showBotSpawnCoord: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41E630, executeObjectMethod 0x41E9A0, +// setArgFromString 0x41E760, getReturnValueAsString 0x41E3F0, D1 0x41E3D0, D0 0x41E390. +// argc 0: dice::hfe::ai::AIMain::getShowBotSpawnCoord() const (call at 0x41EA0F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowBotSpawnCoord(bool) (call at 0x41E9F0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass213 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotSpawnCoord", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowBotSpawnCoord(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowBotSpawnCoord(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject213; + +// ConsoleClass214 AI.showStrategies: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41ECD0, executeObjectMethod 0x41F040, +// setArgFromString 0x41EE00, getReturnValueAsString 0x41EA90, D1 0x41EA70, D0 0x41EA30. +// argc 0: dice::hfe::ai::AIMain::getShowStrategies() const (call at 0x41F0AF; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowStrategies(bool) (call at 0x41F090; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass214 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showStrategies", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowStrategies(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowStrategies(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject214; + +// ConsoleClass215 AI.showSAIStats: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41F370, executeObjectMethod 0x41F6E0, +// setArgFromString 0x41F4A0, getReturnValueAsString 0x41F130, D1 0x41F110, D0 0x41F0D0. +// argc 0: dice::hfe::ai::AIMain::getShowSAIStats() const (call at 0x41F74F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowSAIStats(bool) (call at 0x41F730; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass215 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showSAIStats", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowSAIStats(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowSAIStats(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject215; + +// ConsoleClass216 AI.showBotStats: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x41FA10, executeObjectMethod 0x41FD80, +// setArgFromString 0x41FB40, getReturnValueAsString 0x41F7D0, D1 0x41F7B0, D0 0x41F770. +// argc 0: dice::hfe::ai::AIMain::getShowBotStats() const (call at 0x41FDEF; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowBotStats(bool) (call at 0x41FDD0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass216 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotStats", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowBotStats(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowBotStats(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject216; + +// ConsoleClass217 AI.showBotSense: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x4200B0, executeObjectMethod 0x420410, +// setArgFromString 0x4201D0, getReturnValueAsString 0x41FE70, D1 0x41FE50, D0 0x41FE10. +// argc 0: dice::hfe::ai::BotManager::getRenderBotSensing() const (slot +0x78 at 0x420484; ledger done) +// argc 1: dice::hfe::ai::BotManager::setRenderBotSensing(bool) (slot +0x74 at 0x420465; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass217 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBotSense", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IBotManager::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManager::instance->getRenderBotSensing(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IBotManager::instance->setRenderBotSensing(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject217; + +// ConsoleClass218 AI.showStrategicAreas: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x420740, executeObjectMethod 0x420AB0, +// setArgFromString 0x420870, getReturnValueAsString 0x420500, D1 0x4204E0, D0 0x4204A0. +// argc 0: dice::hfe::ai::AIMain::getShowStrategicAreas() const (call at 0x420B1F; ledger done) +// argc 1: dice::hfe::ai::AIMain::setShowStrategicAreas(bool) (call at 0x420B00; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass218 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showStrategicAreas", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveAIMain()->getShowStrategicAreas(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->setShowStrategicAreas(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject218; + +// ConsoleClass219 AI.showAll: method, 1..1 arguments, no result. +// ELF isObjectActive 0x420BE0, executeObjectMethod 0x420F50, +// setArgFromString 0x420D10, getReturnValueAsString 0x420BA0, D1 0x420B80, D0 0x420B40. +// argc 1: dice::hfe::ai::AIMain::showAll(bool) (call at 0x420F96; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass219 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showAll", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->showAll(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject219; + +// ConsoleClass220 AI.showStrategic: method, 1..1 arguments, no result. +// ELF isObjectActive 0x421040, executeObjectMethod 0x4213B0, +// setArgFromString 0x421170, getReturnValueAsString 0x421000, D1 0x420FE0, D0 0x420FA0. +// argc 1: dice::hfe::ai::AIMain::showStrategic(bool) (call at 0x4213F6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass220 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showStrategic", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->showStrategic(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject220; + +// ConsoleClass221 AI.showBot: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4214A0, executeObjectMethod 0x421810, +// setArgFromString 0x4215D0, getReturnValueAsString 0x421460, D1 0x421440, D0 0x421400. +// argc 1: dice::hfe::ai::AIMain::showBot(bool) (call at 0x421856; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass221 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showBot", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveAIMain() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveAIMain()->showBot(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject221; + +// ConsoleClass223 AI.getRendCameraPosition: method, 0..0 arguments, returns hfe::Vec3. +// ELF isObjectActive 0x421B60, executeObjectMethod 0x421C90, +// setArgFromString 0x421C80, getReturnValueAsString 0x4218C0, D1 0x4218A0, D0 0x421860. +// argc 0: dice::hfe::ai::AIConsole::getRendCameraPosition() (call at 0x421CD3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass223 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getRendCameraPosition", 0, 0, 0, "hfe::Vec3", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getRendCameraPosition(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject223; + +// ConsoleClass224 AI.getRendCameraRotation: method, 0..0 arguments, returns hfe::Vec3. +// ELF isObjectActive 0x422010, executeObjectMethod 0x422140, +// setArgFromString 0x422130, getReturnValueAsString 0x421D70, D1 0x421D50, D0 0x421D10. +// argc 0: dice::hfe::ai::AIConsole::getRendCameraRotation() (call at 0x422183; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass224 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getRendCameraRotation", 0, 0, 0, "hfe::Vec3", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getRendCameraRotation(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject224; + +// ConsoleClass228 AI.getCurrentPitchAngle: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x422460, executeObjectMethod 0x422590, +// setArgFromString 0x422580, getReturnValueAsString 0x422220, D1 0x422200, D0 0x4221C0. +// argc 0: dice::hfe::ai::AIConsole::getCurrentPitchAngle() const (call at 0x4225C3; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass228 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCurrentPitchAngle", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getCurrentPitchAngle(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject228; + +// ConsoleClass229 AI.getCurrentYawAngle: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x422890, executeObjectMethod 0x4229C0, +// setArgFromString 0x4229B0, getReturnValueAsString 0x422650, D1 0x422630, D0 0x4225F0. +// argc 0: dice::hfe::ai::AIConsole::getCurrentYawAngle() const (call at 0x4229F3; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass229 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCurrentYawAngle", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getCurrentYawAngle(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject229; + +// ConsoleClass248 AI.addPlacement: method, 6..6 arguments, returns bool. +// ELF isObjectActive 0x422CC0, executeObjectMethod 0x423D10, +// setArgFromString 0x422DE0, getReturnValueAsString 0x422A80, D1 0x422A60, D0 0x422A20. +// argc 6: dice::hfe::ai::BotPlacementManager::addPlacement(std::string const&, dice::hfe::Vec3 const&, dice::hfe::Vec3 const&, std::string const&, int, std::string const&) (call at 0x423DFC; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass248 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addPlacement", 0, 6, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "hfe::Vec3"; + m_argTypes[2] = "hfe::Vec3"; + m_argTypes[3] = "std::string"; + m_argTypes[4] = "int"; + m_argTypes[5] = "std::string"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return BotPlacementManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = BotPlacementManager::m_instance->addPlacement(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(hfe::Vec3, 1), BF2_CC_ARG(hfe::Vec3, 2), BF2_CC_ARG(std::string, 3), BF2_CC_ARG(int, 4), BF2_CC_ARG(std::string, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(hfe::Vec3, 2) + AIMODULE_CC_EXTRACT(hfe::Vec3, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + AIMODULE_CC_EXTRACT(int, 5) + AIMODULE_CC_EXTRACT(std::string, 6) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject248; + +// ConsoleClass249 AI.spawnBot: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x424140, executeObjectMethod 0x4244A0, +// setArgFromString 0x424260, getReturnValueAsString 0x423F00, D1 0x423EE0, D0 0x423EA0. +// argc 1: dice::hfe::ai::BotPlacementManager::spawnBot(int) (call at 0x4244DB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass249 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("spawnBot", 0, 1, 1, "bool", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return BotPlacementManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = BotPlacementManager::m_instance->spawnBot(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject249; + +// ConsoleClass252 AI.pause: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x4247A0, executeObjectMethod 0x424B00, +// setArgFromString 0x4248C0, getReturnValueAsString 0x424560, D1 0x424540, D0 0x424500. +// argc 0: dice::hfe::ai::BFTimer::getPause() (slot +0x1C at 0x424B74; bf2 ELF 0x841C080) +// argc 1: dice::hfe::ai::BFTimer::setPause(bool) (slot +0x18 at 0x424B55; bf2 ELF 0x841C060) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass252 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("pause", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iBFTimer) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iBFTimer)->getPause(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iBFTimer)->setPause(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject252; + +SetConsoleClassDefaults aiSettingsfullAccessSetConsoleClassDefaults("aiSettings", 2, 0); + +// ConsoleClass259 aiSettings.setMaxNBots: method, 1..1 arguments, no result. +// ELF isObjectActive 0x424C30, executeObjectMethod 0x424F90, +// setArgFromString 0x424D50, getReturnValueAsString 0x424BF0, D1 0x424BD0, D0 0x424B90. +// argc 1: dice::hfe::ai::AISettings::setMaxNBots(int) (slot +0x0 at 0x424FD3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass259 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setMaxNBots", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setMaxNBots(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject259; + +// ConsoleClass260 aiSettings.maxBotsIncludeHumans: method, 1..1 arguments, no result. +// ELF isObjectActive 0x425080, executeObjectMethod 0x4253E0, +// setArgFromString 0x4251A0, getReturnValueAsString 0x425040, D1 0x425020, D0 0x424FE0. +// argc 1: dice::hfe::ai::AISettings::maxBotsIncludeHumans(bool) (slot +0x4 at 0x42542B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass260 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("maxBotsIncludeHumans", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->maxBotsIncludeHumans(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject260; + +// ConsoleClass261 aiSettings.setIgnoreCommanderDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4254D0, executeObjectMethod 0x425830, +// setArgFromString 0x4255F0, getReturnValueAsString 0x425490, D1 0x425470, D0 0x425430. +// argc 1: dice::hfe::ai::AISettings::setIgnoreCommanderDistance(float) (slot +0x8 at 0x425873; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass261 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setIgnoreCommanderDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setIgnoreCommanderDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject261; + +// ConsoleClass262 aiSettings.setMaxNumberOfBehaviours: method, 1..1 arguments, no result. +// ELF isObjectActive 0x425920, executeObjectMethod 0x425C80, +// setArgFromString 0x425A40, getReturnValueAsString 0x4258E0, D1 0x4258C0, D0 0x425880. +// argc 1: dice::hfe::ai::AISettings::setMaxNumberOfBehaviours(int) (slot +0xC at 0x425CC3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass262 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setMaxNumberOfBehaviours", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setMaxNumberOfBehaviours(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject262; + +// ConsoleClass263 aiSettings.setViewDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x425D70, executeObjectMethod 0x4260D0, +// setArgFromString 0x425E90, getReturnValueAsString 0x425D30, D1 0x425D10, D0 0x425CD0. +// argc 1: dice::hfe::ai::AISettings::setViewDistance(float) (slot +0x34 at 0x426113; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass263 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setViewDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setViewDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject263; + +// ConsoleClass264 aiSettings.setStatsViewDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4261C0, executeObjectMethod 0x426520, +// setArgFromString 0x4262E0, getReturnValueAsString 0x426180, D1 0x426160, D0 0x426120. +// argc 1: dice::hfe::ai::AISettings::setStatsViewDistance(float) (slot +0x38 at 0x426563; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass264 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStatsViewDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setStatsViewDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject264; + +// ConsoleClass265 aiSettings.setDrawBotStats: method, 1..1 arguments, no result. +// ELF isObjectActive 0x426610, executeObjectMethod 0x426970, +// setArgFromString 0x426730, getReturnValueAsString 0x4265D0, D1 0x4265B0, D0 0x426570. +// argc 1: dice::hfe::ai::AISettings::setDrawBotStats(bool) (slot +0x3C at 0x4269BB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass265 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setDrawBotStats", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setDrawBotStats(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject265; + +// ConsoleClass266 aiSettings.setInformationGridDimension: method, 1..1 arguments, no result. +// ELF isObjectActive 0x426A60, executeObjectMethod 0x426DC0, +// setArgFromString 0x426B80, getReturnValueAsString 0x426A20, D1 0x426A00, D0 0x4269C0. +// argc 1: dice::hfe::ai::AISettings::setInformationGridDimension(int) (slot +0x40 at 0x426E03; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass266 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setInformationGridDimension", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setInformationGridDimension(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject266; + +// ConsoleClass267 aiSettings.setVehicle: method, 1..1 arguments, no result. +// ELF isObjectActive 0x426EB0, executeObjectMethod 0x427250, +// setArgFromString 0x426FD0, getReturnValueAsString 0x426E70, D1 0x426E50, D0 0x426E10. +// argc 1: dice::hfe::ai::AISettings::setVehicle(std::string const&) (slot +0x5C at 0x4272AF; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass267 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicle", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setVehicle(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject267; + +// ConsoleClass268 aiSettings.setVehicleClusterMapping: method, 2..2 arguments, no result. +// ELF isObjectActive 0x427380, executeObjectMethod 0x427990, +// setArgFromString 0x4274A0, getReturnValueAsString 0x427340, D1 0x427320, D0 0x4272E0. +// argc 2: dice::hfe::ai::AISettings::setVehicleClusterMapping(std::string const&, std::string const&) (slot +0x60 at 0x427A10; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass268 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleClusterMapping", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setVehicleClusterMapping(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject268; + +// ConsoleClass269 aiSettings.setVehicleMaterialCost: method, 3..3 arguments, no result. +// ELF isObjectActive 0x427B00, executeObjectMethod 0x4282E0, +// setArgFromString 0x427C20, getReturnValueAsString 0x427AC0, D1 0x427AA0, D0 0x427A60. +// argc 3: dice::hfe::ai::AISettings::setVehicleMaterialCost(std::string const&, unsigned char, float) (slot +0x8C at 0x428356; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass269 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleMaterialCost", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "materialId"; + m_argTypes[2] = "float"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setVehicleMaterialCost(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(materialId, 1), BF2_CC_ARG(float, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(materialId, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject269; + +// ConsoleClass270 aiSettings.setManDownEquipment: method, 1..1 arguments, no result. +// ELF isObjectActive 0x428430, executeObjectMethod 0x4287D0, +// setArgFromString 0x428550, getReturnValueAsString 0x4283F0, D1 0x4283D0, D0 0x428390. +// argc 1: dice::hfe::ai::AISettings::setManDownEquipment(std::string const&) (slot +0x88 at 0x42882F; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass270 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setManDownEquipment", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setManDownEquipment(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject270; + +// ConsoleClass271 aiSettings.getInformationGridDimension: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x428B30, executeObjectMethod 0x428C60, +// setArgFromString 0x428C50, getReturnValueAsString 0x4288C0, D1 0x4288A0, D0 0x428860. +// argc 0: dice::hfe::ai::AISettings::getInformationGridDimension() const (slot +0x3C at 0x428C95; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass271 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getInformationGridDimension", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getInformationGridDimension(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject271; + +// ConsoleClass272 aiSettings.getViewDistance: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x428F60, executeObjectMethod 0x429090, +// setArgFromString 0x429080, getReturnValueAsString 0x428D20, D1 0x428D00, D0 0x428CC0. +// argc 0: dice::hfe::ai::AISettings::getViewDistance() const (slot +0x28 at 0x4290C5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass272 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getViewDistance", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getViewDistance(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject272; + +// ConsoleClass273 aiSettings.getStatsViewDistance: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x429390, executeObjectMethod 0x4294C0, +// setArgFromString 0x4294B0, getReturnValueAsString 0x429150, D1 0x429130, D0 0x4290F0. +// argc 0: dice::hfe::ai::AISettings::getStatsViewDistance() const (slot +0x2C at 0x4294F5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass273 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStatsViewDistance", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getStatsViewDistance(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject273; + +// ConsoleClass274 aiSettings.getVehicle: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x429840, executeObjectMethod 0x429BA0, +// setArgFromString 0x429960, getReturnValueAsString 0x429600, D1 0x429590, D0 0x429520. +// argc 1: dice::hfe::ai::AISettings::getVehicle(int) const (slot +0x50 at 0x429BE3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass274 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicle", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicle(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject274; + +// ConsoleClass275 aiSettings.getVehicleClusterMapping: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x429F30, executeObjectMethod 0x42A2D0, +// setArgFromString 0x42A050, getReturnValueAsString 0x429CF0, D1 0x429C80, D0 0x429C10. +// argc 1: dice::hfe::ai::AISettings::getVehicleClusterMapping(std::string const&) const (slot +0x58 at 0x42A326; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass275 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicleClusterMapping", 0, 1, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleClusterMapping(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject275; + +// ConsoleClass276 aiSettings.setNSides: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42A410, executeObjectMethod 0x42A770, +// setArgFromString 0x42A530, getReturnValueAsString 0x42A3D0, D1 0x42A3B0, D0 0x42A370. +// argc 1: dice::hfe::ai::AISettings::setNSides(int) (slot +0x44 at 0x42A7B3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass276 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setNSides", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setNSides(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject276; + +// ConsoleClass277 aiSettings.getNSides: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x42AA90, executeObjectMethod 0x42ABC0, +// setArgFromString 0x42ABB0, getReturnValueAsString 0x42A820, D1 0x42A800, D0 0x42A7C0. +// argc 0: dice::hfe::ai::AISettings::getNSides() const (slot +0x40 at 0x42ABF5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass277 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNSides", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getNSides(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject277; + +// ConsoleClass278 aiSettings.setBotSkill: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42ACC0, executeObjectMethod 0x42B020, +// setArgFromString 0x42ADE0, getReturnValueAsString 0x42AC80, D1 0x42AC60, D0 0x42AC20. +// argc 1: dice::hfe::ai::AISettings::setBotSkill(float) (slot +0x48 at 0x42B063; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass278 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBotSkill", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setBotSkill(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject278; + +// ConsoleClass279 aiSettings.getBotSkill: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x42B310, executeObjectMethod 0x42B440, +// setArgFromString 0x42B430, getReturnValueAsString 0x42B0D0, D1 0x42B0B0, D0 0x42B070. +// argc 0: dice::hfe::ai::AISettings::getBotSkill() const (slot +0x44 at 0x42B475; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass279 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBotSkill", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject279; + +// ConsoleClass280 aiSettings.getNumberOfVehicleGroups: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x42B770, executeObjectMethod 0x42B8A0, +// setArgFromString 0x42B890, getReturnValueAsString 0x42B500, D1 0x42B4E0, D0 0x42B4A0. +// argc 0: dice::hfe::ai::AISettings::getNumberOfVehicleGroups() const (slot +0x64 at 0x42B8D5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass280 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfVehicleGroups", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfVehicleGroups(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject280; + +// ConsoleClass281 aiSettings.getVehicleGroup: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x42BBD0, executeObjectMethod 0x42BF30, +// setArgFromString 0x42BCF0, getReturnValueAsString 0x42B960, D1 0x42B940, D0 0x42B900. +// argc 1: dice::hfe::ai::AISettings::getVehicleGroup(int) const (slot +0x68 at 0x42BF6D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass281 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicleGroup", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject281; + +// ConsoleClass282 aiSettings.getVehicleGroupName: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x42C2B0, executeObjectMethod 0x42C610, +// setArgFromString 0x42C3D0, getReturnValueAsString 0x42C070, D1 0x42C000, D0 0x42BF90. +// argc 1: dice::hfe::ai::AISettings::getVehicleGroupName(int) const (slot +0x70 at 0x42C653; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass282 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVehicleGroupName", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroupName(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject282; + +// ConsoleClass283 aiSettings.createVehicleGroup: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42C720, executeObjectMethod 0x42CAC0, +// setArgFromString 0x42C840, getReturnValueAsString 0x42C6E0, D1 0x42C6C0, D0 0x42C680. +// argc 1: dice::hfe::ai::AISettings::createVehicleGroup(std::string const&) (slot +0x64 at 0x42CB1F; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass283 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createVehicleGroup", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->createVehicleGroup(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject283; + +// ConsoleClass284 aiSettings.addVehicleToVehicleGroup: method, 2..2 arguments, no result. +// ELF isObjectActive 0x42CBF0, executeObjectMethod 0x42D200, +// setArgFromString 0x42CD10, getReturnValueAsString 0x42CBB0, D1 0x42CB90, D0 0x42CB50. +// argc 2: dice::hfe::ai::AISettings::addVehicleToVehicleGroup(std::string const&, std::string const&) (slot +0x6C at 0x42D280; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass284 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addVehicleToVehicleGroup", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->addVehicleToVehicleGroup(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject284; + +// ConsoleClass285 aiSettings.getSAIUpdateFrequency: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x42D570, executeObjectMethod 0x42D6A0, +// setArgFromString 0x42D690, getReturnValueAsString 0x42D330, D1 0x42D310, D0 0x42D2D0. +// argc 0: dice::hfe::ai::AISettings::getSAIUpdateFrequency() const (slot +0x48 at 0x42D6D5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass285 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSAIUpdateFrequency", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getSAIUpdateFrequency(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject285; + +// ConsoleClass286 aiSettings.setSAIUpdateFrequency: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42D7A0, executeObjectMethod 0x42DB00, +// setArgFromString 0x42D8C0, getReturnValueAsString 0x42D760, D1 0x42D740, D0 0x42D700. +// argc 1: dice::hfe::ai::AISettings::setSAIUpdateFrequency(float) (slot +0x4C at 0x42DB43; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass286 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSAIUpdateFrequency", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setSAIUpdateFrequency(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject286; + +// ConsoleClass287 aiSettings.setRespawnAllowed: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42DBF0, executeObjectMethod 0x42DF50, +// setArgFromString 0x42DD10, getReturnValueAsString 0x42DBB0, D1 0x42DB90, D0 0x42DB50. +// argc 1: dice::hfe::ai::AISettings::setRespawnAllowed(bool) (slot +0x58 at 0x42DF9B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass287 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setRespawnAllowed", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->setRespawnAllowed(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject287; + +// ConsoleClass288 aiSettings.addBotName: method, 2..2 arguments, no result. +// ELF isObjectActive 0x42E040, executeObjectMethod 0x42E650, +// setArgFromString 0x42E160, getReturnValueAsString 0x42E000, D1 0x42DFE0, D0 0x42DFA0. +// argc 2: dice::hfe::ai::AISettings::addBotName(std::string const&, std::string const&) (slot +0x90 at 0x42E6D0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass288 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addBotName", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettingsModifier) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iaiSettingsModifier)->addBotName(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject288; + +// ConsoleClass289 aiSettings.isRespawnAllowed: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x42E9C0, executeObjectMethod 0x42EAF0, +// setArgFromString 0x42EAE0, getReturnValueAsString 0x42E780, D1 0x42E760, D0 0x42E720. +// argc 0: dice::hfe::ai::AISettings::isRespawnAllowed() const (slot +0x4C at 0x42EB25; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass289 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isRespawnAllowed", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->isRespawnAllowed(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject289; + +// ConsoleClass290 aiSettings.overrideMenuSettings: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x42EDF0, executeObjectMethod 0x42F160, +// setArgFromString 0x42EF20, getReturnValueAsString 0x42EBB0, D1 0x42EB90, D0 0x42EB50. +// argc 0: dice::hfe::ai::AISettings::getOverrideMenuSettings() const (slot +0xBC at 0x42F1D1; ledger done) +// argc 1: dice::hfe::ai::AISettings::setOverrideMenuSettings(bool) (slot +0x15C at 0x42F1B2; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass290 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("overrideMenuSettings", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getAISettings() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getAISettings()->getOverrideMenuSettings(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(getAISettings())->setOverrideMenuSettings(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject290; + +// ConsoleClass293 aiSettings.lodEnable: method, 0..1 arguments, returns bool. +// ELF isObjectActive 0x42F490, executeObjectMethod 0x42F7F0, +// setArgFromString 0x42F5B0, getReturnValueAsString 0x42F250, D1 0x42F230, D0 0x42F1F0. +// argc 0: dice::hfe::ai::AILODManager::lodEnable() (call at 0x42F862; ledger done) +// argc 1: dice::hfe::ai::AILODManager::lodEnable(bool) (call at 0x42F835; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass293 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("lodEnable", 0, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AILODManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AILODManager::m_instance->lodEnable(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AILODManager::m_instance->lodEnable(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject293; + +// ConsoleClass294 aiSettings.setBasicLODDistance: method, 1..1 arguments, no result. +// ELF isObjectActive 0x42F910, executeObjectMethod 0x42FC70, +// setArgFromString 0x42FA30, getReturnValueAsString 0x42F8D0, D1 0x42F8B0, D0 0x42F870. +// argc 1: dice::hfe::ai::AILODManager::setBasicLODDistance(float) (call at 0x42FCB1; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass294 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBasicLODDistance", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AILODManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AILODManager::m_instance->setBasicLODDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject294; + +// ConsoleClass296 aiSettings.setVehicleMods: method, 2..2 arguments, no result. +// ELF isObjectActive 0x42FD60, executeObjectMethod 0x430370, +// setArgFromString 0x42FE80, getReturnValueAsString 0x42FD20, D1 0x42FD00, D0 0x42FCC0. +// argc 2: dice::hfe::ai::AIConsole::setVehicleMods(std::string const&, std::string const&) (call at 0x4303EE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass296 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleMods", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setVehicleMods(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject296; + +// ConsoleClass297 aiSettings.setStandardPersonality: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4304E0, executeObjectMethod 0x430AB0, +// setArgFromString 0x430600, getReturnValueAsString 0x4304A0, D1 0x430480, D0 0x430440. +// argc 2: dice::hfe::ai::AIConsole::setStandardPersonality(std::string const&, int) (call at 0x430B16; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass297 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStandardPersonality", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setStandardPersonality(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject297; + +// ConsoleClass298 aiSettings.setVehicleBehaviour: method, 7..7 arguments, no result. +// ELF isObjectActive 0x430BE0, executeObjectMethod 0x431D90, +// setArgFromString 0x430D00, getReturnValueAsString 0x430BA0, D1 0x430B80, D0 0x430B40. +// argc 7: dice::hfe::ai::AIConsole::setVehicleBehaviour(std::string, std::string, std::string, std::string, int, std::string, std::string) (call at 0x431F5A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass298 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleBehaviour", 0, 7, 7, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + m_argTypes[4] = "int"; + m_argTypes[5] = "std::string"; + m_argTypes[6] = "std::string"; + AIMODULE_CC_TAIL(7) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 7) + { + m_hasReturnValue = false; + AIConsole::m_instance->setVehicleBehaviour(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3), BF2_CC_ARG(int, 4), BF2_CC_ARG(std::string, 5), BF2_CC_ARG(std::string, 6)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + AIMODULE_CC_EXTRACT(int, 5) + AIMODULE_CC_EXTRACT(std::string, 6) + AIMODULE_CC_EXTRACT(std::string, 7) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject298; + +// ConsoleClass299 aiSettings.setVehicleDefaultBehaviour: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4321D0, executeObjectMethod 0x4327E0, +// setArgFromString 0x4322F0, getReturnValueAsString 0x432190, D1 0x432170, D0 0x432130. +// argc 2: dice::hfe::ai::AIConsole::setVehicleDefaultBehaviour(std::string&, std::string&) (call at 0x43285E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass299 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVehicleDefaultBehaviour", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setVehicleDefaultBehaviour(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject299; + +// ConsoleClass300 aiSettings.addInterpreterEntry: method, 2..3 arguments, no result. +// ELF isObjectActive 0x432950, executeObjectMethod 0x433180, +// setArgFromString 0x432A70, getReturnValueAsString 0x432910, D1 0x4328F0, D0 0x4328B0. +// argc 2: dice::hfe::ai::AIConsole::addInterpreterEntry(std::string, std::string) (call at 0x43333D; ledger done) +// argc 3: dice::hfe::ai::AIConsole::addInterpreterEntry(std::string, std::string, dice::hfe::ai::BotLodLevel) (call at 0x43323F; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass300 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addInterpreterEntry", 0, 2, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "BotLodLevel"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->addInterpreterEntry(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + else if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->addInterpreterEntry(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(BotLodLevel, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT_WITH(BotLodLevel, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject300; + +// ConsoleClass301 aiSettings.removeInterpreterEntry: method, 3..3 arguments, no result. +// ELF isObjectActive 0x433460, executeObjectMethod 0x433C90, +// setArgFromString 0x433580, getReturnValueAsString 0x433420, D1 0x433400, D0 0x4333C0. +// argc 3: dice::hfe::ai::AIConsole::removeInterpreterEntry(std::string, std::string, dice::hfe::ai::BotLodLevel) (call at 0x433D3E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass301 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeInterpreterEntry", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "BotLodLevel"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->removeInterpreterEntry(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(BotLodLevel, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT_WITH(BotLodLevel, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject301; + +// ConsoleClass302 aiSettings.activateDefaultInterpreter: method, 3..3 arguments, no result. +// ELF isObjectActive 0x433E70, executeObjectMethod 0x434650, +// setArgFromString 0x433F90, getReturnValueAsString 0x433E30, D1 0x433E10, D0 0x433DD0. +// argc 3: dice::hfe::ai::AIConsole::activateDefaultInterpreter(std::string, dice::hfe::ai::BAPStatementType, dice::hfe::ai::BotLodLevel) (call at 0x4346DF; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass302 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activateDefaultInterpreter", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "BAPStatementType"; + m_argTypes[2] = "BotLodLevel"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIConsole::m_instance->activateDefaultInterpreter(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(BAPStatementType, 1), BF2_CC_ARG(BotLodLevel, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(BAPStatementType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(BotLodLevel, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject302; + +// ConsoleClass303 aiSettings.setBasicBotWeights: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4347D0, executeObjectMethod 0x434B70, +// setArgFromString 0x4348F0, getReturnValueAsString 0x434790, D1 0x434770, D0 0x434730. +// argc 1: dice::hfe::ai::AIConsole::setBasicBotWeights(std::string) (call at 0x434BE1; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass303 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBasicBotWeights", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setBasicBotWeights(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject303; + +// ConsoleClass304 aiSettings.setBehaviour: method, 2..2 arguments, no result. +// ELF isObjectActive 0x434CD0, executeObjectMethod 0x4352C0, +// setArgFromString 0x434DF0, getReturnValueAsString 0x434C90, D1 0x434C70, D0 0x434C30. +// argc 2: dice::hfe::ai::AIConsole::setBehaviour(int, std::string) (call at 0x435340; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass304 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBehaviour", 0, 2, 2, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setBehaviour(BF2_CC_ARG(int, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject304; + +// ConsoleClass305 aiSettings.getBehaviour: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x4356B0, executeObjectMethod 0x435A10, +// setArgFromString 0x4357D0, getReturnValueAsString 0x435470, D1 0x435400, D0 0x435390. +// argc 1: dice::hfe::ai::AIConsole::getBehaviour(int) (call at 0x435A5B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass305 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBehaviour", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getBehaviour(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject305; + +// ConsoleClass306 aiSettings.createBehaviourModifiers: method, 1..1 arguments, no result. +// ELF isObjectActive 0x435B50, executeObjectMethod 0x435EF0, +// setArgFromString 0x435C70, getReturnValueAsString 0x435B10, D1 0x435AF0, D0 0x435AB0. +// argc 1: dice::hfe::ai::AIConsole::createBehaviourModifiers(std::string) (call at 0x435F61; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass306 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createBehaviourModifiers", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->createBehaviourModifiers(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject306; + +// ConsoleClass307 aiSettings.activeBehaviourModifiers: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x4362D0, executeObjectMethod 0x436670, +// setArgFromString 0x4363F0, getReturnValueAsString 0x436090, D1 0x436020, D0 0x435FB0. +// argc 0: dice::hfe::ai::AIConsole::getActiveBehaviourModifiers() (call at 0x436755; ledger stop) +// argc 1: dice::hfe::ai::AIConsole::setActiveBehaviourModifiers(std::string) (call at 0x4366EF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass307 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activeBehaviourModifiers", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getActiveBehaviourModifiers(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setActiveBehaviourModifiers(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject307; + +// ConsoleClass308 aiSettings.setBehaviourModifier: method, 2..2 arguments, no result. +// ELF isObjectActive 0x436840, executeObjectMethod 0x436E10, +// setArgFromString 0x436960, getReturnValueAsString 0x436800, D1 0x4367E0, D0 0x4367A0. +// argc 2: dice::hfe::ai::AIConsole::setBehaviourModifier(std::string, float) (call at 0x436E90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass308 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setBehaviourModifier", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->setBehaviourModifier(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject308; + +// ConsoleClass309 aiSettings.getBehaviourModifier: method, 1..1 arguments, returns float. +// ELF isObjectActive 0x437180, executeObjectMethod 0x437520, +// setArgFromString 0x4372A0, getReturnValueAsString 0x436F40, D1 0x436F20, D0 0x436EE0. +// argc 1: dice::hfe::ai::AIConsole::getBehaviourModifier(std::string) (call at 0x437583; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass309 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getBehaviourModifier", 0, 1, 1, "float", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getBehaviourModifier(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject309; + +// ConsoleClass310 aiSettings.listBehaviourModifiers: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x437920, executeObjectMethod 0x437A50, +// setArgFromString 0x437A40, getReturnValueAsString 0x4376E0, D1 0x437670, D0 0x437600. +// argc 0: dice::hfe::ai::AIConsole::listBehaviourModifiers() (call at 0x437A93; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass310 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listBehaviourModifiers", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->listBehaviourModifiers(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject310; + +// ConsoleClass311 aiSettings.showAISettings: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x437E10, executeObjectMethod 0x437F40, +// setArgFromString 0x437F30, getReturnValueAsString 0x437BD0, D1 0x437B60, D0 0x437AF0. +// argc 0: dice::hfe::ai::AIConsole::showAISettings() (call at 0x437F83; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass311 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showAISettings", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->showAISettings(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject311; + +// ConsoleClass312 aiSettings.createUCConstant: method, 2..2 arguments, no result. +// ELF isObjectActive 0x438080, executeObjectMethod 0x438650, +// setArgFromString 0x4381A0, getReturnValueAsString 0x438040, D1 0x438020, D0 0x437FE0. +// argc 2: dice::hfe::ai::BotBehaviourManager::createUCConstant(std::string&, float) (call at 0x4386C2; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass312 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createUCConstant", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return BotBehaviourManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + BotBehaviourManager::m_instance->createUCConstant(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject312; + +// ConsoleClass313 aiSettings.createUCLinear: method, 3..3 arguments, no result. +// ELF isObjectActive 0x4387B0, executeObjectMethod 0x438F90, +// setArgFromString 0x4388D0, getReturnValueAsString 0x438770, D1 0x438750, D0 0x438710. +// argc 3: dice::hfe::ai::BotBehaviourManager::createUCLinear(std::string&, float, float) (call at 0x439011; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass313 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createUCLinear", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + m_argTypes[2] = "float"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return BotBehaviourManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + BotBehaviourManager::m_instance->createUCLinear(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(float, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(float, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject313; + +// ConsoleClass314 aiSettings.createUCXInverse: method, 5..5 arguments, no result. +// ELF isObjectActive 0x439100, executeObjectMethod 0x439D00, +// setArgFromString 0x439220, getReturnValueAsString 0x4390C0, D1 0x4390A0, D0 0x439060. +// argc 5: dice::hfe::ai::BotBehaviourManager::createUCXInverse(std::string&, float, float, float, float) (call at 0x439D93; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass314 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createUCXInverse", 0, 5, 5, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + m_argTypes[2] = "float"; + m_argTypes[3] = "float"; + m_argTypes[4] = "float"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return BotBehaviourManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + BotBehaviourManager::m_instance->createUCXInverse(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(float, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(float, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT(float, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT(float, 5) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject314; + +// ConsoleClass315 aiSettings.createLODManager: method, 2..2 arguments, std::string result discarded. +// ELF isObjectActive 0x439E80, executeObjectMethod 0x43A420, +// setArgFromString 0x439FA0, getReturnValueAsString 0x439E40, D1 0x439E20, D0 0x439DE0. +// argc 2: dice::hfe::ai::AIConsole::createLODManager(float, float) (call at 0x43A47E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass315 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createLODManager", 0, 2, 2, "std::string", false) + m_argTypes[0] = "float"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->createLODManager(BF2_CC_ARG(float, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject315; + +// ConsoleClass316 aiSettings.setSensingAgentPatternName: method, 1..1 arguments, no result. +// ELF isObjectActive 0x43A550, executeObjectMethod 0x43A8F0, +// setArgFromString 0x43A670, getReturnValueAsString 0x43A510, D1 0x43A4F0, D0 0x43A4B0. +// argc 1: dice::hfe::ai::AIConsole::setSensingAgentPatternName(std::string const&) (call at 0x43A94D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass316 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSensingAgentPatternName", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setSensingAgentPatternName(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject316; + +// ConsoleClass317 aiSettings.setSensingAgentNullPattern: method, 1..1 arguments, no result. +// ELF isObjectActive 0x43AA20, executeObjectMethod 0x43ADC0, +// setArgFromString 0x43AB40, getReturnValueAsString 0x43A9E0, D1 0x43A9C0, D0 0x43A980. +// argc 1: dice::hfe::ai::AIConsole::setSensingAgentNullPattern(std::string const&) (call at 0x43AE1D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass317 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSensingAgentNullPattern", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setSensingAgentNullPattern(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject317; + +// ConsoleClass318 aiSettings.addSensingAgentPattern: method, 2..2 arguments, no result. +// ELF isObjectActive 0x43AEF0, executeObjectMethod 0x43B500, +// setArgFromString 0x43B010, getReturnValueAsString 0x43AEB0, D1 0x43AE90, D0 0x43AE50. +// argc 2: dice::hfe::ai::AIConsole::addSensingAgentPattern(std::string const&, std::string const&) (call at 0x43B57E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass318 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addSensingAgentPattern", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIConsole::m_instance->addSensingAgentPattern(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject318; + +// ConsoleClass319 aiSettings.sensingAgentDebug: method, 0..0 arguments, no result. +// ELF isObjectActive 0x43B670, executeObjectMethod 0x43B7A0, +// setArgFromString 0x43B790, getReturnValueAsString 0x43B630, D1 0x43B610, D0 0x43B5D0. +// argc 0: dice::hfe::ai::AIConsole::sensingAgentDebug() (call at 0x43B7D9; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass319 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("sensingAgentDebug", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIConsole::m_instance->sensingAgentDebug(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject319; + +// ConsoleClass321 aiSettings.autoSpawnBots: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x43BA80, executeObjectMethod 0x43BDE0, +// setArgFromString 0x43BBA0, getReturnValueAsString 0x43B840, D1 0x43B820, D0 0x43B7E0. +// argc 0: dice::hfe::ai::AISettings::getAutoSpawnBots() const (slot +0x90 at 0x43BE54; ledger done) +// argc 1: dice::hfe::ai::AISettings::setAutoSpawnBots(bool) (slot +0x148 at 0x43BE35; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass321 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("autoSpawnBots", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getAutoSpawnBots(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(static_cast(CommonSingletonServer::m_iaiSettings))->setAutoSpawnBots(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject321; + +SetConsoleClassDefaults AIBotManagerfullAccessSetConsoleClassDefaults("AIBotManager", 2, 0); + +// ConsoleClass327 AIBotManager.setLodLevelTicks: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43BF10, executeObjectMethod 0x43C6E0, +// setArgFromString 0x43C030, getReturnValueAsString 0x43BED0, D1 0x43BEB0, D0 0x43BE70. +// argc 3: dice::hfe::ai::BotManager::setLodLevelTicks(unsigned int, unsigned int, unsigned int) (slot +0x8 at 0x43C741; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass327 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setLodLevelTicks", 0, 3, 3, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + m_argTypes[2] = "hfe::uint"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setLodLevelTicks(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1), BF2_CC_ARG(hfe::uint, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + AIMODULE_CC_EXTRACT(hfe::uint, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject327; + +// ConsoleClass328 AIBotManager.setLodLevelPriority: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43C7F0, executeObjectMethod 0x43CFC0, +// setArgFromString 0x43C910, getReturnValueAsString 0x43C7B0, D1 0x43C790, D0 0x43C750. +// argc 3: dice::hfe::ai::BotManager::setLodLevelPriority(unsigned int, unsigned int, unsigned int) (slot +0xC at 0x43D021; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass328 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setLodLevelPriority", 0, 3, 3, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + m_argTypes[2] = "hfe::uint"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setLodLevelPriority(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1), BF2_CC_ARG(hfe::uint, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + AIMODULE_CC_EXTRACT(hfe::uint, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject328; + +// ConsoleClass329 AIBotManager.setPlannedDecisionMakingThreshold: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43D0D0, executeObjectMethod 0x43D8A0, +// setArgFromString 0x43D1F0, getReturnValueAsString 0x43D090, D1 0x43D070, D0 0x43D030. +// argc 3: dice::hfe::ai::BotManager::setPlannedDecisionMakingThreshold(double const&, double const&, double const&) (slot +0x10 at 0x43D907; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass329 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPlannedDecisionMakingThreshold", 0, 3, 3, "void", false) + m_argTypes[0] = "double"; + m_argTypes[1] = "double"; + m_argTypes[2] = "double"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setPlannedDecisionMakingThreshold(BF2_CC_ARG(double, 0), BF2_CC_ARG(double, 1), BF2_CC_ARG(double, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + AIMODULE_CC_EXTRACT(double, 2) + AIMODULE_CC_EXTRACT(double, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject329; + +// ConsoleClass330 AIBotManager.setUnplannedDecisionMakingThreshold: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43D9B0, executeObjectMethod 0x43E180, +// setArgFromString 0x43DAD0, getReturnValueAsString 0x43D970, D1 0x43D950, D0 0x43D910. +// argc 3: dice::hfe::ai::BotManager::setUnplannedDecisionMakingThreshold(double const&, double const&, double const&) (slot +0x14 at 0x43E1E7; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass330 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setUnplannedDecisionMakingThreshold", 0, 3, 3, "void", false) + m_argTypes[0] = "double"; + m_argTypes[1] = "double"; + m_argTypes[2] = "double"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setUnplannedDecisionMakingThreshold(BF2_CC_ARG(double, 0), BF2_CC_ARG(double, 1), BF2_CC_ARG(double, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(double, 1) + AIMODULE_CC_EXTRACT(double, 2) + AIMODULE_CC_EXTRACT(double, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject330; + +// ConsoleClass331 AIBotManager.setDecisionMakingInterleave: method, 2..2 arguments, no result. +// ELF isObjectActive 0x43E290, executeObjectMethod 0x43E830, +// setArgFromString 0x43E3B0, getReturnValueAsString 0x43E250, D1 0x43E230, D0 0x43E1F0. +// argc 2: dice::hfe::ai::BotManager::setDecisionMakingInterleave(unsigned int, unsigned int) (slot +0x18 at 0x43E886; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass331 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setDecisionMakingInterleave", 0, 2, 2, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setDecisionMakingInterleave(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject331; + +// ConsoleClass332 AIBotManager.setSensingQuotient: method, 2..2 arguments, no result. +// ELF isObjectActive 0x43E930, executeObjectMethod 0x43EED0, +// setArgFromString 0x43EA50, getReturnValueAsString 0x43E8F0, D1 0x43E8D0, D0 0x43E890. +// argc 2: dice::hfe::ai::BotManager::setSensingQuotient(unsigned int, unsigned int) (slot +0x1C at 0x43EF26; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass332 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSensingQuotient", 0, 2, 2, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setSensingQuotient(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject332; + +// ConsoleClass333 AIBotManager.setSystemQuotient: method, 3..3 arguments, no result. +// ELF isObjectActive 0x43EFD0, executeObjectMethod 0x43F7A0, +// setArgFromString 0x43F0F0, getReturnValueAsString 0x43EF90, D1 0x43EF70, D0 0x43EF30. +// argc 3: dice::hfe::ai::BotManager::setSystemQuotient(unsigned int, unsigned int, unsigned int) (slot +0x20 at 0x43F801; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass333 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSystemQuotient", 0, 3, 3, "void", false) + m_argTypes[0] = "hfe::uint"; + m_argTypes[1] = "hfe::uint"; + m_argTypes[2] = "hfe::uint"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->setSystemQuotient(BF2_CC_ARG(hfe::uint, 0), BF2_CC_ARG(hfe::uint, 1), BF2_CC_ARG(hfe::uint, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::uint, 1) + AIMODULE_CC_EXTRACT(hfe::uint, 2) + AIMODULE_CC_EXTRACT(hfe::uint, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject333; + +// ConsoleClass334 AIBotManager.getLodLevelFullTicks: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x43FAB0, executeObjectMethod 0x43FBE0, +// setArgFromString 0x43FBD0, getReturnValueAsString 0x43F870, D1 0x43F850, D0 0x43F810. +// argc 0: dice::hfe::ai::BotManager::getLodLevelFullTicks() const (slot +0x24 at 0x43FC15; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass334 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelFullTicks", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelFullTicks(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject334; + +// ConsoleClass335 AIBotManager.getLodLevelMediumTicks: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x43FEE0, executeObjectMethod 0x440010, +// setArgFromString 0x440000, getReturnValueAsString 0x43FCA0, D1 0x43FC80, D0 0x43FC40. +// argc 0: dice::hfe::ai::BotManager::getLodLevelMediumTicks() const (slot +0x28 at 0x440045; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass335 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelMediumTicks", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelMediumTicks(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject335; + +// ConsoleClass336 AIBotManager.getLodLevelLightTicks: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440310, executeObjectMethod 0x440440, +// setArgFromString 0x440430, getReturnValueAsString 0x4400D0, D1 0x4400B0, D0 0x440070. +// argc 0: dice::hfe::ai::BotManager::getLodLevelLightTicks() const (slot +0x2C at 0x440475; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass336 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelLightTicks", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelLightTicks(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject336; + +// ConsoleClass337 AIBotManager.getLodLevelFullPriority: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440740, executeObjectMethod 0x440870, +// setArgFromString 0x440860, getReturnValueAsString 0x440500, D1 0x4404E0, D0 0x4404A0. +// argc 0: dice::hfe::ai::BotManager::getLodLevelFullPriority() const (slot +0x30 at 0x4408A5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass337 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelFullPriority", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelFullPriority(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject337; + +// ConsoleClass338 AIBotManager.getLodLevelMediumPriority: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440B70, executeObjectMethod 0x440CA0, +// setArgFromString 0x440C90, getReturnValueAsString 0x440930, D1 0x440910, D0 0x4408D0. +// argc 0: dice::hfe::ai::BotManager::getLodLevelMediumPriority() const (slot +0x34 at 0x440CD5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass338 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelMediumPriority", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelMediumPriority(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject338; + +// ConsoleClass339 AIBotManager.getLodLevelLightPriority: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x440FA0, executeObjectMethod 0x4410D0, +// setArgFromString 0x4410C0, getReturnValueAsString 0x440D60, D1 0x440D40, D0 0x440D00. +// argc 0: dice::hfe::ai::BotManager::getLodLevelLightPriority() const (slot +0x38 at 0x441105; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass339 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getLodLevelLightPriority", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getLodLevelLightPriority(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject339; + +// ConsoleClass340 AIBotManager.getPlannedDecisionMakingThresholdFull: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x4413D0, executeObjectMethod 0x441500, +// setArgFromString 0x4414F0, getReturnValueAsString 0x441190, D1 0x441170, D0 0x441130. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdFull() const (slot +0x3C at 0x441535; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass340 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingThresholdFull", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingThresholdFull(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject340; + +// ConsoleClass341 AIBotManager.getPlannedDecisionMakingThresholdMedium: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x441800, executeObjectMethod 0x441930, +// setArgFromString 0x441920, getReturnValueAsString 0x4415C0, D1 0x4415A0, D0 0x441560. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdMedium() const (slot +0x40 at 0x441965; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass341 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingThresholdMedium", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingThresholdMedium(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject341; + +// ConsoleClass342 AIBotManager.getPlannedDecisionMakingThresholdLight: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x441C30, executeObjectMethod 0x441D60, +// setArgFromString 0x441D50, getReturnValueAsString 0x4419F0, D1 0x4419D0, D0 0x441990. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdLight() const (slot +0x44 at 0x441D95; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass342 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingThresholdLight", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingThresholdLight(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject342; + +// ConsoleClass343 AIBotManager.getUnplannedDecisionMakingThresholdFull: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x442060, executeObjectMethod 0x442190, +// setArgFromString 0x442180, getReturnValueAsString 0x441E20, D1 0x441E00, D0 0x441DC0. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdFull() const (slot +0x48 at 0x4421C5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass343 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingThresholdFull", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingThresholdFull(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject343; + +// ConsoleClass344 AIBotManager.getUnplannedDecisionMakingThresholdMedium: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x442490, executeObjectMethod 0x4425C0, +// setArgFromString 0x4425B0, getReturnValueAsString 0x442250, D1 0x442230, D0 0x4421F0. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdMedium() const (slot +0x4C at 0x4425F5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass344 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingThresholdMedium", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingThresholdMedium(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject344; + +// ConsoleClass345 AIBotManager.getUnplannedDecisionMakingThresholdLight: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x4428C0, executeObjectMethod 0x4429F0, +// setArgFromString 0x4429E0, getReturnValueAsString 0x442680, D1 0x442660, D0 0x442620. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdLight() const (slot +0x50 at 0x442A25; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass345 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingThresholdLight", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingThresholdLight(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject345; + +// ConsoleClass346 AIBotManager.getPlannedDecisionMakingInterleave: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x442CF0, executeObjectMethod 0x442E20, +// setArgFromString 0x442E10, getReturnValueAsString 0x442AB0, D1 0x442A90, D0 0x442A50. +// argc 0: dice::hfe::ai::BotManager::getPlannedDecisionMakingInterleave() const (slot +0x54 at 0x442E55; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass346 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPlannedDecisionMakingInterleave", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getPlannedDecisionMakingInterleave(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject346; + +// ConsoleClass347 AIBotManager.getUnplannedDecisionMakingInterleave: method, 0..0 arguments, returns hfe::uint. +// ELF isObjectActive 0x443120, executeObjectMethod 0x443250, +// setArgFromString 0x443240, getReturnValueAsString 0x442EE0, D1 0x442EC0, D0 0x442E80. +// argc 0: dice::hfe::ai::BotManager::getUnplannedDecisionMakingInterleave() const (slot +0x58 at 0x443285; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass347 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getUnplannedDecisionMakingInterleave", 0, 0, 0, "hfe::uint", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getUnplannedDecisionMakingInterleave(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::uint m_returnValue; +}; +BF2_CC_NAME consoleObject347; + +// ConsoleClass348 AIBotManager.getSensingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x443550, executeObjectMethod 0x443680, +// setArgFromString 0x443670, getReturnValueAsString 0x443310, D1 0x4432F0, D0 0x4432B0. +// argc 0: dice::hfe::ai::BotManager::getSensingQuotient() const (slot +0x5C at 0x4436B5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass348 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSensingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSensingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject348; + +// ConsoleClass349 AIBotManager.getMemoryUpdateQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x443980, executeObjectMethod 0x443AB0, +// setArgFromString 0x443AA0, getReturnValueAsString 0x443740, D1 0x443720, D0 0x4436E0. +// argc 0: dice::hfe::ai::BotManager::getMemoryUpdateQuotient() const (slot +0x60 at 0x443AE5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass349 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getMemoryUpdateQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getMemoryUpdateQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject349; + +// ConsoleClass350 AIBotManager.getSystemDecisionMakingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x443DB0, executeObjectMethod 0x443EE0, +// setArgFromString 0x443ED0, getReturnValueAsString 0x443B70, D1 0x443B50, D0 0x443B10. +// argc 0: dice::hfe::ai::BotManager::getSystemDecisionMakingQuotient() const (slot +0x64 at 0x443F15; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass350 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSystemDecisionMakingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSystemDecisionMakingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject350; + +// ConsoleClass351 AIBotManager.getSystemPathfindingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x4441E0, executeObjectMethod 0x444310, +// setArgFromString 0x444300, getReturnValueAsString 0x443FA0, D1 0x443F80, D0 0x443F40. +// argc 0: dice::hfe::ai::BotManager::getSystemPathfindingQuotient() const (slot +0x68 at 0x444345; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass351 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSystemPathfindingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSystemPathfindingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject351; + +// ConsoleClass352 AIBotManager.getSystemSensingQuotient: method, 0..0 arguments, returns double. +// ELF isObjectActive 0x444610, executeObjectMethod 0x444740, +// setArgFromString 0x444730, getReturnValueAsString 0x4443D0, D1 0x4443B0, D0 0x444370. +// argc 0: dice::hfe::ai::BotManager::getSystemSensingQuotient() const (slot +0x6C at 0x444775; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass352 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSystemSensingQuotient", 0, 0, 0, "double", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IBotManagerModifier::instance->getSystemSensingQuotient(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + double m_returnValue; +}; +BF2_CC_NAME consoleObject352; + +// ConsoleClass353 AIBotManager.enableBotScriptDebugger: method, 1..1 arguments, no result. +// ELF isObjectActive 0x444840, executeObjectMethod 0x444BA0, +// setArgFromString 0x444960, getReturnValueAsString 0x444800, D1 0x4447E0, D0 0x4447A0. +// argc 1: dice::hfe::ai::BotManager::enableBotScriptDebugger(bool) (slot +0xA8 at 0x444BEB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass353 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("enableBotScriptDebugger", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IBotManagerModifier::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + IBotManagerModifier::instance->enableBotScriptDebugger(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject353; + +SetConsoleClassDefaults aiStrategyfullAccessSetConsoleClassDefaults("aiStrategy", 2, 0); + +// ConsoleClass361 aiStrategy.createStrategy: method, 1..1 arguments, no result. +// ELF isObjectActive 0x444CA0, executeObjectMethod 0x445050, +// setArgFromString 0x444DD0, getReturnValueAsString 0x444C60, D1 0x444C40, D0 0x444C00. +// argc 1: dice::hfe::ai::StrategyManager::createStrategy(std::string) (call at 0x4450BE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass361 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createStrategy", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->createStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject361; + +// ConsoleClass362 aiStrategy.setActiveStrategy: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4451B0, executeObjectMethod 0x445560, +// setArgFromString 0x4452E0, getReturnValueAsString 0x445170, D1 0x445150, D0 0x445110. +// argc 1: dice::hfe::ai::StrategyManager::setActiveStrategy(std::string) (call at 0x4455CE; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass362 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActiveStrategy", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setActiveStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject362; + +// ConsoleClass363 aiStrategy.getActiveStrategyName: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x445940, executeObjectMethod 0x445A80, +// setArgFromString 0x445A70, getReturnValueAsString 0x445700, D1 0x445690, D0 0x445620. +// argc 0: dice::hfe::ai::StrategyManager::getActiveStrategyName() (call at 0x445AC0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass363 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActiveStrategyName", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getActiveStrategyName(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject363; + +// ConsoleClass364 aiStrategy.aggression: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x445DB0, executeObjectMethod 0x446120, +// setArgFromString 0x445EE0, getReturnValueAsString 0x445B70, D1 0x445B50, D0 0x445B10. +// argc 0: dice::hfe::ai::Strategy::getAggression() const (call at 0x446186; ledger done) +// argc 1: dice::hfe::ai::Strategy::setAggression(float) (call at 0x44616E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass364 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("aggression", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getAggression(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setAggression(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject364; + +// ConsoleClass365 aiStrategy.timeLimit: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x446440, executeObjectMethod 0x4467B0, +// setArgFromString 0x446570, getReturnValueAsString 0x446200, D1 0x4461E0, D0 0x4461A0. +// argc 0: inline accessor, reads the member at +0x20 (m_f20) +// argc 1: inline accessor, stores the member at +0x20 (m_f20) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass365 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("timeLimit", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->m_f20; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->m_f20 = BF2_CC_ARG(float, 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject365; + +// ConsoleClass366 aiStrategy.getPrerequisiteWeight: method, 0..0 arguments, returns float. +// ELF isObjectActive 0x446AC0, executeObjectMethod 0x446C00, +// setArgFromString 0x446BF0, getReturnValueAsString 0x446880, D1 0x446860, D0 0x446820. +// argc 0: dice::hfe::ai::Strategy::getPrerequisiteWeight() const (call at 0x446C30; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass366 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPrerequisiteWeight", 0, 0, 0, "float", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getPrerequisiteWeight(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject366; + +// ConsoleClass367 aiStrategy.setPrerequisiteWeight: method, 1..1 arguments, no result. +// ELF isObjectActive 0x446D00, executeObjectMethod 0x447070, +// setArgFromString 0x446E30, getReturnValueAsString 0x446CC0, D1 0x446CA0, D0 0x446C60. +// argc 1: dice::hfe::ai::Strategy::setPrerequisiteWeight(float) (call at 0x4470B8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass367 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPrerequisiteWeight", 0, 1, 1, "void", false) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setPrerequisiteWeight(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject367; + +// ConsoleClass368 aiStrategy.listStrategies: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x4473F0, executeObjectMethod 0x447530, +// setArgFromString 0x447520, getReturnValueAsString 0x4471B0, D1 0x447140, D0 0x4470D0. +// argc 0: dice::hfe::ai::StrategyManager::listStrategies() (call at 0x447570; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass368 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listStrategies", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->listStrategies(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject368; + +// ConsoleClass369 aiStrategy.setTreeModifier: method, 2..2 arguments, float result discarded. +// ELF isObjectActive 0x447660, executeObjectMethod 0x447C10, +// setArgFromString 0x447790, getReturnValueAsString 0x447620, D1 0x447600, D0 0x4475C0. +// argc 2: dice::hfe::ai::Strategy::setTreeModifier(dice::hfe::ai::TemperatureTreeNode, float) (call at 0x447C63; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass369 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setTreeModifier", 0, 2, 2, "float", false) + m_argTypes[0] = "TemperatureTreeNode"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveStrategy()->setTreeModifier(BF2_CC_ARG(TemperatureTreeNode, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject369; + +// ConsoleClass370 aiStrategy.getTreeModifier: method, 1..1 arguments, returns float. +// ELF isObjectActive 0x447F10, executeObjectMethod 0x448280, +// setArgFromString 0x448040, getReturnValueAsString 0x447CD0, D1 0x447CB0, D0 0x447C70. +// argc 1: dice::hfe::ai::Strategy::getTreeModifier(dice::hfe::ai::TemperatureTreeNode) const (call at 0x4482BB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass370 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getTreeModifier", 0, 1, 1, "float", true) + m_argTypes[0] = "TemperatureTreeNode"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getTreeModifier(BF2_CC_ARG(TemperatureTreeNode, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject370; + +// ConsoleClass371 aiStrategy.setTreeModifierCombatStrength: method, 3..3 arguments, float result discarded. +// ELF isObjectActive 0x448390, executeObjectMethod 0x448B70, +// setArgFromString 0x4484C0, getReturnValueAsString 0x448350, D1 0x448330, D0 0x4482F0. +// argc 3: dice::hfe::ai::Strategy::setTreeModifierCombatStrength(dice::hfe::ai::TemperatureTreeNode, dice::hfe::ai::CombatStrengthType, float) (call at 0x448BD2; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass371 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setTreeModifierCombatStrength", 0, 3, 3, "float", false) + m_argTypes[0] = "TemperatureTreeNode"; + m_argTypes[1] = "CombatStrengthType"; + m_argTypes[2] = "float"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + getActiveStrategy()->setTreeModifierCombatStrength(BF2_CC_ARG(TemperatureTreeNode, 0), BF2_CC_ARG(CombatStrengthType, 1), BF2_CC_ARG(float, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject371; + +// ConsoleClass372 aiStrategy.getTreeModifierCombatStrength: method, 2..2 arguments, returns float. +// ELF isObjectActive 0x448E80, executeObjectMethod 0x449430, +// setArgFromString 0x448FB0, getReturnValueAsString 0x448C40, D1 0x448C20, D0 0x448BE0. +// argc 2: dice::hfe::ai::Strategy::getTreeModifierCombatStrength(dice::hfe::ai::TemperatureTreeNode, dice::hfe::ai::CombatStrengthType) const (call at 0x449479; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass372 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getTreeModifierCombatStrength", 0, 2, 2, "float", true) + m_argTypes[0] = "TemperatureTreeNode"; + m_argTypes[1] = "CombatStrengthType"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getTreeModifierCombatStrength(BF2_CC_ARG(TemperatureTreeNode, 0), BF2_CC_ARG(CombatStrengthType, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(TemperatureTreeNode, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 2, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject372; + +// ConsoleClass373 aiStrategy.numberOfAttacks: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x449780, executeObjectMethod 0x449AF0, +// setArgFromString 0x4498B0, getReturnValueAsString 0x449510, D1 0x4494F0, D0 0x4494B0. +// argc 0: dice::hfe::ai::Strategy::getNumberOfAttacks() const (call at 0x449B56; ledger done) +// argc 1: dice::hfe::ai::Strategy::setNumberOfAttacks(unsigned int) (call at 0x449B3E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass373 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("numberOfAttacks", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getNumberOfAttacks(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setNumberOfAttacks(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject373; + +// ConsoleClass374 aiStrategy.numberOfDefences: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x449E40, executeObjectMethod 0x44A1B0, +// setArgFromString 0x449F70, getReturnValueAsString 0x449BD0, D1 0x449BB0, D0 0x449B70. +// argc 0: dice::hfe::ai::Strategy::getNumberOfDefences() const (call at 0x44A216; ledger done) +// argc 1: dice::hfe::ai::Strategy::setNumberOfDefences(unsigned int) (call at 0x44A1FE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass374 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("numberOfDefences", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getNumberOfDefences(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategy()->setNumberOfDefences(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject374; + +// ConsoleClass375 aiStrategy.setPrerequisite: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44A2D0, executeObjectMethod 0x44A680, +// setArgFromString 0x44A400, getReturnValueAsString 0x44A290, D1 0x44A270, D0 0x44A230. +// argc 1: dice::hfe::ai::StrategyManager::setPrerequisite(std::string) (call at 0x44A6EE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass375 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPrerequisite", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setPrerequisite(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject375; + +// ConsoleClass376 aiStrategy.addRequiredPrecedingStrategy: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x44A9E0, executeObjectMethod 0x44AD90, +// setArgFromString 0x44AB10, getReturnValueAsString 0x44A7A0, D1 0x44A780, D0 0x44A740. +// argc 1: dice::hfe::ai::StrategyManager::addRequiredPrecedingStrategy(std::string) (call at 0x44ADF0; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass376 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addRequiredPrecedingStrategy", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->addRequiredPrecedingStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject376; + +// ConsoleClass377 aiStrategy.addProhibitedPrecedingStrategy: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x44B110, executeObjectMethod 0x44B4C0, +// setArgFromString 0x44B240, getReturnValueAsString 0x44AED0, D1 0x44AEB0, D0 0x44AE70. +// argc 1: dice::hfe::ai::StrategyManager::addProhibitedPrecedingStrategy(std::string) (call at 0x44B520; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass377 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addProhibitedPrecedingStrategy", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->addProhibitedPrecedingStrategy(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject377; + +// ConsoleClass378 aiStrategy.setStrategicObjectsModifier: method, 2..3 arguments, no result. +// ELF isObjectActive 0x44B640, executeObjectMethod 0x44BE20, +// setArgFromString 0x44B770, getReturnValueAsString 0x44B600, D1 0x44B5E0, D0 0x44B5A0. +// argc 2: dice::hfe::ai::Strategy::setStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType, float) (call at 0x44BEBE; ledger done) +// argc 3: dice::hfe::ai::Strategy::setStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType, float, dice::hfe::ai::StatusMap::Status) (call at 0x44BE90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass378 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStrategicObjectsModifier", 0, 2, 3, "void", false) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + m_argTypes[1] = "float"; + m_argTypes[2] = "StatusMap::Status"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveStrategy()->setStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0), BF2_CC_ARG(float, 1)); + } + else if (m_argCount == 3) + { + m_hasReturnValue = false; + getActiveStrategy()->setStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0), BF2_CC_ARG(float, 1), BF2_CC_ARG(StatusMap::Status, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 2) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 3, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject378; + +// ConsoleClass379 aiStrategy.getStrategicObjectsModifier: method, 1..2 arguments, returns float. +// ELF isObjectActive 0x44C170, executeObjectMethod 0x44C720, +// setArgFromString 0x44C2A0, getReturnValueAsString 0x44BF30, D1 0x44BF10, D0 0x44BED0. +// argc 1: dice::hfe::ai::Strategy::getStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType) const (call at 0x44C7AD; ledger done) +// argc 2: dice::hfe::ai::Strategy::getStrategicObjectsModifier(dice::hfe::ai::AIStrategicObject::StrategicObjectType, dice::hfe::ai::StatusMap::Status) const (call at 0x44C773; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass379 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStrategicObjectsModifier", 0, 1, 2, "float", true) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + m_argTypes[1] = "StatusMap::Status"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0)); + } + else if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategy()->getStrategicObjectsModifier(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0), BF2_CC_ARG(StatusMap::Status, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 2, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject379; + +// ConsoleClass380 aiStrategy.clearAllStrategicObjectsModifiers: method, 0..0 arguments, no result. +// ELF isObjectActive 0x44C860, executeObjectMethod 0x44C9A0, +// setArgFromString 0x44C990, getReturnValueAsString 0x44C820, D1 0x44C800, D0 0x44C7C0. +// argc 0: dice::hfe::ai::Strategy::clearAllStrategicObjectsModifiers() (call at 0x44C9D6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass380 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clearAllStrategicObjectsModifiers", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategy() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveStrategy()->clearAllStrategicObjectsModifiers(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject380; + +// ConsoleClass381 aiStrategy.addSpecificObjectModifier: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x44CC80, executeObjectMethod 0x44D260, +// setArgFromString 0x44CDB0, getReturnValueAsString 0x44CA40, D1 0x44CA20, D0 0x44C9E0. +// argc 2: dice::hfe::ai::StrategyManager::addSpecificObjectModifier(std::string, float) (call at 0x44D2CF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass381 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addSpecificObjectModifier", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->addSpecificObjectModifier(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject381; + +// ConsoleClass382 aiStrategy.completeStrategies: method, 0..0 arguments, no result. +// ELF isObjectActive 0x44D3F0, executeObjectMethod 0x44D530, +// setArgFromString 0x44D520, getReturnValueAsString 0x44D3B0, D1 0x44D390, D0 0x44D350. +// argc 0: dice::hfe::ai::StrategyManager::completeStrategies() (call at 0x44D566; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass382 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("completeStrategies", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->completeStrategies(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject382; + +// ConsoleClass385 aiStrategy.createPrerequisite: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44D610, executeObjectMethod 0x44D9C0, +// setArgFromString 0x44D740, getReturnValueAsString 0x44D5D0, D1 0x44D5B0, D0 0x44D570. +// argc 1: dice::hfe::ai::StrategyManager::createPrerequisite(std::string) (call at 0x44DA2E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass385 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createPrerequisite", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->createPrerequisite(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject385; + +// ConsoleClass386 aiStrategy.setActivePrerequisite: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44DB20, executeObjectMethod 0x44DED0, +// setArgFromString 0x44DC50, getReturnValueAsString 0x44DAE0, D1 0x44DAC0, D0 0x44DA80. +// argc 1: dice::hfe::ai::StrategyManager::setActivePrerequisite(std::string) (call at 0x44DF3E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass386 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActivePrerequisite", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setActivePrerequisite(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject386; + +// ConsoleClass387 aiStrategy.getActivePrerequisiteName: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44E2B0, executeObjectMethod 0x44E3F0, +// setArgFromString 0x44E3E0, getReturnValueAsString 0x44E070, D1 0x44E000, D0 0x44DF90. +// argc 0: dice::hfe::ai::StrategyManager::getActivePrerequisiteName() (call at 0x44E430; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass387 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActivePrerequisiteName", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getActivePrerequisiteName(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject387; + +// ConsoleClass388 aiStrategy.listPrerequisites: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44E7A0, executeObjectMethod 0x44E8E0, +// setArgFromString 0x44E8D0, getReturnValueAsString 0x44E560, D1 0x44E4F0, D0 0x44E480. +// argc 0: dice::hfe::ai::StrategyManager::listPrerequisites() (call at 0x44E920; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass388 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listPrerequisites", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->listPrerequisites(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject388; + +// ConsoleClass389 aiStrategy.addCondition: method, 1..2 arguments, no result. +// ELF isObjectActive 0x44EA10, executeObjectMethod 0x44EFF0, +// setArgFromString 0x44EB40, getReturnValueAsString 0x44E9D0, D1 0x44E9B0, D0 0x44E970. +// argc 1: dice::hfe::ai::StrategyManager::addCondition(std::string) (call at 0x44F10A; ledger done) +// argc 2: dice::hfe::ai::StrategyManager::addCondition(std::string, float) (call at 0x44F081; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass389 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addCondition", 0, 1, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "float"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->addCondition(BF2_CC_ARG(std::string, 0)); + } + else if (m_argCount == 2) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->addCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(float, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(float, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject389; + +// ConsoleClass392 aiStrategy.setActiveCondition: method, 1..1 arguments, no result. +// ELF isObjectActive 0x44F1F0, executeObjectMethod 0x44F5A0, +// setArgFromString 0x44F320, getReturnValueAsString 0x44F1B0, D1 0x44F190, D0 0x44F150. +// argc 1: dice::hfe::ai::StrategyManager::setActiveCondition(std::string) (call at 0x44F60E; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass392 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActiveCondition", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setActiveCondition(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject392; + +// ConsoleClass393 aiStrategy.getActiveConditionName: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44F980, executeObjectMethod 0x44FAC0, +// setArgFromString 0x44FAB0, getReturnValueAsString 0x44F740, D1 0x44F6D0, D0 0x44F660. +// argc 0: dice::hfe::ai::StrategyManager::getActiveConditionName() (call at 0x44FB00; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass393 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActiveConditionName", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getActiveConditionName(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject393; + +// ConsoleClass394 aiStrategy.listConditions: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x44FE70, executeObjectMethod 0x44FFB0, +// setArgFromString 0x44FFA0, getReturnValueAsString 0x44FC30, D1 0x44FBC0, D0 0x44FB50. +// argc 0: dice::hfe::ai::StrategyManager::listConditions() (call at 0x44FFF0; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass394 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listConditions", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->listConditions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject394; + +// ConsoleClass395 aiStrategy.createConstantCondition: method, 6..6 arguments, returns bool. +// ELF isObjectActive 0x4502E0, executeObjectMethod 0x451100, +// setArgFromString 0x450410, getReturnValueAsString 0x4500A0, D1 0x450080, D0 0x450040. +// argc 6: dice::hfe::ai::StrategyManager::createConstantCondition(std::string, dice::hfe::ai::StrategyCondition::CompareType, dice::hfe::ai::StrategyCondition::Compare, dice::hfe::ai::StrategyCondition::ConditionSide, dice::hfe::ai::StrategyCondition::Conditional, float) (call at 0x4511A5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass395 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createConstantCondition", 0, 6, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StrategyCondition::CompareType"; + m_argTypes[2] = "StrategyCondition::Compare"; + m_argTypes[3] = "StrategyCondition::ConditionSide"; + m_argTypes[4] = "StrategyCondition::Conditional"; + m_argTypes[5] = "float"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createConstantCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StrategyCondition::CompareType, 1), BF2_CC_ARG(StrategyCondition::Compare, 2), BF2_CC_ARG(StrategyCondition::ConditionSide, 3), BF2_CC_ARG(StrategyCondition::Conditional, 4), BF2_CC_ARG(float, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::CompareType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Compare, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::ConditionSide, 4, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 5, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(float, 6) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject395; + +// ConsoleClass396 aiStrategy.createHomogenousCondition: method, 4..4 arguments, returns bool. +// ELF isObjectActive 0x4514C0, executeObjectMethod 0x451EC0, +// setArgFromString 0x4515F0, getReturnValueAsString 0x451280, D1 0x451260, D0 0x451220. +// argc 4: dice::hfe::ai::StrategyManager::createHomogenousCondition(std::string, dice::hfe::ai::StrategyCondition::CompareType, dice::hfe::ai::StrategyCondition::Compare, dice::hfe::ai::StrategyCondition::Conditional) (call at 0x451F47; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass396 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createHomogenousCondition", 0, 4, 4, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StrategyCondition::CompareType"; + m_argTypes[2] = "StrategyCondition::Compare"; + m_argTypes[3] = "StrategyCondition::Conditional"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createHomogenousCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StrategyCondition::CompareType, 1), BF2_CC_ARG(StrategyCondition::Compare, 2), BF2_CC_ARG(StrategyCondition::Conditional, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::CompareType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Compare, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 4, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject396; + +// ConsoleClass397 aiStrategy.createHeterogeneousCondition: method, 6..6 arguments, returns bool. +// ELF isObjectActive 0x452260, executeObjectMethod 0x453080, +// setArgFromString 0x452390, getReturnValueAsString 0x452020, D1 0x452000, D0 0x451FC0. +// argc 6: dice::hfe::ai::StrategyManager::createHeterogeneousCondition(std::string, dice::hfe::ai::StrategyCondition::CompareType, dice::hfe::ai::StrategyCondition::Compare, dice::hfe::ai::StrategyCondition::ConditionSide, dice::hfe::ai::StrategyCondition::Conditional, dice::hfe::ai::StrategyCondition::Conditional) (call at 0x453125; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass397 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createHeterogeneousCondition", 0, 6, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StrategyCondition::CompareType"; + m_argTypes[2] = "StrategyCondition::Compare"; + m_argTypes[3] = "StrategyCondition::ConditionSide"; + m_argTypes[4] = "StrategyCondition::Conditional"; + m_argTypes[5] = "StrategyCondition::Conditional"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createHeterogeneousCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StrategyCondition::CompareType, 1), BF2_CC_ARG(StrategyCondition::Compare, 2), BF2_CC_ARG(StrategyCondition::ConditionSide, 3), BF2_CC_ARG(StrategyCondition::Conditional, 4), BF2_CC_ARG(StrategyCondition::Conditional, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::CompareType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Compare, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::ConditionSide, 4, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 5, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::Conditional, 6, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject397; + +// ConsoleClass398 aiStrategy.createAreaCondition: method, 3..3 arguments, returns bool. +// ELF isObjectActive 0x453440, executeObjectMethod 0x453C80, +// setArgFromString 0x453570, getReturnValueAsString 0x453200, D1 0x4531E0, D0 0x4531A0. +// argc 3: dice::hfe::ai::StrategyManager::createAreaCondition(std::string, std::string, dice::hfe::ai::StatusMap::Status) (call at 0x453D1D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass398 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createAreaCondition", 0, 3, 3, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "StatusMap::Status"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->createAreaCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(StatusMap::Status, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 3, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject398; + +// ConsoleClass399 aiStrategy.setConditionStrength: method, 1..1 arguments, no result. +// ELF isObjectActive 0x453E80, executeObjectMethod 0x4541F0, +// setArgFromString 0x453FB0, getReturnValueAsString 0x453E40, D1 0x453E20, D0 0x453DE0. +// argc 1: dice::hfe::ai::StrategyCondition::setConditionStrength(dice::hfe::ai::StrategyCondition::ConditionStrength) (call at 0x454238; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass399 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setConditionStrength", 0, 1, 1, "void", false) + m_argTypes[0] = "StrategyCondition::ConditionStrength"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveCondition()->setConditionStrength(BF2_CC_ARG(StrategyCondition::ConditionStrength, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(StrategyCondition::ConditionStrength, 1, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject399; + +// ConsoleClass400 aiStrategy.getConditionStrength: method, 0..0 arguments, returns StrategyCondition::ConditionStrength. +// ELF isObjectActive 0x4544E0, executeObjectMethod 0x454620, +// setArgFromString 0x454610, getReturnValueAsString 0x4542A0, D1 0x454280, D0 0x454240. +// argc 0: dice::hfe::ai::StrategyCondition::getConditionStrength() const (call at 0x454650; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass400 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getConditionStrength", 0, 0, 0, "StrategyCondition::ConditionStrength", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveCondition()->getConditionStrength(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + StrategyCondition::ConditionStrength m_returnValue; +}; +BF2_CC_NAME consoleObject400; + +// ConsoleClass401 aiStrategy.setIsAbortCondition: method, 1..1 arguments, no result. +// ELF isObjectActive 0x454720, executeObjectMethod 0x454A90, +// setArgFromString 0x454850, getReturnValueAsString 0x4546E0, D1 0x4546C0, D0 0x454680. +// argc 1: dice::hfe::ai::StrategyCondition::setIsAbortCondition(bool) (call at 0x454AD6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass401 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setIsAbortCondition", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveCondition()->setIsAbortCondition(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject401; + +// ConsoleClass402 aiStrategy.isAbortCondition: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x454D80, executeObjectMethod 0x454EC0, +// setArgFromString 0x454EB0, getReturnValueAsString 0x454B40, D1 0x454B20, D0 0x454AE0. +// argc 0: dice::hfe::ai::StrategyCondition::isAbortCondition() const (call at 0x454EF0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass402 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isAbortCondition", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveCondition()->isAbortCondition(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject402; + +// ConsoleClass403 aiStrategy.completeConditions: method, 0..0 arguments, no result. +// ELF isObjectActive 0x454FC0, executeObjectMethod 0x455100, +// setArgFromString 0x4550F0, getReturnValueAsString 0x454F80, D1 0x454F60, D0 0x454F20. +// argc 0: dice::hfe::ai::StrategyManager::completeConditions() (call at 0x455136; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass403 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("completeConditions", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->completeConditions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject403; + +// ConsoleClass404 aiStrategy.targetValue: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x4553E0, executeObjectMethod 0x455750, +// setArgFromString 0x455510, getReturnValueAsString 0x4551A0, D1 0x455180, D0 0x455140. +// argc 0: dice::hfe::ai::StrategyCondition::getTargetValue() const (call at 0x4557BF; ledger done) +// argc 1: dice::hfe::ai::StrategyCondition::setTargetValue(float) (call at 0x45579E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass404 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("targetValue", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveCondition() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveCondition()->getTargetValue(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveCondition()->setTargetValue(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject404; + +// ConsoleClass407 aiStrategy.forceStrategy: method, 2..2 arguments, returns std::string. +// ELF isObjectActive 0x455B00, executeObjectMethod 0x4560E0, +// setArgFromString 0x455C30, getReturnValueAsString 0x4558C0, D1 0x455850, D0 0x4557E0. +// argc 2: dice::hfe::ai::StrategyManager::forceStrategy(std::string, int) (call at 0x456159; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass407 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("forceStrategy", 0, 2, 2, "std::string", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "int"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->forceStrategy(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(int, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(int, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject407; + +// ConsoleClass408 aiStrategy.enableDebug: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x456490, executeObjectMethod 0x456800, +// setArgFromString 0x4565C0, getReturnValueAsString 0x456250, D1 0x456230, D0 0x4561F0. +// argc 0: dice::hfe::ai::StrategyManager::getEnableDebug() (call at 0x45686F; ledger done) +// argc 1: dice::hfe::ai::StrategyManager::setEnableDebug(bool) (call at 0x456850; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass408 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("enableDebug", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return StrategyManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = StrategyManager::getInstance()->getEnableDebug(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + StrategyManager::getInstance()->setEnableDebug(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject408; + +// ConsoleClass411 aiStrategy.thresholdSpeed: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x456B30, executeObjectMethod 0x456E90, +// setArgFromString 0x456C50, getReturnValueAsString 0x4568F0, D1 0x4568D0, D0 0x456890. +// argc 0: dice::hfe::ai::AIConsole::getFastThreshold() (call at 0x456EF6; ledger stop) +// argc 1: dice::hfe::ai::AIConsole::setFastThreshold(float) (call at 0x456EDB; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass411 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("thresholdSpeed", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->getFastThreshold(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->setFastThreshold(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject411; + +SetConsoleClassDefaults AIStrategicAreafullAccessSetConsoleClassDefaults("AIStrategicArea", 2, 0); + +// ConsoleClass417 AIStrategicArea.create: method, 5..6 arguments, returns bool. +// ELF isObjectActive 0x4571B0, executeObjectMethod 0x4580E0, +// setArgFromString 0x4572E0, getReturnValueAsString 0x456F70, D1 0x456F50, D0 0x456F10. +// argc 5: dice::hfe::ai::AIStrategicObjectManager::create(std::string, dice::hfe::Vec2, dice::hfe::Vec2, float, float, std::string const&) (call at 0x458399; ledger done) +// argc 6: dice::hfe::ai::AIStrategicObjectManager::create(std::string, dice::hfe::Vec2, dice::hfe::Vec2, float, float, std::string const&) (call at 0x45820B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass417 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("create", 0, 5, 6, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec2"; + m_argTypes[2] = "Vec2"; + m_argTypes[3] = "float"; + m_argTypes[4] = "float"; + m_argTypes[5] = "std::string"; + AIMODULE_CC_TAIL(6) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->create(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(Vec2, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(float, 4)); + } + else if (m_argCount == 6) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->create(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(Vec2, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(float, 4), BF2_CC_ARG(std::string, 5)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + AIMODULE_CC_EXTRACT(Vec2, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT(float, 5) + AIMODULE_CC_EXTRACT(std::string, 6) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject417; + +// ConsoleClass418 AIStrategicArea.setFlankPosition: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4584D0, executeObjectMethod 0x458BC0, +// setArgFromString 0x458600, getReturnValueAsString 0x458490, D1 0x458470, D0 0x458430. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::setFlankPosition(dice::hfe::Vec3, dice::hfe::Vec3) (call at 0x458C53; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass418 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setFlankPosition", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->setFlankPosition(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject418; + +// ConsoleClass419 AIStrategicArea.createFromControlPoint: method, 3..4 arguments, returns bool. +// ELF isObjectActive 0x458F00, executeObjectMethod 0x459950, +// setArgFromString 0x459030, getReturnValueAsString 0x458CC0, D1 0x458CA0, D0 0x458C60. +// argc 3: dice::hfe::ai::AIStrategicObjectManager::createFromControlPoint(std::string const&, unsigned int, float, std::string const&) (call at 0x459AC9; ledger done) +// argc 4: dice::hfe::ai::AIStrategicObjectManager::createFromControlPoint(std::string const&, unsigned int, float, std::string const&) (call at 0x4599EB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass419 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createFromControlPoint", 0, 3, 4, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "u32"; + m_argTypes[2] = "float"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->createFromControlPoint(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(u32, 1), BF2_CC_ARG(float, 2)); + } + else if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->createFromControlPoint(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(u32, 1), BF2_CC_ARG(float, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(u32, 2) + AIMODULE_CC_EXTRACT(float, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject419; + +// ConsoleClass420 AIStrategicArea.removeActive: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x459DD0, executeObjectMethod 0x459F10, +// setArgFromString 0x459F00, getReturnValueAsString 0x459B90, D1 0x459B70, D0 0x459B30. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::removeActive() (call at 0x459F40; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass420 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeActive", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->removeActive(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject420; + +// ConsoleClass421 AIStrategicArea.setActive: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x45A210, executeObjectMethod 0x45A5C0, +// setArgFromString 0x45A340, getReturnValueAsString 0x459FD0, D1 0x459FB0, D0 0x459F70. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::setActive(std::string) (call at 0x45A620; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass421 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setActive", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->setActive(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject421; + +// ConsoleClass422 AIStrategicArea.getActive: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x45A9C0, executeObjectMethod 0x45AB00, +// setArgFromString 0x45AAF0, getReturnValueAsString 0x45A780, D1 0x45A710, D0 0x45A6A0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getActive() const (call at 0x45AB40; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass422 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getActive", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getActive(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject422; + +// ConsoleClass423 AIStrategicArea.addNeighbour: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x45AE30, executeObjectMethod 0x45B1E0, +// setArgFromString 0x45AF60, getReturnValueAsString 0x45ABF0, D1 0x45ABD0, D0 0x45AB90. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::addNeighbour(std::string) (call at 0x45B240; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass423 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addNeighbour", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->addNeighbour(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject423; + +// ConsoleClass424 AIStrategicArea.addTwoWayNeighbour: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x45B560, executeObjectMethod 0x45BB80, +// setArgFromString 0x45B690, getReturnValueAsString 0x45B320, D1 0x45B300, D0 0x45B2C0. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::addTwoWayNeighbour(std::string, std::string) (call at 0x45BC0E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass424 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addTwoWayNeighbour", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->addTwoWayNeighbour(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject424; + +// ConsoleClass425 AIStrategicArea.getNeighbours: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x45BFF0, executeObjectMethod 0x45C130, +// setArgFromString 0x45C120, getReturnValueAsString 0x45BDB0, D1 0x45BD40, D0 0x45BCD0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getNeighbours() (call at 0x45C170; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass425 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNeighbours", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getNeighbours(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject425; + +// ConsoleClass426 AIStrategicArea.layer: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x45C490, executeObjectMethod 0x45C800, +// setArgFromString 0x45C5C0, getReturnValueAsString 0x45C220, D1 0x45C200, D0 0x45C1C0. +// argc 0: inline accessor, reads the member at +0x190 (m_i400) +// argc 1: inline accessor, stores the member at +0x190 (m_i400) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass426 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("layer", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_i400; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->m_i400 = BF2_CC_ARG(int, 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject426; + +// ConsoleClass427 AIStrategicArea.setVisible: method, 1..1 arguments, no result. +// ELF isObjectActive 0x45C920, executeObjectMethod 0x45CC90, +// setArgFromString 0x45CA50, getReturnValueAsString 0x45C8E0, D1 0x45C8C0, D0 0x45C880. +// argc 1: verified inline body, normalized visibility store +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass427 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setVisible", 0, 1, 1, "void", false) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_visible = (value != 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject427; + +// ConsoleClass428 AIStrategicArea.getVisible: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x45CF80, executeObjectMethod 0x45D0C0, +// setArgFromString 0x45D0B0, getReturnValueAsString 0x45CD40, D1 0x45CD20, D0 0x45CCE0. +// argc 0: verified inline body, normalized visibility load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass428 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getVisible", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = (getActiveStrategicArea()->m_visible != 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject428; + +// ConsoleClass429 AIStrategicArea.drawVehicleSearchRadi: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x45D3C0, executeObjectMethod 0x45D730, +// setArgFromString 0x45D4F0, getReturnValueAsString 0x45D180, D1 0x45D160, D0 0x45D120. +// argc 0: verified inline body, vehicle-search-radius drawing switch +// argc 1: verified inline body, vehicle-search-radius drawing switch +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass429 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("drawVehicleSearchRadi", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->m_drawVehicleSearchRadii; + } + else if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->m_drawVehicleSearchRadii = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject429; + +// ConsoleClass430 AIStrategicArea.removeAllNeighbours: method, 0..0 arguments, no result. +// ELF isObjectActive 0x45D840, executeObjectMethod 0x45D980, +// setArgFromString 0x45D970, getReturnValueAsString 0x45D800, D1 0x45D7E0, D0 0x45D7A0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::removeAllNeighbours() (call at 0x45D9B6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass430 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeAllNeighbours", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->removeAllNeighbours(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject430; + +// ConsoleClass431 AIStrategicArea.setPosition: method, 1..1 arguments, no result. +// ELF isObjectActive 0x45DA60, executeObjectMethod 0x45DE30, +// setArgFromString 0x45DB90, getReturnValueAsString 0x45DA20, D1 0x45DA00, D0 0x45D9C0. +// argc 1: dice::hfe::ai::AIStrategicArea::setPosition(dice::hfe::Vec2 const&) (call at 0x45DE84; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass431 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPosition", 0, 1, 1, "void", false) + m_argTypes[0] = "hfe::Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setPosition(BF2_CC_ARG(hfe::Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::Vec2, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject431; + +// ConsoleClass432 AIStrategicArea.getPosition: method, 0..0 arguments, returns hfe::Vec2. +// ELF isObjectActive 0x45E160, executeObjectMethod 0x45E2A0, +// setArgFromString 0x45E290, getReturnValueAsString 0x45DEF0, D1 0x45DED0, D0 0x45DE90. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getPosition() const (call at 0x45E2E5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass432 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getPosition", 0, 0, 0, "hfe::Vec2", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getPosition(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject432; + +// ConsoleClass433 AIStrategicArea.centerPosition: property, 0..1 arguments, returns hfe::Vec2. +// ELF isObjectActive 0x45E5F0, executeObjectMethod 0x45E9C0, +// setArgFromString 0x45E720, getReturnValueAsString 0x45E380, D1 0x45E360, D0 0x45E320. +// argc 0: dice::hfe::ai::AIStrategicArea::getCenterPosition() const (call at 0x45EA38; ledger done) +// argc 1: dice::hfe::ai::AIStrategicArea::setCenterPosition(dice::hfe::Vec2 const&) (call at 0x45EA1A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass433 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("centerPosition", 1, 0, 1, "hfe::Vec2", true) + m_argTypes[0] = "hfe::Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getCenterPosition(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setCenterPosition(BF2_CC_ARG(hfe::Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject433; + +// ConsoleClass434 AIStrategicArea.topLeftCorner: property, 0..1 arguments, returns hfe::Vec2. +// ELF isObjectActive 0x45ED20, executeObjectMethod 0x45F0F0, +// setArgFromString 0x45EE50, getReturnValueAsString 0x45EAB0, D1 0x45EA90, D0 0x45EA50. +// argc 0: inline accessor, reads the member at +0x110 (m_centre) +// argc 1: dice::hfe::ai::AIStrategicArea::setTopLeftCorner(dice::hfe::Vec2 const&) (call at 0x45F14A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass434 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("topLeftCorner", 1, 0, 1, "hfe::Vec2", true) + m_argTypes[0] = "hfe::Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_centre; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setTopLeftCorner(BF2_CC_ARG(hfe::Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(hfe::Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + hfe::Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject434; + +// ConsoleClass435 AIStrategicArea.list: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x45F4A0, executeObjectMethod 0x45F5E0, +// setArgFromString 0x45F5D0, getReturnValueAsString 0x45F260, D1 0x45F1F0, D0 0x45F180. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::list() const (call at 0x45F620; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass435 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("list", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->list(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject435; + +// ConsoleClass436 AIStrategicArea.addObjectTypeFlag: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x45F940, executeObjectMethod 0x45FCB0, +// setArgFromString 0x45FA70, getReturnValueAsString 0x45F6D0, D1 0x45F6B0, D0 0x45F670. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::addObjectTypeFlag(dice::hfe::ai::AIStrategicObject::StrategicObjectType) (call at 0x45FCEB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass436 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addObjectTypeFlag", 0, 1, 1, "int", true) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->addObjectTypeFlag(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject436; + +// ConsoleClass437 AIStrategicArea.setObjectTypeFlags: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x45FFF0, executeObjectMethod 0x460360, +// setArgFromString 0x460120, getReturnValueAsString 0x45FD80, D1 0x45FD60, D0 0x45FD20. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::setObjectTypeFlags(int) (call at 0x46039B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass437 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setObjectTypeFlags", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->setObjectTypeFlags(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject437; + +// ConsoleClass438 AIStrategicArea.getObjectTypeFlags: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x4606A0, executeObjectMethod 0x4607E0, +// setArgFromString 0x4607D0, getReturnValueAsString 0x460430, D1 0x460410, D0 0x4603D0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getObjectTypeFlags() (call at 0x460810; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass438 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getObjectTypeFlags", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getObjectTypeFlags(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject438; + +// ConsoleClass439 AIStrategicArea.removeObjectTypeFlag: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x460B10, executeObjectMethod 0x460E80, +// setArgFromString 0x460C40, getReturnValueAsString 0x4608A0, D1 0x460880, D0 0x460840. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::removeObjectTypeFlag(dice::hfe::ai::AIStrategicObject::StrategicObjectType) (call at 0x460EBB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass439 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeObjectTypeFlag", 0, 1, 1, "int", true) + m_argTypes[0] = "AIStrategicObject::StrategicObjectType"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->removeObjectTypeFlag(BF2_CC_ARG(AIStrategicObject::StrategicObjectType, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(AIStrategicObject::StrategicObjectType, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject439; + +// ConsoleClass440 AIStrategicArea.setStatus: method, 2..2 arguments, returns StatusMap::Status. +// ELF isObjectActive 0x461190, executeObjectMethod 0x461740, +// setArgFromString 0x4612C0, getReturnValueAsString 0x460F50, D1 0x460F30, D0 0x460EF0. +// argc 2: verified inline body, unchecked status stores: saved pair first, current pair second, then return the status +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass440 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setStatus", 0, 2, 2, "StatusMap::Status", true) + m_argTypes[0] = "int"; + m_argTypes[1] = "StatusMap::Status"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + const int side = BF2_CC_ARG(int, 0); + const StatusMap::Status value = BF2_CC_ARG(StatusMap::Status, 1); + m_hasReturnValue = true; + AIStrategicArea* const object = getActiveStrategicArea(); + object->m_status[side + 1] = value; + object->m_status[side - 1] = value; + m_returnValue = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 2, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + StatusMap::Status m_returnValue; +}; +BF2_CC_NAME consoleObject440; + +// ConsoleClass441 AIStrategicArea.category: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x461A80, executeObjectMethod 0x461DF0, +// setArgFromString 0x461BB0, getReturnValueAsString 0x461810, D1 0x4617F0, D0 0x4617B0. +// argc 0: verified inline body, inherited category property +// argc 1: verified inline body, inherited category property +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass441 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("category", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_category; + } + else if (m_argCount == 1) + { + const int value = BF2_CC_ARG(int, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_category = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject441; + +// ConsoleClass442 AIStrategicArea.vehicleSearchRadius: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x462110, executeObjectMethod 0x462480, +// setArgFromString 0x462240, getReturnValueAsString 0x461ED0, D1 0x461EB0, D0 0x461E70. +// argc 0: inline accessor, reads the member at +0x18C (m_f396) +// argc 1: inline accessor, stores the member at +0x18C (m_f396) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass442 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("vehicleSearchRadius", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_f396; + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->m_f396 = BF2_CC_ARG(float, 0); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject442; + +// ConsoleClass443 AIStrategicArea.setTakeable: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4625A0, executeObjectMethod 0x462B50, +// setArgFromString 0x4626D0, getReturnValueAsString 0x462560, D1 0x462540, D0 0x462500. +// argc 2: verified inline body, unchecked one-based takeability store +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass443 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setTakeable", 0, 2, 2, "void", false) + m_argTypes[0] = "int"; + m_argTypes[1] = "bool"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + const int side = BF2_CC_ARG(int, 0); + const bool value = BF2_CC_ARG(bool, 1); + m_hasReturnValue = false; + getActiveStrategicArea()->m_sideEnabled[side - 1] = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(bool, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject443; + +// ConsoleClass444 AIStrategicArea.isTakeable: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x462E50, executeObjectMethod 0x4631C0, +// setArgFromString 0x462F80, getReturnValueAsString 0x462C10, D1 0x462BF0, D0 0x462BB0. +// argc 1: verified inline body, unchecked one-based takeability load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass444 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isTakeable", 0, 1, 1, "bool", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const int side = BF2_CC_ARG(int, 0); + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_sideEnabled[side - 1]; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject444; + +// ConsoleClass445 AIStrategicArea.removeAllObjectTypeFlags: method, 0..0 arguments, no result. +// ELF isObjectActive 0x4632C0, executeObjectMethod 0x463400, +// setArgFromString 0x4633F0, getReturnValueAsString 0x463280, D1 0x463260, D0 0x463220. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::removeAllObjectTypeFlags() (call at 0x463436; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass445 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeAllObjectTypeFlags", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->removeAllObjectTypeFlags(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject445; + +// ConsoleClass446 AIStrategicArea.getObjectTypeFlagMapping: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x463760, executeObjectMethod 0x4638A0, +// setArgFromString 0x463890, getReturnValueAsString 0x463520, D1 0x4634B0, D0 0x463440. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getObjectTypeFlagMapping() const (call at 0x4638E0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass446 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getObjectTypeFlagMapping", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getObjectTypeFlagMapping(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject446; + +// ConsoleClass447 AIStrategicArea.basicTemperature: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x463BD0, executeObjectMethod 0x463F40, +// setArgFromString 0x463D00, getReturnValueAsString 0x463990, D1 0x463970, D0 0x463930. +// argc 0: verified inline body, inherited baseline temperature, the first word of the shared temperature/radius storage +// argc 1: verified inline body, inherited baseline temperature, the first word of the shared temperature/radius storage +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass447 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("basicTemperature", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_size[AIStrategicObject::kBasicTemperature]; + } + else if (m_argCount == 1) + { + const float value = BF2_CC_ARG(float, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_size[AIStrategicObject::kBasicTemperature] = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject447; + +// ConsoleClass448 AIStrategicArea.setOrderPosition: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x464260, executeObjectMethod 0x4648F0, +// setArgFromString 0x464390, getReturnValueAsString 0x464020, D1 0x464000, D0 0x463FC0. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::setOrderPosition(std::string, dice::hfe::Vec3 const&) (call at 0x46496B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass448 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setOrderPosition", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->setOrderPosition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject448; + +// ConsoleClass449 AIStrategicArea.getOrderPosition: method, 1..1 arguments, returns Vec3. +// ELF isObjectActive 0x464CE0, executeObjectMethod 0x465090, +// setArgFromString 0x464E10, getReturnValueAsString 0x464A40, D1 0x464A20, D0 0x4649E0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::getOrderPosition(std::string) (call at 0x465100; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass449 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getOrderPosition", 0, 1, 1, "Vec3", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getOrderPosition(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject449; + +// ConsoleClass450 AIStrategicArea.listOrderPositions: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x4654A0, executeObjectMethod 0x4655E0, +// setArgFromString 0x4655D0, getReturnValueAsString 0x465260, D1 0x4651F0, D0 0x465180. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::listOrderPositions() (call at 0x465620; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass450 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listOrderPositions", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->listOrderPositions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject450; + +// ConsoleClass451 AIStrategicArea.addWayPoint: method, 4..4 arguments, no result. +// ELF isObjectActive 0x465710, executeObjectMethod 0x466290, +// setArgFromString 0x465840, getReturnValueAsString 0x4656D0, D1 0x4656B0, D0 0x465670. +// argc 4: dice::hfe::ai::AIStrategicObjectManager::addWayPoint(dice::hfe::Vec3 const&, std::string const&, std::string const&, std::string const&) (call at 0x46634B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass451 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addWayPoint", 0, 4, 4, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->addWayPoint(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject451; + +// ConsoleClass452 AIStrategicArea.removeWayPoint: method, 4..4 arguments, returns bool. +// ELF isObjectActive 0x466660, executeObjectMethod 0x4671E0, +// setArgFromString 0x466790, getReturnValueAsString 0x466420, D1 0x466400, D0 0x4663C0. +// argc 4: dice::hfe::ai::AIStrategicObjectManager::removeWayPoint(dice::hfe::Vec3 const&, std::string const&, std::string const&, std::string const&) (call at 0x467287; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass452 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("removeWayPoint", 0, 4, 4, "bool", true) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + m_argTypes[3] = "std::string"; + AIMODULE_CC_TAIL(4) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 4) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->removeWayPoint(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2), BF2_CC_ARG(std::string, 3)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + AIMODULE_CC_EXTRACT(std::string, 4) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject452; + +// ConsoleClass453 AIStrategicArea.clearWayPoints: method, 3..3 arguments, no result. +// ELF isObjectActive 0x4673C0, executeObjectMethod 0x467C40, +// setArgFromString 0x4674F0, getReturnValueAsString 0x467380, D1 0x467360, D0 0x467320. +// argc 3: dice::hfe::ai::AIStrategicObjectManager::clearWayPoints(std::string const&, std::string const&, std::string const&) (call at 0x467CD7; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass453 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clearWayPoints", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + m_argTypes[2] = "std::string"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->clearWayPoints(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1), BF2_CC_ARG(std::string, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + AIMODULE_CC_EXTRACT(std::string, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject453; + +// ConsoleClass454 AIStrategicArea.setWayPointsToDraw: method, 2..2 arguments, no result. +// ELF isObjectActive 0x467DE0, executeObjectMethod 0x468400, +// setArgFromString 0x467F10, getReturnValueAsString 0x467DA0, D1 0x467D80, D0 0x467D40. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::setWayPointsToDraw(std::string const&, std::string const&) (call at 0x46847B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass454 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setWayPointsToDraw", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->setWayPointsToDraw(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject454; + +// ConsoleClass455 AIStrategicArea.clearWaypointToDraw: method, 0..0 arguments, no result. +// ELF isObjectActive 0x468570, executeObjectMethod 0x4686B0, +// setArgFromString 0x4686A0, getReturnValueAsString 0x468530, D1 0x468510, D0 0x4684D0. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::clearWaypointToDraw() (call at 0x4686E6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass455 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clearWaypointToDraw", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->clearWaypointToDraw(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject455; + +// ConsoleClass456 AIStrategicArea.setSide: method, 1..1 arguments, no result. +// ELF isObjectActive 0x468790, executeObjectMethod 0x468B00, +// setArgFromString 0x4688C0, getReturnValueAsString 0x468750, D1 0x468730, D0 0x4686F0. +// argc 1: dice::hfe::ai::AIStrategicObject::setSide(int) (call at 0x468B48; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass456 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setSide", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->setSide(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject456; + +// ConsoleClass457 AIStrategicArea.getSide: method, 0..0 arguments, returns int. +// ELF isObjectActive 0x468E20, executeObjectMethod 0x468F60, +// setArgFromString 0x468F50, getReturnValueAsString 0x468BB0, D1 0x468B90, D0 0x468B50. +// argc 0: dice::hfe::ai::AIStrategicObject::getSide() (call at 0x468F90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass457 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getSide", 0, 0, 0, "int", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getSide(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject457; + +// ConsoleClass458 AIStrategicArea.enableDebug: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x469260, executeObjectMethod 0x4695D0, +// setArgFromString 0x469390, getReturnValueAsString 0x469020, D1 0x469000, D0 0x468FC0. +// argc 1: verified inline body, store and return the debug switch +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass458 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("enableDebug", 0, 1, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = true; + AIStrategicObjectManager::getInstance()->m_debugEnabled = value; + m_returnValue = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject458; + +// ConsoleClass459 AIStrategicArea.addAllowedVehicleGroup: method, 1..1 arguments, no result. +// ELF isObjectActive 0x4696D0, executeObjectMethod 0x469A80, +// setArgFromString 0x469800, getReturnValueAsString 0x469690, D1 0x469670, D0 0x469630. +// argc 1: dice::hfe::ai::AIStrategicObject::addAllowedVehicleGroup(std::string const&) (call at 0x469ADA; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass459 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addAllowedVehicleGroup", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->addAllowedVehicleGroup(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject459; + +// ConsoleClass460 AIStrategicArea.attachLandingZone: method, 1..1 arguments, no result. +// ELF isObjectActive 0x469BB0, executeObjectMethod 0x469F60, +// setArgFromString 0x469CE0, getReturnValueAsString 0x469B70, D1 0x469B50, D0 0x469B10. +// argc 1: dice::hfe::ai::AIStrategicArea::attachLandingZone(std::string const&) (call at 0x469FC6; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass460 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("attachLandingZone", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveStrategicArea()->attachLandingZone(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject460; + +// ConsoleClass461 AIStrategicArea.listLandingZones: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x46A330, executeObjectMethod 0x46A470, +// setArgFromString 0x46A460, getReturnValueAsString 0x46A0F0, D1 0x46A080, D0 0x46A010. +// argc 0: dice::hfe::ai::AIStrategicArea::listLandingZones() (call at 0x46A4B0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass461 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listLandingZones", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->listLandingZones(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject461; + +// ConsoleClass462 AIStrategicArea.getTemperature: method, 1..1 arguments, returns float. +// ELF isObjectActive 0x46A7A0, executeObjectMethod 0x46AB10, +// setArgFromString 0x46A8D0, getReturnValueAsString 0x46A560, D1 0x46A540, D0 0x46A500. +// argc 1: verified inline body, unchecked one-based current-temperature load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass462 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getTemperature", 0, 1, 1, "float", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const int side = BF2_CC_ARG(int, 0); + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_f164[side - 1]; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject462; + +// ConsoleClass463 AIStrategicArea.getStatus: method, 1..1 arguments, returns StatusMap::Status. +// ELF isObjectActive 0x46AE10, executeObjectMethod 0x46B180, +// setArgFromString 0x46AF40, getReturnValueAsString 0x46ABD0, D1 0x46ABB0, D0 0x46AB70. +// argc 1: verified inline body, unchecked one-based current-status load +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass463 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStatus", 0, 1, 1, "StatusMap::Status", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + const int side = BF2_CC_ARG(int, 0); + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_status[side - 1]; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + StatusMap::Status m_returnValue; +}; +BF2_CC_NAME consoleObject463; + +// ConsoleClass464 AIStrategicArea.getNumberOfPresentUnits: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46B4B0, executeObjectMethod 0x46B820, +// setArgFromString 0x46B5E0, getReturnValueAsString 0x46B240, D1 0x46B220, D0 0x46B1E0. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfPresentUnits(int) const (call at 0x46B85B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass464 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfPresentUnits", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfPresentUnits(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject464; + +// ConsoleClass465 AIStrategicArea.getNumberOfAvailableAttackers: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46BB60, executeObjectMethod 0x46BED0, +// setArgFromString 0x46BC90, getReturnValueAsString 0x46B8F0, D1 0x46B8D0, D0 0x46B890. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfAvailableAttackers(int) const (call at 0x46BF0B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass465 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfAvailableAttackers", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfAvailableAttackers(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject465; + +// ConsoleClass466 AIStrategicArea.getNumberOfAvailableDefenders: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46C210, executeObjectMethod 0x46C580, +// setArgFromString 0x46C340, getReturnValueAsString 0x46BFA0, D1 0x46BF80, D0 0x46BF40. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfAvailableDefenders(int) const (call at 0x46C5BB; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass466 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfAvailableDefenders", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfAvailableDefenders(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject466; + +// ConsoleClass467 AIStrategicArea.getNumberOfAssignedUnits: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46C8C0, executeObjectMethod 0x46CC30, +// setArgFromString 0x46C9F0, getReturnValueAsString 0x46C650, D1 0x46C630, D0 0x46C5F0. +// argc 1: dice::hfe::ai::AIStrategicObject::getNumberOfAssignedUnits(int) const (call at 0x46CC6B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass467 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getNumberOfAssignedUnits", 0, 1, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->getNumberOfAssignedUnits(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject467; + +// ConsoleClass468 AIStrategicArea.getCategoryName: method, 1..1 arguments, returns std::string. +// ELF isObjectActive 0x46CFC0, executeObjectMethod 0x46D330, +// setArgFromString 0x46D0F0, getReturnValueAsString 0x46CD80, D1 0x46CD10, D0 0x46CCA0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::getCategoryName(int) const (call at 0x46D371; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass468 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCategoryName", 0, 1, 1, "std::string", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getCategoryName(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject468; + +// ConsoleClass469 AIStrategicArea.getCategoryFromName: method, 1..1 arguments, returns int. +// ELF isObjectActive 0x46D670, executeObjectMethod 0x46DA20, +// setArgFromString 0x46D7A0, getReturnValueAsString 0x46D400, D1 0x46D3E0, D0 0x46D3A0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::getCategoryFromName(std::string const&) const (call at 0x46DA6E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass469 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getCategoryFromName", 0, 1, 1, "int", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getCategoryFromName(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject469; + +// ConsoleClass470 AIStrategicArea.createNewCategory: method, 1..1 arguments, no result. +// ELF isObjectActive 0x46DB60, executeObjectMethod 0x46DF10, +// setArgFromString 0x46DC90, getReturnValueAsString 0x46DB20, D1 0x46DB00, D0 0x46DAC0. +// argc 1: dice::hfe::ai::AIStrategicObjectManager::createNewCategory(std::string const&) (call at 0x46DF6A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass470 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createNewCategory", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIStrategicObjectManager::getInstance()->createNewCategory(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject470; + +// ConsoleClass471 AIStrategicArea.showNeighbours: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x46E240, executeObjectMethod 0x46E5B0, +// setArgFromString 0x46E370, getReturnValueAsString 0x46E000, D1 0x46DFE0, D0 0x46DFA0. +// argc 0: verified inline body, neighbour drawing switch +// argc 1: verified inline body, neighbour drawing switch +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass471 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("showNeighbours", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_showNeighbours; + } + else if (m_argCount == 1) + { + const bool value = BF2_CC_ARG(bool, 0); + m_hasReturnValue = false; + getActiveStrategicArea()->m_showNeighbours = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject471; + +// ConsoleClass472 AIStrategicArea.getStrategicAreaNames: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x46E950, executeObjectMethod 0x46EA90, +// setArgFromString 0x46EA80, getReturnValueAsString 0x46E710, D1 0x46E6A0, D0 0x46E630. +// argc 0: dice::hfe::ai::AIStrategicObjectManager::getStrategicAreaNames() (call at 0x46EAD0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass472 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getStrategicAreaNames", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->getStrategicAreaNames(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject472; + +// ConsoleClass473 AIStrategicArea.isInside: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x46EDC0, executeObjectMethod 0x46F400, +// setArgFromString 0x46EEF0, getReturnValueAsString 0x46EB80, D1 0x46EB60, D0 0x46EB20. +// argc 2: dice::hfe::ai::AIStrategicObjectManager::isInside(std::string const&, dice::hfe::Vec2 const&) (call at 0x46F46D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass473 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("isInside", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "hfe::Vec2"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIStrategicObjectManager::getInstance() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIStrategicObjectManager::getInstance()->isInside(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(hfe::Vec2, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(hfe::Vec2, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject473; + +// ConsoleClass474 AIStrategicArea.strategicAreaName: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x46F7E0, executeObjectMethod 0x46FB90, +// setArgFromString 0x46F910, getReturnValueAsString 0x46F5A0, D1 0x46F530, D0 0x46F4C0. +// argc 0: verified inline body, name load; shipped defect: setter copies and destroys the argument without assigning it +// argc 1: verified inline body, name load; shipped defect: setter copies and destroys the argument without assigning it +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass474 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("strategicAreaName", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveStrategicArea() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveStrategicArea()->m_name; + } + else if (m_argCount == 1) + { + std::string value(BF2_CC_ARG(std::string, 0)); + m_hasReturnValue = false; + (void)getActiveStrategicArea(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject474; + +// ConsoleClass476 AIStrategicArea.saveAll: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x46FED0, executeObjectMethod 0x4704E0, +// setArgFromString 0x46FFF0, getReturnValueAsString 0x46FC90, D1 0x46FC70, D0 0x46FC30. +// argc 2: dice::hfe::ai::AIConsole::saveAll(std::string const&, std::string const&) (call at 0x470550; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass476 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saveAll", 0, 2, 2, "bool", true) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "std::string"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = AIConsole::m_instance->saveAll(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(std::string, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(std::string, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject476; + +// ConsoleClass477 AIStrategicArea.addAllowedUnit: method, 1..1 arguments, no result. +// ELF isObjectActive 0x470670, executeObjectMethod 0x470A10, +// setArgFromString 0x470790, getReturnValueAsString 0x470630, D1 0x470610, D0 0x4705D0. +// argc 1: dice::hfe::ai::AIConsole::addAllowedUnit(std::string const&) (call at 0x470A6D; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass477 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addAllowedUnit", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->addAllowedUnit(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject477; + +// ConsoleClass478 AIStrategicArea.addExpelledUnit: method, 1..1 arguments, no result. +// ELF isObjectActive 0x470B40, executeObjectMethod 0x470EE0, +// setArgFromString 0x470C60, getReturnValueAsString 0x470B00, D1 0x470AE0, D0 0x470AA0. +// argc 1: dice::hfe::ai::AIConsole::addExpelledUnit(std::string const&) (call at 0x470F3D; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass478 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addExpelledUnit", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->addExpelledUnit(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject478; + +// ConsoleClass479 AIStrategicArea.addLandingZoneUnit: method, 1..1 arguments, no result. +// ELF isObjectActive 0x471010, executeObjectMethod 0x4713B0, +// setArgFromString 0x471130, getReturnValueAsString 0x470FD0, D1 0x470FB0, D0 0x470F70. +// argc 1: dice::hfe::ai::AIConsole::addLandingZoneUnit(std::string const&) (call at 0x47140D; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass479 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addLandingZoneUnit", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIConsole::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + AIConsole::m_instance->addLandingZoneUnit(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject479; + +SetConsoleClassDefaults AILandingZonefullAccessSetConsoleClassDefaults("AILandingZone", 2, 0); + +// ConsoleClass485 AILandingZone.activeZone: method, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x471760, executeObjectMethod 0x471B00, +// setArgFromString 0x471880, getReturnValueAsString 0x471520, D1 0x4714B0, D0 0x471440. +// argc 0: dice::hfe::ai::AILandingZoneManager::activeZone() (call at 0x471BB8; ledger done) +// argc 1: dice::hfe::ai::AILandingZoneManager::activeZone(std::string const&) (call at 0x471B5A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass485 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activeZone", 0, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AILandingZoneManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AILandingZoneManager::m_instance->activeZone(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = AILandingZoneManager::m_instance->activeZone(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject485; + +// ConsoleClass486 AILandingZone.createLandingZone: method, 5..5 arguments, no result. +// ELF isObjectActive 0x471C70, executeObjectMethod 0x472990, +// setArgFromString 0x471D90, getReturnValueAsString 0x471C30, D1 0x471C10, D0 0x471BD0. +// argc 5: dice::hfe::ai::AILandingZoneManager::createLandingZone(std::string const&, dice::hfe::Vec2 const&, dice::hfe::Vec2 const&, float, dice::hfe::ai::LandingZoneDirection) (call at 0x472A38; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass486 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createLandingZone", 0, 5, 5, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec2"; + m_argTypes[2] = "Vec2"; + m_argTypes[3] = "float"; + m_argTypes[4] = "LandingZoneDirection"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return AILandingZoneManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + AILandingZoneManager::m_instance->createLandingZone(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(Vec2, 2), BF2_CC_ARG(float, 3), BF2_CC_ARG(LandingZoneDirection, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + AIMODULE_CC_EXTRACT(Vec2, 3) + AIMODULE_CC_EXTRACT(float, 4) + AIMODULE_CC_EXTRACT_WITH(LandingZoneDirection, 5, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject486; + +// ConsoleClass487 AILandingZone.listZones: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x472D90, executeObjectMethod 0x472EC0, +// setArgFromString 0x472EB0, getReturnValueAsString 0x472B50, D1 0x472AE0, D0 0x472A70. +// argc 0: dice::hfe::ai::AILandingZoneManager::listZones() (call at 0x472F03; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass487 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("listZones", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return AILandingZoneManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AILandingZoneManager::m_instance->listZones(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject487; + +// ConsoleClass488 AILandingZone.minCorner: property, 0..1 arguments, returns Vec2. +// ELF isObjectActive 0x473230, executeObjectMethod 0x473600, +// setArgFromString 0x473360, getReturnValueAsString 0x472FC0, D1 0x472FA0, D0 0x472F60. +// argc 0: dice::hfe::ai::AILandingZone::getMinCorner() const (call at 0x473678; ledger done) +// argc 1: dice::hfe::ai::AILandingZone::setMinCorner(dice::hfe::Vec2 const&) (call at 0x47365A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass488 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("minCorner", 1, 0, 1, "Vec2", true) + m_argTypes[0] = "Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveLandingZone() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveLandingZone()->getMinCorner(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveLandingZone()->setMinCorner(BF2_CC_ARG(Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject488; + +// ConsoleClass489 AILandingZone.maxCorner: property, 0..1 arguments, returns Vec2. +// ELF isObjectActive 0x473960, executeObjectMethod 0x473D30, +// setArgFromString 0x473A90, getReturnValueAsString 0x4736F0, D1 0x4736D0, D0 0x473690. +// argc 0: dice::hfe::ai::AILandingZone::getMaxCorner() const (call at 0x473DA8; ledger done) +// argc 1: dice::hfe::ai::AILandingZone::setMaxCorner(dice::hfe::Vec2 const&) (call at 0x473D8A; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass489 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("maxCorner", 1, 0, 1, "Vec2", true) + m_argTypes[0] = "Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveLandingZone() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveLandingZone()->getMaxCorner(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveLandingZone()->setMaxCorner(BF2_CC_ARG(Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec2 m_returnValue; +}; +BF2_CC_NAME consoleObject489; + +// ConsoleClass490 AILandingZone.beachDirection: property, 0..1 arguments, returns LandingZoneDirection. +// ELF isObjectActive 0x474060, executeObjectMethod 0x4743D0, +// setArgFromString 0x474190, getReturnValueAsString 0x473E20, D1 0x473E00, D0 0x473DC0. +// argc 0: dice::hfe::ai::AILandingZone::getBeachDirection() const (call at 0x474436; ledger done) +// argc 1: dice::hfe::ai::AILandingZone::setBeachDirection(dice::hfe::ai::LandingZoneDirection) (call at 0x47441E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass490 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("beachDirection", 1, 0, 1, "LandingZoneDirection", true) + m_argTypes[0] = "LandingZoneDirection"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveLandingZone() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveLandingZone()->getBeachDirection(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveLandingZone()->setBeachDirection(BF2_CC_ARG(LandingZoneDirection, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT_WITH(LandingZoneDirection, 1, dice::hfe::ai::operator>>) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + LandingZoneDirection m_returnValue; +}; +BF2_CC_NAME consoleObject490; + +SetConsoleClassDefaults AIPathFindingfullAccessSetConsoleClassDefaults("AIPathFinding", 2, 0); + +// ConsoleClass496 AIPathFinding.createMap: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x4746F0, executeObjectMethod 0x474A90, +// setArgFromString 0x474810, getReturnValueAsString 0x4744B0, D1 0x474490, D0 0x474450. +// argc 1: dice::hfe::ai::AIPathfinding::createMap(std::string const&) (slot +0x10 at 0x474AE3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass496 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createMap", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->createMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject496; + +// ConsoleClass497 AIPathFinding.deleteMap: method, 1..1 arguments, returns bool. +// ELF isObjectActive 0x474DD0, executeObjectMethod 0x475170, +// setArgFromString 0x474EF0, getReturnValueAsString 0x474B90, D1 0x474B70, D0 0x474B30. +// argc 1: dice::hfe::ai::AIPathfinding::deleteMap(std::string const&) (slot +0x14 at 0x4751C3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass497 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("deleteMap", 0, 1, 1, "bool", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->deleteMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject497; + +// ConsoleClass498 AIPathFinding.activeMap: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x475530, executeObjectMethod 0x4758D0, +// setArgFromString 0x475650, getReturnValueAsString 0x4752F0, D1 0x475280, D0 0x475210. +// argc 0: dice::hfe::ai::AIPathfinding::getActiveMap() const (slot +0x1C at 0x47597A; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setActiveMap(std::string const&) (slot +0x18 at 0x475933; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass498 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("activeMap", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getActiveMap(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->setActiveMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject498; + +// ConsoleClass499 AIPathFinding.traceMap: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x475CB0, executeObjectMethod 0x476050, +// setArgFromString 0x475DD0, getReturnValueAsString 0x475A70, D1 0x475A00, D0 0x475990. +// argc 0: dice::hfe::ai::AIPathfinding::getTraceMap() const (slot +0x24 at 0x4760FA; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setTraceMap(std::string const&) (slot +0x20 at 0x4760B3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass499 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("traceMap", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getTraceMap(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->setTraceMap(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject499; + +// ConsoleClass500 AIPathFinding.getMapList: method, 0..0 arguments, returns std::string. +// ELF isObjectActive 0x476430, executeObjectMethod 0x476560, +// setArgFromString 0x476550, getReturnValueAsString 0x4761F0, D1 0x476180, D0 0x476110. +// argc 0: dice::hfe::ai::AIPathfinding::getMapList() (slot +0x3C at 0x4765A5; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass500 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("getMapList", 0, 0, 0, "std::string", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getMapList(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject500; + +// ConsoleClass502 AIPathFinding.map.maxSlope: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x4768A0, executeObjectMethod 0x476C10, +// setArgFromString 0x4769D0, getReturnValueAsString 0x476660, D1 0x476640, D0 0x476600. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getMaxSlope() const (slot +0x1C at 0x476C78; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setMaxSlope(float) (slot +0x20 at 0x476C60; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass502 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.maxSlope", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getMaxSlope(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setMaxSlope(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject502; + +// ConsoleClass503 AIPathFinding.map.headClearance: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x476F30, executeObjectMethod 0x4772A0, +// setArgFromString 0x477060, getReturnValueAsString 0x476CF0, D1 0x476CD0, D0 0x476C90. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getHeadClearance() const (slot +0x28 at 0x477308; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setHeadClearance(float) (slot +0x24 at 0x4772F0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass503 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.headClearance", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getHeadClearance(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setHeadClearance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject503; + +// ConsoleClass504 AIPathFinding.map.radius: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x4775C0, executeObjectMethod 0x477930, +// setArgFromString 0x4776F0, getReturnValueAsString 0x477380, D1 0x477360, D0 0x477320. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getRadius() const (slot +0x30 at 0x477998; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setRadius(float) (slot +0x2C at 0x477980; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass504 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.radius", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getRadius(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setRadius(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject504; + +// ConsoleClass505 AIPathFinding.map.allowedHeightDiff: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x477C50, executeObjectMethod 0x477FC0, +// setArgFromString 0x477D80, getReturnValueAsString 0x477A10, D1 0x4779F0, D0 0x4779B0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getAllowedHeightDiff() const (slot +0x38 at 0x478028; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setAllowedHeightDiff(float) (slot +0x34 at 0x478010; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass505 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.allowedHeightDiff", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getAllowedHeightDiff(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setAllowedHeightDiff(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject505; + +// ConsoleClass506 AIPathFinding.map.minPolygonsInLeaf: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x478310, executeObjectMethod 0x478680, +// setArgFromString 0x478440, getReturnValueAsString 0x4780A0, D1 0x478080, D0 0x478040. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getMinPolygonsInLeaf() const (slot +0xC at 0x4786E8; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setMinPolygonsInLeaf(int) (slot +0x10 at 0x4786D0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass506 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.minPolygonsInLeaf", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getMinPolygonsInLeaf(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setMinPolygonsInLeaf(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject506; + +// ConsoleClass507 AIPathFinding.map.maxDepthInTree: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x4789D0, executeObjectMethod 0x478D40, +// setArgFromString 0x478B00, getReturnValueAsString 0x478760, D1 0x478740, D0 0x478700. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::getMaxDepthInTree() const (slot +0x14 at 0x478DA8; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::setMaxDepthInTree(int) (slot +0x18 at 0x478D90; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass507 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.maxDepthInTree", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveMapContainer()->getMaxDepthInTree(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->setMaxDepthInTree(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject507; + +// ConsoleClass509 AIPathFinding.map.addVehicleForClusterCost: method, 1..1 arguments, no result. +// ELF isObjectActive 0x478E60, executeObjectMethod 0x479210, +// setArgFromString 0x478F90, getReturnValueAsString 0x478E20, D1 0x478E00, D0 0x478DC0. +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::addVehicleForClusterCost(std::string const&) (slot +0x70 at 0x47926C; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass509 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.addVehicleForClusterCost", 0, 1, 1, "void", false) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->addVehicleForClusterCost(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject509; + +// ConsoleClass510 AIPathFinding.map.draw: method, 0..0 arguments, no result. +// ELF isObjectActive 0x479340, executeObjectMethod 0x479480, +// setArgFromString 0x479470, getReturnValueAsString 0x479300, D1 0x4792E0, D0 0x4792A0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::draw() const (slot +0x3C at 0x4794B8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass510 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.draw", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->draw(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject510; + +// ConsoleClass511 AIPathFinding.map.undraw: method, 0..0 arguments, no result. +// ELF isObjectActive 0x479560, executeObjectMethod 0x4796A0, +// setArgFromString 0x479690, getReturnValueAsString 0x479520, D1 0x479500, D0 0x4794C0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::undraw() const (slot +0x40 at 0x4796D8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass511 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.undraw", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->undraw(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject511; + +// ConsoleClass512 AIPathFinding.map.drawCluster: method, 0..0 arguments, no result. +// ELF isObjectActive 0x479780, executeObjectMethod 0x4798C0, +// setArgFromString 0x4798B0, getReturnValueAsString 0x479740, D1 0x479720, D0 0x4796E0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::drawCluster() const (slot +0x44 at 0x4798F8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass512 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.drawCluster", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->drawCluster(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject512; + +// ConsoleClass513 AIPathFinding.map.undrawCluster: method, 0..0 arguments, no result. +// ELF isObjectActive 0x4799A0, executeObjectMethod 0x479AE0, +// setArgFromString 0x479AD0, getReturnValueAsString 0x479960, D1 0x479940, D0 0x479900. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::undrawCluster() const (slot +0x48 at 0x479B18; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass513 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.undrawCluster", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->undrawCluster(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject513; + +// ConsoleClass514 AIPathFinding.map.drawClusterNeighbourIndices: method, 1..1 arguments, no result. +// ELF isObjectActive 0x479BC0, executeObjectMethod 0x479FD0, +// setArgFromString 0x479CF0, getReturnValueAsString 0x479B80, D1 0x479B60, D0 0x479B20. +// argc 1: dice::hfe::ai::AIPathfinding::MapContainer::drawClusterNeighbourIndices(dice::hfe::Vec3 const&) const (slot +0x4C at 0x47A02E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass514 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.drawClusterNeighbourIndices", 0, 1, 1, "void", false) + m_argTypes[0] = "Vec3"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveMapContainer()->drawClusterNeighbourIndices(BF2_CC_ARG(Vec3, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject514; + +// ConsoleClass516 AIPathFinding.map.buildDebugMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A0E0, executeObjectMethod 0x47A220, +// setArgFromString 0x47A210, getReturnValueAsString 0x47A0A0, D1 0x47A080, D0 0x47A040. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::buildDebugMeshes() (slot +0x54 at 0x47A258; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass516 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.buildDebugMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->buildDebugMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject516; + +// ConsoleClass517 AIPathFinding.map.buildDebugClusterMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A300, executeObjectMethod 0x47A440, +// setArgFromString 0x47A430, getReturnValueAsString 0x47A2C0, D1 0x47A2A0, D0 0x47A260. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::buildDebugClusterMeshes() (slot +0x5C at 0x47A478; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass517 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.buildDebugClusterMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->buildDebugClusterMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject517; + +// ConsoleClass518 AIPathFinding.map.loadGTSDebugMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A520, executeObjectMethod 0x47A660, +// setArgFromString 0x47A650, getReturnValueAsString 0x47A4E0, D1 0x47A4C0, D0 0x47A480. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::loadGTSDebugMeshes() (slot +0x50 at 0x47A698; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass518 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.loadGTSDebugMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->loadGTSDebugMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject518; + +// ConsoleClass519 AIPathFinding.map.unloadDebugMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A740, executeObjectMethod 0x47A880, +// setArgFromString 0x47A870, getReturnValueAsString 0x47A700, D1 0x47A6E0, D0 0x47A6A0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::unloadDebugMeshes() (slot +0x58 at 0x47A8B8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass519 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.unloadDebugMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->unloadDebugMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject519; + +// ConsoleClass520 AIPathFinding.map.unloadDebugClusterMeshes: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47A960, executeObjectMethod 0x47AAA0, +// setArgFromString 0x47AA90, getReturnValueAsString 0x47A920, D1 0x47A900, D0 0x47A8C0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::unloadDebugClusterMeshes() (slot +0x60 at 0x47AAD8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass520 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.unloadDebugClusterMeshes", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->unloadDebugClusterMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject520; + +// ConsoleClass521 AIPathFinding.map.recalculatePortalCosts: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47AB80, executeObjectMethod 0x47ACC0, +// setArgFromString 0x47ACB0, getReturnValueAsString 0x47AB40, D1 0x47AB20, D0 0x47AAE0. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::recalculatePortalCosts() (slot +0x74 at 0x47ACF8; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass521 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.recalculatePortalCosts", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->recalculatePortalCosts(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject521; + +// ConsoleClass524 AIPathFinding.map.loadQuadTrees: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47ADA0, executeObjectMethod 0x47AEE0, +// setArgFromString 0x47AED0, getReturnValueAsString 0x47AD60, D1 0x47AD40, D0 0x47AD00. +// argc 0: dice::hfe::ai::AIPathfinding::MapContainer::loadQuadTrees() (slot +0x68 at 0x47AF18; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass524 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("map.loadQuadTrees", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return getActiveMapContainer() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + getActiveMapContainer()->loadQuadTrees(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject524; + +// ConsoleClass525 AIPathFinding.saveQuadTrees: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47AFC0, executeObjectMethod 0x47B0F0, +// setArgFromString 0x47B0E0, getReturnValueAsString 0x47AF80, D1 0x47AF60, D0 0x47AF20. +// argc 0: dice::hfe::ai::AIPathfinding::saveQuadTrees() (slot +0x28 at 0x47B12B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass525 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("saveQuadTrees", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->saveQuadTrees(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject525; + +// ConsoleClass526 AIPathFinding.loadQuadTrees: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47B1D0, executeObjectMethod 0x47B300, +// setArgFromString 0x47B2F0, getReturnValueAsString 0x47B190, D1 0x47B170, D0 0x47B130. +// argc 0: dice::hfe::ai::AIPathfinding::loadQuadTrees() (slot +0x2C at 0x47B33B; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass526 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("loadQuadTrees", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->loadQuadTrees(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject526; + +// ConsoleClass527 AIPathFinding.loadGTSData: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47B3E0, executeObjectMethod 0x47B510, +// setArgFromString 0x47B500, getReturnValueAsString 0x47B3A0, D1 0x47B380, D0 0x47B340. +// argc 0: dice::hfe::ai::AIPathfinding::loadGTSData() (slot +0x30 at 0x47B54B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass527 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("loadGTSData", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->loadGTSData(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject527; + +// ConsoleClass528 AIPathFinding.exportGTSMeshes: method, 0..0 arguments, returns bool. +// ELF isObjectActive 0x47B7F0, executeObjectMethod 0x47B920, +// setArgFromString 0x47B910, getReturnValueAsString 0x47B5B0, D1 0x47B590, D0 0x47B550. +// argc 0: dice::hfe::ai::AIPathfinding::exportGTSMeshes() const (slot +0x34 at 0x47B955; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass528 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("exportGTSMeshes", 0, 0, 0, "bool", true) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->exportGTSMeshes(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject528; + +// ConsoleClass529 AIPathFinding.exportGTSMeshesWithinBoundary: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x47BC20, executeObjectMethod 0x47C280, +// setArgFromString 0x47BD40, getReturnValueAsString 0x47B9E0, D1 0x47B9C0, D0 0x47B980. +// argc 2: dice::hfe::ai::AIPathfinding::exportGTSMeshesWithinBoundary(dice::hfe::Vec2 const&, dice::hfe::Vec2 const&) const (slot +0x38 at 0x47C2E1; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass529 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("exportGTSMeshesWithinBoundary", 0, 2, 2, "bool", true) + m_argTypes[0] = "Vec2"; + m_argTypes[1] = "Vec2"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->exportGTSMeshesWithinBoundary(BF2_CC_ARG(Vec2, 0), BF2_CC_ARG(Vec2, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject529; + +// ConsoleClass530 AIPathFinding.maxWaterDepth: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x47C5B0, executeObjectMethod 0x47C910, +// setArgFromString 0x47C6D0, getReturnValueAsString 0x47C370, D1 0x47C350, D0 0x47C310. +// argc 0: dice::hfe::ai::AIPathfinding::getMaxWaterDepth() const (slot +0x44 at 0x47C978; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setMaxWaterDepth(float) (slot +0x40 at 0x47C95D; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass530 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("maxWaterDepth", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfindingSetup::instance->getMaxWaterDepth(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->setMaxWaterDepth(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject530; + +// ConsoleClass531 AIPathFinding.drawDynamicAIObjects: method, 0..0 arguments, no result. +// ELF isObjectActive 0x47CA30, executeObjectMethod 0x47CB60, +// setArgFromString 0x47CB50, getReturnValueAsString 0x47C9F0, D1 0x47C9D0, D0 0x47C990. +// argc 0: dice::hfe::ai::AIPathfinding::drawDynamicAIObjects() const (slot +0x48 at 0x47CB9B; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass531 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("drawDynamicAIObjects", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return IAIPathfindingSetup::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + IAIPathfindingSetup::instance->drawDynamicAIObjects(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject531; + +SetConsoleClassDefaults AIDebugfullAccessSetConsoleClassDefaults("AIDebug", 2, 0); + +// ConsoleClass537 AIDebug.textGamma: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x47CE40, executeObjectMethod 0x47D1A0, +// setArgFromString 0x47CF60, getReturnValueAsString 0x47CC00, D1 0x47CBE0, D0 0x47CBA0. +// argc 0: dice::hfe::ai::DPManager::getTextGamma() const (slot +0x58 at 0x47D208; ledger done) +// argc 1: dice::hfe::ai::DPManager::setTextGamma(float) (slot +0x54 at 0x47D1ED; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass537 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("textGamma", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iDPManager) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iDPManager)->getTextGamma(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(CommonSingletonServer::m_iDPManager)->setTextGamma(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject537; + +// ConsoleClass538 AIDebug.draw: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x47D4C0, executeObjectMethod 0x47D820, +// setArgFromString 0x47D5E0, getReturnValueAsString 0x47D280, D1 0x47D260, D0 0x47D220. +// argc 0: dice::hfe::ai::AISettings::getDraw() const (slot +0x80 at 0x47D894; ledger done) +// argc 1: dice::hfe::ai::AISettings::setDraw(bool) (slot +0x138 at 0x47D875; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass538 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("draw", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return static_cast(CommonSingletonServer::m_iaiSettings) != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = static_cast(CommonSingletonServer::m_iaiSettings)->getDraw(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + static_cast(static_cast(CommonSingletonServer::m_iaiSettings))->setDraw(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject538; + +// ConsoleClass539 AIDebug.ToolPathfinding: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x47DB50, executeObjectMethod 0x47DEB0, +// setArgFromString 0x47DC70, getReturnValueAsString 0x47D910, D1 0x47D8F0, D0 0x47D8B0. +// argc 0: dice::hfe::ai::AIPathfinding::getActivatePathfindingDebugTool() const (slot +0x108 at 0x47DF24; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setActivatePathfindingDebugTool(bool) (slot +0x104 at 0x47DF05; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass539 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("ToolPathfinding", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfinding::instance->getActivatePathfindingDebugTool(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setActivatePathfindingDebugTool(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject539; + +// ConsoleClass540 AIDebug.pathfindingDebugToolVehicle: property, 0..1 arguments, returns std::string. +// ELF isObjectActive 0x47E260, executeObjectMethod 0x47E600, +// setArgFromString 0x47E380, getReturnValueAsString 0x47E020, D1 0x47DFB0, D0 0x47DF40. +// argc 0: dice::hfe::ai::AIPathfinding::getPathfindingDebugToolVehicle() const (slot +0x110 at 0x47E6AA; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setPathfindingDebugToolVehicle(std::string const&) (slot +0x10C at 0x47E663; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass540 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("pathfindingDebugToolVehicle", 1, 0, 1, "std::string", true) + m_argTypes[0] = "std::string"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfinding::instance->getPathfindingDebugToolVehicle(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setPathfindingDebugToolVehicle(BF2_CC_ARG(std::string, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + std::string m_returnValue; +}; +BF2_CC_NAME consoleObject540; + +// ConsoleClass541 AIDebug.clusterSearch: property, 0..1 arguments, returns bool. +// ELF isObjectActive 0x47E970, executeObjectMethod 0x47ECD0, +// setArgFromString 0x47EA90, getReturnValueAsString 0x47E730, D1 0x47E710, D0 0x47E6D0. +// argc 0: dice::hfe::ai::AIPathfinding::getClusterSearch() const (slot +0x100 at 0x47ED44; ledger done) +// argc 1: dice::hfe::ai::AIPathfinding::setClusterSearch(bool) (slot +0xFC at 0x47ED25; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass541 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("clusterSearch", 1, 0, 1, "bool", true) + m_argTypes[0] = "bool"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = IAIPathfinding::instance->getClusterSearch(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setClusterSearch(BF2_CC_ARG(bool, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(bool, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject541; + +// ConsoleClass542 AIDebug.setPathfindingDebugToolVehicleId: method, 1..1 arguments, no result. +// ELF isObjectActive 0x47EE00, executeObjectMethod 0x47F160, +// setArgFromString 0x47EF20, getReturnValueAsString 0x47EDC0, D1 0x47EDA0, D0 0x47ED60. +// argc 1: dice::hfe::ai::AIPathfinding::setPathfindingDebugToolVehicleId(int) (slot +0x114 at 0x47F1A3; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass542 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("setPathfindingDebugToolVehicleId", 0, 1, 1, "void", false) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + IAIPathfinding::instance->setPathfindingDebugToolVehicleId(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject542; + +// ConsoleClass543 AIDebug.tryPath: method, 2..2 arguments, no result. +// ELF isObjectActive 0x47F250, executeObjectMethod 0x47F930, +// setArgFromString 0x47F370, getReturnValueAsString 0x47F210, D1 0x47F1F0, D0 0x47F1B0. +// argc 2: dice::hfe::ai::AIPathfinding::tryPath(dice::hfe::Vec3 const&, dice::hfe::Vec3 const&) (slot +0xF4 at 0x47F9B2; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass543 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("tryPath", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IAIPathfinding::instance->tryPath(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject543; + +// ConsoleClass544 AIDebug.tryClusterPath: method, 2..2 arguments, no result. +// ELF isObjectActive 0x47FA60, executeObjectMethod 0x480140, +// setArgFromString 0x47FB80, getReturnValueAsString 0x47FA20, D1 0x47FA00, D0 0x47F9C0. +// argc 2: dice::hfe::ai::AIPathfinding::tryClusterPath(dice::hfe::Vec3 const&, dice::hfe::Vec3 const&) (slot +0xF8 at 0x4801C2; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass544 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("tryClusterPath", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec3"; + m_argTypes[1] = "Vec3"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return IAIPathfinding::instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + IAIPathfinding::instance->tryClusterPath(BF2_CC_ARG(Vec3, 0), BF2_CC_ARG(Vec3, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + AIMODULE_CC_EXTRACT(Vec3, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject544; + +SetConsoleClassDefaults AIOrderfullAccessSetConsoleClassDefaults("AIOrder", 2, 0); + +// ConsoleClass551 AIOrder.createPatrolPath: method, 3..3 arguments, no result. +// ELF isObjectActive 0x480270, executeObjectMethod 0x480A50, +// setArgFromString 0x480390, getReturnValueAsString 0x480230, D1 0x480210, D0 0x4801D0. +// argc 3: dice::hfe::ai::UserOrderManager::createPatrolPath(std::string const&, dice::hfe::ai::CombatStrengthType, int) (call at 0x480ABF; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass551 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createPatrolPath", 0, 3, 3, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "CombatStrengthType"; + m_argTypes[2] = "int"; + AIMODULE_CC_TAIL(3) + virtual bool isObjectActive() const { return UserOrderManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 3) + { + m_hasReturnValue = false; + UserOrderManager::m_instance->createPatrolPath(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(CombatStrengthType, 1), BF2_CC_ARG(int, 2)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 2, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(int, 3) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject551; + +// ConsoleClass553 AIOrder.addPathPoint: method, 1..1 arguments, no result. +// ELF isObjectActive 0x480B90, executeObjectMethod 0x480F60, +// setArgFromString 0x480CC0, getReturnValueAsString 0x480B50, D1 0x480B30, D0 0x480AF0. +// argc 1: dice::hfe::ai::PatrolPath::addPathPoint(dice::hfe::Vec2 const&) (call at 0x480FB4; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass553 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addPathPoint", 0, 1, 1, "void", false) + m_argTypes[0] = "Vec2"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->addPathPoint(BF2_CC_ARG(Vec2, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject553; + +// ConsoleClass554 AIOrder.requiredResources: property, 0..1 arguments, returns int. +// ELF isObjectActive 0x481290, executeObjectMethod 0x481600, +// setArgFromString 0x4813C0, getReturnValueAsString 0x481020, D1 0x481000, D0 0x480FC0. +// argc 0: dice::hfe::ai::PatrolPath::getRequiredResources() const (call at 0x481666; ledger done) +// argc 1: dice::hfe::ai::PatrolPath::setRequiredResources(int) (call at 0x48164E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass554 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("requiredResources", 1, 0, 1, "int", true) + m_argTypes[0] = "int"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActivePatrolPathIfManager()->getRequiredResources(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->setRequiredResources(BF2_CC_ARG(int, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + int m_returnValue; +}; +BF2_CC_NAME consoleObject554; + +// ConsoleClass555 AIOrder.minDistance: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x481920, executeObjectMethod 0x481C90, +// setArgFromString 0x481A50, getReturnValueAsString 0x4816E0, D1 0x4816C0, D0 0x481680. +// argc 0: dice::hfe::ai::PatrolPath::getMinDistance() const (call at 0x481CF6; ledger done) +// argc 1: dice::hfe::ai::PatrolPath::setMinDistance(float) (call at 0x481CDE; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass555 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("minDistance", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActivePatrolPathIfManager()->getMinDistance(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->setMinDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject555; + +// ConsoleClass556 AIOrder.patrolSpeed: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x481FB0, executeObjectMethod 0x482320, +// setArgFromString 0x4820E0, getReturnValueAsString 0x481D70, D1 0x481D50, D0 0x481D10. +// argc 0: dice::hfe::ai::PatrolPath::getPatrolSpeed() const (call at 0x482386; ledger done) +// argc 1: dice::hfe::ai::PatrolPath::setPatrolSpeed(float) (call at 0x48236E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass556 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("patrolSpeed", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActivePatrolPathIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActivePatrolPathIfManager()->getPatrolSpeed(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActivePatrolPathIfManager()->setPatrolSpeed(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject556; + +// ConsoleClass559 AIOrder.createGuardPosition: method, 5..5 arguments, no result. +// ELF isObjectActive 0x482440, executeObjectMethod 0x483100, +// setArgFromString 0x482560, getReturnValueAsString 0x482400, D1 0x4823E0, D0 0x4823A0. +// argc 5: dice::hfe::ai::UserOrderManager::createGuardPosition(std::string const&, dice::hfe::Vec2 const&, dice::hfe::ai::CombatStrengthType, int, int) (call at 0x483199; ledger stop) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass559 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createGuardPosition", 0, 5, 5, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "Vec2"; + m_argTypes[2] = "CombatStrengthType"; + m_argTypes[3] = "int"; + m_argTypes[4] = "int"; + AIMODULE_CC_TAIL(5) + virtual bool isObjectActive() const { return UserOrderManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 5) + { + m_hasReturnValue = false; + UserOrderManager::m_instance->createGuardPosition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(Vec2, 1), BF2_CC_ARG(CombatStrengthType, 2), BF2_CC_ARG(int, 3), BF2_CC_ARG(int, 4)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + AIMODULE_CC_EXTRACT_WITH(CombatStrengthType, 3, dice::hfe::ai::operator>>) + AIMODULE_CC_EXTRACT(int, 4) + AIMODULE_CC_EXTRACT(int, 5) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject559; + +// ConsoleClass560 AIOrder.minDistance: property, 0..1 arguments, returns float. +// ELF isObjectActive 0x483470, executeObjectMethod 0x4837E0, +// setArgFromString 0x4835A0, getReturnValueAsString 0x483230, D1 0x483210, D0 0x4831D0. +// argc 0: dice::hfe::ai::GuardPosition::getMinDistance() const (call at 0x483846; ledger done) +// argc 1: dice::hfe::ai::GuardPosition::setMinDistance(float) (call at 0x48382E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass560 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("minDistance", 1, 0, 1, "float", true) + m_argTypes[0] = "float"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveGuardPositionIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveGuardPositionIfManager()->getMinDistance(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveGuardPositionIfManager()->setMinDistance(BF2_CC_ARG(float, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(float, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + float m_returnValue; +}; +BF2_CC_NAME consoleObject560; + +// ConsoleClass561 AIOrder.rotation: property, 0..1 arguments, returns Vec3. +// ELF isObjectActive 0x483B60, executeObjectMethod 0x483F70, +// setArgFromString 0x483C90, getReturnValueAsString 0x4838C0, D1 0x4838A0, D0 0x483860. +// argc 0: dice::hfe::ai::GuardPosition::getRotation() const (call at 0x483FF5; ledger done) +// argc 1: dice::hfe::ai::GuardPosition::setRotation(dice::hfe::Vec3 const&) (call at 0x483FD0; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass561 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("rotation", 1, 0, 1, "Vec3", true) + m_argTypes[0] = "Vec3"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return getActiveGuardPositionIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = getActiveGuardPositionIfManager()->getRotation(); + } + else if (m_argCount == 1) + { + m_hasReturnValue = false; + getActiveGuardPositionIfManager()->setRotation(BF2_CC_ARG(Vec3, 0)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec3, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + Vec3 m_returnValue; +}; +BF2_CC_NAME consoleObject561; + +// ConsoleClass562 AIOrder.addStrategicAreaAbortCondition: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4840C0, executeObjectMethod 0x4846A0, +// setArgFromString 0x4841F0, getReturnValueAsString 0x484080, D1 0x484060, D0 0x484020. +// argc 2: dice::hfe::ai::GuardPosition::addStrategicAreaAbortCondition(std::string const&, dice::hfe::ai::StatusMap::Status) (call at 0x484709; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass562 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("addStrategicAreaAbortCondition", 0, 2, 2, "void", false) + m_argTypes[0] = "std::string"; + m_argTypes[1] = "StatusMap::Status"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return getActiveGuardPositionIfManager() != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + getActiveGuardPositionIfManager()->addStrategicAreaAbortCondition(BF2_CC_ARG(std::string, 0), BF2_CC_ARG(StatusMap::Status, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(std::string, 1) + AIMODULE_CC_EXTRACT_WITH(StatusMap::Status, 2, dice::hfe::ai::operator>>) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject562; + +SetConsoleClassDefaults AICoverfullAccessSetConsoleClassDefaults("AICover", 2, 0); + +// ConsoleClass569 AICover.createCoverPosition: method, 2..2 arguments, no result. +// ELF isObjectActive 0x4847D0, executeObjectMethod 0x484E30, +// setArgFromString 0x4848F0, getReturnValueAsString 0x484790, D1 0x484770, D0 0x484730. +// argc 2: dice::hfe::ai::CoverPositionManager::createCoverPosition(dice::hfe::Vec2 const&, dice::hfe::Vec2 const&) (call at 0x484E9E; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass569 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("createCoverPosition", 0, 2, 2, "void", false) + m_argTypes[0] = "Vec2"; + m_argTypes[1] = "Vec2"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return CoverPositionManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = false; + CoverPositionManager::m_instance->createCoverPosition(BF2_CC_ARG(Vec2, 0), BF2_CC_ARG(Vec2, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(Vec2, 1) + AIMODULE_CC_EXTRACT(Vec2, 2) + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject569; + +// ConsoleClass570 AICover.finaliseCoverPositions: method, 0..0 arguments, no result. +// ELF isObjectActive 0x484F50, executeObjectMethod 0x485080, +// setArgFromString 0x485070, getReturnValueAsString 0x484F10, D1 0x484EF0, D0 0x484EB0. +// argc 0: dice::hfe::ai::CoverPositionManager::finaliseCoverPositions() (call at 0x4850B9; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass570 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("finaliseCoverPositions", 0, 0, 0, "void", false) + AIMODULE_CC_TAIL(0) + virtual bool isObjectActive() const { return CoverPositionManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = false; + CoverPositionManager::m_instance->finaliseCoverPositions(); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + } + BF2_CC_NO_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +}; +BF2_CC_NAME consoleObject570; + +// ConsoleClass571 AICover.search: method, 2..2 arguments, returns bool. +// ELF isObjectActive 0x485360, executeObjectMethod 0x485900, +// setArgFromString 0x485480, getReturnValueAsString 0x485120, D1 0x485100, D0 0x4850C0. +// argc 2: dice::hfe::ai::CoverPositionManager::search(int, int) (call at 0x485944; ledger done) +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass571 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("search", 0, 2, 2, "bool", true) + m_argTypes[0] = "int"; + m_argTypes[1] = "int"; + AIMODULE_CC_TAIL(2) + virtual bool isObjectActive() const { return CoverPositionManager::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 2) + { + m_hasReturnValue = true; + m_returnValue = CoverPositionManager::m_instance->search(BF2_CC_ARG(int, 0), BF2_CC_ARG(int, 1)); + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(int, 1) + AIMODULE_CC_EXTRACT(int, 2) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + bool m_returnValue; +}; +BF2_CC_NAME consoleObject571; + +SetConsoleClassDefaults AIRandomfullAccessSetConsoleClassDefaults("AIRandom", 2, 0); + +// ConsoleClass576 AIRandom.seed: property, 0..1 arguments, returns u32. +// ELF isObjectActive 0x485C10, executeObjectMethod 0x485F70, +// setArgFromString 0x485D30, getReturnValueAsString 0x4859D0, D1 0x4859B0, D0 0x485970. +// argc 0: verified inline body, seed word at offset zero of a non-polymorphic receiver +// argc 1: verified inline body, seed word at offset zero of a non-polymorphic receiver +#undef BF2_CC_NAME +#define BF2_CC_NAME ConsoleClass576 +class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl +{ + BF2_CC_HEAD_NAMED("seed", 1, 0, 1, "u32", true) + m_argTypes[0] = "u32"; + AIMODULE_CC_TAIL(1) + virtual bool isObjectActive() const { return AIRandom::m_instance != 0; } + virtual void executeObjectMethod() + { + if (m_argCount == 0) + { + m_hasReturnValue = true; + m_returnValue = AIRandom::m_instance->m_seed; + } + else if (m_argCount == 1) + { + const u32 value = BF2_CC_ARG(u32, 0); + m_hasReturnValue = false; + AIRandom::m_instance->m_seed = value; + } + } + virtual void setArgFromString(int index, const std::string& value) + { + AIMODULE_CC_EXTRACT(u32, 1) + } + BF2_CC_RETURN_AS_STRING + BF2_CC_COMMON_HOOKS +private: + u32 m_returnValue; +}; +BF2_CC_NAME consoleObject576; + +#undef AIMODULE_CC_TAIL +#undef AIMODULE_CC_EXTRACT_WITH +#undef AIMODULE_CC_EXTRACT +#pragma pop_macro("BF2_CC_NAME") diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp index bc0df3c76..5f2b53236 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp @@ -1,21 +1,34 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIPathfinding operations. +// Navigation searches, map lifecycle and offline GTS export. + +// static init: ELF 0x3AE2B0 (__tcf_0 0x3AE310, _GLOBAL__I 0x3AE340): 's Init object only. +#include #include "AIPathfinding.h" #include // std::remove - deleteMap uses the erase-remove idiom +#include // traceKnown's line length #include - +#include +#include "../../../../Core/Debug.h" +#include "../../../../IO/File/File.h" +#include "../../../../IO/File/FileManager.h" + +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/BFTerrain.h" +#include "../AIUtils/DebugRendering/AIRenderUtil.h" +#include "../DrawPrimitives/DPManager.h" +#include "../AIPathFinding/NavMesh/MeshImporterExporter.h" +#include "../AIBot/BotNavigation.h" // trace(BotNavigation*): getMapIndex +#include "../AIPathFinding/Cluster/ClusterGraph.h" // areNeighbours, updatePortalCosts #include "../AIPathFinding/Cluster/ClusterNodeManager.h" // init builds one per cluster search +#include "../AIPathFinding/Material/MaterialManager.h" // traceKnown: isValidMaterial #include "../AIPathFinding/NavMesh/QuadTree.h" // MapContainer polygon vertex query #include "../AIPathFinding/NavMesh/QTSearchNodeManager.h" // init builds one per local search #include "../AIStrategicEntity/AIStrategicObjectManager.h" // loadQuadTrees' tail calls initAreas #include "../AIUtils/checkPointer.h" -#include "AIDllFrontier.h" #include "AIMineManager.h" // loadQuadTrees / loadGTSData call IAIMineManager::init #include "AISettingsInterfaces.h" // IAISettings::getVehicle / getVehicleMaterialManager #include "CommonSingletonServer.h" -#include "../../../../Core/ConsoleObjectMacro.h" // the aiPathfinding.* bindings at the foot namespace dice { namespace hfe { @@ -33,7 +46,9 @@ typedef AStarResource ClusterResource; + // Allocates the pathfinding engines, search resources and debug paths. +// ELF 0x3A1DC0, 0x3A2630 (compiler-emitted variants). AIPathfinding::AIPathfinding() : m_activatePathfindingDebugTool(false) , m_pathfindingDebugToolVehicleId(0) @@ -73,6 +88,7 @@ AIPathfinding::AIPathfinding() // Resets debug paths before deleting engines, paths, maps, and search points. // Preserves the explicit null check before each map deletion. +// ELF 0x3A2EA0, 0x3A3060, 0x3A3220 (compiler-emitted variants). AIPathfinding::~AIPathfinding() { reset(); @@ -92,6 +108,7 @@ AIPathfinding::~AIPathfinding() } // Resets pathfinding debug state. Loaded maps and in-flight searches remain active. +// ELF 0x3A4120. int AIPathfinding::reset() { m_activatePathfindingDebugTool = false; @@ -111,21 +128,25 @@ int AIPathfinding::reset() // Requests a cooperative pause. Poll isLockComplete() until both search pools are idle. // This is not a thread synchronization primitive. +// ELF 0x3A4260. void AIPathfinding::lock() { m_locking = true; } +// ELF 0x3A4270. void AIPathfinding::unlock() { m_locking = false; } +// ELF 0x3A4280. bool AIPathfinding::isLocking() const { return m_locking; } +// ELF 0x3A4290. bool AIPathfinding::isLockComplete() const { if (m_engine->m_inFlight.size() != 0) @@ -136,11 +157,13 @@ bool AIPathfinding::isLockComplete() const } // Map-name lookup is case-insensitive. Negative stored IDs are treated as missing. +// ELF 0x3A7350. int AIPathfinding::getNumberOfMaps() const { return static_cast(m_maps.size()); } +// ELF 0x3A7370. bool AIPathfinding::isMapUsed(int id) const { if (id < 0) @@ -150,6 +173,7 @@ bool AIPathfinding::isMapUsed(int id) const // Returns the stored map name directly for a nonnegative id; the caller must ensure // it is below the map count. Negative ids use the fallback name. +// ELF 0x3A7280. const std::string& AIPathfinding::getMapNameFromId(int id) const { if (id >= 0) @@ -159,6 +183,7 @@ const std::string& AIPathfinding::getMapNameFromId(int id) const return m_returnedName; } +// ELF 0x3A72F0. int AIPathfinding::getMapIdFromName(const std::string& name) const { const std::map::const_iterator i = m_mapIds.find(name); @@ -167,6 +192,7 @@ int AIPathfinding::getMapIdFromName(const std::string& name) const return i->second; } +// ELF 0x3A6CD0. void AIPathfinding::setActiveMap(const std::string& name) { const std::map::const_iterator i = m_mapIds.find(name); @@ -176,6 +202,7 @@ void AIPathfinding::setActiveMap(const std::string& name) m_activeMap = m_maps[i->second]; } +// ELF 0x3A6D40. const std::string& AIPathfinding::getActiveMap() const { if (m_activeMap) @@ -186,6 +213,7 @@ const std::string& AIPathfinding::getActiveMap() const } // 666 is the "NO TRACE MAP" sentinel, not -1, and it is written here on every miss. +// ELF 0x3A6DB0. void AIPathfinding::setTraceMap(const std::string& name) { const std::map::const_iterator i = m_mapIds.find(name); @@ -197,6 +225,7 @@ void AIPathfinding::setTraceMap(const std::string& name) // the literal has no space before its closing star - "* NO ACTIVE TRACE MAP*" - unlike its // neighbour above. Copied exactly; it is a shipped string a console user can see. +// ELF 0x3A6E10. const std::string& AIPathfinding::getTraceMap() const { if (m_traceMapIndex == -666) @@ -207,11 +236,13 @@ const std::string& AIPathfinding::getTraceMap() const return m_maps[m_traceMapIndex]->getName(); } +// ELF 0x3B1CB0. int AIPathfinding::getTraceMapIndex() const { return m_traceMapIndex; } +// ELF 0x3A6E80. IAIPathfindingSetup::IMapContainer* AIPathfinding::getActiveMapContainer() const { return m_activeMap; @@ -219,6 +250,7 @@ IAIPathfindingSetup::IMapContainer* AIPathfinding::getActiveMapContainer() const // no bounds check and no guard - it walks whatever is in the list and calls the non-virtual // `MapContainer::init` on each. +// ELF 0x3A40D0. void AIPathfinding::initMaps() { for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) @@ -226,48 +258,57 @@ void AIPathfinding::initMaps() } // Debug vehicle selection uses the vehicle IDs and names in AI settings. +// ELF 0x3A6810. bool AIPathfinding::getActivatePathfindingDebugTool() const { return m_activatePathfindingDebugTool; } +// ELF 0x3A53A0. void AIPathfinding::setPathfindingDebugToolVehicle(const std::string& name) { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); m_pathfindingDebugToolVehicleId = settings->getVehicle(name); } -void* AIPathfinding::getPathfindingDebugToolVehicle() const +// ELF 0x3A53E0. +const std::string& AIPathfinding::getPathfindingDebugToolVehicle() const { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); - return const_cast(&settings->getVehicle(m_pathfindingDebugToolVehicleId)); + return settings->getVehicle(m_pathfindingDebugToolVehicleId); } +// ELF 0x3A5420. void AIPathfinding::setPathfindingDebugToolVehicleId(int id) { m_pathfindingDebugToolVehicleId = id; } +// ELF 0x3A5380. void AIPathfinding::setClusterSearch(bool on) { m_clusterSearch = on; } +// ELF 0x3A5390. bool AIPathfinding::getClusterSearch() const { return m_clusterSearch; } +// ELF 0x3A6710. int AIPathfinding::getSearchPointToSet() const { return m_searchPointToSet; } +// ELF 0x3A6720. QTPath* AIPathfinding::getDebugPath() const { return m_debugPath; } +// ELF 0x3A6730. ClusterNodePath* AIPathfinding::getDebugClusterPath() const { return m_debugClusterPath; @@ -275,22 +316,26 @@ ClusterNodePath* AIPathfinding::getDebugClusterPath() const // unchecked, and the array has exactly two elements. `searchPointSelected` subscripts it with // `m_searchPointToSet`, which that function is careful to keep at 0 or 1; nothing here enforces it. +// ELF 0x3A6740. Vec3* AIPathfinding::getSearchPoint(int index) const { return m_searchPoint[index]; } +// ELF 0x3A09B0. void AIPathfinding::setMaxWaterDepth(float depth) { m_maxWaterDepth = depth; } +// ELF 0x3A09A0. float AIPathfinding::getMaxWaterDepth() const { return m_maxWaterDepth; } // Queries navigation using the selected map and vehicle-specific material rules. +// ELF 0x3A79D0. bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& polygon, unsigned int& quadTree, int vehicleId) const { @@ -303,6 +348,7 @@ bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& poly return m_maps[map]->getPolygon(position, polygon, quadTree, materials); } +// ELF 0x3A7B00. void AIPathfinding::getPolygonsInRadius(std::list& polygons, int map, unsigned int quadTree, unsigned int polygon, const Vec3& centre, float radius) const @@ -313,6 +359,7 @@ void AIPathfinding::getPolygonsInRadius(std::list& polygons, int m m_maps[map]->getPolygonsInRadius(polygons, quadTree, polygon, centre, radius); } +// ELF 0x3A7B70. void AIPathfinding::getPolygonsInTriangle(std::list& polygons, int map, unsigned int quadTree, unsigned int polygon, const Vec3& corner0, const Vec3& corner1, @@ -324,14 +371,15 @@ void AIPathfinding::getPolygonsInTriangle(std::list& polygons, int m_maps[map]->getPolygonsInTriangle(polygons, quadTree, polygon, corner0, corner1, corner2); } -// no bounds check - see the block above. -void AIPathfinding::setMaterial(int map, unsigned int quadTree, unsigned int polygon, +// no bounds check - see the block above. ELF 0x3A7D50 returns the container's result. +bool AIPathfinding::setMaterial(int map, unsigned int quadTree, unsigned int polygon, unsigned char material) const { - m_maps[map]->setMaterial(quadTree, polygon, material); + return m_maps[map]->setMaterial(quadTree, polygon, material); } // no bounds check. +// ELF 0x3A7D00. bool AIPathfinding::getMaterial(int map, unsigned int quadTree, unsigned int polygon, unsigned char& material) const { @@ -339,6 +387,7 @@ bool AIPathfinding::getMaterial(int map, unsigned int quadTree, unsigned int pol } // no bounds check, and it draws unconditionally in the shipped server build. +// ELF 0x3A7F30. void AIPathfinding::drawPolygon(int map, unsigned int quadTree, unsigned int polygon, float* colour, float duration) const { @@ -347,43 +396,184 @@ void AIPathfinding::drawPolygon(int map, unsigned int quadTree, unsigned int pol // Requires a valid map index. Validation checks the vehicle vector while cost lookup // indexes the other vector; the caller must also ensure that lookup index is valid. +// ELF 0x3AE200. bool AIPathfinding::isValidClusterType(int map, unsigned int type) const { return type < m_maps[map]->m_clusterCostVehicles.size(); } +// ELF 0x3A5E10. Acquires a search resource (owner 2000), empties the shared debug path and runs +// the portal-to-portal search with the vehicle of cluster cost type `costType`, updating the +// engine (10 ms budget) until it stops searching. Appends -1 when a polygon is missing or its +// material is invalid for that vehicle, or when the search fails. Retail quirk kept: a search +// that finds its path on the first call appends the straight distance times the first polygon's +// material cost, not the path cost; only a search that needed updates appends the path cost. +// Topology smoothing is switched on for every map but map 0. The resource is released last. +void AIPathfinding::getPortalCost(std::vector& costs, unsigned short costType, int map, + unsigned int island, const Vec3& from, + unsigned int fromPolygon, const Vec3& to, + unsigned int toPolygon, + const std::set& allowedClusters) +{ + unsigned int resource = 0xFFFFFFFFu; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + acquireResource(resource, 2000); + + const int vehicleId = settings->getVehicle(m_maps[map]->m_clusterCostVehicles[costType]); + QTPath* const path = m_debugPath; + path->m_nodes.resize(0); + path->m_i0 = 0; + path->m_i20 = 0.0f; + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + + if (fromPolygon == 0xFFFFFFFFu || toPolygon == 0xFFFFFFFFu) + { + costs.push_back(-1.0f); + } + else + { + const unsigned char fromMaterial = quadTree->getMaterialOfPolygon(fromPolygon); + if (!materials->isValidMaterial(fromMaterial) + || !materials->isValidMaterial(quadTree->getMaterialOfPolygon(toPolygon))) + { + costs.push_back(-1.0f); + } + else + { + QTSearchNodeManager* const manager = m_engine->m_searches[resource]->m_nodeManager; + manager->m_allowedClusters = &allowedClusters; + if (map != 0) + manager->m_usePathTopologySmoothing = true; + + if (localSearch(resource, map, island, fromPolygon, from, toPolygon, to, vehicleId, + m_debugPath) == astarStatus::kFound) + { + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); + costs.push_back(materials->getMaterialCost(fromMaterial) * distance); + } + else + { + while (m_engine->m_searches[resource]->m_status == astarStatus::kSearching) + m_engine->update(10.0f); + if (localSearch(resource, map, island, fromPolygon, from, toPolygon, to, + vehicleId, m_debugPath) != astarStatus::kFound) + m_debugPath->m_i20 = -1.0f; + costs.push_back(m_debugPath->m_i20); + } + } + } + + releaseResource(resource, 2000); +} + +// ELF 0x3A63B0. Runs the portal-to-portal search on the shared debug path (m_debugPath is +// emptied first: resize(0), step and cost zeroed) with the vehicle of cluster cost type +// `costType`. Both polygons must exist and carry a material valid for that vehicle, else the cost +// is -1 (true). The search is limited to `allowedClusters`; topology smoothing is switched on +// for every map but map 0 (retail tests the map index, nothing else). Search status 1 (still +// running) answers false; 2 (found) takes the path cost, or for a zero-cost path (both portals +// on one polygon) the straight distance times the first polygon's material cost; anything else +// is -1. All non-running outcomes answer true. +bool AIPathfinding::getPortalCost(float& cost, unsigned int resource, int map, unsigned int island, + unsigned short costType, const Vec3& from, + unsigned int fromPolygon, const Vec3& to, + unsigned int toPolygon, + const std::set& allowedClusters) +{ + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + + QTPath* const path = m_debugPath; + path->m_nodes.resize(0); + path->m_i0 = 0; + path->m_i20 = 0.0f; + + const int vehicleId = settings->getVehicle(m_maps[map]->m_clusterCostVehicles[costType]); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + + if (fromPolygon == 0xFFFFFFFFu || toPolygon == 0xFFFFFFFFu) + { + cost = -1.0f; + return true; + } + const unsigned char fromMaterial = quadTree->getMaterialOfPolygon(fromPolygon); + if (!materials->isValidMaterial(fromMaterial) + || !materials->isValidMaterial(quadTree->getMaterialOfPolygon(toPolygon))) + { + cost = -1.0f; + return true; + } + + QTSearchNodeManager* const manager = m_engine->m_searches[resource]->m_nodeManager; + manager->m_allowedClusters = &allowedClusters; + if (map != 0) + manager->m_usePathTopologySmoothing = true; + + const int status = localSearch(resource, map, island, fromPolygon, from, toPolygon, to, + vehicleId, m_debugPath); + if (status == astarStatus::kSearching) + return false; + if (status != astarStatus::kFound) + { + cost = -1.0f; + return true; + } + if (m_debugPath->m_i20 == 0.0f) + { + const float dx = to.x - from.x; + const float dy = to.y - from.y; + const float dz = to.z - from.z; + cost = std::sqrt(dx * dx + dy * dy + dz * dz); + cost = materials->getMaterialCost(fromMaterial) * cost; + return true; + } + cost = m_debugPath->m_i20; + return true; +} + +// ELF 0x3AE280. int AIPathfinding::getClusterCostType(int map, unsigned int type) const { return m_maps[map]->m_clusterCostTypes[type]; } // AIPathfinding::MapContainer - the trivial accessors. -const std::string& AIPathfinding::MapContainer::getName() +// ELF 0x3B1CC0. +const std::string& AIPathfinding::MapContainer::getName() const { return m_name; } -int AIPathfinding::MapContainer::getMinPolygonsInLeaf() +// ELF 0x3A08F0. +int AIPathfinding::MapContainer::getMinPolygonsInLeaf() const { return m_minPolygonsInLeaf; } +// ELF 0x3A0900. void AIPathfinding::MapContainer::setMinPolygonsInLeaf(int n) { m_minPolygonsInLeaf = n; } -int AIPathfinding::MapContainer::getMaxDepthInTree() +// ELF 0x3A0910. +int AIPathfinding::MapContainer::getMaxDepthInTree() const { return m_maxDepthInTree; } +// ELF 0x3A0920. void AIPathfinding::MapContainer::setMaxDepthInTree(int n) { m_maxDepthInTree = n; } // Owns a navigation map with defaults of four polygons per leaf and tree depth eight. +// ELF 0x39FAD0, 0x39FDA0 (compiler-emitted variants). AIPathfinding::MapContainer::MapContainer(const std::string& name, int id) : m_id(id) , m_name(name) @@ -403,6 +593,7 @@ AIPathfinding::MapContainer::MapContainer(const std::string& name, int id) // manager goes first and the properties second, which is the reverse of the order the constructor // built them - and both are `delete` with a null test the binary spells out even though `delete` // already handles null. +// ELF 0x3A0070, 0x3A01C0, 0x3A0310 (compiler-emitted variants). AIPathfinding::MapContainer::~MapContainer() { delete m_quadTreeManager; @@ -410,107 +601,127 @@ AIPathfinding::MapContainer::~MapContainer() } // Slope setters accept degrees; getters return radians. -float AIPathfinding::MapContainer::getMaxSlope() +// ELF 0x3A0930. +float AIPathfinding::MapContainer::getMaxSlope() const { return m_properties->getMaxSlope(); } // Converts the supplied slope from degrees to radians. The corresponding getter // returns radians, so console input and output use different units. +// ELF 0x3A0960. void AIPathfinding::MapContainer::setMaxSlope(float degrees) { m_properties->setMaxSlope(0.017453292f * degrees); } +// ELF 0x3A0C50. void AIPathfinding::MapContainer::setHeadClearance(float clearance) { m_properties->setHeadClearance(clearance); } -float AIPathfinding::MapContainer::getHeadClearance() +// ELF 0x3A0C80. +float AIPathfinding::MapContainer::getHeadClearance() const { return m_properties->getHeadClearance(); } +// ELF 0x3A0BE0. void AIPathfinding::MapContainer::setRadius(float radius) { m_properties->setRadius(radius); } -float AIPathfinding::MapContainer::getRadius() +// ELF 0x3A0BB0. +float AIPathfinding::MapContainer::getRadius() const { return m_properties->getRadius(); } +// ELF 0x3A0C10. void AIPathfinding::MapContainer::setAllowedHeightDiff(float diff) { m_properties->setAllowedHeightDiff(diff); } // A direct member read - see the block above. -float AIPathfinding::MapContainer::getAllowedHeightDiff() +// ELF 0x3A0C40. +float AIPathfinding::MapContainer::getAllowedHeightDiff() const { return m_properties->m_allowedHeightDiff; } // Forwards map operations to QuadTreeManager. Build/load operations use m_name as the // file stem for quad-tree and GTS mesh data. -void AIPathfinding::MapContainer::draw() +// ELF 0x3A0CB0. +void AIPathfinding::MapContainer::draw() const { m_quadTreeManager->draw(); } -void AIPathfinding::MapContainer::undraw() +// ELF 0x3A0CE0. +void AIPathfinding::MapContainer::undraw() const { m_quadTreeManager->undraw(); } -void AIPathfinding::MapContainer::drawCluster() +// ELF 0x3A0D10. +void AIPathfinding::MapContainer::drawCluster() const { m_quadTreeManager->drawCluster(); } -void AIPathfinding::MapContainer::undrawCluster() +// ELF 0x3A0D40. +void AIPathfinding::MapContainer::undrawCluster() const { m_quadTreeManager->undrawCluster(); } -void AIPathfinding::MapContainer::drawClusterNeighbourIndices(const Vec3& position) +// ELF 0x3A0D70. +void AIPathfinding::MapContainer::drawClusterNeighbourIndices(const Vec3& position) const { m_quadTreeManager->drawClusterNeighbourIndices(position); } +// ELF 0x3A0DA0. void AIPathfinding::MapContainer::loadGTSDebugMeshes() { m_quadTreeManager->loadGTSDebugMeshes(m_name); } +// ELF 0x3A0DD0. void AIPathfinding::MapContainer::buildDebugMeshes() { m_quadTreeManager->buildDebugMeshes(m_name); } +// ELF 0x3A0E00. void AIPathfinding::MapContainer::unloadDebugMeshes() { m_quadTreeManager->unloadDebugMeshes(); } +// ELF 0x3A0E30. void AIPathfinding::MapContainer::buildDebugClusterMeshes() { m_quadTreeManager->buildDebugClusterMeshes(m_name); } +// ELF 0x3A0E60. void AIPathfinding::MapContainer::unloadDebugClusterMeshes() { m_quadTreeManager->unloadDebugClusterMeshes(); } +// ELF 0x3A0740. void AIPathfinding::MapContainer::saveQuadTrees() { m_quadTreeManager->saveQuadTrees(m_name); } // Loads navigation data and supplies its dimensions to the mine manager. +// ELF 0x3A0770. void AIPathfinding::MapContainer::loadQuadTrees() { m_quadTreeManager->loadQuadTrees(m_name); @@ -522,6 +733,7 @@ void AIPathfinding::MapContainer::loadQuadTrees() islands); } +// ELF 0x3A07F0. void AIPathfinding::MapContainer::loadGTSData(int a, float b) { // the tree parameters GO in depth-then-leaf order, which is the reverse of the order they are @@ -536,16 +748,19 @@ void AIPathfinding::MapContainer::loadGTSData(int a, float b) } // Appends a vehicle name only. init populates the parallel cost-type vector later. +// ELF 0x3A0880. void AIPathfinding::MapContainer::addVehicleForClusterCost(const std::string& vehicle) { m_clusterCostVehicles.push_back(vehicle); } +// ELF 0x3A0E90. void AIPathfinding::MapContainer::recalculatePortalCosts() { m_quadTreeManager->recalculatePortalCosts(m_id); } +// ELF 0x3A0470. void AIPathfinding::MapContainer::init() { // Build the map-local vehicle @@ -572,27 +787,85 @@ void AIPathfinding::MapContainer::init() } } -bool AIPathfinding::MapContainer::isValidPosition(const Vec3&, MaterialManager*, bool) const +// ELF 0x3A0F30. A position is valid when it lies on a polygon; unless `ignoreMaterial` is set, the +// polygon's material must also be readable and not 5. [INFERRED] name of the flag. +bool AIPathfinding::MapContainer::isValidPosition(const Vec3& position, MaterialManager* materials, + bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::isValidPosition"); -} - -bool AIPathfinding::MapContainer::isValidPosition(const Vec3&, MaterialManager*, unsigned int, - bool) const -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::isValidPosition"); + unsigned int polygon; + const unsigned int island = m_quadTreeManager->findPolygon( + position, polygon, materials, m_properties->m_allowedHeightDiff); + bool valid = false; + if (island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu) + { + valid = true; + if (!ignoreMaterial) + { + unsigned char material; + if (!getMaterial(island, polygon, material)) + return false; + if (material == 5) + return false; + } + } + return valid; } -bool AIPathfinding::MapContainer::isValidPosition(const Vec3&, MaterialManager*, unsigned int, - unsigned int, bool) const +// ELF 0x3A0FD0. The island is given; only that island's quad tree is searched. The return value of +// QuadTree::findPolygon and the polygon output are both tested. +bool AIPathfinding::MapContainer::isValidPosition(const Vec3& position, MaterialManager* materials, + unsigned int island, bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::isValidPosition"); + unsigned int polygon; + const bool found = m_quadTreeManager->getIsland(island)->findPolygon( + position, polygon, materials, m_properties->m_allowedHeightDiff); + bool valid = false; + if (found && polygon != 0xFFFFFFFFu) + valid = true; + if (valid && !ignoreMaterial) + { + unsigned char material; + if (!getMaterial(island, polygon, material)) + return false; + if (material == 5) + return false; + } + return valid; +} + +// ELF 0x3A1090. The known island and polygon seed the manager's search; note the order: the +// first unsigned argument is the island (0x3A10B7..0x3A10C8 pass the second as findPolygon's +// known polygon), the reverse of the getPolygon overload at 0x3A12A0. +bool AIPathfinding::MapContainer::isValidPosition(const Vec3& position, MaterialManager* materials, + unsigned int knownIsland, + unsigned int knownPolygon, + bool ignoreMaterial) const +{ + unsigned int polygon; + const unsigned int island = m_quadTreeManager->findPolygon( + position, polygon, knownPolygon, knownIsland, materials, + m_properties->m_allowedHeightDiff); + bool valid = false; + if (island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu) + { + valid = true; + if (!ignoreMaterial) + { + unsigned char material; + if (!getMaterial(island, polygon, material)) + return false; + if (material == 5) + return false; + } + } + return valid; } // Resolves polygon then island outputs. Always writes the full-width island result; // on failure it is UINT_MAX and the polygon output is unchanged. The vertex overload // appends without clearing, and known ids are validated before reuse. -bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, Vec3& position, +// ELF 0x3A1140. +bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, const Vec3& position, unsigned int& polygon, unsigned int& island, MaterialManager* materials) const { @@ -601,6 +874,7 @@ bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, return getPolygon(vertices, polygon, island); } +// ELF 0x3A11C0. bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, unsigned int polygon, unsigned int island) const { @@ -611,6 +885,7 @@ bool AIPathfinding::MapContainer::getPolygon(std::vector& vertices, return true; } +// ELF 0x3A1230. bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& polygon, unsigned int& island, MaterialManager* materials) const @@ -620,6 +895,7 @@ bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& return island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu; } +// ELF 0x3A12A0. bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& polygon, unsigned int& island, unsigned int knownPolygon, unsigned int knownIsland, @@ -630,32 +906,54 @@ bool AIPathfinding::MapContainer::getPolygon(const Vec3& position, unsigned int& return island != 0xFFFFFFFFu && polygon != 0xFFFFFFFFu; } -void AIPathfinding::MapContainer::getPolygonsInRadius(std::list&, unsigned int, - unsigned int, const Vec3&, float) const +// ELF 0x3A1320: forwarded unchanged to the quad-tree manager. +void AIPathfinding::MapContainer::getPolygonsInRadius(std::list& polygons, + unsigned int quadTree, unsigned int polygon, + const Vec3& centre, float radius) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonsInRadius"); + m_quadTreeManager->getPolygonsInRadius(polygons, quadTree, polygon, centre, radius); } -void AIPathfinding::MapContainer::getPolygonsInTriangle(std::list&, unsigned int, - unsigned int, const Vec3&, const Vec3&, - const Vec3&) const +// ELF 0x3A1370: forwarded unchanged to the quad-tree manager. +void AIPathfinding::MapContainer::getPolygonsInTriangle(std::list& polygons, + unsigned int quadTree, + unsigned int polygon, const Vec3& a, + const Vec3& b, const Vec3& c) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonsInTriangle"); + m_quadTreeManager->getPolygonsInTriangle(polygons, quadTree, polygon, a, b, c); } -bool AIPathfinding::MapContainer::getPolygonFromIsland(const Vec3&, unsigned int&, unsigned int&, - MaterialManager*) const +// ELF 0x3A13D0. Searches only the given island; QuadTree::findPolygon's own result is discarded and +// the polygon output decides. The island reference is read, never written. +bool AIPathfinding::MapContainer::getPolygonFromIsland(const Vec3& position, unsigned int& polygon, + unsigned int& island, + MaterialManager* materials) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonFromIsland"); + const float allowedHeightDiff = m_properties->m_allowedHeightDiff; + m_quadTreeManager->getIsland(island)->findPolygon(position, polygon, materials, + allowedHeightDiff); + return polygon != 0xFFFFFFFFu; } -bool AIPathfinding::MapContainer::getMaterial(const Vec3&, MaterialManager*, unsigned char&) const +// ELF 0x3A1440. The material is zeroed when no polygon is found. +bool AIPathfinding::MapContainer::getMaterial(const Vec3& position, MaterialManager* materials, + unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getMaterial"); + unsigned int polygon; + const unsigned int island = m_quadTreeManager->findPolygon( + position, polygon, materials, m_properties->m_allowedHeightDiff); + if (island == 0xFFFFFFFFu || polygon == 0xFFFFFFFFu) + { + material = 0; + return false; + } + material = m_quadTreeManager->getIsland(island)->getMaterialOfPolygon(polygon); + return true; } // UINT_MAX in either index is the only rejected input. Other // out-of-range values retain retail's unchecked island and polygon indexing. +// ELF 0x3A14E0. bool AIPathfinding::MapContainer::getMaterial(unsigned int quadTree, unsigned int polygon, unsigned char& material) const { @@ -669,45 +967,172 @@ bool AIPathfinding::MapContainer::getMaterial(unsigned int quadTree, unsigned in return true; } -bool AIPathfinding::MapContainer::setMaterial(unsigned int, unsigned int, unsigned char) +// ELF 0x3A1550. UINT_MAX in either index is rejected; other values index unchecked. +bool AIPathfinding::MapContainer::setMaterial(unsigned int quadTree, unsigned int polygon, + unsigned char material) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::setMaterial"); + if (quadTree == 0xFFFFFFFFu || polygon == 0xFFFFFFFFu) + return false; + m_quadTreeManager->getIsland(quadTree)->setMaterialOfPolygon(polygon, material); + return true; } -void AIPathfinding::MapContainer::getPolygonCentre(Vec3&, unsigned int, unsigned int) const +// ELF 0x3A15C0. +void AIPathfinding::MapContainer::getPolygonCentre(Vec3& centre, unsigned int polygon, + unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getPolygonCentre"); + m_quadTreeManager->getIsland(island)->getCentreOfPolygon(centre, polygon); } -void AIPathfinding::MapContainer::getEdge(Vec3&, Vec3&, unsigned int, unsigned int, - unsigned int) const +// ELF 0x3A1610. The shared edge of `polygon` towards `neighbour`: its two corners, the vertex at the +// neighbour's index and the next one (wrapping). False when the polygon id is out of range or the +// neighbour is not adjacent. +bool AIPathfinding::MapContainer::getEdge(Vec3& first, Vec3& second, unsigned int polygon, + unsigned int neighbour, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getEdge"); -} + const QuadTree* const quadTree = m_quadTreeManager->getIsland(island); + const Polygon* const record = quadTree->getPolygon(polygon); + if (record == 0) + return false; -bool AIPathfinding::MapContainer::trace(unsigned int&, unsigned int&, const Vec3&, const Vec3&, - Vec3&, unsigned int&, int, float, MaterialManager*, - unsigned char, unsigned char*) const -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::trace"); + unsigned char index = 0; + if (!quadTree->getNeighbourIndexForPolygon(index, polygon, neighbour)) + return false; + + first = *quadTree->getVertexForPolygon(polygon, index); + second = *quadTree->getVertexForPolygon( + polygon, static_cast((index + 1) % record->m_numberOfVertices)); + return true; } -bool AIPathfinding::MapContainer::traceKnown(unsigned int, unsigned int, const Vec3&, const Vec3&, - Vec3&, unsigned int&, int, float, MaterialManager*, - unsigned char, unsigned char*) const +// ELF 0x3A1720. Resolves the start polygon from the caller's hints (both written back), then traces +// from that known polygon. +bool AIPathfinding::MapContainer::trace(unsigned int& polygon, unsigned int& island, + const Vec3& from, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int maxSteps, float width, + MaterialManager* materials, unsigned char flags, + unsigned char* materialOut) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::traceKnown"); + island = m_quadTreeManager->findPolygon(from, polygon, polygon, island, materials, + m_properties->m_allowedHeightDiff); + if (polygon == 0xFFFFFFFFu || island == 0xFFFFFFFFu) + return false; + return traceKnown(polygon, island, from, to, end, endPolygon, maxSteps, width, materials, + flags, materialOut); +} + +// ELF 0x3A1800. Walks polygon to polygon along the XZ line from `from` towards `to`, starting in +// the known polygon. True when `to` is reached (within 0.05 along the line or 0.025 squared in +// XZ; `end` is then `to`), or when the very first polygon has no exit at all. False on a border, +// after `maxSteps` polygons (-1: no limit) or 30,001, on a material the vehicle cannot use, on +// `stopMaterial` (5 and 6 also stop on 7), or where a non-zero `width` does not fit through an +// edge. `endPolygon` tracks the last polygon entered; `end` the last edge crossing. +// [INFERRED] parameter names. +bool AIPathfinding::MapContainer::traceKnown(unsigned int polygon, unsigned int island, + const Vec3& from, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int maxSteps, float width, + MaterialManager* materials, + unsigned char stopMaterial, + unsigned char* materialOut) const +{ + const QuadTree* const quadTree = m_quadTreeManager->getIsland(island); + + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + const float length = + std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (!(length > 1e-6f)) + { + endPolygon = polygon; + return true; + } + const float inverse = 1.0f / length; + direction.x *= inverse; + direction.y *= inverse; + direction.z *= inverse; + + end = from; + unsigned int previousPolygon = 0xFFFFFFFFu; + endPolygon = polygon; + int steps = 0; + for (;;) + { + if (polygon == 0xFFFFFFFFu) + return false; + if (maxSteps != -1 && steps >= maxSteps) + return false; + if (steps > 30000) + return false; + endPolygon = polygon; + ++steps; + + float clearance; + // [CHOSEN, not recovered] The callee never writes its second float output, so retail + // compares an uninitialised stack value below. Zero keeps that width test inert. + float unused = 0.0f; + unsigned char edge; + const bool crossed = quadTree->getLineIntersectionOnEdgeInPolygon( + end, polygon, edge, previousPolygon, from, direction, + width == 0.0f ? 0 : &clearance, width == 0.0f ? 0 : &unused); + if (!crossed) + { + if (previousPolygon != 0xFFFFFFFFu) + return false; + end = to; + return true; + } + previousPolygon = polygon; + + const float dx = end.x - from.x; + const float dy = end.y - from.y; + const float dz = end.z - from.z; + if (std::sqrt(dx * dx + dy * dy + dz * dz) + 0.05f >= length || + 0.025f >= distXZSqr(to, end)) + { + end = to; + return true; + } + + if (width != 0.0f && unused > clearance + clearance && width > clearance) + return false; + + polygon = quadTree->getNeighbourOfPolygon(polygon, edge); + if (polygon == 0xFFFFFFFFu) + return false; + const unsigned char material = quadTree->getMaterialOfPolygon(polygon); + if (materialOut != 0) + *materialOut = material; + if (!materials->isValidMaterial(material)) + return false; + if (stopMaterial != 0) + { + if (material == stopMaterial) + return false; + if (static_cast(stopMaterial - 5) <= 1 && material == 7) + return false; + } + } } -bool AIPathfinding::MapContainer::getLineIntersectionWithPolygon(Vec3&, unsigned int, unsigned int, - const Vec3&, const Vec3&) const +// ELF 0x3A1B90. Any edge of the polygon (no previous edge, UINT_MAX) and no parameter outputs. +bool AIPathfinding::MapContainer::getLineIntersectionWithPolygon(Vec3& intersection, + unsigned int polygon, + unsigned int island, + const Vec3& from, + const Vec3& to) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::getLineIntersectionWithPolygon"); + unsigned char edge; + return m_quadTreeManager->getIsland(island)->getLineIntersectionOnEdgeInPolygon( + intersection, polygon, edge, 0xFFFFFFFFu, from, to, 0, 0); } -void AIPathfinding::MapContainer::drawPolygon(unsigned int, unsigned int, float*, float) const +// ELF 0x3A1C10. +void AIPathfinding::MapContainer::drawPolygon(unsigned int island, unsigned int polygon, + float* height, float duration) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::drawPolygon"); + m_quadTreeManager->getIsland(island)->drawPolygon(polygon, height, duration); } // Sample `limit` equally spaced points from @@ -715,8 +1140,9 @@ void AIPathfinding::MapContainer::drawPolygon(unsigned int, unsigned int, float* // advances `closest` once more after the final failed sample, so failure can leave it beyond `to`; // preserve that observable quirk. The output ids are cleared before the zero-limit return, polygon // first and island second, and receive the successful lookup in that same order. -bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& quadTree, - unsigned int& polygon, Vec3& closest, +// ELF 0x3A1C60. +bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& polygon, + unsigned int& island, Vec3& closest, const Vec3& from, const Vec3& to, unsigned int limit, MaterialManager* materials) const @@ -735,8 +1161,8 @@ bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& quadTree } closest = from; + island = 0xFFFFFFFFu; // stores 0x3A1D19 (second) then 0x3A1D1F (first) polygon = 0xFFFFFFFFu; - quadTree = 0xFFFFFFFFu; if (limit == 0) return false; @@ -754,74 +1180,239 @@ bool AIPathfinding::MapContainer::findClosestValidPolygon(unsigned int& quadTree return false; } + // 0x3A1D91..0x3A1D9F: the first reference receives getPolygon's polygon, the second its island. + island = foundIsland; polygon = foundPolygon; - quadTree = foundIsland; return true; } -void AIPathfinding::MapContainer::updateClusterPortalCosts( - unsigned int&, triple&, unsigned int, - unsigned short) +// ELF 0x3A0EC0. The map id is this container's own. +bool AIPathfinding::MapContainer::updateClusterPortalCosts( + unsigned int& resource, triple& portal, + unsigned int island, unsigned short costType) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::MapContainer::updateClusterPortalCosts"); + return m_quadTreeManager->getClusterGraph(island)->updatePortalCosts(resource, portal, m_id, + island, costType); } // AIPathfinding, the unwritten half // Resets destroyable map parts in every map's quad-tree manager. +// ELF 0x3A8680. void AIPathfinding::resetDestroyableMapParts() { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->resetDestroyableMapParts(); } -int AIPathfinding::localSearch(int, int, unsigned int, unsigned int, const Vec3&, unsigned int, - const Vec3&, int, QTPath*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::localSearch"); -} +// ELF 0x3A5430. Polls or starts the resource's navigation-mesh search. A failed (3) search reports +// that until the resource is released; a found (2) one hands its path over through +// internalLocalSearch with the polygon hints cleared. A new search needs all three polygon ids; +// otherwise the answer is 4 and nothing starts. Retail fetches the vehicle's material table here +// and discards it. +int AIPathfinding::localSearch(int resource, int map, unsigned int island, + unsigned int startPolygon, const Vec3& start, + unsigned int goalPolygon, const Vec3& goal, int vehicleId, + QTPath* path) +{ + const int status = m_engine->m_searches[resource]->m_status; + if (status == astarStatus::kFailed || status == astarStatus::kInvalid) + return status; + if (status == astarStatus::kFound) + return internalLocalSearch(resource, map, 0xFFFFFFFFu, 0xFFFFFFFFu, start, 0xFFFFFFFFu, + goal, vehicleId, path); + if (status == astarStatus::kSearching) + return status; -int AIPathfinding::clusterSearch(int, int, unsigned int, unsigned int, const Vec3&, unsigned int, - const Vec3&, int, ClusterNodePath*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::clusterSearch"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + settings->getVehicleMaterialManager(vehicleId); + if (island == 0xFFFFFFFFu || startPolygon == 0xFFFFFFFFu || goalPolygon == 0xFFFFFFFFu) + return astarStatus::kInvalid; + return internalLocalSearch(resource, map, island, startPolygon, start, goalPolygon, goal, + vehicleId, path); +} + +// ELF 0x3A5990. Polls or starts the resource's cluster-graph search. Failed (3) and invalid (4) +// report as such; a found one appends its path when a goal node exists. A new search runs on +// `island`'s cluster graph from the start polygon's cluster to the goal polygon's, with the +// vehicle's cluster cost type, the two positions and emptied open, overflow and closed sets. +// Unlike localSearch the polygon ids are not checked. +int AIPathfinding::clusterSearch(int resource, int map, unsigned int island, + unsigned int startPolygon, const Vec3& start, + unsigned int goalPolygon, const Vec3& goal, int vehicleId, + ClusterNodePath* path) +{ + ClusterResource* search = m_clusterEngine->m_searches[resource]; + const int status = search->m_status; + if (status == astarStatus::kFailed || status == astarStatus::kInvalid) + return status; + if (status == astarStatus::kFound) + { + if (search->m_goal != 0) + search->m_nodeManager->buildPath(*path, search->m_goal); + return status; + } + if (status == astarStatus::kSearching) + return status; + + ClusterNodeManager* const manager = search->m_nodeManager; + path->m_island = static_cast(island); + path->setVehicle(map, vehicleId); + + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + manager->setQuadTree(quadTree); + manager->setClusterGraph(m_maps[map]->m_quadTreeManager->getClusterGraph(island)); + + ClusterNode* const startNode = + manager->getNewNode(quadTree->getPolygon(startPolygon)->m_cluster, 0, 0); + ClusterNode* const goalNode = + manager->getNewNode(quadTree->getPolygon(goalPolygon)->m_cluster, 0, 0); + manager->m_start = start; + manager->m_goalPosition = goal; + manager->m_costType = m_maps[map]->m_clusterCostTypes[vehicleId]; + + search = m_clusterEngine->m_searches[resource]; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + search = m_clusterEngine->m_searches[resource]; + if (startNode->m_key == goalNode->m_key) + { + search->m_nodeManager->recycleNode(goalNode); + search->m_status = astarStatus::kFound; + search->m_goal = startNode; + return search->m_status; + } + + search->m_nodeManager->setGoal(goalNode); + search->pushOpenNode(startNode); + search->m_status = astarStatus::kSearching; + return search->m_status; } -int AIPathfinding::internalLocalSearch(int, int, unsigned int, unsigned int, const Vec3&, - unsigned int, const Vec3&, int, QTPath*) +// ELF 0x3A5550. While the resource is searching it only reports; once found it appends the path +// (when a goal node exists) and reports. Otherwise it starts a new search: the quad tree of +// `island`, a start and a goal node, the vehicle's material table, and emptied open, overflow and +// closed sets. A start already on the goal polygon is found at once; else the goal is stored and +// the start opened. +int AIPathfinding::internalLocalSearch(int resource, int map, unsigned int island, + unsigned int startPolygon, const Vec3& start, + unsigned int goalPolygon, const Vec3& goal, int vehicleId, + QTPath* path) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::internalLocalSearch"); + LocalResource* search = m_engine->m_searches[resource]; + if (search->m_status == astarStatus::kSearching || search->m_status == astarStatus::kFound) + { + search = m_engine->m_searches[resource]; + if (search->m_status == astarStatus::kFound && search->m_goal != 0) + search->m_nodeManager->buildPath(*path, search->m_goal); + return m_engine->m_searches[resource]->m_status; + } + + QTSearchNodeManager* const manager = search->m_nodeManager; + path->m_island = static_cast(island); + manager->setQuadTree(m_maps[map]->m_quadTreeManager->getIsland(island)); + + QTSearchNode* const startNode = manager->getNewNode(startPolygon, 0, 0); + startNode->m_position = start; + startNode->m_g = 0.0f; + QTSearchNode* const goalNode = manager->getNewNode(goalPolygon, 0, 0); + goalNode->m_position = goal; + + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + manager->m_materials = settings->getVehicleMaterialManager(vehicleId); + + search = m_engine->m_searches[resource]; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + search = m_engine->m_searches[resource]; + if (startNode->m_key == goalNode->m_key) + { + search->m_nodeManager->recycleNode(goalNode); + search->m_status = astarStatus::kFound; + search->m_goal = startNode; + return search->m_status; + } + + search->m_nodeManager->setGoal(goalNode); + search->pushOpenNode(startNode); + search->m_status = astarStatus::kSearching; + return search->m_status; } -bool AIPathfinding::isValidPosition(int, int, const Vec3&, bool) const +// ELF 0x3A70E0. A negative map index means "no map" and every position is valid; the upper bound +// is not checked. The next two overloads share the shape. +bool AIPathfinding::isValidPosition(int map, int vehicleId, const Vec3& position, + bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::isValidPosition"); + if (map < 0) + return true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->isValidPosition(position, materials, ignoreMaterial); } -bool AIPathfinding::isValidPosition(int, int, const Vec3&, unsigned int, bool) const +// ELF 0x3A7160. +bool AIPathfinding::isValidPosition(int map, int vehicleId, const Vec3& position, + unsigned int island, bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::isValidPosition"); + if (map < 0) + return true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->isValidPosition(position, materials, island, ignoreMaterial); } -bool AIPathfinding::isValidPosition(int, int, const Vec3&, unsigned int, unsigned int, bool) const +// ELF 0x3A71F0. +bool AIPathfinding::isValidPosition(int map, int vehicleId, const Vec3& position, + unsigned int knownIsland, unsigned int knownPolygon, + bool ignoreMaterial) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::isValidPosition"); + if (map < 0) + return true; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->isValidPosition(position, materials, knownIsland, knownPolygon, + ignoreMaterial); } -int AIPathfinding::getPolygon(std::vector&, int, const Vec3&, int) const +// ELF 0x3A7910. Unlike the Vec3-only overloads, the vertex overloads do not check the map index. +bool AIPathfinding::getPolygon(std::vector& vertices, int map, + const Vec3& position, int vehicleId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygon"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + unsigned int polygon; + unsigned int island; + return m_maps[map]->getPolygon(vertices, position, polygon, island, materials); } -int AIPathfinding::getPolygon(std::vector&, int, const Vec3&, unsigned int&, - unsigned int&, int) const +// ELF 0x3A78A0. +bool AIPathfinding::getPolygon(std::vector& vertices, int map, + const Vec3& position, unsigned int& polygon, + unsigned int& island, int vehicleId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygon"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->getPolygon(vertices, position, polygon, island, materials); } -int AIPathfinding::getPolygon(std::vector&, int, unsigned int, unsigned int) const +// ELF 0x3A7980. +bool AIPathfinding::getPolygon(std::vector& vertices, int map, + unsigned int polygon, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygon"); + return m_maps[map]->getPolygon(vertices, polygon, island); } // This is the saved-position variant used by the information @@ -829,6 +1420,7 @@ int AIPathfinding::getPolygon(std::vector&, int, unsigned int, unsi // they can be reused or whether it must fall back to a normal spatial search. As in the adjacent // overload, retail leaves both output references untouched when the map index is invalid and does // not guard the settings singleton. +// ELF 0x3A7A60. bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& polygon, unsigned int& quadTree, unsigned int knownPolygon, unsigned int knownQuadTree, int vehicleId) const @@ -843,77 +1435,141 @@ bool AIPathfinding::getPolygon(const Vec3& position, int map, unsigned int& poly materials); } -int AIPathfinding::getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const +// ELF 0x3A7BE0. The island is passed by value and handed down by reference to a local copy. +bool AIPathfinding::getPolygonFromIsland(const Vec3& position, int map, unsigned int& polygon, + unsigned int island, int vehicleId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygonFromIsland"); + if (map < 0 || getNumberOfMaps() <= map) + return false; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->getPolygonFromIsland(position, polygon, island, materials); } -bool AIPathfinding::getMaterial(const Vec3&, int, int, unsigned char&) const +// ELF 0x3A7C70. An invalid map index returns false and leaves the material untouched. +bool AIPathfinding::getMaterial(const Vec3& position, int map, int vehicleId, + unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getMaterial"); + if (map < 0 || getNumberOfMaps() <= map) + return false; + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->getMaterial(position, materials, material); } -void* AIPathfinding::getQuadTree(int, unsigned int) const +// ELF 0x3A7DF0. +void* AIPathfinding::getQuadTree(int map, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getQuadTree"); + return m_maps[map]->m_quadTreeManager->getIsland(island); } -void* AIPathfinding::getClusterGraph(int, unsigned int) const +// ELF 0x3A7E30. +void* AIPathfinding::getClusterGraph(int map, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getClusterGraph"); + return m_maps[map]->m_quadTreeManager->getClusterGraph(island); } -void AIPathfinding::getPolygonCentre(Vec3&, int, unsigned int, unsigned int) const +// ELF 0x3A7DA0. +void AIPathfinding::getPolygonCentre(Vec3& centre, int map, unsigned int polygon, + unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getPolygonCentre"); + m_maps[map]->getPolygonCentre(centre, polygon, island); } -void AIPathfinding::getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const +// ELF 0x3A7E70. +bool AIPathfinding::getEdge(Vec3& first, Vec3& second, int map, unsigned int polygon, + unsigned int neighbour, unsigned int island) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getEdge"); + return m_maps[map]->getEdge(first, second, polygon, neighbour, island); } -bool AIPathfinding::getLineIntersectionWithPolygon(Vec3&, int, unsigned int, unsigned int, - const Vec3&, const Vec3&) const +// ELF 0x3A7ED0. +bool AIPathfinding::getLineIntersectionWithPolygon(Vec3& intersection, int map, + unsigned int polygon, unsigned int island, + const Vec3& from, const Vec3& to) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getLineIntersectionWithPolygon"); + return m_maps[map]->getLineIntersectionWithPolygon(intersection, polygon, island, from, to); } -int AIPathfinding::getClusterOfPolygon(int, unsigned int, unsigned int) const +// ELF 0x3A7F80. The polygon's 16-bit cluster id; an out-of-range polygon dereferences null, as in +// retail. +int AIPathfinding::getClusterOfPolygon(int map, unsigned int island, unsigned int polygon) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getClusterOfPolygon"); + return m_maps[map]->m_quadTreeManager->getIsland(island)->getPolygon(polygon)->m_cluster; } -bool AIPathfinding::areNeighbouringClusters(int, unsigned int, unsigned short, - unsigned short) const +// ELF 0x3A7FD0. +bool AIPathfinding::areNeighbouringClusters(int map, unsigned int island, unsigned short first, + unsigned short second) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::areNeighbouringClusters"); + return m_maps[map]->m_quadTreeManager->getClusterGraph(island)->areNeighbours(first, second); } -void AIPathfinding::updateClusterPortalCosts(unsigned int&, +// ELF 0x3A8040. +bool AIPathfinding::updateClusterPortalCosts(unsigned int& resource, triple&, int, unsigned int, - unsigned short) + unsigned short>& portal, int map, + unsigned int island, unsigned short costType) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::updateClusterPortalCosts"); + return m_maps[map]->updateClusterPortalCosts(resource, portal, island, costType); } -bool AIPathfinding::trace(int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, - unsigned char, unsigned char*) const +// ELF 0x3A80A0. No polygon or island hint. +bool AIPathfinding::trace(int map, const Vec3& from, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int vehicleId, int maxSteps, float width, + unsigned char stopMaterial, unsigned char* materialOut) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::trace"); + return trace(0xFFFFFFFFu, 0xFFFFFFFFu, map, from, to, end, endPolygon, vehicleId, maxSteps, + width, stopMaterial, materialOut); } -bool AIPathfinding::trace(unsigned int, unsigned int, int, const Vec3&, const Vec3&, Vec3&, - unsigned int&, int, int, float, unsigned char, unsigned char*) const +// ELF 0x3A8120. The hints are local copies: the container's resolved ids are not handed back. +// No map-index check. +bool AIPathfinding::trace(unsigned int polygon, unsigned int island, int map, const Vec3& from, + const Vec3& to, Vec3& end, unsigned int& endPolygon, int vehicleId, + int maxSteps, float width, unsigned char stopMaterial, + unsigned char* materialOut) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::trace"); + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); + return m_maps[map]->trace(polygon, island, from, to, end, endPolygon, maxSteps, width, + materials, stopMaterial, materialOut); } -bool AIPathfinding::trace(BotNavigation*, bool, const Vec3&, Vec3&, unsigned int&, int, int, float, - unsigned char, unsigned char*) const +namespace { + +// [TEMP] BotNavigation::getTraceData (ELF 0x194F10, ai-bot's AIBot/BotNavigation) is declared but +// not recovered yet; request on coord/ai-requests.md. Replace with the direct call once it lands. +void traceDataOf(BotNavigation* navigation, int map, unsigned int& polygon, unsigned int& island, + Vec3& from) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::trace"); + navigation->getTraceData(map, polygon, island, from); +} + +} // anonymous namespace + +// ELF 0x3A81C0. Traces from the bot's current trace start: on the trace map when +// `useTraceMap`, else on the bot's own map (BotNavigation +0x50). The start position, polygon +// and island come from BotNavigation::getTraceData; without a polygon or island the answer is +// false. The trace itself is MapContainer::traceKnown, with the vehicle's material table. +bool AIPathfinding::trace(BotNavigation* navigation, bool useTraceMap, const Vec3& to, Vec3& end, + unsigned int& endPolygon, int vehicleId, int maxSteps, float width, + unsigned char stopMaterial, unsigned char* materialOut) const +{ + IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); + MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); // +0xB0 + const int map = useTraceMap ? m_traceMapIndex : navigation->getMapIndex(); + Vec3 from; + from.x = 0.0f; + from.y = 0.0f; + from.z = 0.0f; + unsigned int polygon; + unsigned int island; + traceDataOf(navigation, map, polygon, island, from); + if (polygon == 0xFFFFFFFFu || island == 0xFFFFFFFFu) + return false; + return m_maps[map]->traceKnown(polygon, island, from, to, end, endPolygon, maxSteps, width, + materials, stopMaterial, materialOut); } // The @@ -922,86 +1578,187 @@ bool AIPathfinding::trace(BotNavigation*, bool, const Vec3&, Vec3&, unsigned int // unguarded - no sign or bounds test on the map index (getPolygon above has one; this has none) // so the -666 "no trace map" sentinel would index before the vector. Both images. Retail always has // a trace map: `aiPathfinding.traceMap Infantry` (AIPathFinding.ai), bound at the foot of this file. -bool AIPathfinding::findClosestValidPolygon(unsigned int& quadTree, unsigned int& polygon, +// ELF 0x3A8310. +bool AIPathfinding::findClosestValidPolygon(unsigned int& polygon, unsigned int& island, Vec3& closest, int map, const Vec3& from, const Vec3& to, unsigned int limit, int vehicleId) const { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); MaterialManager* const materials = settings->getVehicleMaterialManager(vehicleId); // +0xB0 - return m_maps[map]->findClosestValidPolygon(quadTree, polygon, closest, from, to, limit, + return m_maps[map]->findClosestValidPolygon(polygon, island, closest, from, to, limit, materials); } -bool AIPathfinding::acquireResource(unsigned int&, int) +// ELF 0x3A73A0. Takes the first free local-search resource for `owner`. Fails (and writes +// UINT_MAX) while map parts are locking, when none is free, or when the first free one is still +// owned. The id moves from the free list to the back of the in-flight list. +bool AIPathfinding::acquireResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::acquireResource"); + if (m_locking) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list& available = m_engine->m_available; + if (available.empty()) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list::iterator first = available.begin(); + resource = *first; + LocalResource* const search = m_engine->m_searches[resource]; + if (search->m_owner >= 0) + { + resource = 0xFFFFFFFFu; + return false; + } + + search->m_owner = owner; + available.erase(first); + m_engine->m_inFlight.insert(m_engine->m_inFlight.end(), resource); + return true; } -void AIPathfinding::releaseResource(unsigned int&, int) +// ELF 0x3A7480. Only the owner can release. Clears the search limits, the node manager's per-search +// options and the status, returns the id to the back of the free list and invalidates the +// caller's handle. +void AIPathfinding::releaseResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::releaseResource"); + if (m_engine->m_searches[resource]->m_owner != owner) + return; + + m_engine->m_searches[resource]->m_owner = -1; + LocalResource* const search = m_engine->m_searches[resource]; + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_status = 0; + search->m_owner = -1; + m_engine->m_available.insert(m_engine->m_available.end(), resource); + m_engine->m_inFlight.remove(resource); + resource = 0xFFFFFFFFu; } -bool AIPathfinding::acquireClusterResource(unsigned int&, int) +// ELF 0x3A7560 (the local body on the cluster engine). Takes the first free cluster-search resource for `owner`. Fails (and writes +// UINT_MAX) while map parts are locking, when none is free, or when the first free one is still +// owned. The id moves from the free list to the back of the in-flight list. +bool AIPathfinding::acquireClusterResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::acquireClusterResource"); + if (m_locking) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list& available = m_clusterEngine->m_available; + if (available.empty()) + { + resource = 0xFFFFFFFFu; + return false; + } + + std::list::iterator first = available.begin(); + resource = *first; + ClusterResource* const search = m_clusterEngine->m_searches[resource]; + if (search->m_owner >= 0) + { + resource = 0xFFFFFFFFu; + return false; + } + + search->m_owner = owner; + available.erase(first); + m_clusterEngine->m_inFlight.insert(m_clusterEngine->m_inFlight.end(), resource); + return true; } -void AIPathfinding::releaseClusterResource(unsigned int&, int) +// ELF 0x3A7640 (the local body on the cluster engine). Only the owner can release. Clears the search limits, the node manager's per-search +// options and the status, returns the id to the back of the free list and invalidates the +// caller's handle. +void AIPathfinding::releaseClusterResource(unsigned int& resource, int owner) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::releaseClusterResource"); + if (m_clusterEngine->m_searches[resource]->m_owner != owner) + return; + + m_clusterEngine->m_searches[resource]->m_owner = -1; + ClusterResource* const search = m_clusterEngine->m_searches[resource]; + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_status = 0; + search->m_owner = -1; + m_clusterEngine->m_available.insert(m_clusterEngine->m_available.end(), resource); + m_clusterEngine->m_inFlight.remove(resource); + resource = 0xFFFFFFFFu; } -// Search-record mutations remain unimplemented: status, iteration/depth limits, -// additional goals, allowed clusters, and smoothing must use the confirmed record layout. -void AIPathfinding::setMaxIterationsForResource(unsigned int&, unsigned int) +// ELF 0x3A7720. +void AIPathfinding::setMaxIterationsForResource(unsigned int& resource, unsigned int iterations) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setMaxIterationsForResource"); + m_engine->m_searches[resource]->m_maxIterations = iterations; } -void AIPathfinding::setMaxSearchDepthForResource(unsigned int&, unsigned int) +// ELF 0x3A7740. +void AIPathfinding::setMaxSearchDepthForResource(unsigned int& resource, unsigned int depth) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setMaxSearchDepthForResource"); + m_engine->m_searches[resource]->m_maxSearchDepth = depth; } -void AIPathfinding::setAdditionalGoals(unsigned int, const std::set*) +// ELF 0x3A8460. The set is borrowed, not copied; releaseResource clears the pointer. +void AIPathfinding::setAdditionalGoals(unsigned int resource, const std::set* goals) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setAdditionalGoals"); + m_engine->m_searches[resource]->m_nodeManager->m_additionalGoals = goals; } -void AIPathfinding::setAllowedClusters(unsigned int, const std::set*) +// ELF 0x3A8480. Borrowed as well; releaseResource leaves it set. +void AIPathfinding::setAllowedClusters(unsigned int resource, + const std::set* clusters) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setAllowedClusters"); + m_engine->m_searches[resource]->m_nodeManager->m_allowedClusters = clusters; } -void AIPathfinding::setUsePathTopologySmoothing(unsigned int, bool) +// ELF 0x3A84A0. +void AIPathfinding::setUsePathTopologySmoothing(unsigned int resource, bool use) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setUsePathTopologySmoothing"); + m_engine->m_searches[resource]->m_nodeManager->m_usePathTopologySmoothing = use; } -int AIPathfinding::getStatus(unsigned int) const +// ELF 0x3A7760. The local engine's status word; cluster searches have their own. +int AIPathfinding::getStatus(unsigned int resource) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getStatus"); + return m_engine->m_searches[resource]->m_status; } -void AIPathfinding::setStatus(unsigned int, astar::Status) +// ELF 0x3A7780. +void AIPathfinding::setStatus(unsigned int resource, astar::Status status) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setStatus"); + m_engine->m_searches[resource]->m_status = status; } -void AIPathfinding::updateQuadTree(unsigned int, int, unsigned int) +// ELF 0x3A77A0. Points the resource's node manager at another quad tree. +void AIPathfinding::updateQuadTree(unsigned int resource, int map, unsigned int island) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::updateQuadTree"); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + m_engine->m_searches[resource]->m_nodeManager->setQuadTree(quadTree); } -float AIPathfinding::calculateCostOfPath(unsigned int, int, unsigned int, const QTPath&) const +// ELF 0x3A7810. Costs `path` with the resource's node manager, which keeps the material table of +// its last search. +float AIPathfinding::calculateCostOfPath(unsigned int resource, int map, unsigned int island, + const QTPath& path) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::calculateCostOfPath"); + QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); + m_engine->m_searches[resource]->m_nodeManager->setQuadTree(quadTree); + return m_engine->m_searches[resource]->m_nodeManager->calculateCostOfPath(path); } // Splits the time budget between cluster and polygon searches by queue length. // With both queues empty, the cluster share is NaN and no cluster work runs. +// ELF 0x3A8390. void AIPathfinding::updatePathfinding(double budget) { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -1014,6 +1771,7 @@ void AIPathfinding::updatePathfinding(double budget) } // Assigns an ID to a destroyable map part and propagates its lifecycle to all navigation meshes. +// ELF 0x3A84C0. void AIPathfinding::initializeDestroyableMapPart(int& mapPartId, bool walkable, const Vec3& minCorner, const Vec3& maxCorner, const Mat4& transformation) { @@ -1023,52 +1781,234 @@ void AIPathfinding::initializeDestroyableMapPart(int& mapPartId, bool walkable, maxCorner, transformation); } +// ELF 0x3A8560. void AIPathfinding::destroyMapPart(int mapPartId) { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->destroyMapPart(mapPartId); } +// ELF 0x3A85C0. void AIPathfinding::restoreMapPart(int mapPartId) { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->restoreMapPart(mapPartId); } +// ELF 0x3A8620. void AIPathfinding::resetOriginalMaterialOfDestroyableMapPart(int mapPartId) { for (unsigned int i = 0; i < m_maps.size(); ++i) m_maps[i]->m_quadTreeManager->resetOriginalMaterialOfDestroyableMapPart(mapPartId); } -void AIPathfinding::searchPointSelected(bool) +// ELF 0x3A42F0. Selects the two debug endpoints with a two-second click interval. +void AIPathfinding::searchPointSelected(bool resetPoints) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::searchPointSelected"); + if (!m_activatePathfindingDebugTool) + return; + const double nextSelection = m_d36 + 2.0; + if (nextSelection >= + static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime()) + return; + if (resetPoints || m_searchPointToSet == 2) + { + m_d36 = -1000.0; + m_searchPointToSet = 0; + m_debugPath->m_nodes.resize(0); + m_debugPath->m_i0 = 0; + m_debugPath->m_i20 = 0.0f; + if (resetPoints) + return; + } + m_d36 = static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime(); + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + Mat4 camera = {{1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}}; + environment->getLocalPlayerCameraTransformation(camera); + const Vec3 origin = {camera.m[12], camera.m[13], camera.m[14]}; + const Vec3 end = {camera.m[8] * 250.0f + origin.x, + camera.m[9] * 250.0f + origin.y, + camera.m[10] * 250.0f + origin.z}; + if (!environment->collideLineWithWorld(origin, end, 0, m_searchPoint[m_searchPointToSet])) + return; + if (!isValidPosition(m_pathfindingDebugToolVehicleId != 3, + m_pathfindingDebugToolVehicleId, + *m_searchPoint[m_searchPointToSet], true)) + return; + unsigned int resource = 0xFFFFFFFFu; + unsigned int fromPolygon, island; + getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, + fromPolygon, island, m_pathfindingDebugToolVehicleId); + if (island == 0xFFFFFFFFu || fromPolygon == 0xFFFFFFFFu) + return; + if (m_searchPointToSet == 0 && m_clusterSearch) + { + QuadTree* const tree = m_maps[m_pathfindingDebugToolVehicleId != 3] + ->m_quadTreeManager->getIsland(island); + const Polygon* const polygon = tree->getPolygon(fromPolygon); + const int type = m_maps[m_pathfindingDebugToolVehicleId != 3] + ->m_clusterCostTypes[m_pathfindingDebugToolVehicleId]; + m_maps[m_pathfindingDebugToolVehicleId != 3]->m_quadTreeManager + ->getClusterGraph(island)->drawCluster(polygon->m_cluster, type); + } + unsigned int toPolygon; + // shipped defect: this also queries the second endpoint before the first click completes. + getPolygonFromIsland(*m_searchPoint[1], m_pathfindingDebugToolVehicleId != 3, + toPolygon, island, m_pathfindingDebugToolVehicleId); + if (toPolygon == 0xFFFFFFFFu) + return; + if (m_searchPointToSet == 1) + { + const bool acquired = !m_clusterSearch ? acquireResource(resource, 2000) + : acquireClusterResource(resource, 2000); + if (!acquired) + { + m_searchPointToSet = 1; + return; + } + } + if (++m_searchPointToSet != 2) + return; + if (!m_clusterSearch) + { + m_debugPath->m_nodes.resize(0); + m_debugPath->m_i0 = 0; + m_debugPath->m_i20 = 0.0f; + if (localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugPath) != 2) + { + while (m_engine->m_searches[resource]->m_status == 1) + m_engine->update(10.0); + localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugPath); + } + } + else + { + m_debugClusterPath->m_nodes.resize(0); + m_debugClusterPath->m_i0 = 0; + if (clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath) != 2) + { + while (m_clusterEngine->m_searches[resource]->m_status == 1) + m_clusterEngine->update(10.0); + clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath); + } + } + if (!m_clusterSearch) + releaseResource(resource, 2000); + else + releaseClusterResource(resource, 2000); } -bool AIPathfinding::tryPath(const Vec3&, const Vec3&) +// ELF 0x3A4D30. Failed endpoint lookup leaves the acquired debug resource owned, as shipped. +void AIPathfinding::tryPath(const Vec3& from, const Vec3& to) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::tryPath"); + unsigned int resource = 0xFFFFFFFFu; + if (!acquireResource(resource, 2000)) + return; + AIRenderUtil::m_instance->unrendenderPathfindingDebug(); + m_searchPointToSet = 2; + m_d36 = -1000.0; + *m_searchPoint[0] = from; + *m_searchPoint[1] = to; + m_debugPath->m_nodes.resize(0); + m_debugPath->m_i0 = 0; + m_debugPath->m_i20 = 0.0f; + unsigned int fromPolygon, island, toPolygon; + getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, + fromPolygon, island, m_pathfindingDebugToolVehicleId); + if (island == 0xFFFFFFFFu || fromPolygon == 0xFFFFFFFFu) + return; + getPolygonFromIsland(*m_searchPoint[1], m_pathfindingDebugToolVehicleId != 3, + toPolygon, island, m_pathfindingDebugToolVehicleId); + if (toPolygon == 0xFFFFFFFFu) + return; + m_debugPath->m_nodes.resize(0); + m_debugPath->m_i0 = 0; + m_debugPath->m_i20 = 0.0f; + if (localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugPath) != 2) + { + while (m_engine->m_searches[resource]->m_status == 1) + m_engine->update(10.0); + localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugPath); + } + releaseResource(resource, 2000); } -bool AIPathfinding::tryClusterPath(const Vec3&, const Vec3&) +// ELF 0x3A5060. Clears the local path first even for a cluster search. +void AIPathfinding::tryClusterPath(const Vec3& from, const Vec3& to) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::tryClusterPath"); + unsigned int resource = 0xFFFFFFFFu; + if (!acquireClusterResource(resource, 2000)) + return; + AIRenderUtil::m_instance->unrendenderPathfindingDebug(); + m_searchPointToSet = 2; + m_d36 = -1000.0; + *m_searchPoint[0] = from; + *m_searchPoint[1] = to; + m_debugPath->m_nodes.resize(0); + m_debugPath->m_i0 = 0; + m_debugPath->m_i20 = 0.0f; + unsigned int fromPolygon, island, toPolygon; + getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, + fromPolygon, island, m_pathfindingDebugToolVehicleId); + if (island == 0xFFFFFFFFu || fromPolygon == 0xFFFFFFFFu) + return; + getPolygonFromIsland(*m_searchPoint[1], m_pathfindingDebugToolVehicleId != 3, + toPolygon, island, m_pathfindingDebugToolVehicleId); + if (toPolygon == 0xFFFFFFFFu) + return; + m_debugClusterPath->m_nodes.resize(0); + m_debugClusterPath->m_i0 = 0; + if (clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath) != 2) + { + while (m_clusterEngine->m_searches[resource]->m_status == 1) + m_clusterEngine->update(10.0); + clusterSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, + *m_searchPoint[0], toPolygon, *m_searchPoint[1], + m_pathfindingDebugToolVehicleId, m_debugClusterPath); + } + releaseClusterResource(resource, 2000); } -void AIPathfinding::setActivatePathfindingDebugTool(bool) +// ELF 0x3A6750. Disabling clears only the polygon path and the endpoint selection. +void AIPathfinding::setActivatePathfindingDebugTool(bool active) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::setActivatePathfindingDebugTool"); + m_activatePathfindingDebugTool = active; + if (!active) + { + m_debugPath->m_nodes.resize(0); + m_debugPath->m_i0 = 0; + m_debugPath->m_i20 = 0.0f; + m_searchPointToSet = 0; + } } -void* AIPathfinding::getEquipmentTypeFromClusterCostType(int, unsigned short) const +// ELF 0x3AE230. Returns the settings vehicle ID for the map's cluster-cost vehicle name. +int AIPathfinding::getEquipmentTypeFromClusterCostType(int map, unsigned short type) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::getEquipmentTypeFromClusterCostType"); + return static_cast(CommonSingletonServer::m_iaiSettings) + ->getVehicle(m_maps[map]->m_clusterCostVehicles[type]); } -// IAIPathfindingSetup, the half that is now one body shorter - // Allocates the search-resource pool: one resource per four bots, with a minimum of two. +// ELF 0x3A33F0. void AIPathfinding::init() { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); @@ -1081,16 +2021,16 @@ void AIPathfinding::init() resource->m_maxIterations = 30000; m_engine->m_searches.push_back(resource); - resource->m_i16 = 0; + resource->m_iterations = 0; resource->m_openSize = 21; resource->m_hashSize = 1031; resource->m_open = checkPointer(new BinarySearchTree(21)); - resource->m_closed = + resource->m_openOverflow = checkPointer(new Hash(1031)); - resource->m_cache = + resource->m_closed = checkPointer(new Hash(1031)); - resource->m_closed->m_nodeManager = resource->m_nodeManager; - resource->m_cache->m_nodeManager = resource->m_nodeManager; + resource->m_openOverflow->m_nodeManager = resource->m_nodeManager; + resource->m_closed->m_nodeManager = resource->m_nodeManager; m_engine->m_available.push_back( static_cast(m_engine->m_searches.size() - 1)); @@ -1101,16 +2041,16 @@ void AIPathfinding::init() clusterResource->m_maxIterations = 5000; m_clusterEngine->m_searches.push_back(clusterResource); - clusterResource->m_i16 = 0; + clusterResource->m_iterations = 0; clusterResource->m_openSize = 13; clusterResource->m_hashSize = 313; clusterResource->m_open = checkPointer(new BinarySearchTree(13)); - clusterResource->m_closed = + clusterResource->m_openOverflow = checkPointer(new Hash(313)); - clusterResource->m_cache = + clusterResource->m_closed = checkPointer(new Hash(313)); - clusterResource->m_closed->m_nodeManager = clusterResource->m_nodeManager; - clusterResource->m_cache->m_nodeManager = clusterResource->m_nodeManager; + clusterResource->m_openOverflow->m_nodeManager = clusterResource->m_nodeManager; + clusterResource->m_closed->m_nodeManager = clusterResource->m_nodeManager; m_clusterEngine->m_available.push_back( static_cast(m_clusterEngine->m_searches.size() - 1)); @@ -1118,6 +2058,7 @@ void AIPathfinding::init() } // Creates and selects a named map. Duplicate names fail and clear the active selection. +// ELF 0x3A6820. bool AIPathfinding::createMap(const std::string& name) { if (m_mapIds.find(name) != m_mapIds.end()) @@ -1137,6 +2078,7 @@ bool AIPathfinding::createMap(const std::string& name) } // Deletes the active map. The supplied map argument does not select the map to remove. +// ELF 0x3A6BA0. bool AIPathfinding::deleteMap(const std::string& name) { const std::map::iterator i = m_mapIds.find(name); @@ -1152,12 +2094,15 @@ bool AIPathfinding::deleteMap(const std::string& name) return true; } +// ELF 0x3A6FE0. void AIPathfinding::saveQuadTrees() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::saveQuadTrees"); + for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) + (*i)->saveQuadTrees(); } // Loads quad trees and notifies the strategic layer after loading. +// ELF 0x3A7020. void AIPathfinding::loadQuadTrees() { for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) @@ -1166,30 +2111,266 @@ void AIPathfinding::loadQuadTrees() AIStrategicObjectManager::getInstance()->initAreas(); } +// ELF 0x3A7070. void AIPathfinding::loadGTSData() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::loadGTSData"); + int map = 0; + for (std::vector::iterator i = m_maps.begin(); i != m_maps.end(); ++i) + { + const float radius = (*i)->getRadius(); + (*i)->loadGTSData(map++, radius); + } + AIStrategicObjectManager::getInstance()->initAreas(); } +// ELF 0x3AD260. bool AIPathfinding::exportGTSMeshes() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::exportGTSMeshes"); -} - -bool AIPathfinding::exportGTSMeshesWithinBoundary(const Vec2&, const Vec2&) const -{ - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::exportGTSMeshesWithinBoundary"); + std::list meshes; + std::list water; + std::map addOns; + std::list ladders; + std::pair bounds = {}; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + if (!environment->initAiCombatAreas()) + return false; + const std::string overgrowth = static_cast(CommonSingletonServer::m_iaiGame) + ->getLevelPath() + "/overgrowth/OvergrowthCollision.con"; + if (!environment->loadOvergrowthCollision(overgrowth)) + return false; + const unsigned char layer = static_cast(environment->getAiCombatAreaLayer()); + if (!environment->getAllStaticCollisionMeshes(meshes, water, addOns, ladders, bounds, layer)) + return false; + std::vector vertices; + std::vector> edges; + std::list> faces; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + terrain->getAllTerrainPolygons(bounds, vertices, edges, faces); + if (!MeshImporterExporter::exportMesh(vertices, edges, faces, "Ground")) + return false; + return createGTSFiles(meshes, water, addOns, ladders, terrain, layer); } -// 18,942 bytes in retail - the offline level compiler. Nothing on a server route reaches it. -bool AIPathfinding::createGTSFiles(std::list&, std::list&, - std::map&, std::list&, - IAITerrain*, unsigned char) const +// ELF 0x3ADA70. +bool AIPathfinding::exportGTSMeshesWithinBoundary(const Vec2& min, const Vec2& max) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::createGTSFiles"); + std::list meshes; + std::list water; + std::map addOns; + std::list ladders; + std::pair bounds = {}; + IAIObjectEnvironment* const environment = + static_cast(CommonSingletonServer::m_iaiObjectEnvironment); + if (!environment->initAiCombatAreas()) + return false; + const std::string overgrowth = static_cast(CommonSingletonServer::m_iaiGame) + ->getLevelPath() + "/overgrowth/OvergrowthCollision.con"; + if (!environment->loadOvergrowthCollision(overgrowth)) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/AIPathfinding.cpp", 2653, "") + << "Couldn't load OvergrowthCollision.con\nABORTING EXPORT!"; + // shipped defect: if the diagnostic is filtered, export continues. + } + const unsigned char layer = static_cast(environment->getAiCombatAreaLayer()); + if (!environment->getAllStaticCollisionMeshesWithinBoundary( + min, max, meshes, water, addOns, ladders, bounds, layer)) + return false; + std::vector vertices; + std::vector> edges; + std::list> faces; + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + terrain->getAllTerrainPolygonsWithinBoundary(bounds, min, max, vertices, edges, faces); + if (!MeshImporterExporter::exportMesh(vertices, edges, faces, "Ground")) + return false; + return createGTSFiles(meshes, water, addOns, ladders, terrain, layer); +} + +// ELF 0x3A86D0. Resets the stream contents and appends a prefix and five-digit decimal index. +void getFileName(std::stringstream& stream, const std::string& prefix, int index) +{ + stream.str(""); + stream << prefix; + if (index <= 9) + stream << "0000" << index; + else if (index <= 99) + stream << "000" << index; + else if (index <= 999) + stream << "00" << index; + else if (index <= 9999) + stream << "0" << index; + else + stream << index; +} + +// ELF 0x3A8860. Exports navigation input meshes and the generator configuration. +bool AIPathfinding::createGTSFiles( + std::list& meshes, + std::list& water, + std::map& addOns, + std::list& ladders, + IAITerrain* terrain, unsigned char layer) const +{ + bool success = false; + MapContainer* const infantry = m_maps[0]; + MapContainer* const vehicle = m_maps[1]; + std::stringstream config; + config << "MaxSlopeInfantry: " << infantry->getMaxSlope() << std::endl; + config << "MaxSlopeVehicle: " << vehicle->getMaxSlope() << std::endl; + config << "RadiusInfantry: " << infantry->getRadius() << std::endl; + config << "RadiusVehicle: " << vehicle->getRadius() << std::endl; + config << "HeadClearanceInfantry: " << infantry->getHeadClearance() << std::endl; + config << "HeadClearanceVehicle: " << vehicle->getHeadClearance() << std::endl; + config << "MaxWaterDepth: " << getMaxWaterDepth() << std::endl; + config << "WaterLevel: " << terrain->getSeaWaterLevel() << std::endl; + std::vector infantryPoints; + static_cast(CommonSingletonServer::m_iaiGame) + ->getSpawnPointPositions(infantryPoints, layer); + config << "Infantry_NumberOfKeyPoints: " << infantryPoints.size() << std::endl; + for (unsigned int i = 0; i < infantryPoints.size(); ++i) + config << infantryPoints[i].x << " " << infantryPoints[i].y << " " + << infantryPoints[i].z << std::endl; + std::vector vehiclePoints; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getVehicleSpawnerPositions(vehiclePoints, layer); + config << "Vehicle_NumberOfKeyPoints: " << vehiclePoints.size() << std::endl; + for (unsigned int i = 0; i < vehiclePoints.size(); ++i) + config << vehiclePoints[i].x << " " << vehiclePoints[i].y << " " + << vehiclePoints[i].z << std::endl; + std::stringstream meshName, boxName, addOnName; + config << "NumberOfMeshes: " << meshes.size() << std::endl; + int meshIndex = 0; + for (std::list::iterator i = meshes.begin(); + i != meshes.end(); ++i) + { + getFileName(meshName, "Object", meshIndex); + getFileName(boxName, "ObjectBB", meshIndex); + // shipped defect: each ordinary mesh overwrites previous export failures. + success = MeshImporterExporter::exportMesh(i->mesh.vertices, i->mesh.edges, + i->mesh.faces, meshName.str()) && + MeshImporterExporter::exportMesh(i->boundingBox.vertices, i->boundingBox.edges, + i->boundingBox.faces, boxName.str()); + config << meshName.str() << " " << i->name << std::endl; + meshName.str(""); + boxName.str(""); + ++meshIndex; + } + config << "NumberOfDestructableMeshes: " << addOns.size() << std::endl; + int addOnIndex = 0; + for (std::map::iterator + i = addOns.begin(); i != addOns.end(); ++i) + { + const std::string walkable = i->second.initiallyWalkable ? "IW" : "INW"; + getFileName(addOnName, "ObjectDestr", addOnIndex); + config << addOnName.str() << " " << walkable << std::endl; + success = success && MeshImporterExporter::exportMesh( + i->second.mesh.vertices, i->second.mesh.edges, + i->second.mesh.faces, addOnName.str()); + ++addOnIndex; + } + std::stringstream waterName; + config << "NumberOfWaterMeshes: " << water.size() << std::endl; + int waterIndex = 0; + for (std::list::iterator i = water.begin(); + i != water.end(); ++i) + { + getFileName(waterName, "ObjectWaterMesh", waterIndex); + success = success && MeshImporterExporter::exportMesh( + i->mesh.vertices, i->mesh.edges, i->mesh.faces, waterName.str()); + config << waterName.str() << std::endl; + ++waterIndex; + waterName.str(""); + } + config << "NumberOfLadders: " << ladders.size() << std::endl; + int ladderIndex = 0; + for (std::list::iterator i = ladders.begin(); + i != ladders.end(); ++i) + { + getFileName(meshName, "Ladder", ladderIndex); + getFileName(boxName, "LaddertBB", ladderIndex); + // shipped defect: ladders also overwrite the accumulated failure status. + success = MeshImporterExporter::exportMesh(i->mesh.vertices, i->mesh.edges, + i->mesh.faces, meshName.str()) && + MeshImporterExporter::exportMesh(i->boundingBox.vertices, i->boundingBox.edges, + i->boundingBox.faces, boxName.str()); + config << meshName.str() << " " << i->name << std::endl; + meshName.str(""); + boxName.str(""); + ++ladderIndex; + } + const std::string levelPath = static_cast(CommonSingletonServer::m_iaiGame) + ->getLevelPath(); + bool deleted; + do + { + deleted = false; + getFileName(meshName, "Object", meshIndex); + getFileName(boxName, "ObjectBB", meshIndex); + getFileName(addOnName, "ObjectDestr", addOnIndex); + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts"); + deleted = true; + } + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts"); + deleted = true; + } + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + addOnName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + addOnName.str() + ".gts"); + deleted = true; + } + ++meshIndex; + ++addOnIndex; + meshName.str(""); + boxName.str(""); + addOnName.str(""); + getFileName(meshName, "Ladder", ladderIndex); + getFileName(boxName, "LaddertBB", ladderIndex); + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + meshName.str() + ".gts"); + deleted = true; + } + if (io::fileManager->fileExists(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts")) + { + io::fileManager->deleteFile(levelPath + "/GTSData/Meshes/" + boxName.str() + ".gts"); + deleted = true; + } + ++ladderIndex; + meshName.str(""); + boxName.str(""); + } while (deleted); + { + io::File file; + if (!file.open(levelPath + "/GTSData/Meshes/config.dat", + static_cast(0), static_cast(1), 0)) + return false; + file.write(config.str()); + file.close(); + } + { + io::File file; + if (!file.open(levelPath + "/GTSData/Meshes/CombatArea.dat", + static_cast(0), static_cast(1), 0)) + return false; + std::stringstream combatArea; + std::list points; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getAICombatArea(points); + combatArea << points.size() << std::endl; + for (std::list::iterator i = points.begin(); i != points.end(); ++i) + combatArea << i->x << " " << i->y << std::endl; + file.write(combatArea.str()); + file.close(); + } + return success; } // Returns virtual getName results joined by newlines, with no trailing newline. +// ELF 0x3A6E90. std::string AIPathfinding::getMapList() { std::string list; @@ -1205,103 +2386,24 @@ std::string AIPathfinding::getMapList() return list; } +// ELF 0x3A09C0. Draws a line between each object's two transformed bounds corners. void AIPathfinding::drawDynamicAIObjects() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPathfinding::drawDynamicAIObjects"); -} - -// Console bindings for pathfinding configuration and map loading. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -// a free function of the generated console TU: the setup's active map, or null -// without a setup. Every `map.*` binding reads through it, and tests it. -IAIPathfindingSetup::IMapContainer* getActiveMapContainer() -{ - if (!IAIPathfindingSetup::instance) - return 0; - return IAIPathfindingSetup::instance->getActiveMapContainer(); // +0x50 -} - -namespace { - -const char* const kAiPathfindingConsoleTag = "aiPathfinding"; - -// No null test on the instance: the binding's isObjectActive is the guard, as in the executor. -bool consoleAiPathfindingCreateMap(const std::string& name) -{ - return IAIPathfindingSetup::instance->createMap(name); // +0x10 -} - -} // anonymous namespace - -BF2_CONSOLE_OBJECT("AIPathFinding", 2, 0) -BF2_CONSOLE_METHOD_1_RET_ACTIVE(createMap, consoleAiPathfindingCreateMap, bool, - IAIPathfindingSetup::instance != 0, std::string, - kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN(activeMap, std::string, IAIPathfindingSetup::instance != 0, - IAIPathfindingSetup::instance->getActiveMap(), - IAIPathfindingSetup::instance->setActiveMap, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN(traceMap, std::string, IAIPathfindingSetup::instance != 0, - IAIPathfindingSetup::instance->getTraceMap(), - IAIPathfindingSetup::instance->setTraceMap, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.maxSlope", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getMaxSlope(), - getActiveMapContainer()->setMaxSlope, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.headClearance", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getHeadClearance(), - getActiveMapContainer()->setHeadClearance, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.radius", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getRadius(), - getActiveMapContainer()->setRadius, kAiPathfindingConsoleTag) -BF2_CONSOLE_PROPERTY_FN_NAMED("map.allowedHeightDiff", float, getActiveMapContainer() != 0, - getActiveMapContainer()->getAllowedHeightDiff(), - getActiveMapContainer()->setAllowedHeightDiff, kAiPathfindingConsoleTag) - -// map.addVehicleForClusterCost is family 1a (BF2_CONSOLE_METHOD_1_ACTIVE's shape: type 0, exactly one -// argument, "void", a real availability test) under a console spelling with a dot in it, which that -// macro cannot take. [CHOSEN] A one-shot local macro with the named head: everything expands inside -// one macro invocation, so `BF2_CC_NAME`'s __LINE__ agrees between the class and its constructor (a -// hand-written class would not). Core/ConsoleObjectMacro.h is another front's live file and is not -// touched for one binding. -#define BF2_AIPATHFINDING_CONSOLE_METHOD_1_ACTIVE_NAMED(fnNameLiteral, target, activeExpr, A0, listTag) \ -namespace { \ -class BF2_CC_NAME : public ::dice::hfe::ConsoleObjectBaseImpl \ -{ \ - BF2_CC_HEAD_NAMED(fnNameLiteral, 0, 1, 1, "void", true) \ - m_argTypes[0] = #A0; \ - BF2_CC_TAIL(1, listTag) \ - virtual bool isObjectActive() const { return (activeExpr); } \ - virtual void executeObjectMethod() \ - { \ - if (m_argCount != 1) return; \ - m_hasReturnValue = false; \ - target(BF2_CC_ARG(A0, 0)); \ - } \ - virtual void setArgFromString(int index, const std::string& value) \ - { \ - BF2_CC_CONVERT(A0, 1) \ - } \ - BF2_CC_NO_RETURN_AS_STRING \ - BF2_CC_COMMON_HOOKS \ -}; \ -static BF2_CC_NAME BF2_CC_INSTANCE; \ -} - -BF2_AIPATHFINDING_CONSOLE_METHOD_1_ACTIVE_NAMED("map.addVehicleForClusterCost", - getActiveMapContainer()->addVehicleForClusterCost, - getActiveMapContainer() != 0, std::string, - kAiPathfindingConsoleTag) -#undef BF2_AIPATHFINDING_CONSOLE_METHOD_1_ACTIVE_NAMED - -BF2_CONSOLE_PROPERTY_FN(maxWaterDepth, float, IAIPathfindingSetup::instance != 0, - IAIPathfindingSetup::instance->getMaxWaterDepth(), - IAIPathfindingSetup::instance->setMaxWaterDepth, kAiPathfindingConsoleTag) - -// Handed to the console registry by AIModule::init, beside the `ai`, `aiSettings` and -// `aiStrategicArea` lists. -ConsoleObjectList& aiPathfindingConsoleObjects() -{ - return consoleBindingList(kAiPathfindingConsoleTag); + std::vector objects; + static_cast(CommonSingletonServer::m_iaiObjectEnvironment) + ->getAllDestroyableObjects(objects); + for (std::vector::iterator i = objects.begin(); i != objects.end(); ++i) + { + const float* const m = i->transform.m; + const Vec3 from = {i->min.x * m[0] + i->min.y * m[4] + i->min.z * m[8] + m[12], + i->min.x * m[1] + i->min.y * m[5] + i->min.z * m[9] + m[13], + i->min.x * m[2] + i->min.y * m[6] + i->min.z * m[10] + m[14]}; + const Vec3 to = {i->max.x * m[0] + i->max.y * m[4] + i->max.z * m[8] + m[12], + i->max.x * m[1] + i->max.y * m[5] + i->max.z * m[9] + m[13], + i->max.x * m[2] + i->max.y * m[6] + i->max.z * m[10] + m[14]}; + static_cast(CommonSingletonServer::m_iDPStaticCreator) + ->createStaticLine(60.0f, 0, from, to, 0.05f); + } } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h index 841cd31c2..0420f6243 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h @@ -1,6 +1,5 @@ // Pathfinding queries and map lifecycle through separate query and setup interfaces. // Use typed interface conversions for the secondary base subobject. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_MAIN_AIPATHFINDING_H #define AI_AIDLL_AI_MAIN_AIPATHFINDING_H @@ -16,6 +15,7 @@ #include "../AIPathFinding/NavMesh/QuadTreeManager.h" // and one of these #include "AIPathfindingSearchTypes.h" // QTPath, ClusterNodePath, PathfindingEngine #include "IAIPathfinding.h" +#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" namespace dice { namespace hfe { @@ -42,24 +42,24 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual ~MapContainer(); // IMapContainer, slots 2..29, in vtable order - virtual const std::string& getName(); - virtual int getMinPolygonsInLeaf(); + virtual const std::string& getName() const; + virtual int getMinPolygonsInLeaf() const; virtual void setMinPolygonsInLeaf(int); - virtual int getMaxDepthInTree(); + virtual int getMaxDepthInTree() const; virtual void setMaxDepthInTree(int); - virtual float getMaxSlope(); + virtual float getMaxSlope() const; virtual void setMaxSlope(float); virtual void setHeadClearance(float); - virtual float getHeadClearance(); + virtual float getHeadClearance() const; virtual void setRadius(float); - virtual float getRadius(); + virtual float getRadius() const; virtual void setAllowedHeightDiff(float); - virtual float getAllowedHeightDiff(); - virtual void draw(); - virtual void undraw(); - virtual void drawCluster(); - virtual void undrawCluster(); - virtual void drawClusterNeighbourIndices(const Vec3&); + virtual float getAllowedHeightDiff() const; + virtual void draw() const; + virtual void undraw() const; + virtual void drawCluster() const; + virtual void undrawCluster() const; + virtual void drawClusterNeighbourIndices(const Vec3&) const; virtual void loadGTSDebugMeshes(); virtual void buildDebugMeshes(); virtual void unloadDebugMeshes(); @@ -78,7 +78,7 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup bool isValidPosition(const Vec3&, MaterialManager *, bool) const; bool isValidPosition(const Vec3&, MaterialManager *, unsigned int, bool) const; bool isValidPosition(const Vec3&, MaterialManager *, unsigned int, unsigned int, bool) const; - bool getPolygon(std::vector&, Vec3&, unsigned int&, unsigned int&, MaterialManager *) const; + bool getPolygon(std::vector&, const Vec3&, unsigned int&, unsigned int&, MaterialManager *) const; bool getPolygon(std::vector&, unsigned int, unsigned int) const; bool getPolygon(const Vec3&, unsigned int&, unsigned int&, MaterialManager *) const; bool getPolygon(const Vec3&, unsigned int&, unsigned int&, unsigned int, unsigned int, MaterialManager *) const; @@ -89,13 +89,13 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup bool getMaterial(unsigned int, unsigned int, unsigned char&) const; bool setMaterial(unsigned int, unsigned int, unsigned char); void getPolygonCentre(Vec3&, unsigned int, unsigned int) const; - void getEdge(Vec3&, Vec3&, unsigned int, unsigned int, unsigned int) const; + bool getEdge(Vec3&, Vec3&, unsigned int, unsigned int, unsigned int) const; bool trace(unsigned int&, unsigned int&, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, float, MaterialManager *, unsigned char, unsigned char *) const; bool traceKnown(unsigned int, unsigned int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, float, MaterialManager *, unsigned char, unsigned char *) const; bool getLineIntersectionWithPolygon(Vec3&, unsigned int, unsigned int, const Vec3&, const Vec3&) const; void drawPolygon(unsigned int, unsigned int, float *, float) const; bool findClosestValidPolygon(unsigned int&, unsigned int&, Vec3&, const Vec3&, const Vec3&, unsigned int, MaterialManager *) const; - void updateClusterPortalCosts(unsigned int&, triple&, unsigned int, unsigned short); + bool updateClusterPortalCosts(unsigned int&, triple&, unsigned int, unsigned short); // the layout, from the 720-byte constructor /* +4 */ int m_id; // = the caller's index into AIPathfinding::m_maps @@ -126,26 +126,26 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual bool isValidPosition(int, int, const Vec3&, bool) const; virtual bool isValidPosition(int, int, const Vec3&, unsigned int, bool) const; virtual bool isValidPosition(int, int, const Vec3&, unsigned int, unsigned int, bool) const; - virtual int getPolygon(std::vector&, int, const Vec3&, int) const; - virtual int getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const; - virtual int getPolygon(std::vector&, int, unsigned int, unsigned int) const; + virtual bool getPolygon(std::vector&, int, const Vec3&, int) const; + virtual bool getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const; + virtual bool getPolygon(std::vector&, int, unsigned int, unsigned int) const; virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, int) const; virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, unsigned int, unsigned int, int) const; virtual void getPolygonsInRadius(std::list&, int, unsigned int, unsigned int, const Vec3&, float) const; virtual void getPolygonsInTriangle(std::list&, int, unsigned int, unsigned int, const Vec3&, const Vec3&, const Vec3&) const; - virtual int getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const; + virtual bool getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const; virtual bool getMaterial(const Vec3&, int, int, unsigned char&) const; virtual bool getMaterial(int, unsigned int, unsigned int, unsigned char&) const; - virtual void setMaterial(int, unsigned int, unsigned int, unsigned char) const; + virtual bool setMaterial(int, unsigned int, unsigned int, unsigned char) const; virtual void* getQuadTree(int, unsigned int) const; virtual void* getClusterGraph(int, unsigned int) const; virtual void getPolygonCentre(Vec3&, int, unsigned int, unsigned int) const; - virtual void getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const; + virtual bool getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const; virtual bool getLineIntersectionWithPolygon(Vec3&, int, unsigned int, unsigned int, const Vec3&, const Vec3&) const; virtual void drawPolygon(int, unsigned int, unsigned int, float *, float) const; virtual int getClusterOfPolygon(int, unsigned int, unsigned int) const; virtual bool areNeighbouringClusters(int, unsigned int, unsigned short, unsigned short) const; - virtual void updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short); + virtual bool updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short); virtual bool trace(int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const; virtual bool trace(unsigned int, unsigned int, int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const; virtual bool trace(BotNavigation *, bool, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const; @@ -173,14 +173,14 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual void restoreMapPart(int); virtual void resetOriginalMaterialOfDestroyableMapPart(int); virtual void searchPointSelected(bool); - virtual bool tryPath(const Vec3&, const Vec3&); - virtual bool tryClusterPath(const Vec3&, const Vec3&); + virtual void tryPath(const Vec3&, const Vec3&); + virtual void tryClusterPath(const Vec3&, const Vec3&); virtual void setClusterSearch(bool); virtual bool getClusterSearch() const; virtual void setActivatePathfindingDebugTool(bool); virtual bool getActivatePathfindingDebugTool() const; virtual void setPathfindingDebugToolVehicle(const std::string&); - virtual void* getPathfindingDebugToolVehicle() const; + virtual const std::string& getPathfindingDebugToolVehicle() const; virtual void setPathfindingDebugToolVehicleId(int); virtual int getClusterCostType(int, unsigned int) const; @@ -199,10 +199,12 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup virtual void loadGTSData(); virtual bool exportGTSMeshes() const; virtual bool exportGTSMeshesWithinBoundary(const Vec2&, const Vec2&) const; - // 18,942 bytes. The offline level-compile path: it turns the level's meshes, water and - // destroyable add-ons into GTS files. Editor work; nothing on a server route reaches it. - virtual bool createGTSFiles(std::list&, std::list&, std::map&, - std::list&, IAITerrain *, unsigned char) const; + // Exports level meshes, water, ladders and destroyable add-ons for navigation generation. + virtual bool createGTSFiles(std::list&, + std::list&, + std::map&, + std::list&, + IAITerrain*, unsigned char) const; virtual IAIPathfindingSetup::IMapContainer* getActiveMapContainer() const; virtual std::string getMapList(); virtual void setMaxWaterDepth(float); @@ -219,7 +221,19 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup ClusterNodePath* getDebugClusterPath() const; Vec3* getSearchPoint(int) const; bool isValidClusterType(int, unsigned int) const; - void* getEquipmentTypeFromClusterCostType(int, unsigned short) const; + // ELF 0x3A5E10. The blocking variant for ClusterGraph::calculatePortalCosts: acquires its own + // resource, runs the search to completion and appends one cost to `costs`; see the definition. + void getPortalCost(std::vector& costs, unsigned short costType, int map, + unsigned int island, const Vec3& from, unsigned int fromPolygon, + const Vec3& to, unsigned int toPolygon, + const std::set& allowedClusters); + // ELF 0x3A63B0. One portal-to-portal local search for ClusterGraph::updatePortalCosts; see + // the definition. False while the search is still running. + bool getPortalCost(float& cost, unsigned int resource, int map, unsigned int island, + unsigned short costType, const Vec3& from, unsigned int fromPolygon, + const Vec3& to, unsigned int toPolygon, + const std::set& allowedClusters); + int getEquipmentTypeFromClusterCostType(int, unsigned short) const; private: // The original layout has base-interface vptrs at +0 and +4; secondary-base calls @@ -233,7 +247,7 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup /* +20 */ Vec3* m_searchPoint[2]; /* +28 */ QTPath* m_debugPath; // = new QTPath /* +32 */ ClusterNodePath* m_debugClusterPath; // = new ClusterNodePath - /* +36 */ double m_d36; // = -1000.0; reset and tryPath restore it [UNRESOLVED] + /* +36 */ double m_d36; // Last debug endpoint selection time; reset sentinel -1000.0. /* +44 */ bool m_clusterSearch; // = false; the debug tool's cluster/local toggle /* +48 */ PathfindingEngine* m_engine; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h b/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h index caff74315..81b7501e3 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfindingSearchTypes.h @@ -1,15 +1,14 @@ // Shared path containers, node records and reusable A* search resources. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIPathfindingSearchTypes operations. #ifndef AI_AIDLL_AI_MAIN_AIPATHFINDINGSEARCHTYPES_H #define AI_AIDLL_AI_MAIN_AIPATHFINDINGSEARCHTYPES_H #include +#include #include #include #include "IAIPathfinding.h" // ai::triple, and Vec3 through AIDllTypes.h -#include "AIDllFrontier.h" // AStarResource::update's named stop #include "CommonSingletonServer.h" // PathfindingEngine::update's clock #include "../../../AIInterface/BFKnowledge/BFTimer.h" @@ -17,128 +16,312 @@ namespace dice { namespace hfe { namespace ai { -// Navigation path result with polygon positions and traversal state. +// Navigation path result. The node vector holds one (polygon, entered-from polygon, entry point) +// triple per step, in travel order. class QTPath { public: - QTPath() - : m_i0(0) - , m_sentinel16(-1) - , m_i20(0) + QTPath(); + ~QTPath(); + + // [INFERRED] Inline accessors as calculateCostOfPath reads them: an index outside the vector + // (signed compare) yields UINT_MAX and a null position. + unsigned int getPolygon(unsigned int index) const + { + return static_cast(index) < static_cast(m_nodes.size()) + ? m_nodes[index].first + : 0xFFFFFFFFu; + } + const Vec3* getPosition(unsigned int index) const { - // The vector is default-constructed (three null pointers in retail) by the member above - // being absent from this list - the binary's four zero stores at +0 and +4..+15 are that - // and nothing more. + return static_cast(index) < static_cast(m_nodes.size()) ? &m_nodes[index].third + : 0; } - /* +0 */ int m_i0; // = 0 [UNRESOLVED] + // m_i0 and m_i20 keep their placeholder names because AIBot code already writes them. + /* +0 */ int m_i0; // = 0; [INFERRED] the first step still ahead /* +4 */ std::vector > m_nodes; - /* +16 */ int m_sentinel16; // = -1 [UNRESOLVED] - /* +20 */ int m_i20; // = 0 [UNRESOLVED] + /* +16 */ int m_island; // = -1; internalLocalSearch stores the quad tree + /* +20 */ float m_i20; // = 0; the path cost: buildPath copies the goal's f }; -// Cluster-level path result and traversal state. +// Cluster-level path result: (cluster, entry portal) pairs in travel order, for one map, island +// and cluster cost type. class ClusterNodePath { public: - ClusterNodePath() - : m_i0(0) - { - // m_gap4 deliberately not initialised - the binary steps over it. See above. - } + // +4 .. +15 deliberately not initialised - the constructor steps over them. + ClusterNodePath(); + ~ClusterNodePath(); - /* +0 */ int m_i0; // = 0 [UNRESOLVED] - /* +4 */ char m_gap4[12]; // never written + // Stores the map and looks up the vehicle's cluster cost type for it. + void setVehicle(int map, int vehicleId); + // The entry portal of step `index`: its position and polygon. False past the end or for the + // start step (no entry portal). + bool getPoint(Vec3& position, unsigned int& polygon, unsigned int index) const; + // The entry portal position of step m_i0 + `index`, or Vec3::getZero(). + const Vec3& getPoint(unsigned int index) const; + + /* +0 */ int m_i0; // = 0; the current step (BotNavigation resets it) + /* +4 */ int m_map; + /* +8 */ int m_costType; // IAIPathfinding::getClusterCostType + /* +12 */ int m_island; // clusterSearch writes it /* +16 */ std::vector > m_nodes; }; -// Reusable A* node pools, hash tables and search state. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIPathfindingSearchTypes operation. +// What QTSearchNodeManager::getNeighbourOfNode found for a neighbour. [INFERRED] enumerator +// names; the values are those the search switches on. +namespace nodeStatus { +enum Status +{ + kUnvisited = 0, // new: costed and to be opened + kOpen = 1, + kClosed = 2, + kGoal = 3, // the goal (or an additional goal) polygon + kInvalid = 4 // no further edge, impassable material or a disallowed cluster +}; +} // namespace nodeStatus -// Allocated only by `BinarySearchTree`'s constructor, which writes two of -// its four words: `+0 = 0` and `+8 = `. The other two are whatever the -// allocator returned. A classic node shape, but which word is left/right/parent is [UNRESOLVED] -// until `insert`/`merge`/`flatten` are read. +// Search-node tree record. `m_left` doubles as the free-list link, and `flatten` threads a whole +// tree through it. template class BSTNode { public: BSTNode() - : m_i0(0) + : m_data(0) { - // +4 and +12 deliberately not initialised - the constructor at writes only +0 and - // +8, and +8 is the free-list link the tree sets after construction. + // +4 .. +12 deliberately not initialised: only +0 is written; insert sets the children and + // the tree's free list writes +8. } - /* +0 */ int m_i0; // = 0 [UNRESOLVED] - /* +4 */ int m_i4; // never written by the constructor - /* +8 */ BSTNode* m_next; // the free-list link [INFERRED] - /* +12 */ int m_i12; // never written by the constructor + /* +0 */ T* m_data; + /* +4 */ BSTNode* m_parent; + /* +8 */ BSTNode* m_left; // smaller f cost; also the free-list link + /* +12 */ BSTNode* m_right; // equal or larger f cost }; -// Search-node tree and reusable node storage. +// The A* open list: an unbalanced binary tree ordered by the nodes' f cost, with its minimum +// cached. Removed tree records go to a free list and are reused. template class BinarySearchTree { public: explicit BinarySearchTree(int n) - : m_root(0) + : m_count(0) , m_free(0) - , m_i12(0) + , m_root(0) { - // m_i8 deliberately not initialised - see above. + // m_min deliberately not initialised: the constructor writes +0, +4 and +12 only. for (int i = n; i > 0; --i) { BSTNode* const node = new BSTNode(); - node->m_next = m_free; + node->m_left = m_free; m_free = node; } } - /* +0 */ BSTNode* m_root; // [INFERRED] - /* +4 */ BSTNode* m_free; // the pre-allocated pool, proven by the loop - /* +8 */ int m_i8; // never written by the constructor [UNRESOLVED] - /* +12 */ int m_i12; // = 0 [UNRESOLVED] + ~BinarySearchTree(); + + void insert(SearchNode* data); + SearchNode* pop(); + SearchNode* remove(SearchNode* data); + BSTNode* get(SearchNode* data, BSTNode* node); + void clear(); + + /* +0 */ int m_count; + /* +4 */ BSTNode* m_free; + /* +8 */ BSTNode* m_min; + /* +12 */ BSTNode* m_root; + +private: + void insert(BSTNode* at, BSTNode* node); + void merge(BSTNode* at, BSTNode* node); + BSTNode* getLeftmostChildOfTree(BSTNode* node) const; + void flatten(BSTNode* node, BSTNode*& last); }; -// Bucketed search-node lookup with a shared node manager. +// The hash key of a stored element: a search node's own key. ClusterNodeManager's status +// records overload it (their key is their node's), found by argument-dependent lookup. +template +inline auto hashKeyOf(const SearchNode* node) -> decltype(node->m_key) +{ + return node->m_key; +} + +// [INFERRED] Helper names. QTSearchNode uses signed division, then adds the capacity for a +// negative key (even when its remainder is zero). ClusterNode uses unsigned division instead. +inline int hashIndexForKey(int key, int capacity) +{ + int index = key % capacity; + if (key < 0) + index += capacity; + return index; +} + +inline int hashIndexForKey(unsigned int key, int capacity) +{ + return hashIndexForKey(static_cast(key), capacity); +} + +inline int hashIndexForKey(unsigned short key, int capacity) +{ + return static_cast(key) % static_cast(capacity); +} + +// CPNode overloads this with its cover position's index (no modulus), and hashKeyEquals with +// its cover position pointer. The hooks are found by argument-dependent lookup. +template +inline int hashIndexOf(const SearchNode* node, int capacity) +{ + return hashIndexForKey(hashKeyOf(node), capacity); +} + +// [INFERRED] Whether two stored elements carry the same key; see hashIndexOf. +template +inline bool hashKeyEquals(const SearchNode* a, const SearchNode* b) +{ + return hashKeyOf(a) == hashKeyOf(b); +} + +// One hash bucket. Non-empty buckets are threaded on a doubly linked "used" list so clearing and +// iteration only visit those. +template +struct HashBucket +{ + // Inlined in Hash's array construction (ELF 0x3B1EB0, also 0x35B3A0). + HashBucket() + : m_nextUsed(0), m_prevUsed(0), m_head(0) + { + } + + HashBucket* m_nextUsed; + HashBucket* m_prevUsed; + SearchNode* m_head; +}; + +template +class Hash; + +// Forward iterator over a Hash: the bucket, the node in it, and the owning hash. +template +struct HashIterator +{ + HashBucket* m_bucket; + SearchNode* m_node; + Hash* m_hash; + + bool operator==(const HashIterator& other) const + { + return m_bucket == other.m_bucket && m_node == other.m_node; + } + bool operator!=(const HashIterator& other) const { return !(*this == other); } + + // ELF 0x321E00 (the OCData instantiation): the next node in the bucket, else the next used + // bucket's head. + HashIterator& operator++() + { + m_node = m_node->m_next; + if (m_node == 0) + { + m_bucket = m_bucket->m_nextUsed; + if (m_bucket != 0) + m_node = m_bucket->m_head; + } + return *this; + } +}; + +// Intrusive chained hash of search nodes keyed by Node::m_key, chained through the nodes' own +// m_next / m_prev words. The modulus is the constructor's n; n + 1 buckets are allocated. template class Hash { public: + typedef HashIterator iterator; + + // ELF instances: 0x3B1CD0 (QTSearchNode), 0x3B1EB0 (ClusterNode), 0x321D60 + // (ClusterNodeManager::OCData), 0x35B3A0 (CPNode). explicit Hash(unsigned int n) - : m_self0((Hash*)this) - , m_i12(0) - , m_i16(0) - , m_self1((Hash*)this) - , m_buckets(new int[3 * n + 3]) - , m_i28(0) - , m_i32(0) + : m_buckets(new HashBucket[n + 1]) + , m_used(0) + , m_count(0) , m_capacity((int)n) , m_nodeManager(0) { - // m_i0 and m_i4 deliberately not initialised - see above. - // n + 1 entries of three words each, cleared from n down through zero. - for (unsigned int i = 0; i <= n; ++i) + // The bucket constructors run before the fields above are initialized. m_begin's + // bucket and node are not written here; begin() fills them. + m_end.m_bucket = 0; + m_end.m_node = 0; + m_end.m_hash = this; + m_begin.m_hash = this; + } + + void insert(SearchNode* node); + SearchNode* get(SearchNode* node) const; + void remove(SearchNode* node); + + // Inlined in every retail user: empties the buckets on the used list without touching the + // nodes, which the node manager owns. + void clear() + { + m_count = 0; + for (HashBucket* bucket = m_used; bucket != 0; bucket = bucket->m_nextUsed) + bucket->m_head = 0; + m_used = 0; + } + + // Inlined in handleOpenCacheUnderflow (ELF 0x35A5E0 / 0x3B0D00): refreshes the cached + // begin iterator even when empty. + iterator begin() + { + if (m_count == 0) + m_begin = m_end; + else { - m_buckets[3 * i] = 0; - m_buckets[3 * i + 1] = 0; - m_buckets[3 * i + 2] = 0; + m_begin.m_bucket = m_used; + m_begin.m_node = m_used->m_head; } + return m_begin; } + const iterator& end() const { return m_end; } + + /* +0 */ iterator m_begin; + /* +12 */ iterator m_end; + /* +24 */ HashBucket* m_buckets; + /* +28 */ HashBucket* m_used; + /* +32 */ int m_count; + /* +36 */ int m_capacity; + /* +40 */ NodeManager* m_nodeManager; // = 0, written by the owner right after construction + +private: + // The bucket of a node (hashIndexOf). + HashBucket* bucketOf(const SearchNode* node) const + { + return &m_buckets[hashIndexOf(node, m_capacity)]; + } +}; + +// Orders search nodes by f cost for handleOpenCacheUnderflow's multiset. Retail defines it in an +// anonymous namespace of AIPathfinding.cpp (attested by the multiset's mangled names); it is here +// because the templates that use it are defined in this header. +template +struct NodeCompare +{ + bool operator()(const SearchNode* a, const SearchNode* b) const { return a->m_f < b->m_f; } +}; - /* +0 */ int m_i0; // never written by the constructor - /* +4 */ int m_i4; // never written by the constructor - /* +8 */ Hash* m_self0; // = this (an intrusive list sentinel) - /* +12 */ int m_i12; // = 0 - /* +16 */ int m_i16; // = 0 - /* +20 */ Hash* m_self1; // = this - /* +24 */ int* m_buckets; // operator new[](3 * n + 3) ints, all zeroed - /* +28 */ int m_i28; // = 0 - /* +32 */ int m_i32; // = 0 - /* +36 */ int m_capacity; // = n - /* +40 */ NodeManager* m_nodeManager;// = 0, written by the owner right after construction +namespace astarStatus { +// Values of AStarResource::m_status. [INFERRED] names; the values are the ones the search writes. +enum +{ + kIdle = 0, + kSearching = 1, + kFound = 2, + kFailed = 3, + kInvalid = 4 // localSearch's answer for an unusable request; never stored }; +} // namespace astarStatus // State for one in-flight A* search. Its node manager and hash tables belong to the search resource. template @@ -149,61 +332,52 @@ class AStarResource : m_status(0) , m_maxIterations(0) , m_maxSearchDepth(-1) - , m_i16(0) + , m_iterations(0) , m_openSize(0) , m_hashSize(0) - , m_i28(-1) + , m_owner(-1) , m_nodeManager(nodeManager) - , m_i36(0) + , m_worstOpen(0) , m_open(0) + , m_openOverflow(0) , m_closed(0) - , m_i48(0) - , m_i52(0) - , m_i56(0) - , m_cache(0) - , m_i64(0) + , m_goal(0) { // m_i4 deliberately not initialised - see above. } - // One A* step against a deadline. ELF: ClusterNode , QTSearchNode - // CPNode , all `...AStarResource...6updateEd`. The - // result is discarded by PathfindingEngine::update. A named stop until the search is read; - // the definition follows the class. + // Runs A* steps until the deadline, the goal, exhaustion or a limit. void update(double deadline); + void pushOpenNode(SearchNode* node); + SearchNode* popOpenNode(); + void handleOpenCacheUnderflow(); - /* +0 */ int m_status; // = 0 `PathfindingEngine::getStatus` reads this word + /* +0 */ int m_status; // astarStatus; PathfindingEngine::getStatus reads this word /* +4 */ int m_i4; // never written - /* +8 */ int m_maxIterations; // = 0 [INFERRED] - `setMaxIterationsForResource` writes +8 - /* +12 */ int m_maxSearchDepth; // = -1 [INFERRED] - `setMaxSearchDepthForResource` writes +12 - /* +16 */ int m_i16; // = 0, set by the owner after the push - /* +20 */ int m_openSize; // = the int handed to BinarySearchTree's constructor + /* +8 */ int m_maxIterations; // 0 = no limit (the counter never equals it) + /* +12 */ int m_maxSearchDepth; // -1 = no limit + /* +16 */ int m_iterations; // closed nodes this search + /* +20 */ int m_openSize; // the tree's capacity before nodes overflow into the hash /* +24 */ int m_hashSize; // = the int handed to both Hash constructors - /* +28 */ int m_i28; // = -1 [UNRESOLVED] + /* +28 */ int m_owner; // = -1 free; acquireResource stores the caller's owner id /* +32 */ NodeManager* m_nodeManager; - /* +36 */ int m_i36; // = 0 [UNRESOLVED] + /* +36 */ SearchNode* m_worstOpen; // the largest f cost refilled into the tree /* +40 */ BinarySearchTree* m_open; - /* +44 */ Hash* m_closed; // [INFERRED] which is which - /* +48 */ int m_i48; // = 0 [UNRESOLVED] - /* +52 */ int m_i52; // = 0 [UNRESOLVED] - /* +56 */ int m_i56; // = 0 [UNRESOLVED] - /* +60 */ Hash* m_cache; // [INFERRED] - /* +64 */ int m_i64; // = 0 [UNRESOLVED] + /* +44 */ Hash* m_openOverflow; + /* +48 */ std::vector m_v48; // [UNRESOLVED] handleOpenCacheUnderflow only resizes it to 0 + /* +60 */ Hash* m_closed; + /* +64 */ SearchNode* m_goal; // the goal node once found; buildPath starts from it }; -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Defined here because every instantiation needs it; reached only when a search is in flight. -template -void AStarResource::update(double) -{ - BF2_AI_FRONTIER("dice::hfe::ai::AStarResource::update"); -} // Pathfinding engine and its pool of reusable search resources. template class PathfindingEngine { public: PathfindingEngine() {} + // ELF 0x3AE720 (QTSearchNode), 0x3AE930 (ClusterNode), 0x3593F0 (CPNode); weak, one per + // instantiation, identical apart from the node manager's calls. + ~PathfindingEngine(); // [INFERRED] Steps active searches round-robin until now + budget, at most once per // search per call, moving each processed search from front to back. @@ -237,6 +411,609 @@ void PathfindingEngine::update(double } } +// Every search resource is first returned and reset inline (the releaseResource and +// internalLocalSearch sequences, in that order), then its parts are deleted: node manager, open +// tree, both hashes (bucket array first: Hash has no destructor of its own, as in +// ~ClusterNodeManager), and the resource itself, whose only implicit member is m_v48. Null slots +// are skipped. The bound is re-read from the vector on every step. The two lists and the vector +// are then destroyed in reverse declaration order (+16, +12, +0). +template +PathfindingEngine::~PathfindingEngine() +{ + for (unsigned int i = 0; i < m_searches.size(); ++i) + { + AStarResource* const search = m_searches[i]; + if (search == 0) + continue; + + search->m_maxIterations = 0; + search->m_maxSearchDepth = -1; + search->m_nodeManager->returnReset(); + search->m_owner = -1; + search->m_iterations = 0; + search->m_status = astarStatus::kIdle; + search->m_worstOpen = 0; + search->m_open->clear(); + search->m_openOverflow->clear(); + search->m_closed->clear(); + search->m_nodeManager->reset(); + + delete search->m_nodeManager; + delete search->m_open; + if (search->m_openOverflow != 0) + { + if (search->m_openOverflow->m_buckets != 0) + delete[] search->m_openOverflow->m_buckets; + delete search->m_openOverflow; + } + if (search->m_closed != 0) + { + if (search->m_closed->m_buckets != 0) + delete[] search->m_closed->m_buckets; + delete search->m_closed; + } + delete search; + } +} + +// BinarySearchTree. Instantiation addresses are the QTSearchNode ones in the ELF. + +// ELF 0x3B0750 (QTSearchNode), 0x35A490 (CPNode), 0x3B07C0 (ClusterNode). +// Pops every element, then frees the record pool. +template +BinarySearchTree::~BinarySearchTree() +{ + while (m_count > 0) + pop(); + while (m_free != 0) + { + BSTNode* const node = m_free; + m_free = node->m_left; + delete node; + } +} + +// ELF 0x3AF950 (QTSearchNode), 0x35A230 (CPNode), 0x3AFB20 (ClusterNode). +// Equal costs go right; the cached minimum moves only to a strictly cheaper node. +template +void BinarySearchTree::insert(SearchNode* data) +{ + BSTNode* node = m_free; + if (node != 0) + m_free = node->m_left; + else + node = new BSTNode(); + node->m_left = 0; + node->m_right = 0; + node->m_data = data; + + if (m_count == 0) + { + m_min = node; + m_root = node; + node->m_parent = 0; + ++m_count; + return; + } + + BSTNode* const root = m_root; + if (root->m_data->m_f > data->m_f) + { + if (root->m_left == 0) + { + root->m_left = node; + node->m_parent = root; + } + else + insert(root->m_left, node); + } + else + { + if (root->m_right == 0) + { + root->m_right = node; + node->m_parent = root; + } + else + insert(root->m_right, node); + } + + if (m_min->m_data->m_f > node->m_data->m_f) + m_min = node; + ++m_count; +} + +// ELF 0x3B2BD0 (QTSearchNode), 0x35BA00 (CPNode), 0x3B2C40 (ClusterNode). +// Descends from `at` to a free child slot. +template +void BinarySearchTree::insert(BSTNode* at, BSTNode* node) +{ + for (;;) + { + if (at->m_data->m_f > node->m_data->m_f) + { + if (at->m_left == 0) + { + at->m_left = node; + break; + } + at = at->m_left; + } + else + { + if (at->m_right == 0) + { + at->m_right = node; + break; + } + at = at->m_right; + } + } + node->m_parent = at; +} + +// ELF 0x3B2CB0 (QTSearchNode), 0x35BA70 (CPNode), 0x3B2D00 (ClusterNode). +// insert with a null subtree accepted. +template +void BinarySearchTree::merge(BSTNode* at, BSTNode* node) +{ + if (node == 0) + return; + insert(at, node); +} + +// ELF 0x3B2C10 (QTSearchNode), 0x35BA40 (CPNode), 0x3B2C80 (ClusterNode). +template +BSTNode* +BinarySearchTree::getLeftmostChildOfTree(BSTNode* node) const +{ + BSTNode* leftmost = 0; + while (node != 0) + { + leftmost = node; + node = node->m_left; + } + return leftmost; +} + +// ELF 0x3AFA40 (QTSearchNode), 0x35A320 (CPNode), 0x3AFC10 (ClusterNode). +// Removes and returns the cheapest node, or null when empty. +template +SearchNode* BinarySearchTree::pop() +{ + BSTNode* const min = m_min; + if (min == 0) + return 0; + + --m_count; + if (min->m_right != 0) + { + if (min->m_parent != 0) + { + min->m_parent->m_left = min->m_right; + min->m_right->m_parent = min->m_parent; + m_min = min->m_right->m_left != 0 ? getLeftmostChildOfTree(min->m_right->m_left) + : min->m_right; + } + else + { + m_root = min->m_right; + min->m_right->m_parent = 0; + m_min = getLeftmostChildOfTree(min->m_right); + } + } + else + { + m_min = min->m_parent; + if (m_min != 0) + m_min->m_left = 0; + else + { + m_min = min->m_right; + m_root = min->m_right; + if (m_min != 0) + { + m_min->m_parent = 0; + while (m_min->m_left != 0) + m_min = m_min->m_left; + } + } + } + + min->m_left = m_free; + m_free = min; + return min->m_data; +} + +// ELF 0x3B2910 (QTSearchNode), 0x35B900 (CPNode), 0x3B2AD0 (ClusterNode). +// Depth-first by key; the left subtree recursively, the right iteratively. +template +BSTNode* BinarySearchTree::get(SearchNode* data, + BSTNode* node) +{ + while (node != 0) + { + if (data->m_key == node->m_data->m_key) + return node; + BSTNode* const found = get(data, node->m_left); + if (found != 0) + return found; + node = node->m_right; + } + return 0; +} + +// ELF 0x3B0B90 (QTSearchNode), 0x35A940 (CPNode), 0x3B1060 (ClusterNode). +// Removes the node with data's key. The cached minimum is only maintained through +// pop; a non-minimum removal leaves it alone. The removed node's left subtree is merged under its +// right one. +template +SearchNode* BinarySearchTree::remove(SearchNode* data) +{ + if (m_count == 0) + return 0; + if (m_min->m_data->m_key == data->m_key) + return pop(); + + BSTNode* const node = get(data, m_root); + if (node == 0) + return 0; + + --m_count; + BSTNode* const parent = node->m_parent; + if (parent != 0) + { + BSTNode** const slot = + parent->m_left == node ? &parent->m_left : &parent->m_right; + if (node->m_right != 0) + { + *slot = node->m_right; + node->m_right->m_parent = node->m_parent; + merge(*slot, node->m_left); + } + else + { + *slot = node->m_left; + if (node->m_left != 0) + node->m_left->m_parent = node->m_parent; + } + } + else if (node->m_right != 0) + { + m_root = node->m_right; + node->m_right->m_parent = 0; + merge(node->m_right, node->m_left); + } + else + { + // Retail does not test the left child here. + m_root = node->m_left; + node->m_left->m_parent = 0; + } + + node->m_left = m_free; + m_free = node; + return node->m_data; +} + +// ELF 0x3B2360 (QTSearchNode), 0x35B720 (CPNode), 0x3B25E0 (ClusterNode). +// Threads the subtree into one chain through m_left: the node, its left chain, then +// its right chain. `last` receives the chain's tail. +template +void BinarySearchTree::flatten(BSTNode* node, + BSTNode*& last) +{ + if (node->m_left == 0) + { + if (node->m_right == 0) + { + last = node; + return; + } + flatten(node->m_right, last); + node->m_left = node->m_right; + return; + } + + BSTNode* leftLast; + flatten(node->m_left, leftLast); + if (node->m_right == 0) + { + last = leftLast; + return; + } + flatten(node->m_right, last); + leftLast->m_left = node->m_right; +} + +// ELF 0x3B22F0 (QTSearchNode), 0x35B6B0 (CPNode), 0x3B2570 (ClusterNode). +// Returns every record to the free list in one splice. +template +void BinarySearchTree::clear() +{ + if (m_root == 0) + return; + BSTNode* last; + flatten(m_root, last); + last->m_left = m_free; + m_free = m_root; + m_count = 0; + m_root = 0; + m_min = 0; +} + +// Hash. Instantiation addresses are the QTSearchNode ones in the ELF. + +// ELF 0x3B24B0 (QTSearchNode), 0x359B20 (CPNode), 0x3B2730 (ClusterNode). +// Pushes at the bucket head; an empty bucket joins the front of the used list. +template +void Hash::insert(SearchNode* node) +{ + HashBucket* const bucket = bucketOf(node); + SearchNode* const head = bucket->m_head; + if (head != 0) + head->m_prev = node; + else + { + bucket->m_nextUsed = m_used; + if (m_used != 0) + m_used->m_prevUsed = bucket; + bucket->m_prevUsed = 0; + m_used = bucket; + } + node->m_next = head; + node->m_prev = 0; + bucket->m_head = node; + ++m_count; +} + +// ELF 0x3B28B0 (QTSearchNode; also 0x3B2A80 ClusterNode, 0x321E40 ClusterNodeManager::OCData, +// 0x35B8C0 CPNode). The stored node with the same key, or null. +template +SearchNode* Hash::get(SearchNode* node) const +{ + for (SearchNode* entry = bucketOf(node)->m_head; entry != 0; entry = entry->m_next) + { + if (hashKeyEquals(entry, node)) + return entry; + } + return 0; +} + +// ELF 0x3B2970 (QTSearchNode), 0x35B960 (CPNode), 0x3B2B30 (ClusterNode). +// Unlinks a stored node; a bucket that empties leaves the used list. +template +void Hash::remove(SearchNode* node) +{ + if (node->m_prev != 0) + node->m_prev->m_next = node->m_next; + else + { + HashBucket* const bucket = bucketOf(node); + bucket->m_head = node->m_next; + if (bucket->m_head == 0) + { + if (m_used == bucket) + m_used = bucket->m_nextUsed; + else + bucket->m_prevUsed->m_nextUsed = bucket->m_nextUsed; + if (bucket->m_nextUsed != 0) + bucket->m_nextUsed->m_prevUsed = bucket->m_prevUsed; + } + } + --m_count; + if (node->m_next != 0) + node->m_next->m_prev = node->m_prev; +} + +// AStarResource. Instantiation addresses are the QTSearchNode ones in the ELF. + +// ELF 0x3B2410 (QTSearchNode), 0x35B7D0 (CPNode), 0x3B2690 (ClusterNode). +// Marks the node open. It goes into the tree only while the tree is non-empty and +// the node is cheaper than the worst node last refilled; a full tree is first flushed, cheapest +// first, into the overflow hash. Everything else goes straight to the overflow hash. +template +void AStarResource::pushOpenNode(SearchNode* node) +{ + m_nodeManager->setNodeOpen(node); + if (m_open->m_count != 0 && m_worstOpen->m_f > node->m_f) + { + if (m_open->m_count >= m_openSize) + { + do + m_openOverflow->insert(m_open->pop()); + while (m_open->m_count != 0); + } + m_open->insert(node); + return; + } + m_openOverflow->insert(node); +} + +// ELF 0x3B2860 (QTSearchNode), 0x35B870 (CPNode), 0x3B2A30 (ClusterNode). +// The cheapest open node, refilling the tree from the overflow hash when it is +// empty; null when both are empty. +template +SearchNode* AStarResource::popOpenNode() +{ + for (;;) + { + if (m_open->m_count != 0) + return m_open->pop(); + if (m_openOverflow->m_count == 0) + return 0; + handleOpenCacheUnderflow(); + } +} + +// ELF 0x3B0830 (QTSearchNode), 0x35A5E0 (CPNode), 0x3B0D00 (ClusterNode). +// Moves the m_openSize cheapest overflow nodes into the tree and remembers the most +// expensive of them. The candidates are kept in a multiset by f cost; displacing the current worst +// erases it by key, which removes every candidate with that same cost (retail behaviour). +template +void AStarResource::handleOpenCacheUnderflow() +{ + m_v48.resize(0); + + Hash* const hash = m_openOverflow; + typename Hash::iterator it = hash->begin(); + if (it == hash->end()) + return; + + std::multiset > best; + SearchNode* worst = it.m_node; + for (int taken = 0; taken < m_openSize && it != hash->end(); ++taken) + { + best.insert(it.m_node); + if (it.m_node->m_f > worst->m_f) + worst = it.m_node; + ++it; + } + + while (it != hash->end()) + { + if (!(it.m_node->m_f > worst->m_f)) + { + typename std::multiset >::iterator last = + best.end(); + --last; + best.erase(*last); + best.insert(it.m_node); + ++it; + last = best.end(); + --last; + worst = *last; + } + else + ++it; + } + + for (typename std::multiset >::iterator i = best.begin(); + i != best.end(); ++i) + { + m_openOverflow->remove(*i); + m_open->insert(*i); + } + m_worstOpen = worst; +} + +// ELF 0x3AEEA0 (QTSearchNode), 0x359BC0 (CPNode), 0x3AF400 (ClusterNode). +// One time slice of the search. Each popped node is expanded edge by edge (never +// back into its own parent); new neighbours are opened, cheaper routes to open or closed nodes +// re-open those, and reaching the goal closes the search. A node whose edges are exhausted is +// closed and counted against the iteration and depth limits. +template +void AStarResource::update(double deadline) +{ + IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); + if (m_status != astarStatus::kSearching) + return; + + for (;;) + { + if (!(deadline > timer->getUpdateTime())) + return; + + SearchNode* const node = popOpenNode(); + if (node == 0) + { + m_status = astarStatus::kFailed; + return; + } + + nodeStatus::Status status; + Key edge; + SearchNode* neighbour = node->expandFirst(m_nodeManager, status, edge); + while (neighbour != 0 && node->m_parent != 0 && neighbour->m_key == node->m_parent->m_key) + { + m_nodeManager->recycleNode(neighbour); + neighbour = node->expand(m_nodeManager, status, edge); + } + + while (neighbour != 0) + { + switch (status) + { + case nodeStatus::kUnvisited: + pushOpenNode(neighbour); + break; + + case nodeStatus::kOpen: + { + SearchNode* existing = m_openOverflow->get(neighbour); + if (existing == 0) + { + BSTNode* const record = m_open->get(neighbour, m_open->m_root); + existing = record != 0 ? record->m_data : 0; + } + if (m_nodeManager->updateNode(node, existing, m_maxSearchDepth)) + { + SearchNode* const hashed = m_openOverflow->get(neighbour); + if (hashed != 0) + m_openOverflow->remove(hashed); + else + m_open->remove(neighbour); + pushOpenNode(existing); + } + m_nodeManager->recycleNode(neighbour); + break; + } + + case nodeStatus::kClosed: + { + SearchNode* const existing = m_closed->get(neighbour); + if (m_nodeManager->updateNode(node, existing, m_maxSearchDepth)) + { + m_closed->remove(existing); + pushOpenNode(existing); + } + m_nodeManager->recycleNode(neighbour); + break; + } + + case nodeStatus::kGoal: + m_goal = neighbour; + neighbour->m_parent = node; + m_nodeManager->setNodeClosed(node); + m_closed->insert(node); + m_status = astarStatus::kFound; + break; + + case nodeStatus::kInvalid: + m_nodeManager->recycleNode(neighbour); + break; + + default: + break; + } + + if (m_status == astarStatus::kFound) + return; + + neighbour = node->expand(m_nodeManager, status, edge); + while (neighbour != 0 && node->m_parent != 0 && + neighbour->m_key == node->m_parent->m_key) + { + m_nodeManager->recycleNode(neighbour); + neighbour = node->expand(m_nodeManager, status, edge); + } + } + + if (m_status == astarStatus::kFound) + return; + + const int depth = node->m_depth; + m_nodeManager->setNodeClosed(node); + m_closed->insert(node); + ++m_iterations; + if (m_iterations == m_maxIterations || m_maxSearchDepth == depth) + { + m_status = astarStatus::kFailed; + return; + } + } +} + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp index 50dbae10d..a827732aa 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp @@ -1,4 +1,6 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining AIPlayerCourier operations. + +// static init: ELF 0x3B3090 (__tcf_0 0x3B30F0, _GLOBAL__I 0x3B3120): 's Init object only. +#include #include "AIPlayerCourier.h" @@ -6,7 +8,11 @@ #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" -#include "AIDllFrontier.h" +#include "IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" namespace dice { namespace hfe { @@ -38,24 +44,55 @@ AIPlayerCourier::~AIPlayerCourier() { } -int AIPlayerCourier::getSelectedVehicle(int) +// ELF 0x3B2E90: the bot's getChangeTarget handle (Bot +0x1BC) resolved through the information pool; the +// information's AI object answers its engine object (IObjectComponent +0x20 getObject). Null for +// a non-bot or an unknown handle. +world::IObject* AIPlayerCourier::getSelectedVehicle(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getSelectedVehicle"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return 0; + Information* const information = informationManager->getInformation(bot->getChangeTarget()); + if (!information) + return 0; + return information->getAIObject()->getObject(); } -int AIPlayerCourier::getRepairTarget(int) +// ELF 0x3B2F20: the bot's getBridgeRepairTarget handle (Bot +0x1D4) resolved through the information pool; the +// information's AI object answers its engine object (IObjectComponent +0x20 getObject). Null for +// a non-bot or an unknown handle. +world::IObject* AIPlayerCourier::getRepairTarget(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getRepairTarget"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return 0; + Information* const information = informationManager->getInformation(bot->getBridgeRepairTarget()); + if (!information) + return 0; + return information->getAIObject()->getObject(); } -int AIPlayerCourier::getReviveTarget(int) +// ELF 0x3B2FB0: the bot's getReviveTarget handle (Bot +0x1DC) resolved through the information pool; the +// information's AI object answers its engine object (IObjectComponent +0x20 getObject). Null for +// a non-bot or an unknown handle. +world::IObject* AIPlayerCourier::getReviveTarget(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getReviveTarget"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return 0; + Information* const information = informationManager->getInformation(bot->getReviveTarget()); + if (!information) + return 0; + return information->getAIObject()->getObject(); } -int AIPlayerCourier::getMineDefuseTarget(int) +// ELF 0x3B3040: the bot's mine target (BotMain +0x1FC, past the Bot interface), or -1. +unsigned int AIPlayerCourier::getMineDefuseTarget(int playerId) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerCourier::getMineDefuseTarget"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(playerId); + if (!bot) + return static_cast(-1); + return static_cast(bot)->getMineTarget(); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h index 7c7218189..863bce38a 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.h @@ -25,10 +25,12 @@ class IAIPlayerCourier public: IAIPlayerCourier(); virtual ~IAIPlayerCourier(); - virtual int getSelectedVehicle(int) = 0; - virtual int getRepairTarget(int) = 0; - virtual int getReviveTarget(int) = 0; - virtual int getMineDefuseTarget(int) = 0; + // The engine side (AIInterface/IAIPlayerCourier.h) reads the first three as world::IObject* + // and the fourth as an unsigned grid id; the ELF names are const (0x3B2E90..0x3B3040). + virtual world::IObject* getSelectedVehicle(int playerId) const = 0; + virtual world::IObject* getRepairTarget(int playerId) const = 0; + virtual world::IObject* getReviveTarget(int playerId) const = 0; + virtual unsigned int getMineDefuseTarget(int playerId) const = 0; }; // AIPlayerCourier - sizeof == 4, from BF2AI::init step 12. @@ -39,10 +41,10 @@ class AIPlayerCourier : public IAIPlayerCourier virtual ~AIPlayerCourier(); // IAIPlayerCourier - virtual int getSelectedVehicle(int); - virtual int getRepairTarget(int); - virtual int getReviveTarget(int); - virtual int getMineDefuseTarget(int); + virtual world::IObject* getSelectedVehicle(int playerId) const; + virtual world::IObject* getRepairTarget(int playerId) const; + virtual world::IObject* getReviveTarget(int playerId) const; + virtual unsigned int getMineDefuseTarget(int playerId) const; }; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp new file mode 100644 index 000000000..18c7cc0eb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.cpp @@ -0,0 +1,77 @@ +// [INFERRED] Source placement; see AIRadio.h. + +// static init: ELF 0x3B3390 (__tcf_0 0x3B33F0, _GLOBAL__I 0x3B3420): 's Init object only. +#include + +#include "AIRadio.h" + +#include "CommonSingletonServer.h" // m_iaiSettings +#include "AISettingsInterfaces.h" // IAISettings::getMaxNBots (slot 0) +#include "../../../AIInterface/BFKnowledge/BFTimer.h" + +namespace dice { +namespace hfe { +namespace ai { + +// .bss: zero until a constructor runs, and none does in the shipped image. +AIRadio* AIRadio::m_instance = 0; + +// ELF 0x3B3190 (C1; C2 0x3B3140 is the same): stores 0.0 (the float constant at ELF 0x49CB34) into +// the update time, asks the settings for the bot count once and discards it, then publishes +// itself. +0x04 is left unwritten. +AIRadio::AIRadio() +{ + m_lastUpdateTime = 0.0f; + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + (void)bots; + m_instance = this; +} + +// ELF 0x3B3240 (D1; D2 0x3B31E0 is the same): asks the settings for the bot count once and clears +// each bot's messages (an empty body, so the shipped loop only counts down), frees the +0x04 +// array, then zeroes m_instance unconditionally. +AIRadio::~AIRadio() +{ + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + for (int bot = 0; bot < bots; ++bot) + clearMessagesForBot(bot); + delete[] m_unresolved4; + m_instance = 0; +} + +// ELF 0x3B3330: push ebp / mov ebp, esp / pop ebp / ret. +void AIRadio::clearMessagesForBot(int) +{ +} + +// ELF 0x3B32A0: the time is stored unless it is less than 0.5 s past the last one. +void AIRadio::update() +{ + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!(0.5f > now - m_lastUpdateTime)) + m_lastUpdateTime = now; +} + +// ELF 0x3B32F0. +bool AIRadio::reset() +{ + const int bots = static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots(); + (void)bots; + return true; +} + +// ELF 0x3B3340. +void AIRadio::setLastUpdateTime() +{ + m_lastUpdateTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); +} + +// ELF 0x3B3380: the float widened into the double. +void AIRadio::setLastUpdateTime(float time) +{ + m_lastUpdateTime = time; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRadio.h b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.h new file mode 100644 index 000000000..c87154a06 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRadio.h @@ -0,0 +1,46 @@ +// The AI radio singleton. Nothing in libaidll.so constructs one: the constructors (ELF 0x3B3140, +// 0x3B3190) have no callers and no PLT entry, and this file's static initializer (0x3B3390) only +// sets up . m_instance (.bss) is written only by the constructor and the destructor, so +// it stays null; AISettings::~AISettings and AISettings::reset still read it, and the destructor +// deletes it when set. +// [INFERRED] Source placement. + +#ifndef AI_AIDLL_AI_MAIN_AIRADIO_H // [INFERRED] guard style +#define AI_AIDLL_AI_MAIN_AIRADIO_H + +namespace dice { +namespace hfe { +namespace ai { + +class AIRadio +{ +public: + AIRadio(); // ELF 0x3B3140 (C2), 0x3B3190 (C1) + ~AIRadio(); // ELF 0x3B31E0 (D2), 0x3B3240 (D1) - not virtual + + void clearMessagesForBot(int); // ELF 0x3B3330 - an empty body + // ELF 0x3B32A0: the update time follows the game time in steps of at least 0.5 s. + void update(); + // ELF 0x3B32F0: asks the settings for the bot count, discards it, returns 1. [INFERRED] bool, + // like the sibling resets; the mangled name carries no return type. + bool reset(); + void setLastUpdateTime(); // ELF 0x3B3340: the game time + void setLastUpdateTime(float); // ELF 0x3B3380 + + static AIRadio* m_instance; + +private: + // Retail layout as far as the recovered bodies touch it; the size is not attested (no + // allocation site exists). + /* +0x00 */ int m_unresolved0; // [UNRESOLVED] never touched by the recovered bodies + // Freed with delete[] by the destructor; the constructor never writes it (shipped). The + // element type is [UNRESOLVED]; delete[] with no element destructor fits a trivial type. + /* +0x04 */ unsigned char* m_unresolved4; + /* +0x08 */ double m_lastUpdateTime; // [INFERRED] name: update and setLastUpdateTime use it +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_MAIN_AIRADIO_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp index 8b48ed183..1d11dee9a 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.cpp @@ -1,4 +1,7 @@ +// static init: ELF 0x3B36E0 (__tcf_0 0x3B3740, _GLOBAL__I 0x3B3770): 's Init object only. +#include + #include "AIRandom.h" #include "CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h index 8b5dbe37a..9ea461a15 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIRandom.h @@ -19,7 +19,8 @@ class AIRandom // Returns the next tempered random value. [CHOSEN] Name for an inline operation. unsigned int next() { - if (m_index > kStateSize - 1) + // Unsigned comparison, including the inlined draws at ELF 0x30C60D / 0x30CD9F. + if (static_cast(m_index) > kStateSize - 1) generateNumbers(); unsigned int y = m_state[m_index++]; @@ -48,7 +49,10 @@ class AIRandom // this index before the draw: PE spills its running weight to float only // across the refill call. No new state, virtual slot or random policy. friend class BotSpawner; +public: + // [CHOSEN, not recovered] Visibility for the generated inline seed property. /* +0x000 */ int m_seed; +private: /* +0x004 */ unsigned int m_state[kStateSize]; /* +0x9C4 */ int m_index; }; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp b/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp index 249f2a31c..8e028c860 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp @@ -3,20 +3,36 @@ #include "AISettings.h" -#include "AIDllFrontier.h" +#include +#include #include "../../../../Core/Debug.h" #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" -#include "../../../../Core/ConsoleObjectMacro.h" // the aiSettings.* bindings at the foot #include "AIMain.h" // IAIMain::spawnBots - setAutoSpawnBots' trigger #include "AILODManager.h" // setViewDistance's second broadcast #include "AIRandom.h" // addBotName's weight draw +#include "AIRadio.h" // the destructor's first delete #include "IBotManager.h" // setViewDistance walks the bot pool #include "../AIBot/BotMain.h" // Bot::isDeactivated / Bot::getPlayer #include "../AIPathFinding/Material/Material.h" // materialId console spelling and extractor #include "../AIPathFinding/Material/MaterialManager.h" #include "../AIUtils/checkPointer.h" +#include "../AIPlanInterpreter/BAPInterpreter.h" // the per-vehicle plan interpreter pool +#include "../AIBotBehaviour/BotBehaviour.h" // the destructor's virtual deleting destructors +#include "../AIBotBehaviourPattern/PlanGenerator.h" // (complete types, or delete skips them) #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer::setViewDistance, slot +0x68 +#include "../AIUtils/DebugRendering/AIRenderUtil.h" + +namespace { +// [CHOSEN, not recovered] These three original TUs share this source file; retain their +// three independent stream-initialization lifetimes with explicit objects. +// static init: ELF 0x3C1570 (__tcf_0 0x3C15D0, _GLOBAL__I 0x3C1600). +std::ios_base::Init aiSettingsStreams; +// static init: ELF 0x3E7400 (__tcf_0 0x3E7460, _GLOBAL__I 0x3E7490). +std::ios_base::Init iaiSettingsStreams; +// static init: ELF 0x3E77B0 (__tcf_0 0x3E7810, _GLOBAL__I 0x3E7840). +std::ios_base::Init iaiSettingsModifierStreams; +} namespace dice { namespace hfe { @@ -25,40 +41,46 @@ extern ClassManager* classManager; namespace ai { // Returns whether AI configuration overrides the game menu settings. +// ELF 0x3C1530. bool AISettings::overrideMenuSettings() const { return m_overrideMenuSettings; } // The same byte, under a second name. See above. +// ELF 0x3C1540. bool AISettings::getOverrideMenuSettings() const { return m_overrideMenuSettings; } -// Recovered accessors and the remaining explicitly named stops follow in shipped declaration order. -// The production stops below diagnose and abort; none returns a fabricated value. +// Recovered accessors follow the shipped declaration order. +// ELF 0x3BEF90. int AISettings::getNumberOfBehaviours() const { return m_numberOfBehaviours; } +// ELF 0x3BEFA0. int AISettings::getNumberOfVehicles() const { return static_cast(m_behaviours.size()); } +// ELF 0x3C0EF0. float* AISettings::getVehicleMods(int vehicle) const { return m_vehicleMods[vehicle]; } +// ELF 0x3BF640. BotBehaviour* AISettings::getBehaviour(int vehicle, int index) const { return m_behaviours[vehicle][index]; } +// ELF 0x3BF670. BotBehaviour* AISettings::getDefaultBehaviour(int vehicle) const { const int index = m_defaultBehaviour[vehicle]; @@ -67,47 +89,56 @@ BotBehaviour* AISettings::getDefaultBehaviour(int vehicle) const return 0; } -void* AISettings::getPlanInterpreter(int vehicle) const +// ELF 0x3BF6B0. +PlanInterpreter* AISettings::getPlanInterpreter(int vehicle) const { return m_planInterpreters[vehicle]; } +// ELF 0x3BF6D0. PlanGenerator* AISettings::getPlanGenerator(int vehicle, int index) const { return m_planGenerators[vehicle][index]; } +// ELF 0x3C0230. float AISettings::getStatsViewDistance() const { return m_statsViewDistance; } +// ELF 0x3C0250. bool AISettings::getDrawBotStats() const { return m_drawBotStats; } +// ELF 0x3C01F0. int AISettings::getNBattleStrengths() { return 6; } +// ELF 0x3C0200. int AISettings::getNStrategicStrengths() { return 2; } +// ELF 0x3C0220. int AISettings::getInformationGridDimension() const { return m_informationGridDimension; } +// ELF 0x3C0A00. float AISettings::getSAIUpdateFrequency() const { return m_saiUpdateFrequency; } // [INFERRED] reference spelling, proven borrowed string object. +// ELF 0x3BF320. const std::string& AISettings::getVehicle(int vehicle) const { if (vehicle < 0 || vehicle >= static_cast(m_vehicleNames.size())) @@ -121,6 +152,7 @@ const std::string& AISettings::getVehicle(int vehicle) const return m_vehicleNames[vehicle]; } +// ELF 0x3BF4A0. int AISettings::getVehicle(const std::string& name) const { // (!) guarded, and the sibling below is not. Same map type, same find, opposite discipline. @@ -131,43 +163,51 @@ int AISettings::getVehicle(const std::string& name) const } // Every lookup/index is unchecked in both images. +// ELF 0x3BF500. const std::string& AISettings::getVehicleClusterMapping(const std::string& name) const { const int vehicle = m_vehicleIndex.find(name)->second; return m_vehicleNames[m_clusterCostTypes[vehicle]]; } +// ELF 0x3BF570. int AISettings::getClusterCostType(int index) const { return m_clusterCostTypes[index]; } +// ELF 0x3BF590. const std::vector& AISettings::getClusterCostTypes() const { return m_clusterCostTypes; } +// ELF 0x3C0950. int AISettings::getNumberOfVehicleGroups() const { return static_cast(m_vehicleGroupNames.size()); } +// ELF 0x3C0970. int AISettings::getVehicleGroup(int index) const { return m_vehicleGroups[index]; } +// ELF 0x3C0990. int AISettings::getVehicleGroup(const std::string& name) const { // Requires an existing group name; the lookup result is dereferenced without checking end(). return m_vehicleGroupIndex.find(name)->second; } +// ELF 0x3C09E0. const std::string& AISettings::getVehicleGroupName(int group) const { return m_vehicleGroupNames[group]; } +// ELF 0x3C0A60. float* AISettings::getStandardPersonality(int side) const { // (!) 1-based. The binary computes `this + 176 + 4*side`, i.e. this array at +180 subscripted @@ -175,11 +215,13 @@ float* AISettings::getStandardPersonality(int side) const return m_standardPersonality[side - 1]; } +// ELF 0x3C0A80. BotMoralAdmin* AISettings::getStandardMoralAdmin(int side) const { return m_standardMoralAdmin[side - 1]; } +// ELF 0x3C0AD0. bool AISettings::hasActiveRenderer() const { // This unsupported operation emits an error diagnostic. @@ -187,17 +229,20 @@ bool AISettings::hasActiveRenderer() const return false; } +// ELF 0x3C0C00. bool AISettings::getDraw() const { return m_draw; } // - a bare member return, the shape every accessor in this run has. +// ELF 0x3C4140. const std::map& AISettings::getSensingAgentPatterns() const { return m_sensingAgentPatterns; } +// ELF 0x3C0E20. ISensingAgentPattern* AISettings::getSensingAgentPattern(int id) const { const std::map::const_iterator i = m_sensingAgentPatterns.find(id); @@ -206,38 +251,45 @@ ISensingAgentPattern* AISettings::getSensingAgentPattern(int id) const return i->second; } +// ELF 0x3C0E70. ISensingAgentPattern* AISettings::getSensingAgentNullPattern() const { return m_sensingAgentNullPattern; } +// ELF 0x3C0FD0. int AISettings::getManDownEquipmentType() { // Preserve virtual dispatch so derived getVehicle implementations are honored. return getVehicle(m_manDownEquipment); } +// ELF 0x3C1090. bool AISettings::isValidMaterial(int vehicle, unsigned char material) const { return m_vehicleMaterialManagers[vehicle]->isValidMaterial(material); } +// ELF 0x3C1110. float AISettings::getVehicleMaterialCost(const std::string& name, unsigned char material) const { return m_vehicleMaterialManagers[getVehicle(name)]->getMaterialCost(material); } +// ELF 0x3C10D0. float AISettings::getVehicleMaterialCost(int vehicle, unsigned char material) const { return m_vehicleMaterialManagers[vehicle]->getMaterialCost(material); } +// ELF 0x3C1170. MaterialManager* AISettings::getVehicleMaterialManager(int vehicle) const { return m_vehicleMaterialManagers[vehicle]; } // Returns the next bot name and rotates the roster for the following request. +// ELF 0x3C1480. const std::string& AISettings::getBotName() const { m_botNames.push_back(m_botNames.front()); @@ -247,92 +299,164 @@ const std::string& AISettings::getBotName() const } // The shared bot value narrows, the settings value does not. +// ELF 0x3BEF50. void AISettings::setMaxNumberOfBehaviours(int count) { BotMain::setNBehaviours(static_cast(count)); m_numberOfBehaviours = count; } -void AISettings::setVehicleMods(int, float *) +// ELF 0x3C0F10: grows the table to the vehicle (new slots null), then stores the set. +void AISettings::setVehicleMods(int vehicle, float* mods) +{ + if (static_cast(m_vehicleMods.size()) <= vehicle) + m_vehicleMods.resize(vehicle + 1, 0); + m_vehicleMods[vehicle] = mods; +} + +// ELF 0x3BF730. +void AISettings::addBehaviour(int vehicle, int index, BotBehaviour* behaviour) +{ + prepareBehaviourPool(vehicle, index); + m_behaviours[vehicle][index] = behaviour; +} + +// ELF 0x3BF7A0: the pool is prepared for (vehicle, index) although only the default slot is set. +void AISettings::setDefaultBehaviour(int vehicle, int index) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setVehicleMods"); + prepareBehaviourPool(vehicle, index); + m_defaultBehaviour[vehicle] = index; } -void AISettings::addBehaviour(int, int, BotBehaviour *) +// ELF 0x3BF870: BAPInterpreter::addEntry(entry) on the vehicle's interpreter. +void AISettings::addInterpreterEntry(int vehicle, BAPEntry* entry) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addBehaviour"); + preparePlanInterpreterPool(vehicle); + static_cast(m_planInterpreters[vehicle])->addEntry(entry); } -void AISettings::setDefaultBehaviour(int, int) +// ELF 0x3BF8D0. +void AISettings::addInterpreterEntry(int vehicle, BotLodLevel lod, BAPEntry* entry) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setDefaultBehaviour"); + preparePlanInterpreterPool(vehicle); + static_cast(m_planInterpreters[vehicle])->addEntry(lod, entry); } -void AISettings::addInterpreterEntry(int, BAPEntry *) +// ELF 0x3BF930. +void AISettings::removeInterpreterEntry(int vehicle, BotLodLevel lod, BAPEntry* entry) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addInterpreterEntry"); + preparePlanInterpreterPool(vehicle); + static_cast(m_planInterpreters[vehicle])->removeEntry(lod, entry); } -void AISettings::addInterpreterEntry(int, BotLodLevel, BAPEntry *) +// ELF 0x3BF990. +void AISettings::activateDefaultInterpreter(int vehicle, BAPStatementType type, BotLodLevel lod) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addInterpreterEntry"); + preparePlanInterpreterPool(vehicle); + static_cast(m_planInterpreters[vehicle])->activateEntry(type, lod); } -void AISettings::removeInterpreterEntry(int, BotLodLevel, BAPEntry *) +// ELF 0x3BF800. +void AISettings::addGenerator(int vehicle, int index, PlanGenerator* generator) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::removeInterpreterEntry"); + preparePlanGeneratorPool(vehicle, index); + m_planGenerators[vehicle][index] = generator; } -void AISettings::activateDefaultInterpreter(int, BAPStatementType, BotLodLevel) +// ELF 0x3BFA20: one behaviour list per vehicle up to `vehicle`; a list too short for `index` is +// sized to the number of behaviours (not to index + 1); the default table grows with -1 entries. +// Every size test is signed (`cmpl ...; jg`). +void AISettings::prepareBehaviourPool(int vehicle, int index) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::activateDefaultInterpreter"); + if (static_cast(m_behaviours.size()) <= vehicle) + m_behaviours.resize(vehicle + 1, std::vector()); + std::vector& behaviours = m_behaviours[vehicle]; + if (static_cast(behaviours.size()) <= index) + behaviours.resize(m_numberOfBehaviours, 0); + prepareVehicleGroup(vehicle); + if (static_cast(m_defaultBehaviour.size()) <= vehicle) + m_defaultBehaviour.resize(vehicle + 1, -1); +} + +// ELF 0x3BFC50: as prepareBehaviourPool, with the vehicle group prepared before the inner list. +void AISettings::preparePlanGeneratorPool(int vehicle, int index) +{ + if (static_cast(m_planGenerators.size()) <= vehicle) + m_planGenerators.resize(vehicle + 1, std::vector()); + prepareVehicleGroup(vehicle); + std::vector& generators = m_planGenerators[vehicle]; + if (static_cast(generators.size()) <= index) + generators.resize(m_numberOfBehaviours, 0); +} + +// ELF 0x3BFDE0: one `new BAPInterpreter(45)` (operator new 0x10; 45 statement types) per missing +// vehicle, each checked (checkPointer, the Debug at line 46) and pushed back. +void AISettings::preparePlanInterpreterPool(int vehicle) +{ + if (static_cast(m_planInterpreters.size()) <= vehicle) + { + for (unsigned int i = m_planInterpreters.size(); i < static_cast(vehicle + 1); ++i) + m_planInterpreters.push_back(checkPointer(new BAPInterpreter(45))); + } + prepareVehicleGroup(vehicle); } -void AISettings::addGenerator(int, int, PlanGenerator *) +// ELF 0x3C0040: the vehicle-group table grows to the vehicle with group 0. +void AISettings::prepareVehicleGroup(int vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addGenerator"); + if (vehicle >= static_cast(m_vehicleGroups.size())) + m_vehicleGroups.resize(vehicle + 1, 0); } -void AISettings::setBasicBotWeights(float *) +// ELF 0x3BF9F0: the class static BotMain reads (BotMain::setBasicWeights). +void AISettings::setBasicBotWeights(float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setBasicBotWeights"); + BotMain::setBasicWeights(weights); } +// ELF 0x3C0240. void AISettings::setStatsViewDistance(float distance) { m_statsViewDistance = distance; } +// ELF 0x3C0260. void AISettings::setDrawBotStats(bool draw) { m_drawBotStats = draw; } +// ELF 0x3C0210. void AISettings::setInformationGridDimension(int dimension) { m_informationGridDimension = dimension; } +// ELF 0x3C0280. void AISettings::setNSides(int sides) { m_nSides = sides; } +// ELF 0x3C0A10. void AISettings::setSAIUpdateFrequency(float frequency) { m_saiUpdateFrequency = frequency; } +// ELF 0x3C0A20. void AISettings::setStandardPersonality(float* weights, int side) { m_standardPersonality[side - 1] = weights; } +// ELF 0x3C0A40. void AISettings::setStandardMoralAdmin(BotMoralAdmin* admin, int side) { m_standardMoralAdmin[side - 1] = admin; } +// ELF 0x3C0AB0. void AISettings::setRespawnAllowed(bool allowed) { m_respawnAllowed = allowed; @@ -340,6 +464,7 @@ void AISettings::setRespawnAllowed(bool allowed) // Duplicate insertion failure is deliberately ignored; the three // parallel vectors still grow, while the name map retains the first id. +// ELF 0x3BEFC0. void AISettings::setVehicle(const std::string& name) { const int id = static_cast(m_vehicleIndex.size()); @@ -350,6 +475,7 @@ void AISettings::setVehicle(const std::string& name) } // Both map finds are intentionally unguarded. +// ELF 0x3BF5A0. void AISettings::setVehicleClusterMapping(const std::string& vehicle, const std::string& clusterVehicle) { @@ -359,6 +485,7 @@ void AISettings::setVehicleClusterMapping(const std::string& vehicle, } // Retail uses resize rather than push_back and ignores duplicates. +// ELF 0x3C0640. void AISettings::createVehicleGroup(const std::string& name) { const int id = static_cast(m_vehicleGroupNames.size()); @@ -366,6 +493,7 @@ void AISettings::createVehicleGroup(const std::string& name) m_vehicleGroupIndex.insert(std::make_pair(name, id)); } +// ELF 0x3C0790. void AISettings::addVehicleToVehicleGroup(int vehicle, const std::string& group) { // [PLATFORM] This single expression is load-bearing: PE captures the destination before the @@ -373,6 +501,7 @@ void AISettings::addVehicleToVehicleGroup(int vehicle, const std::string& group) m_vehicleGroups[vehicle] = getVehicleGroup(group); } +// ELF 0x3C07D0. void AISettings::addVehicleToVehicleGroup(const std::string& vehicle, const std::string& group) { @@ -392,6 +521,7 @@ void AISettings::addVehicleToVehicleGroup(const std::string& vehicle, // Stores the auto-spawn flag. Enabling also requests immediate spawning when IAIMain // exists; disabling performs no spawn action. +// ELF 0x3C0EA0. void AISettings::setAutoSpawnBots(bool enable) { m_autoSpawnBots = enable; @@ -400,31 +530,41 @@ void AISettings::setAutoSpawnBots(bool enable) IAIMain::m_instance->spawnBots(); } -void AISettings::setDraw(bool) +// ELF 0x3C0C10. Disabling drawing clears render objects without a singleton guard. +void AISettings::setDraw(bool draw) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setDraw"); + m_draw = draw; + if (!draw) + AIRenderUtil::m_instance->unrenderAll(); } -void AISettings::setSensingAgentPatternName(const std::string&) +// ELF 0x3C0C50: registers the name under the next index (insert_unique: a known name keeps its +// index). +void AISettings::setSensingAgentPatternName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::setSensingAgentPatternName"); + const int index = static_cast(m_sensingAgentPatternIds.size()); + m_sensingAgentPatternIds.insert(std::pair(name, index)); } +// ELF 0x3C0D80. void AISettings::setSensingAgentNullPattern(ISensingAgentPattern* pattern) { m_sensingAgentNullPattern = pattern; } -void AISettings::addSensingAgentPattern(int, ISensingAgentPattern *) +// ELF 0x3C0DA0: insert_unique(vehicle, pattern) into the +0x6C map. +void AISettings::addSensingAgentPattern(int vehicle, ISensingAgentPattern* pattern) { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::addSensingAgentPattern"); + m_sensingAgentPatterns.insert(std::pair(vehicle, pattern)); } +// ELF 0x3C0FF0. void AISettings::setManDownEquipment(const std::string& equipment) { m_manDownEquipment = equipment; } +// ELF 0x3C1020. void AISettings::setVehicleMaterialCost(const std::string& vehicle, unsigned char material, float cost) @@ -433,6 +573,7 @@ void AISettings::setVehicleMaterialCost(const std::string& vehicle, } // Adds a name to the bot-name roster used by getBotName. +// ELF 0x3C1190. void AISettings::addBotName(const std::string& first, const std::string& last) { const unsigned int count = static_cast(m_botNames.size()); @@ -458,6 +599,7 @@ void AISettings::addBotName(const std::string& first, const std::string& last) m_botNames.insert(position, std::pair(weight, first + " " + last)); } +// ELF 0x3C1520. void AISettings::setBotNameUnused(const std::string&) { // (*) five bytes in the binary - a bare `ret`. dice declared it, the .ai console binds it, and @@ -465,7 +607,7 @@ void AISettings::setBotNameUnused(const std::string&) } -// Initializes AI settings and their default values. +// ELF 0x3BD020 / 0x3BD5B0. Initializes AI settings and their default values. AISettings::AISettings() : m_maxNBots(-1) , m_numberOfBehaviours(0) @@ -508,104 +650,122 @@ AISettings::AISettings() // Registers the first settings/modifier instance using roster-static guards. // Those guards can remain stale until updateStaticMethods refreshes the roster. +// ELF 0x3E7100 / 0x3E71A0. IAISettings::IAISettings() { if (!CommonSingletonServer::m_iaiSettings) classManager->registerSimpleSingleton("IAISettings", this); } +// ELF 0x3E7240 / 0x3E72D0 / 0x3E7360. IAISettings::~IAISettings() { if (CommonSingletonServer::m_iaiSettings == this) classManager->unregisterSimpleSingleton("IAISettings"); } +// ELF 0x3E74B0 / 0x3E7550. IAISettingsModifier::IAISettingsModifier() { if (!CommonSingletonServer::m_iaiSettingsModifier) classManager->registerSimpleSingleton("IAISettingsModifier", this); } +// ELF 0x3E75F0 / 0x3E7680 / 0x3E7710. IAISettingsModifier::~IAISettingsModifier() { if (CommonSingletonServer::m_iaiSettingsModifier == this) classManager->unregisterSimpleSingleton("IAISettingsModifier"); } -// Remaining recovered field accessors. The constructor now supplies their proven backing fields; -// AISettings teardown remains a separate named frontier below. +// Remaining recovered field accessors. +// ELF 0x3BEF20. int AISettings::getMaxNBots() const { return m_maxNBots; } +// ELF 0x3BEF30. bool AISettings::getmaxBotsIncludeHumans() const { return m_maxBotsIncludeHumans; } +// ELF 0x3BEF40. float AISettings::getIgnoreCommanderDistance() const { return m_ignoreCommanderDistance; } +// ELF 0x3C00F0. float AISettings::getViewDistance() const { return m_viewDistance; } +// ELF 0x3C0620. float AISettings::getBotSkill() const { return m_botSkill; } +// ELF 0x3C0290. int AISettings::getNSides() const { return m_nSides; } +// ELF 0x3C0AA0. bool AISettings::isRespawnAllowed() const { return m_respawnAllowed; } +// ELF 0x3C0E90. bool AISettings::getAutoSpawnBots() const { return m_autoSpawnBots; } +// ELF 0x3C0BD0. const float* AISettings::getArmourClassValues() const { return m_armourClassValues; } +// ELF 0x3C0BE0. float AISettings::getArmourClassValue(int index) const { return m_armourClassValues[index]; } +// ELF 0x3BF700. void AISettings::setMaxNBots(int n) { m_maxNBots = n; } +// ELF 0x3BF710. void AISettings::maxBotsIncludeHumans(bool include) { m_maxBotsIncludeHumans = include; } +// ELF 0x3BF720. void AISettings::setIgnoreCommanderDistance(float distance) { m_ignoreCommanderDistance = distance; } +// ELF 0x3C0630. void AISettings::setBotSkill(float skill) { m_botSkill = skill; } // Sets the AI view distance and propagates it to every live bot player. +// ELF 0x3C0100. void AISettings::setViewDistance(float distance) { m_viewDistance = distance; @@ -639,179 +799,78 @@ void AISettings::setViewDistance(float distance) } } +// ELF 0x3C1550. void AISettings::setOverrideMenuSettings(bool override_) { m_overrideMenuSettings = override_; } -void AISettings::reset() -{ - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::reset"); -} - - -// [FRONTIER] Destruction requires cleanup of owned settings collections. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AISettings operation. +// ELF 0x3C02A0. Resets only the shipped subset of settings and registries. +bool AISettings::reset() +{ + if (AIRadio::m_instance) + AIRadio::m_instance->reset(); + // shipped defect: deleted entries stay in their vectors and can be deleted again. + for (unsigned int row = 0; row < m_behaviours.size(); ++row) + for (unsigned int i = 0; i < m_behaviours[row].size(); ++i) + if (m_behaviours[row][i]) + delete m_behaviours[row][i]; + for (unsigned int row = 0; row < m_planGenerators.size(); ++row) + for (unsigned int i = 0; i < m_planGenerators[row].size(); ++i) + if (m_planGenerators[row][i]) + delete m_planGenerators[row][i]; + for (unsigned int i = 0; i < m_planInterpreters.size(); ++i) + if (m_planInterpreters[i]) + delete m_planInterpreters[i]; + m_vehicleIndex.clear(); + m_vehicleNames.resize(0); + m_sensingAgentPatternIds.clear(); + m_sensingAgentPatterns.clear(); + m_maxNBots = -1; + // [UNRESOLVED] Types/names of the two words at +0x10/+0x14; both are zeroed here. + std::memset(m_gap16, 0, sizeof(m_gap16)); + m_numberOfBehaviours = 0; + m_informationGridDimension = 32; + m_viewDistance = 600.0f; + m_nSides = 0; + m_standardPersonality[0] = 0; + m_statsViewDistance = 512.0f; + m_standardPersonality[1] = 0; + m_autoSpawnBots = false; + m_botSkill = 0.75f; + m_respawnAllowed = true; + m_draw = false; + m_saiUpdateFrequency = 2.0f; + m_standardMoralAdmin[0] = 0; + m_standardMoralAdmin[1] = 0; + return true; +} + + +// ELF 0x3BE130 (1772 B; the other variants are 0x3BDA40 and 0x3BE820). The shipped body first deletes +// AIRadio::m_instance (null-tested, nonvirtual D1 + operator delete). Nothing in libaidll.so +// constructs an AIRadio (see AIRadio.h), so the pointer is null and the step does nothing; it is +// kept because the instruction is there. Then every behaviour and every plan generator (per +// vehicle row) and every plan interpreter go through their virtual deleting destructors (+4), +// and every vehicle material manager through its nonvirtual one. The pointers are not cleared. +// The containers, the strings and both interface bases follow as members. AISettings::~AISettings() { - BF2_AI_FRONTIER("dice::hfe::ai::AISettings::~AISettings"); -} - -// Console bindings for bot population and startup settings. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - -namespace { - -const char* const kAiSettingsConsoleTag = "aiSettings"; - -// Every forwarder takes the same receiver, and the [CHOSEN] caveat above covers all of them. -AISettings* consoleAiSettings() -{ - return static_cast( - static_cast(CommonSingletonServer::m_iaiSettings)); -} - -void consoleAiSettingsSetMaxNBots(int n) { consoleAiSettings()->setMaxNBots(n); } -void consoleAiSettingsSetNSides(int sides) { consoleAiSettings()->setNSides(sides); } -void consoleAiSettingsSetBotSkill(float skill) { consoleAiSettings()->setBotSkill(skill); } -void consoleAiSettingsMaxBotsIncludeHumans(bool include){ consoleAiSettings()->maxBotsIncludeHumans(include); } -void consoleAiSettingsSetInformationGridDimension(int d){ consoleAiSettings()->setInformationGridDimension(d); } -// the only forwarder here that is not A store: `setAutoSpawnBots` also calls -// `IAIMain::spawnBots`, so this console line has a side effect the other five do not. -void consoleAiSettingsSetAutoSpawnBots(bool enable) { consoleAiSettings()->setAutoSpawnBots(enable); } -// two arguments for one name: the console splits `addBotName T. Karlsson` on whitespace and -// the receiver puts the space back. See addBotName's own note. -void consoleAiSettingsAddBotName(std::string first, std::string last) - { consoleAiSettings()->addBotName(first, last); } - -// The recovered roster classes dispatch through the registered write interface and report -// inactive while it is absent. Their argument type strings and relative order are paired in both -// generated-console images. -IAISettingsModifier* consoleAiSettingsModifier() -{ - return static_cast(CommonSingletonServer::m_iaiSettingsModifier); -} - -void consoleAiSettingsSetMaxNumberOfBehaviours(int count) -{ - consoleAiSettingsModifier()->setMaxNumberOfBehaviours(count); -} - -void consoleAiSettingsSetVehicle(std::string name) -{ - consoleAiSettingsModifier()->setVehicle(name); -} - -void consoleAiSettingsSetVehicleClusterMapping(std::string vehicle, - std::string clusterVehicle) -{ - consoleAiSettingsModifier()->setVehicleClusterMapping(vehicle, clusterVehicle); -} - -void consoleAiSettingsSetVehicleMaterialCost(std::string vehicle, - materialId material, - float cost) -{ - consoleAiSettingsModifier()->setVehicleMaterialCost(vehicle, material, cost); -} - -void consoleAiSettingsSetManDownEquipment(std::string equipment) -{ - consoleAiSettingsModifier()->setManDownEquipment(equipment); -} - -void consoleAiSettingsCreateVehicleGroup(std::string name) -{ - consoleAiSettingsModifier()->createVehicleGroup(name); -} - -void consoleAiSettingsAddVehicleToVehicleGroup(std::string vehicle, - std::string group) -{ - consoleAiSettingsModifier()->addVehicleToVehicleGroup(vehicle, group); -} - -// Generic generated arguments retain the shared temp-and-commit extraction rule. materialId is the -// one recovered exception: its generated class calls the AI material extractor directly into the -// byte-sized static storage. -template -void convertAiSettingsRosterArgument(const std::string& text, T& storage) -{ - T value = storage; - std::istringstream stream(text); - stream >> value; - if (!stream.fail()) - storage = value; -} - -void convertAiSettingsRosterArgument(const std::string& text, materialId& storage) -{ - std::istringstream stream(text); - ::dice::hfe::ai::operator>>(stream, storage); -} - -} // anonymous namespace - -// Console bindings for AI settings and vehicle definitions. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -BF2_CONSOLE_OBJECT("aiSettings", 2, 0) -BF2_CONSOLE_METHOD_1(setMaxNBots, consoleAiSettingsSetMaxNBots, int, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(setNSides, consoleAiSettingsSetNSides, int, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(setBotSkill, consoleAiSettingsSetBotSkill, float, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(maxBotsIncludeHumans, consoleAiSettingsMaxBotsIncludeHumans, bool, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1(setInformationGridDimension, consoleAiSettingsSetInformationGridDimension, int, kAiSettingsConsoleTag) -// Exposes the auto-spawn setting used by level scripts. -BF2_CONSOLE_METHOD_1(setAutoSpawnBots, consoleAiSettingsSetAutoSpawnBots, bool, kAiSettingsConsoleTag) -// Registers the command used by BotNames.ai to populate the bot-name roster. -BF2_CONSOLE_METHOD_2(addBotName, consoleAiSettingsAddBotName, std::string, std::string, kAiSettingsConsoleTag) - -// ELF generated classes 262/267/268/269/270/283/284 and the matching PE CRT initializer order. The -// temporary BF2_CC_CONVERT specialization keeps every ordinary conversion unchanged while routing -// the `materialId` spelling through Material.cpp rather than std's character extractor. -#pragma push_macro("BF2_CC_CONVERT") -#undef BF2_CC_CONVERT -#define BF2_CC_CONVERT(T, oneBasedIndex) \ - if (index == (oneBasedIndex)) \ - { \ - static T s; \ - convertAiSettingsRosterArgument(value, s); \ - m_args[(oneBasedIndex) - 1] = reinterpret_cast(&s); \ - } - -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setMaxNumberOfBehaviours, - consoleAiSettingsSetMaxNumberOfBehaviours, - CommonSingletonServer::m_iaiSettingsModifier != 0, - int, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setVehicle, consoleAiSettingsSetVehicle, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_2_STATIC_ACTIVE(setVehicleClusterMapping, - consoleAiSettingsSetVehicleClusterMapping, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_3_STATIC_ACTIVE(setVehicleMaterialCost, - consoleAiSettingsSetVehicleMaterialCost, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, materialId, float, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(setManDownEquipment, - consoleAiSettingsSetManDownEquipment, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_1_STATIC_ACTIVE(createVehicleGroup, - consoleAiSettingsCreateVehicleGroup, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, kAiSettingsConsoleTag) -BF2_CONSOLE_METHOD_2_STATIC_ACTIVE(addVehicleToVehicleGroup, - consoleAiSettingsAddVehicleToVehicleGroup, - CommonSingletonServer::m_iaiSettingsModifier != 0, - std::string, std::string, kAiSettingsConsoleTag) - -#pragma pop_macro("BF2_CC_CONVERT") - -// Handed to the console registry by AIModule::init, beside the `ai` object's list. -ConsoleObjectList& aiSettingsConsoleObjects() -{ - return consoleBindingList(kAiSettingsConsoleTag); + delete AIRadio::m_instance; + for (unsigned int row = 0; row < m_behaviours.size(); ++row) + for (unsigned int i = 0; i < m_behaviours[row].size(); ++i) + if (m_behaviours[row][i]) + delete m_behaviours[row][i]; + for (unsigned int row = 0; row < m_planGenerators.size(); ++row) + for (unsigned int i = 0; i < m_planGenerators[row].size(); ++i) + if (m_planGenerators[row][i]) + delete m_planGenerators[row][i]; + for (unsigned int i = 0; i < m_planInterpreters.size(); ++i) + if (m_planInterpreters[i]) + delete m_planInterpreters[i]; + for (unsigned int i = 0; i < m_vehicleMaterialManagers.size(); ++i) + if (m_vehicleMaterialManagers[i]) + delete m_vehicleMaterialManagers[i]; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettings.h b/Code/BF2/AI/AIDLL/AI/Main/AISettings.h index abb85fb56..34ccac5d6 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettings.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettings.h @@ -10,7 +10,13 @@ #include #include +#include + +#include "../AIStrategic/StatusMap.h" +#include "../AIStrategic/StrategyCondition.h" +#include "../AIStrategicEntity/AIStrategicObject.h" #include "AISettingsInterfaces.h" // the two bases, all 87 slots - RW-9's retirement +#include "AIStreamOperators.h" // the console argument extractors namespace dice { namespace hfe { @@ -21,6 +27,7 @@ class BotBehaviour; class BotMoralAdmin; class ISensingAgentPattern; class PlanGenerator; +class PlanInterpreter; // The two abstract halves are declared in AISettingsInterfaces.h with all 87 virtual positions. // AISettings is the concrete implementation in both recovered images. @@ -44,7 +51,7 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual float* getVehicleMods(int) const; virtual BotBehaviour* getBehaviour(int, int) const; virtual BotBehaviour* getDefaultBehaviour(int) const; - virtual void* getPlanInterpreter(int) const; + virtual PlanInterpreter* getPlanInterpreter(int) const; virtual PlanGenerator* getPlanGenerator(int, int) const; virtual float getViewDistance() const; virtual float getStatsViewDistance() const; @@ -75,7 +82,7 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual bool getAutoSpawnBots() const; virtual const float* getArmourClassValues() const; virtual float getArmourClassValue(int) const; - virtual void reset(); + virtual bool reset(); virtual int getManDownEquipmentType(); virtual bool isValidMaterial(int, unsigned char) const; virtual float getVehicleMaterialCost(const std::string&, unsigned char) const; @@ -86,8 +93,11 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual bool overrideMenuSettings() const; virtual bool getOverrideMenuSettings() const; - // IAISettingsModifier, slots 0..38 in vtable order; reset is shared with the read - // side above and is therefore declared only once. + // The IAISettingsModifier overriders, in AISettings's own primary-vtable order (ELF vtable for + // AISettings +0xC8..+0x15C; the order differs from the interface's: createVehicleGroup precedes + // setVehicle, and setAutoSpawnBots follows addSensingAgentPattern). The interface's own slot + // order is IAISettingsModifier's declaration order. reset is shared with the read side above + // and is therefore declared only once. virtual void setMaxNBots(int); virtual void maxBotsIncludeHumans(bool); virtual void setIgnoreCommanderDistance(float); @@ -108,19 +118,19 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual void setNSides(int); virtual void setBotSkill(float); virtual void setSAIUpdateFrequency(float); - virtual void setStandardPersonality(float *, int); - virtual void setStandardMoralAdmin(BotMoralAdmin *, int); - virtual void setRespawnAllowed(bool); + virtual void createVehicleGroup(const std::string&); virtual void setVehicle(const std::string&); virtual void setVehicleClusterMapping(const std::string&, const std::string&); - virtual void createVehicleGroup(const std::string&); virtual void addVehicleToVehicleGroup(int, const std::string&); virtual void addVehicleToVehicleGroup(const std::string&, const std::string&); - virtual void setAutoSpawnBots(bool); + virtual void setStandardPersonality(float *, int); + virtual void setStandardMoralAdmin(BotMoralAdmin *, int); + virtual void setRespawnAllowed(bool); virtual void setDraw(bool); virtual void setSensingAgentPatternName(const std::string&); virtual void setSensingAgentNullPattern(ISensingAgentPattern *); virtual void addSensingAgentPattern(int, ISensingAgentPattern *); + virtual void setAutoSpawnBots(bool); virtual void setManDownEquipment(const std::string&); virtual void setVehicleMaterialCost(const std::string&, unsigned char, float); virtual void addBotName(const std::string&, const std::string&); @@ -128,11 +138,16 @@ class AISettings : public IAISettings, public IAISettingsModifier virtual void setOverrideMenuSettings(bool); private: + // Non-virtual pool helpers (direct PLT calls), ELF 0x3BFA20 / 0x3BFC50 / 0x3BFDE0 / 0x3C0040. + void prepareBehaviourPool(int vehicle, int index); + void preparePlanGeneratorPool(int vehicle, int index); + void preparePlanInterpreterPool(int vehicle); + void prepareVehicleGroup(int vehicle); + // Field offsets describe retail x86 layout; native STL sizes may differ. /* 8 */ int m_maxNBots; // = -1 getMaxNBots / setMaxNBots /* 12 */ int m_numberOfBehaviours; // = 0 getNumberOfBehaviours - /* 16 */ char m_gap16[8]; // the constructor never writes these eight bytes - // and no accessor reads them. [UNRESOLVED] + /* 16 */ char m_gap16[8]; // [UNRESOLVED] two words reset zeroes; ctor leaves them alone /* 24 */ float m_viewDistance; // = -1.0f getViewDistance /* 28 */ float m_statsViewDistance; // = 30.0f get/setStatsViewDistance /* 32 */ float m_botSkill; // = 0.75f get/setBotSkill @@ -154,7 +169,7 @@ class AISettings : public IAISettings, public IAISettingsModifier /* 60 */ std::vector > m_behaviours; /* 72 */ std::vector m_defaultBehaviour; // index into m_behaviours[v]; -1 = none /* 84 */ std::vector > m_planGenerators; - /* 96 */ std::vector m_planInterpreters; // [UNRESOLVED] element type - placeholder + /* 96 */ std::vector m_planInterpreters; // each a BAPInterpreter (vector::_M_insert_aux) /* 108 */ std::map m_sensingAgentPatterns; /* 120 */ std::vector m_vehicleMaterialManagers; @@ -178,13 +193,17 @@ class AISettings : public IAISettings, public IAISettingsModifier // Six zero-based armor-class weights, initialized to 1, 3, 8, 15, 10, and 12. /* 240 */ float m_armourClassValues[6]; - /* 264 */ std::map m_tree264; // [UNRESOLVED] Key and mapped types are placeholders. + // Pattern name -> registration index (setSensingAgentPatternName, ELF 0x3C0C50: insert_unique of + // the map's size before the insert). Name [INFERRED]. + /* 264 */ std::map m_sensingAgentPatternIds; // Mutable because getBotName rotates the list while satisfying the const interface. /* 276 */ mutable std::list > m_botNames; // addBotName / getBotName /* 280 */ bool m_overrideMenuSettings; // = false overrideMenuSettings + getOverrideMenuSettings /* 281 */ bool m_drawBotStats; // = true getDrawBotStats / setDrawBotStats }; +// The console argument extractors moved to AIStreamOperators.h (included above). + } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h b/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h index a9fc688ab..07c17284b 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h @@ -19,6 +19,7 @@ class BotBehaviour; class BotMoralAdmin; class ISensingAgentPattern; class PlanGenerator; +class PlanInterpreter; // [UNRESOLVED] enumerators. Both are one dword on the stack at every call site. enum BotLodLevel : int; @@ -38,7 +39,7 @@ class IAISettings virtual float* getVehicleMods(int) const = 0; virtual BotBehaviour* getBehaviour(int, int) const = 0; virtual BotBehaviour* getDefaultBehaviour(int) const = 0; - virtual void* getPlanInterpreter(int) const = 0; + virtual PlanInterpreter* getPlanInterpreter(int) const = 0; virtual PlanGenerator* getPlanGenerator(int, int) const = 0; virtual float getViewDistance() const = 0; virtual float getStatsViewDistance() const = 0; @@ -72,7 +73,7 @@ class IAISettings virtual bool getAutoSpawnBots() const = 0; virtual const float* getArmourClassValues() const = 0; virtual float getArmourClassValue(int) const = 0; - virtual void reset() = 0; + virtual bool reset() = 0; virtual int getManDownEquipmentType() = 0; virtual bool isValidMaterial(int, unsigned char) const = 0; virtual float getVehicleMaterialCost(const std::string&, unsigned char) const = 0; @@ -124,7 +125,7 @@ class IAISettingsModifier virtual void setSensingAgentPatternName(const std::string&) = 0; virtual void setSensingAgentNullPattern(ISensingAgentPattern *) = 0; virtual void addSensingAgentPattern(int, ISensingAgentPattern *) = 0; - virtual void reset() = 0; + virtual bool reset() = 0; virtual void setManDownEquipment(const std::string&) = 0; virtual void setVehicleMaterialCost(const std::string&, unsigned char, float) = 0; virtual void addBotName(const std::string&, const std::string&) = 0; diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp new file mode 100644 index 000000000..fdd229400 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp @@ -0,0 +1,1026 @@ +// The AI script vocabulary: stream operators for the AI enums. AI/Main/AIStreamOperators.cpp is an +// attested FILE symbol of libaidll.so (its static initializer is named after the TU's first function, +// operator>>(istream&, vector&) 0x3C4150); the text runs to 0x3C9170. + +// static init: ELF 0x3C9170 (__tcf_0 0x3C91D0, _GLOBAL__I 0x3C9200): 's Init object only. +#include + +#include "AIStreamOperators.h" +#include "../../../../Core/StringUtil.h" +#include "../../../../IO/Input/Input.h" + +#include + +namespace dice { +namespace hfe { +namespace ai { + +// The strategy vocabulary extractors (moved from AISettings.cpp; this TU is their image placement). Each table is the ELF's compare chain +// in code order; the chains compare the whole token with std::string::compare. +namespace { + +struct AIEnumSpelling +{ + const char* name; + int value; +}; + +// Answers the first matching spelling's value, or `fallback`; the caller decides whether to assign it. +int readAIEnumSpelling(std::istream& in, const AIEnumSpelling* table, int count, int fallback) +{ + std::string token; + in >> token; + for (int i = 0; i < count; ++i) + { + if (token.compare(table[i].name) == 0) + return table[i].value; + } + return fallback; +} + +} // anonymous namespace + +static const AIEnumSpelling kTemperatureTreeNodeSpellings[] = { + { "TTNTop", 0 }, + { "TTNDynamic", 1 }, + { "TTNStatic", 2 }, + { "TTNFriendly", 3 }, + { "TTNHostile", 4 }, + { "TTNTactical", 5 }, + { "TTNStrategic", 6 }, + { "TTNFriendGroundAndNaval", 7 }, + { "TTNHostileGroundAndNaval", 8 }, + { "TTNFriendArtillery", 9 }, + { "TTNHostileArtillery", 10 }, + { "TTNFriendGround", 11 }, + { "TTNFriendNaval", 12 }, + { "TTNFriendAir", 13 }, + { "TTNHostileGround", 14 }, + { "TTNHostileAir", 15 }, + { "TTNHostileNaval", 16 }, + { "TTNFriendGroundFixed", 17 }, + { "TTNFriendGroundMobile", 18 }, + { "TTNFriendNavalFixed", 19 }, + { "TTNFriendNavalMobile", 20 }, + { "TTNFriendAirFixed", 21 }, + { "TTNFriendAirMobile", 22 }, + { "TTNHostileGroundFixed", 23 }, + { "TTNHostileGroundMobile", 24 }, + { "TTNHostileNavalFixed", 25 }, + { "TTNHostileNavalMobile", 26 }, + { "TTNHostileAirFixed", 27 }, + { "TTNHostileAirMobile", 28 }, + { "TTNDefensivePos", 29 }, + { "TTNTopography", 30 }, + { "TTNEditors", 31 }, + { "TTNFixedWeapons", 32 }, + { "TTNAirfield", 33 }, + { "TTNProduction", 34 }, + { "TTNRadar", 35 }, + { "TTNTransportation", 36 }, + { "TTNControlPoint", 37 }, + { "TTNSupplies", 38 }, + { "TTNSuppliesRepair", 39 }, + { "TTNSuppliesAmmunition", 40 }, +}; + +// ELF 0x3C5400 +std::istream& operator>>(std::istream& in, TemperatureTreeNode& value) +{ + value = static_cast(readAIEnumSpelling(in, kTemperatureTreeNodeSpellings, + sizeof(kTemperatureTreeNodeSpellings) / sizeof(kTemperatureTreeNodeSpellings[0]), -1)); + return in; +} + +static const AIEnumSpelling kCombatStrengthTypeSpellings[] = { + { "0", 0 }, { "CSTInfantry", 0 }, { "CSTInfantery", 0 }, { "Infantry", 0 }, { "Infantery", 0 }, + { "1", 1 }, { "CSTLightArmour", 1 }, { "LightArmour", 1 }, + { "2", 2 }, { "CSTHeavyArmour", 2 }, { "HeavyArmour", 2 }, + { "3", 3 }, { "CSTNavalArmour", 3 }, { "NavalArmour", 3 }, + { "4", 4 }, { "CSTHelicopter", 4 }, { "Helicopter", 4 }, + { "5", 5 }, { "CSTAirPlane", 5 }, { "AirPlane", 5 }, + { "CSTNumberOfTypes", 6 }, { "All", 6 }, +}; + +// ELF 0x3C5A60. The final "All" comparison is made even though either outcome stores 6. +std::istream& operator>>(std::istream& in, CombatStrengthType& value) +{ + value = static_cast(readAIEnumSpelling(in, kCombatStrengthTypeSpellings, + sizeof(kCombatStrengthTypeSpellings) / sizeof(kCombatStrengthTypeSpellings[0]), 6)); + return in; +} + +static const AIEnumSpelling kLandingZoneDirectionSpellings[] = { + { "LZXMin", 0 }, { "XMin", 0 }, { "0", 0 }, + { "LZZMin", 1 }, { "ZMin", 1 }, { "1", 1 }, + { "LZXMax", 2 }, { "XMax", 2 }, { "2", 2 }, + { "LZZMax", 3 }, { "ZMax", 3 }, { "3", 3 }, + { "LZUndefined", 4 }, { "Undefined", 4 }, { "-1", 4 }, { "4", 4 }, +}; + +// ELF 0x3C8A20. The final "4" comparison is made even though either outcome stores 4. +std::istream& operator>>(std::istream& in, LandingZoneDirection& value) +{ + value = static_cast(readAIEnumSpelling(in, kLandingZoneDirectionSpellings, + sizeof(kLandingZoneDirectionSpellings) / sizeof(kLandingZoneDirectionSpellings[0]), 4)); + return in; +} + +// ELF 0x3C5F00. +static const AIEnumSpelling kConditionStrengthSpellings[] = { + { "Required", 0 }, + { "RequiredPositive", 1 }, + { "RequiredNegative", 2 }, + { "Advisory", 3 }, + { "AdvisoryPositive", 4 }, + { "AdvisoryNegative", 5 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionStrength& value) +{ + value = static_cast(readAIEnumSpelling(in, kConditionStrengthSpellings, sizeof(kConditionStrengthSpellings) / sizeof(kConditionStrengthSpellings[0]), 6)); + return in; +} + +// ELF 0x3C60E0. +static const AIEnumSpelling kCompareTypeSpellings[] = { + { "Crisp", 0 }, + { "Fuzzy", 1 }, + { "FuzzySqr", 2 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::CompareType& value) +{ + value = static_cast(readAIEnumSpelling(in, kCompareTypeSpellings, sizeof(kCompareTypeSpellings) / sizeof(kCompareTypeSpellings[0]), 3)); + return in; +} + +// ELF 0x3C6240. +static const AIEnumSpelling kConditionSideSpellings[] = { + { "Friendly", 0 }, + { "Enemy", 1 }, + { "Both", 2 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionSide& value) +{ + value = static_cast(readAIEnumSpelling(in, kConditionSideSpellings, sizeof(kConditionSideSpellings) / sizeof(kConditionSideSpellings[0]), 3)); + return in; +} + +// ELF 0x3C68A0. +static const AIEnumSpelling kCompareSpellings[] = { + { "Equal", 0 }, + { "=", 0 }, + { "EqualGreater", 1 }, + { ">=", 1 }, + { "EqualSmaller", 2 }, + { "<=", 2 }, + { "Quotient", 3 }, + { "/", 3 }, + { "QuotientGreater", 4 }, + { ">/", 4 }, + { "QuotientSmaller", 5 }, + { "-", 7 }, + { "DifferenceSmaller", 8 }, + { "<-", 8 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::Compare& value) +{ + value = static_cast(readAIEnumSpelling(in, kCompareSpellings, sizeof(kCompareSpellings) / sizeof(kCompareSpellings[0]), 9)); + return in; +} + +// ELF 0x3C6D30. +static const AIEnumSpelling kConditionalSpellings[] = { + { "Ticket", 13 }, + { "ControlPoint", 14 }, + { "Time", 15 }, + { "StartTime", 16 }, + { "Attacks", 17 }, + { "Defences", 18 }, + { "Carrier", 0 }, + { "HeavyNaval", 1 }, + { "Naval", 3 }, + { "Bomber", 4 }, + { "Fighter", 5 }, + { "AntiAir", 6 }, + { "Air", 7 }, + { "LCVP", 2 }, + { "Infantry", 8 }, + { "Infantery", 8 }, + { "Artillery", 9 }, + { "AntiTank", 10 }, + { "HeavyAttack", 11 }, + { "FastAttack", 12 }, + { "NumberOfFriendlyAreas", 19 }, + { "NumberOfNeutralAreas", 20 }, + { "NumberOfHostileAreas", 21 }, + { "Flank", 22 }, + { "Base", 23 }, + { "Close", 24 }, + { "Centre", 25 }, + { "Remote", 26 }, + { "North", 29 }, + { "East", 32 }, + { "South", 31 }, + { "West", 30 }, + { "Route", 27 }, + { "Bridge", 28 }, + { "FrontFlank", 33 }, + { "FrontBase", 34 }, + { "FrontClose", 35 }, + { "FrontCentre", 36 }, + { "FrontRemote", 37 }, + { "FrontNeutral", 38 }, + { "Front", 39 }, + { "Safe", 40 }, + { "EnemyObject", 41 }, + { "UnReachable", 42 }, + { "UnitConstant", 43 }, +}; + +std::istream& operator>>(std::istream& in, StrategyCondition::Conditional& value) +{ + value = static_cast(readAIEnumSpelling(in, kConditionalSpellings, sizeof(kConditionalSpellings) / sizeof(kConditionalSpellings[0]), 44)); + return in; +} + +// ELF 0x3C6330: a 27-entry jump table (cmpl $0x1a); 0, 21, 25 and values above 26 print nothing. +std::ostream& operator<<(std::ostream& out, AIStrategicObject::StrategicObjectType type) +{ + switch (type) + { + case AIStrategicObject::Flank: out << "Flank"; break; + case AIStrategicObject::Centre: out << "Centre"; break; + case AIStrategicObject::Base: out << "Base"; break; + case AIStrategicObject::Close: out << "Close"; break; + case AIStrategicObject::Remote: out << "Remote"; break; + case AIStrategicObject::AirSpawner: out << "AirSpawner"; break; + case AIStrategicObject::LandSpawner: out << "LandSpawner"; break; + case AIStrategicObject::NavalSpawner: out << "NavalSpawner"; break; + case AIStrategicObject::SoldierSpawner: out << "SoldierSpawner"; break; + case AIStrategicObject::StrongPoint: out << "StrongPoint"; break; + case AIStrategicObject::ChokePoint: out << "ChokePoint"; break; + case AIStrategicObject::Bridge: out << "Bridge"; break; + case AIStrategicObject::AirField: out << "AirField"; break; + case AIStrategicObject::SupplyPoint: out << "SupplyPoint"; break; + case AIStrategicObject::Route: out << "Route"; break; + case AIStrategicObject::ControlPoint: out << "ControlPoint"; break; + case AIStrategicObject::North: out << "North"; break; + case AIStrategicObject::West: out << "West"; break; + case AIStrategicObject::South: out << "South"; break; + case AIStrategicObject::East: out << "East"; break; + case AIStrategicObject::Front: out << "Front"; break; + case AIStrategicObject::Safe: out << "Safe"; break; + case AIStrategicObject::Enemy: out << "Enemy"; break; + case AIStrategicObject::NeutralType: out << "Neutral"; break; + default: break; + } + return out; +} + +// ELF 0x3C6460. +static const AIEnumSpelling kStrategicObjectTypeSpellings[] = { + { "Flank", 1 }, + { "Centre", 2 }, + { "Base", 3 }, + { "Close", 4 }, + { "Remote", 5 }, + { "AirSpawner", 6 }, + { "LandSpawner", 7 }, + { "NavalSpawner", 8 }, + { "SoldierSpawner", 9 }, + { "StrongPoint", 10 }, + { "ChokePoint", 11 }, + { "Bridge", 12 }, + { "AirField", 13 }, + { "SupplyPoint", 14 }, + { "Route", 15 }, + { "ControlPoint", 16 }, + { "Front", 22 }, + { "Safe", 23 }, + { "Enemy", 24 }, + { "Neutral", 26 }, + { "North", 17 }, + { "West", 18 }, + { "South", 19 }, + { "East", 20 }, +}; + +std::istream& operator>>(std::istream& in, AIStrategicObject::StrategicObjectType& value) +{ + value = static_cast(readAIEnumSpelling(in, kStrategicObjectTypeSpellings, sizeof(kStrategicObjectTypeSpellings) / sizeof(kStrategicObjectTypeSpellings[0]), 27)); + return in; +} + +// ELF 0x3C8CC0. +static const AIEnumSpelling kStatusSpellings[] = { + { "Owned", 0 }, + { "Hostile", 1 }, + { "Neutral", 2 }, + { "Unknown", 3 }, +}; + +std::istream& operator>>(std::istream& in, StatusMap::Status& value) +{ + const int read = readAIEnumSpelling(in, kStatusSpellings, sizeof(kStatusSpellings) / sizeof(kStatusSpellings[0]), -1); + if (read != -1) + value = static_cast(read); + return in; +} + +// ELF 0x3C78B0: the four spellings; any other value prints nothing. +std::ostream& operator<<(std::ostream& out, BotLodLevel lod) +{ + switch (lod) + { + case 0: out << "BLLFull"; break; + case 1: out << "BLLMedium"; break; + case 2: out << "BLLLight"; break; + case 3: out << "BLLNone"; break; + default: break; + } + return out; +} + +// ELF 0x3C7930: "BLLFull"/"Full"/"0" 0, "BLLMedium"/"Medium"/"1" 1, "BLLLight"/"Light"/"2" 2, +// anything else 3 (BLLNone). The image still compares "BLLNone" and then "None", but both +// outcomes store 3 (the last compare's result is not tested). +std::istream& operator>>(std::istream& in, BotLodLevel& lod) +{ + std::string token; + in >> token; + if (token.compare("BLLFull") == 0 || token.compare("Full") == 0 || token.compare("0") == 0) + lod = static_cast(0); + else if (token.compare("BLLMedium") == 0 || token.compare("Medium") == 0 || token.compare("1") == 0) + lod = static_cast(1); + else if (token.compare("BLLLight") == 0 || token.compare("Light") == 0 || token.compare("2") == 0) + lod = static_cast(2); + else + lod = static_cast(3); // BotMain.h's enum has no name for 3 (BLLNone) + return in; +} + +// ELF 0x3C7AE0: a 59-entry jump table (cmpl $0x3a); 48 and values above 58 print nothing. +std::ostream& operator<<(std::ostream& out, BAPConditionType type) +{ + static const char* const kNames[59] = { + "LookDeviation", "Precision", "Precision3d", "BombPrecision3d", "&&", "EndOfPath", "false", + "Generic1Arg", "Generic2Arg", "InsideBattleZone", "Iteration", "LineOfFire", + "PointDistance", "PointInFront", "!", "DistanceToProj", "StrategicObjectStatus", + "ObjectBehind", "ObjectDistance", "ObjectDistanceToPoint", "ObjectEnemyOccupied", + "ObjectExists", "ObjectHealth", "ObjectInFront", "ObjectInLandingZone", + "ObjectInsideFrustum", "ObjectLineOfFire", "ObjectManDown", "ObjectMoved", + "ObjectOccupied", "ObjectSpeed", "ObjectTouchingGround", "ObjectValidAiming", + "ObjectValidPosition", "ObjectVisible", "||", "PointAt", "Position", "SharedCondition", + "Time", "true", "WeaponMagAmmo", "WeaponTotalAmmo", "TotalWeaponAmmo", + "WeaponReadyToFire", "WeaponTargetReachable", "WeaponHeat", "WeaponHasLockOnTarget", + 0, "IsTriggered", "Allow fire", "Sprinting", "Zoomed", "Detonator active", + "Weapon active", "<", "Ok to throw grenade", "Splash damage", "Triggerable Active" + }; + const unsigned int index = static_cast(type); // `ja` default: unsigned bound + if (index < 59 && kNames[index]) + out << kNames[index]; + return out; +} + +// ELF 0x3C7D90: a 45-entry jump table (cmpl $0x2c); 30 and values above 44 print nothing. +// The names are the BAPST* spellings without the prefix, except "if" and "while" (lower case). +std::ostream& operator<<(std::ostream& out, BAPStatementType type) +{ + static const char* const kNames[45] = { + "Parallel", "Serial", "PlanEnd", "if", "Wait", "while", "AimAt", "MoveTo", + "MoveToDirection", "MoveToObject", "MoveAwayFromObject", "Trigger", "TriggerContinously", + "Idle", "ResetControls", "InfoWrapper", "AimingWrapper", "FinishedWrapper", + "WeaponWrapper", "LookAtWrapper", "Sense", "OverrideSensingAgent", "PlaceC4", "LookAt", + "Turn", "Roll3d", "SoldierPose", "UpdateVehicle", "ChangeWeapon", "ICChangeVehicle", 0, + "ICTurnLock", "Evaluate", "NotifyBot", "PhysicsEnable", "SetSensingAgentFocus", + "MergeSoldierInputs", "SendRadioMessage", "Debug", "ForgetTarget", + "UseFlareOnMissileLock", "RunOverObject", "HonkHorn", "EvaluateCondition", "Revive" + }; + const unsigned int index = static_cast(type); + if (index < 45 && kNames[index]) + out << kNames[index]; + return out; +} + +// ELF 0x3C7FA0: the BAPST* spelling or the bare name, in the image's compare order (note "AImAt", +// "TurnLock" and "ChangeVehicle" for the IC statements); no match gives 45. +static const AIEnumSpelling kStatementTypeSpellings[] = { + { "BAPSTParallel", 0 }, { "Parallel", 0 }, + { "BAPSTSerial", 1 }, { "Serial", 1 }, + { "BAPSTPlanEnd", 2 }, { "PlanEnd", 2 }, + { "BAPSTIf", 3 }, { "If", 3 }, + { "BAPSTWait", 4 }, { "Wait", 4 }, + { "BAPSTWhile", 5 }, { "While", 5 }, + { "BAPSTAimAt", 6 }, { "AImAt", 6 }, + { "BAPSTMoveTo", 7 }, { "MoveTo", 7 }, + { "BAPSTTurn", 24 }, { "Turn", 24 }, + { "BAPSTMoveToDirection", 8 }, { "MoveToDirection", 8 }, + { "BAPSTMoveToObject", 9 }, { "MoveToObject", 9 }, + { "BAPSTMoveAwayFromObject", 10 }, { "MoveAwayFromObject", 10 }, + { "BAPSTTrigger", 11 }, { "Trigger", 11 }, + { "BAPSTTriggerContinously", 12 }, { "TriggerContinously", 12 }, + { "BAPSTIdle", 13 }, { "Idle", 13 }, + { "BAPSTResetControls", 14 }, { "ResetControls", 14 }, + { "BAPSTInfoWrapper", 15 }, { "InfoWrapper", 15 }, + { "BAPSTSense", 20 }, { "Sense", 20 }, + { "BAPSTLookAt", 23 }, { "LookAt", 23 }, + { "BAPSTOverrideSensingAgent", 21 }, { "OverrideSensingAgent", 21 }, + { "BAPSTPlaceC4", 22 }, { "PlaceC4", 22 }, + { "BAPSTRoll3d", 25 }, { "Roll3d", 25 }, + { "BAPSTSoldierPose", 26 }, { "SoldierPose", 26 }, + { "BAPSTUpdateVehicle", 27 }, { "UpdateVehicle", 27 }, + { "BAPSTChangeWeapon", 28 }, { "ChangeWeapon", 28 }, + { "BAPSTICTurnLock", 31 }, { "TurnLock", 31 }, + { "BAPSTICChangeVehicle", 29 }, { "ChangeVehicle", 29 }, + { "BAPSTEvaluate", 32 }, { "Evaluate", 32 }, + { "BAPSTNotifyBot", 33 }, { "NotifyBot", 33 }, + { "BAPSTAimingWrapper", 16 }, { "AimingWrapper", 16 }, + { "BAPSTWeaponWrapper", 18 }, { "WeaponWrapper", 18 }, + { "BAPSTLookAtWrapper", 19 }, { "LookAtWrapper", 19 }, + { "BAPSTFinishedWrapper", 17 }, { "FinishedWrapper", 17 }, + { "BAPSTPhysicsEnable", 34 }, { "PhysicsEnable", 34 }, + { "BAPSTSetSensingAgentFocus", 35 }, { "SetSensingAgentFocus", 35 }, + { "BAPSTMergeSoldierInputs", 36 }, { "MergeSoldierInputs", 36 }, + { "BAPSTSendRadioMessage", 37 }, { "SendRadioMessage", 37 }, + { "BAPSTDebug", 38 }, { "Debug", 38 }, + { "BAPSTForgetTarget", 39 }, { "ForgetTarget", 39 }, + { "BAPSTUseFlareOnMissileLock", 40 }, { "UseFlareOnMissileLock", 40 }, + { "BAPSTRunOverObject", 41 }, { "RunOverObject", 41 }, + { "BAPSTHonkHorn", 42 }, { "HonkHorn", 42 }, + { "BAPSTEvaluateCondition", 43 }, { "EvaluateCondition", 43 }, + { "BAPSTRevive", 44 }, { "Revive", 44 }, +}; + +std::istream& operator>>(std::istream& in, BAPStatementType& type) +{ + type = static_cast(readAIEnumSpelling(in, kStatementTypeSpellings, sizeof(kStatementTypeSpellings) / sizeof(kStatementTypeSpellings[0]), 45)); + return in; +} + +// ELF 0x3C4150 +std::istream& operator>>(std::istream& in, std::vector& values) +{ + values.erase(values.begin(), values.end()); + unsigned value; + for (;;) + { + in >> value; + values.push_back(value); + if (in.peek() == std::char_traits::eof() || in.peek() == ' ') + break; + char separator; + in >> separator; + } + return in; +} + +// ELF 0x3C4220 +std::ostream& operator>>(std::ostream& out, const std::vector& values) +{ + for (std::vector::const_iterator it = values.begin(); it != values.end(); ++it) + { + out << static_cast(*it); + // shipped defect: tests the current iterator, so even the final element gets a slash. + if (it != values.end()) + out << "/"; + } + return out; +} + +// ELF 0x3C42A0 +std::ostream& operator<<(std::ostream& out, const std::list& values) +{ + std::list::const_iterator it = values.begin(); + // shipped defect: the iterator is never incremented. + while (it != values.end()) + { + out << it->x << '/'; + out << it->y; + if (it != values.end()) + out << ","; + } + return out; +} + +// ELF 0x3C4350 +std::istream& operator>>(std::istream& in, std::list& values) +{ + values.clear(); + float value; + for (;;) + { + Vec2 point = { 0.0f, 0.0f }; + char separator; + in >> value >> separator; + point.x = value; + in >> value; + point.y = value; + values.insert(values.end(), point); + if (in.peek() == std::char_traits::eof() || in.peek() == ' ') + break; + in >> separator; + } + return in; +} + +static const char* const kInformationNames[] = { + "ITProduction", + "ITAmmunition", + "ITRepair", + "ITUnit", + "ITAir", + "ITHelicopter", + "ITGround", + "ITNaval", + "ITControlpoint", + "ITRadar", + "ITAirfield", + "ITTransportation", + "ITArtillery", + "ITFixed", + "ITCover", + "ITMobile", + "ITUnmanned", + "ITLowPriority", + "ITStructure", + "ITBiological", + "ITVegetation", + "ITSoldier", + "ITObstructedView", + "ITNoTemperature", + "ITHasWreck", + "ITObstacle", + "ITHasCarHorn", +}; +// ELF 0x3C4440 +std::ostream& operator<<(std::ostream& out, InformationType value) +{ + const unsigned index = static_cast(value); + if (index < 27) + out << kInformationNames[index]; + return out; +} + +// ELF 0x3C4590 +std::istream& operator>>(std::istream& in, InformationType& value) +{ + static const AIEnumSpelling spellings[] = { + { "ITProduction", 0 }, + { "ITAmmunition", 1 }, + { "ITRepair", 2 }, + { "ITUnit", 3 }, + { "ITAir", 4 }, + { "ITGround", 6 }, + { "ITNaval", 7 }, + { "ITControlpoint", 8 }, + { "ITRadar", 9 }, + { "ITAirfield", 10 }, + { "ITTransportation", 11 }, + { "ITArtillery", 12 }, + { "ITFixed", 13 }, + { "ITCover", 14 }, + { "ITMobile", 15 }, + { "ITHasWreck", 24 }, + { "ITObstacle", 25 }, + { "ITHasCarHorn", 26 }, + { "ITUnmanned", 16 }, + { "ITLowPriority", 17 }, + { "ITStructure", 18 }, + { "ITBiological", 19 }, + { "ITVegetation", 20 }, + { "ITSoldier", 21 }, + { "ITObstructedView", 22 }, + { "ITNoTemperature", 23 }, + { "ITHelicopter", 5 }, + }; + value = static_cast(readAIEnumSpelling(in, spellings, 27, -1)); + return in; +} + +static const char* const kPlayerInputNames[] = { + "PIYaw", + "PIPitch", + "PIRoll", + "PIThrottle", + "PIMouseLookX", + "PIMouseLookY", + "PICameraX", + "PICameraY", + "PIFire", + "PIAction", + "PIUse", + "PIMouseLook", + "PIAltSprint", + "PISprint", + "PIWeaponSelect1", + "PIWeaponSelect2", + "PIWeaponSelect3", + "PIWeaponSelect4", + "PIWeaponSelect5", + "PIWeaponSelect6", + "PIWeaponSelect7", + "PIWeaponSelect8", + "PIWeaponSelect9", + "PIPositionSelect1", + "PIPositionSelect2", + "PIPositionSelect3", + "PIPositionSelect4", + "PIPositionSelect5", + "PIPositionSelect6", + "PIPositionSelect7", + "PIPositionSelect8", + "PIAltFire", + "PIReload", + nullptr, + "PIDrop", + "PIToggleCameraMode", + "PIToggleCamera", + "PILie", + "PICrouch", + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + "PIFlareFire", + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + "PISayAll", + "PISayTeam", + "PINextItem", + "PIPrevItem", + "PICommunication", + nullptr, + "PINone", +}; +// These are the AI namespace overloads, distinct from IO/Input's io namespace operators. +// ELF 0x3C4990 +std::ostream& operator<<(std::ostream& out, io::PlayerInputMap value) +{ + const unsigned index = static_cast(value); + if (index < 65 && kPlayerInputNames[index]) + out << kPlayerInputNames[index]; + return out; +} + +// ELF 0x3C4BB0 +std::istream& operator>>(std::istream& in, io::PlayerInputMap& value) +{ + static const AIEnumSpelling spellings[] = { + { "PIYaw", 0 }, + { "PIPitch", 1 }, + { "PIRoll", 2 }, + { "PIThrottle", 3 }, + { "PIMouseLookX", 4 }, + { "PIMouseLookY", 5 }, + { "PICameraX", 6 }, + { "PICameraY", 7 }, + { "PIFire", 8 }, + { "PIAction", 9 }, + { "PIUse", 10 }, + { "PIMouseLook", 11 }, + { "PIAltSprint", 12 }, + { "PISprint", 13 }, + { "PISayAll", 58 }, + { "PISayTeam", 59 }, + { "PINextItem", 60 }, + { "PIPrevItem", 61 }, + { "PICommunication", 62 }, + { "PIWeaponSelect1", 14 }, + { "PIWeaponSelect2", 15 }, + { "PIWeaponSelect3", 16 }, + { "PIWeaponSelect4", 17 }, + { "PIWeaponSelect5", 18 }, + { "PIWeaponSelect6", 19 }, + { "PIWeaponSelect7", 20 }, + { "PIWeaponSelect8", 21 }, + { "PIWeaponSelect9", 22 }, + { "PIPositionSelect1", 23 }, + { "PIPositionSelect2", 24 }, + { "PIPositionSelect3", 25 }, + { "PIPositionSelect4", 26 }, + { "PIPositionSelect5", 27 }, + { "PIPositionSelect6", 28 }, + { "PIPositionSelect7", 29 }, + { "PIPositionSelect8", 30 }, + { "PIAltFire", 31 }, + { "PIReload", 32 }, + { "PIDrop", 34 }, + { "PIFlareFire", 47 }, + { "PIToggleCameraMode", 35 }, + { "PIToggleCamera", 36 }, + { "PILie", 37 }, + { "PICrouch", 38 }, + { "PINone", 64 }, + }; + value = static_cast(readAIEnumSpelling(in, spellings, + sizeof(spellings) / sizeof(spellings[0]), -1)); + return in; +} + +// ELF 0x3C5210 +std::ostream& operator<<(std::ostream& out, TemperatureTreeNode value) +{ + const unsigned index = static_cast(value); + if (index < 41) + out << kTemperatureTreeNodeSpellings[index].name; + return out; +} + +static const char* const kCombatStrengthNames[] = { + "CSTInfantry", + "CSTLightArmour", + "CSTHeavyArmour", + "CSTNavalArmour", + "CSTHelicopter", + "CSTAirPlane", + "CSTNumberOfTypes", +}; +// ELF 0x3C59D0 +std::ostream& operator<<(std::ostream& out, CombatStrengthType value) +{ + const unsigned index = static_cast(value); + if (index < 7) + out << kCombatStrengthNames[index]; + return out; +} + +static const char* const kConditionTypeNames[] = { + "Constant", + "Homogeneous", + "Heterogeneous", +}; +// ELF 0x3C5D20 +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionType value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kConditionTypeNames[index]; + return out; +} + +// ELF 0x3C5D90 +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionType& value) +{ + static const AIEnumSpelling spellings[] = { + { "Constant", 0 }, { "Homogeneous", 1 }, { "Heterogeneous", 2 } + }; + value = static_cast(readAIEnumSpelling(in, spellings, 3, 4)); + return in; +} + +// ELF 0x3C5E80 +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionStrength value) +{ + const unsigned index = static_cast(value); + if (index < 6) + out << kConditionStrengthSpellings[index].name; + return out; +} + +// ELF 0x3C6070 +std::ostream& operator<<(std::ostream& out, StrategyCondition::CompareType value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kCompareTypeSpellings[index].name; + return out; +} + +// ELF 0x3C61D0 +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionSide value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kConditionSideSpellings[index].name; + return out; +} + +// ELF 0x3C6800 +std::ostream& operator<<(std::ostream& out, StrategyCondition::Compare value) +{ + const unsigned index = static_cast(value); + if (index < 9) + out << kCompareSpellings[index * 2].name; + return out; +} + +static const char* const kConditionalNames[] = { + "Carrier", + "BattleShip", + "LCVP", + "Naval", + "Bomber", + "Fighter", + "AntiAir", + "Air", + "Infantery", + "Artillery", + "AntiTank", + "HeavyAttack", + "FastAttack", + "Ticket", + "ControlPoint", + "Time", + "StartTime", + "Attacks", + "Defences", + "NumberOfFriendlyAreas", + "NumberOfNeutralAreas", + "NumberOfHostileAreas", + "Flank", + "Base", + "Close", + "Centre", + "Remote", + "Route", + "Bridge", + "North", + "West", + "South", + "East", + "FrontFlank", + "FrontBase", + "FrontClose", + "FrontCentre", + "FrontRemote", + "FrontNeutral", + "Front", + "Safe", + "EnemyObject", + "UnReachable", + "UnitConstant", +}; +// ELF 0x3C6B20 +std::ostream& operator<<(std::ostream& out, StrategyCondition::Conditional value) +{ + const unsigned index = static_cast(value); + if (index < 44) + out << kConditionalNames[index]; + return out; +} + +static const char* const kKitNames[] = { + "KTSpecops", + "KTSniper", + "KTAssault", + "KTSupport", + "KTEngineer", + "KTMedic", + "KTAT", + "KTExtended1", + "KTExtended2", + "KTExtended3", + "KTExtended4", + "KTExtended5", + "KTExtended6", +}; +// ELF 0x3C7370 +std::ostream& operator<<(std::ostream& out, KitType value) +{ + const unsigned index = static_cast(value); + if (index < 13) + out << kKitNames[index]; + return out; +} + +// ELF 0x3C7430 +std::istream& operator>>(std::istream& in, KitType& value) +{ + static const AIEnumSpelling spellings[] = { + { "KTSpecops", 0 }, { "Specops", 0 }, { "0", 0 }, + { "KTSniper", 1 }, { "Sniper", 1 }, { "1", 1 }, + { "KTAssault", 2 }, { "Assault", 2 }, { "2", 2 }, + { "KTSupport", 3 }, { "Support", 3 }, { "3", 3 }, + { "KTEngineer", 4 }, { "Engineer", 4 }, { "4", 4 }, + { "KTMedic", 5 }, { "Medic", 5 }, { "5", 5 }, + { "KTAT", 6 }, { "AT", 6 }, { "6", 6 }, + { "KTExtended1", 7 }, { "Extended1", 7 }, { "7", 7 }, + { "KTExtended2", 8 }, { "Extended2", 8 }, { "8", 8 }, + { "KTExtended3", 9 }, { "Extended3", 9 }, { "9", 9 }, + { "KTExtended4", 10 }, { "Extended4", 10 }, { "10", 10 }, + { "KTExtended5", 11 }, { "Extended5", 11 }, { "11", 11 }, + { "KTExtended6", 12 }, { "Extended6", 12 }, { "12", 12 }, + }; + value = static_cast(readAIEnumSpelling(in, spellings, 39, 13)); + return in; +} + +static const char* const kLandingZoneNames[] = { + "LZXMin", + "LZZMin", + "LZXMax", + "LZZMax", + "LZUndefined", +}; +// ELF 0x3C89A0 +std::ostream& operator<<(std::ostream& out, LandingZoneDirection value) +{ + const unsigned index = static_cast(value); + if (index < 5) + out << kLandingZoneNames[index]; + return out; +} + +static const char* const kStatusNames[] = { + "Owned", + "Hostile", + "Neutral", +}; +// ELF 0x3C8C50 +std::ostream& operator<<(std::ostream& out, StatusMap::Status value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kStatusNames[index]; + else + out << "Unknown"; + return out; +} + +static const char* const kMeshNames[] = { + "Bullet", + "Vehicle", + "Soldier", +}; +// ELF 0x3C8DC0 +std::ostream& operator<<(std::ostream& out, mesh::MeshType value) +{ + const unsigned index = static_cast(value); + if (index < 3) + out << kMeshNames[index]; + else + out << "Error"; + return out; +} + +// ELF 0x3C8E30 +std::istream& operator>>(std::istream& in, mesh::MeshType& value) +{ + std::string token; + in >> token; + if (equalsIgnoreCase(token, std::string("Bullet"))) + value = static_cast(0); + else if (equalsIgnoreCase(token, std::string("Vehicle"))) + value = static_cast(1); + else if (equalsIgnoreCase(token, std::string("Soldier"))) + value = static_cast(2); + else + { + equalsIgnoreCase(token, std::string("Error")); + value = static_cast(4); + } + return in; +} + +static const char* const kMTStatusNames[] = { + "Forward", + "Behind", + "Right Forwards", + "Left Forwards", + "Avoid obstacle forwards left", + "Avoid obstacle forwards right", + "Avoid Obstacle Forward", + "Ignore obstacle", + "Back up", + "Right Backwards", + "Avoid Obstacle Backwards", + "Left Backwards", + "Back up until room", + "Avoid obstacle backwards right", + "Avoid obstacle backwards left", +}; +// ELF 0x3C90A0 +std::ostream& operator<<(std::ostream& out, MTStatus value) +{ + const unsigned index = static_cast(value); + if (index < 15) + out << kMTStatusNames[index]; + else + out << "Error"; + return out; +} + + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h new file mode 100644 index 000000000..4e391d0f9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.h @@ -0,0 +1,79 @@ +// Stream operators for the AI script vocabulary (AI/Main/AIStreamOperators.cpp, attested FILE +// symbol; header path [INFERRED]). The console uses the extractors to parse enum arguments; the +// plan dumps (streamSelf) and BAPInterpreter's diagnostics use the inserters. + +#ifndef AI_AIDLL_AI_MAIN_AISTREAMOPERATORS_H +#define AI_AIDLL_AI_MAIN_AISTREAMOPERATORS_H + +#include +#include +#include +#include +#include "../../../../Math/Vec3.h" +#include "../../../AIInterface/BFKnowledge/InformationType.h" + +#include "../AIBotActionPlan/BAPTypes.h" +#include "../AIStrategic/StatusMap.h" +#include "../AIStrategic/StrategyCondition.h" +#include "../AIStrategicEntity/AIStrategicObject.h" + +namespace dice { +namespace hfe { +enum KitType : int; +namespace ai { +namespace mesh { enum MeshType : int; } + +enum TemperatureTreeNode : int; +enum CombatStrengthType : int; +enum LandingZoneDirection : int; +enum MTStatus : int; + +std::istream& operator>>(std::istream& in, std::vector& values); +// The output overload is spelled >> in the shipped symbol and always writes a trailing slash. +std::ostream& operator>>(std::ostream& out, const std::vector& values); +// A nonempty list never advances its iterator in the shipped inserter. +std::ostream& operator<<(std::ostream& out, const std::list& values); +std::istream& operator>>(std::istream& in, std::list& values); +std::ostream& operator<<(std::ostream& out, TemperatureTreeNode value); +std::ostream& operator<<(std::ostream& out, CombatStrengthType value); +std::ostream& operator<<(std::ostream& out, LandingZoneDirection value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionType value); +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionType& value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionStrength value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::CompareType value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::ConditionSide value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::Compare value); +std::ostream& operator<<(std::ostream& out, StrategyCondition::Conditional value); +std::ostream& operator<<(std::ostream& out, KitType value); +std::istream& operator>>(std::istream& in, KitType& value); +std::ostream& operator<<(std::ostream& out, StatusMap::Status value); +std::ostream& operator<<(std::ostream& out, mesh::MeshType value); +std::istream& operator>>(std::istream& in, mesh::MeshType& value); +std::ostream& operator<<(std::ostream& out, MTStatus value); + +// Each extractor reads one token and maps its spelling. Unknown tokens normally yield the value +// one past the last name; TemperatureTreeNode yields -1, Status retains its previous value, +// BotLodLevel yields 3, CombatStrengthType yields 6, and LandingZoneDirection yields 4. +std::istream& operator>>(std::istream& in, TemperatureTreeNode& value); +std::istream& operator>>(std::istream& in, CombatStrengthType& value); +std::istream& operator>>(std::istream& in, LandingZoneDirection& value); +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionStrength& value); // 0x3C5F00 +std::istream& operator>>(std::istream& in, StrategyCondition::CompareType& value); // 0x3C60E0 +std::istream& operator>>(std::istream& in, StrategyCondition::ConditionSide& value); // 0x3C6240 +std::istream& operator>>(std::istream& in, StrategyCondition::Compare& value); // 0x3C68A0 +std::istream& operator>>(std::istream& in, StrategyCondition::Conditional& value); // 0x3C6D30 +std::ostream& operator<<(std::ostream& out, AIStrategicObject::StrategicObjectType type); // 0x3C6330 +std::istream& operator>>(std::istream& in, AIStrategicObject::StrategicObjectType& value); // 0x3C6460 +std::istream& operator>>(std::istream& in, StatusMap::Status& value); // 0x3C8CC0 + +std::ostream& operator<<(std::ostream& out, BotLodLevel lod); // 0x3C78B0 +std::istream& operator>>(std::istream& in, BotLodLevel& lod); // 0x3C7930 +std::ostream& operator<<(std::ostream& out, BAPConditionType type); // 0x3C7AE0 +std::ostream& operator<<(std::ostream& out, BAPStatementType type); // 0x3C7D90 +std::istream& operator>>(std::istream& in, BAPStatementType& type); // 0x3C7FA0 + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_MAIN_AISTREAMOPERATORS_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp index 7bbd8b5bb..3dc7150e4 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp @@ -3,10 +3,11 @@ // These statics belong to the AI module; do not share their definitions with the engine image. // [INFERRED] Source placement. +// static init: ELF 0x3EE360 (__tcf_0 0x3EE3C0, _GLOBAL__I 0x3EE3F0): 's Init object only. +#include + #include "BF2AI.h" -#include // the [FRONTIER] stop in init - stderr, not BF2Log; see that body -#include // std::abort - same #include #include "../../../../Core/ClassManager.h" @@ -25,9 +26,12 @@ #include "AIMineManager.h" // step 13 #include "AIPlayerCourier.h" // step 12 #include "AIConsole.h" // step 15 +#include "../AIUtils/DebugRendering/AIRenderUtil.h" // clear: the debug renderer +#include "../AIStrategicEntity/AILandingZoneManager.h" // clear: the landing-zone manager #include "BotBehaviourManager.h" // step 16 #include "../AIStrategicEntity/AIStrategicObjectManager.h" // step 17 #include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" // step 18 +#include "BotPlacementManager.h" // clear only - the static initializer builds it #include "AILODManager.h" // clear only - `init` never builds one #include "AIPathfinding.h" // step 21, and clear #include "AIRandom.h" // step 22, and clear @@ -50,6 +54,7 @@ namespace ai { // Registers the first AI in the simple-singleton registry. Later instances remain // unregistered; this intentionally differs from AIModule::close's normal-registry lookup. +// ELF 0x3EE430 / 0x3EE540 IAI::IAI() { if (!classManager->getSimpleSingleton("AI")) @@ -58,6 +63,7 @@ IAI::IAI() // The exact mirror of the constructor: unregister only if the registered "AI" is still this object. // A second IAI that never registered will not tear down the first one's entry on its way out. +// ELF 0x3EE650 / 0x3EE740 / 0x3EE830 IAI::~IAI() { if (classManager->getSimpleSingleton("AI") == this) @@ -65,6 +71,7 @@ IAI::~IAI() } // Two bytes. Everything that matters happened in the base constructor above. +// ELF 0x3EC720 / 0x3EC770 BF2AI::BF2AI() : m_initialized(false) , m_shuttingDown(false) @@ -75,11 +82,13 @@ BF2AI::BF2AI() // call are the whole body. It does not call clear; tearing the AI down is shutdown's job and // nothing chains the two. Destroying a BF2AI without shutting it down first leaks every one of the // twenty-four subsystems init built. +// ELF 0x3EC7C0 / 0x3EC800 / 0x3EC840 BF2AI::~BF2AI() { } // Constructs the AI subsystems and refreshes their registered interfaces. +// ELF 0x3EC890 bool BF2AI::init() { // Raises the shutdown flag before checking initialization. A repeated init returns @@ -241,6 +250,7 @@ bool BF2AI::init() } // Tears down AI subsystems in dependency order, refreshing cached interfaces during destruction. +// ELF 0x3EDDF0 bool BF2AI::clear() { if (!m_initialized) @@ -258,8 +268,11 @@ bool BF2AI::clear() if (updater) delete updater; - // [FRONTIER: AIRenderUtil] delete AIRenderUtil::m_instance; � , then operator delete - // Never built by `init` either; see the note beside AILODManager near the end. + // ELF D1 call at 0x3EDEAC: the debug renderer, nonvirtual D1 + operator delete. + // Recovered on the client track (docs/macos-c-singleplayer.md); init never builds it, so + // this only runs once a debug command has made one. + if (AIRenderUtil::m_instance) + delete AIRenderUtil::m_instance; if (CommonSingletonServer::m_iaiInformationCourier) delete static_cast(CommonSingletonServer::m_iaiInformationCourier); @@ -300,8 +313,10 @@ bool BF2AI::clear() if (UserOrderManager::m_instance) delete UserOrderManager::m_instance; - // [FRONTIER: AIConsole] Cleanup is deferred until AIConsole destruction is implemented. - // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BF2AI operation. + // ELF D1 call at 0x3EDFFB: the console (its destructor resets it and deletes the SquadManager). + // Recovered on the client track (docs/macos-c-singleplayer.md). + if (AIConsole::m_instance) + delete AIConsole::m_instance; // Destruction clears the behavior-manager singleton, making repeated cleanup harmless. if (BotBehaviourManager::m_instance) @@ -362,19 +377,31 @@ bool BF2AI::clear() if (AIRandom::m_instance) delete AIRandom::m_instance; - // Deletes the LOD manager when present; an existing instance reaches its teardown frontier. + // Deletes the LOD manager when present. delete AILODManager::m_instance; - // [FRONTIER: AILandingZoneManager] Cleanup is deferred until its destructor is implemented. + // ELF D1 call at 0x3EE1A0 / PE read at 0x10001D5B: the landing-zone manager the static installer made. + // Its destructor does not zero m_instance (ELF 0x399D60, PE 0x10039B00), so the pointer dangles + // until the library is unloaded and its static initializers run again on the next load + // (AIConnection::clear unloads it right after this). No platform reset is added: on macOS + // dlclose does unmap libaidll.dylib (no thread-local or Objective-C sections, only libc++ and + // libSystem as dependencies; a dlopen/dlclose/RTLD_NOLOAD probe finds it gone after each close), + // so the next load re-runs the installer exactly as the retail DLL reload does. + if (AILandingZoneManager::m_instance) + delete AILandingZoneManager::m_instance; if (CommunicationHub::m_instance) delete CommunicationHub::m_instance; - // [FRONTIER: BotPlacementManager] delete BotPlacementManager::m_instance; init never made it + // ELF D1 call at 0x3EE1D0, the last delete: the placement manager the static initializer + // (0x3E4BD5) made at load. Its destructor zeroes m_instance. + if (BotPlacementManager::m_instance) + delete BotPlacementManager::m_instance; m_initialized = false; return true; } // Invokes virtual clear so a derived implementation can override shutdown cleanup. +// ELF 0x3EE270 bool BF2AI::shutdown() { clear(); // virtual, IAI vtable +0x0C @@ -382,12 +409,14 @@ bool BF2AI::shutdown() } // Advances the AI using its own timer. The supplied engine delta is ignored. +// ELF 0x3EE290 int BF2AI::update(double /*dt*/) { return IAIMain::m_instance->action(); // IAIMain vtable +0x34 } // Copies game settings into the AI configuration and initializes the runtime as needed. +// ELF 0x3EE2C0 int BF2AI::getSettingsFromMenu(bool /*fromMenu*/) { IAISettings* const settings = @@ -418,12 +447,14 @@ int BF2AI::getSettingsFromMenu(bool /*fromMenu*/) } // - a bare byte load. The engine's gate on every .ai load and on the AI tick. +// ELF 0x3EE410 bool BF2AI::isInitialized() const { return m_initialized; } // - a bare byte load. Also reports true for the whole of init; see BF2AI.h. +// ELF 0x3EE420 bool BF2AI::isShuttingDown() const { return m_shuttingDown; diff --git a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h index 08fcf136a..61a27a3b0 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.h @@ -34,7 +34,7 @@ class BF2AI : public IAI virtual ~BF2AI(); virtual bool init(); - virtual bool clear(); // [FRONTIER] + virtual bool clear(); virtual bool shutdown(); virtual int getSettingsFromMenu(bool fromMenu); virtual int update(double dt); diff --git a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp index 7bca24084..661379a32 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp @@ -1,14 +1,29 @@ // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BFPathfindingCourier operations. +// static init: ELF 0x2E8670 (__tcf_0 0x2E86D0, _GLOBAL__I 0x2E8700): 's Init object only. +#include + +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" #include "BFPathfindingCourier.h" +#include +#include #include #include "../../../../Core/ClassManager.h" #include "CommonSingletonServer.h" #include "AIDllFrontier.h" #include "IAIPathfinding.h" // getVehicleNumberFromName's one forward -#include "AISettingsInterfaces.h" // IAISettings::getVehicle - findClosestValidInfantryPolygon +#include "AISettingsInterfaces.h" +#include "../AIBot/SquadManager.h" +#include "../AIBot/SquadMember.h" +#include "../AIKnowledge/IPIMobile.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // IAISettings::getVehicle - findClosestValidInfantryPolygon namespace dice { namespace hfe { @@ -41,29 +56,104 @@ BFPathfindingCourier::~BFPathfindingCourier() { } +// ELF 0x2E8200. A "vehicle" here is a pathfinding map. int BFPathfindingCourier::getNumberOfVehicles() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::getNumberOfVehicles"); + return IAIPathfinding::instance->getNumberOfMaps(); } -bool BFPathfindingCourier::isVehicleUsed(unsigned int) const +// ELF 0x2E8230. +bool BFPathfindingCourier::isVehicleUsed(unsigned int map) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::isVehicleUsed"); + return IAIPathfinding::instance->isMapUsed(static_cast(map)); } -bool BFPathfindingCourier::isValidPosition(int, int, const Vec3&) const +// ELF 0x2E8270. Ignores materials. +bool BFPathfindingCourier::isValidPosition(int map, int vehicleId, const Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::isValidPosition"); + return IAIPathfinding::instance->isValidPosition(map, vehicleId, position, true); } -bool BFPathfindingCourier::isValidPosition(const Vec3&) const +// ELF 0x2E82C0. On the trace map, as vehicle 1, ignoring materials. +bool BFPathfindingCourier::isValidPosition(const Vec3& position) const +{ + IAIPathfinding* const pathfinding = IAIPathfinding::instance; + return pathfinding->isValidPosition(pathfinding->getTraceMapIndex(), 1, position, true); +} + +namespace { + +// [TEMP] [RETIRE-WHEN: ai-bot-squad-leader-closest] Neither callee is declared yet (request to +// ai-bot in coord/ai-requests.md); each stops by name until it is. +SquadMember* squadLeaderClosestTo(SquadManager* manager, const Vec3& position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::isValidPosition"); + return manager->getSquadLeaderClosestTo(position); } -void BFPathfindingCourier::getLastValidSquadleaderPosition(const Vec3&) const +int sideOf(SquadMember* member) +{ + return member->getSide(); +} + +} // anonymous namespace + +// ELF 0x2E8320. The squad leader closest to `position` (no null test, as in retail): the last +// valid infantry position of its vehicle's information for its side when the vehicle, that +// information, its unit and mobile plug-ins exist and the position's polygon is valid. +// Otherwise the eligible spawn point of its side closest (strictly, squared) to the leader's +// position; (-4000, -4000, -4000) when the leader has no position or no spawn point qualifies. +Vec3 BFPathfindingCourier::getLastValidSquadleaderPosition(const Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPathfindingCourier::getLastValidSquadleaderPosition"); + SquadMember* const leader = squadLeaderClosestTo(SquadManager::m_instance, position); + const int side = sideOf(leader); + + IAIObject* const vehicle = leader->getPlayer()->getCurrentVehicle(); + if (vehicle != 0) + { + Information* const information = + informationManager->getInformation(vehicle->getInformation(side)); + if (information != 0 && information->getUnit() != 0 && information->getMobile() != 0) + { + const IPIMobile::ValidPos& valid = information->getMobile()->getLastValidInfantryPos(); + if (valid.polygon != 0xFFFFFFFFu) + return valid.position; + } + } + + IAIGame* const game = static_cast(CommonSingletonServer::m_iaiGame); + const std::list& spawnPoints = game->getSpawnPointList(side); + float bestDistance = FLT_MAX; + std::list::const_iterator best = spawnPoints.end(); + Vec3 leaderPosition; + leaderPosition.x = 0.0f; + leaderPosition.y = 0.0f; + leaderPosition.z = 0.0f; + if (leader->getPosition(leaderPosition)) + { + for (std::list::const_iterator i = spawnPoints.begin(); i != spawnPoints.end(); ++i) + { + if (!game->isEligibleSpawnpoint(side, *i)) + continue; + const Vec3& spawn = game->getSpawnPointPosition(*i); + const float dx = leaderPosition.x - spawn.x; + const float dy = leaderPosition.y - spawn.y; + const float dz = leaderPosition.z - spawn.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (bestDistance > distance) + { + bestDistance = distance; + best = i; + } + } + if (best != spawnPoints.end()) + return game->getSpawnPointPosition(*best); + } + + Vec3 nowhere; + nowhere.x = -4000.0f; + nowhere.y = -4000.0f; + nowhere.z = -4000.0f; + return nowhere; } // Returns the case-insensitive pathfinding map id, or -1 for an unknown name. diff --git a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h index 128aefa7c..902de49e4 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.h @@ -33,7 +33,8 @@ class IAIPathfindingCourier virtual bool isVehicleUsed(unsigned int) const = 0; virtual bool isValidPosition(int, int, const Vec3&) const = 0; virtual bool isValidPosition(const Vec3&) const = 0; - virtual void getLastValidSquadleaderPosition(const Vec3&) const = 0; + // Returns by value (ELF `ret $4`: hidden result pointer), not void. + virtual Vec3 getLastValidSquadleaderPosition(const Vec3&) const = 0; virtual int getVehicleNumberFromName(const std::string&) const = 0; // bool // with no widening before `ret 10h` - an int return would need the `movzx` it lacks. (The ELF's @@ -53,7 +54,7 @@ class BFPathfindingCourier : public IAIPathfindingCourier virtual bool isVehicleUsed(unsigned int) const; virtual bool isValidPosition(int, int, const Vec3&) const; virtual bool isValidPosition(const Vec3&) const; - virtual void getLastValidSquadleaderPosition(const Vec3&) const; + virtual Vec3 getLastValidSquadleaderPosition(const Vec3&) const; virtual int getVehicleNumberFromName(const std::string&) const; virtual bool findClosestValidInfantryPolygon(Vec3&, const Vec3&, const Vec3&, unsigned int) const; diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp index 3df8a4614..63e1067ee 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.cpp @@ -1,9 +1,69 @@ +// static init: ELF 0x3D3120 (__tcf_0 0x3D3180, _GLOBAL__I 0x3D31B0): 's Init object only. +#include + #include "BotBehaviourManager.h" #include "../AIBotBehaviour/UrgeCurve.h" // UCConstant / UCLinear / UCXInverse - the three factories #include "../AIUtils/checkPointer.h" // inlined 26 times in the constructor #include "AIDllFrontier.h" +#include "../AIBotBehaviour/BBAvoid.h" +#include "../AIBotBehaviour/BBBridgeRepair.h" +#include "../AIBotBehaviour/BBC4.h" +#include "../AIBotBehaviour/BBCallForMedic.h" +#include "../AIBotBehaviour/BBChange.h" +#include "../AIBotBehaviour/BBChangeLandingCraft.h" +#include "../AIBotBehaviour/BBChangeTeleport.h" +#include "../AIBotBehaviour/BBDefuseMines.h" +#include "../AIBotBehaviour/BBFire.h" +#include "../AIBotBehaviour/BBFire3d.h" +#include "../AIBotBehaviour/BBFireArtilleryDriver.h" +#include "../AIBotBehaviour/BBFireInfantery.h" +#include "../AIBotBehaviour/BBFireLargeBore.h" +#include "../AIBotBehaviour/BBFireUnarmed.h" +#include "../AIBotBehaviour/BBIdle.h" +#include "../AIBotBehaviour/BBMedicAssist.h" +#include "../AIBotBehaviour/BBMoveTo.h" +#include "../AIBotBehaviour/BBMoveToFixed.h" +#include "../AIBotBehaviour/BBRandom.h" +#include "../AIBotBehaviour/BBRevive.h" +#include "../AIBotBehaviour/BBRunOverSoldier.h" +#include "../AIBotBehaviour/BBSuicide.h" +#include "../AIBotBehaviour/BBTakeCover.h" +#include "../AIBotBehaviour/BBTakeCover3d.h" +#include "../AIBotBehaviour/BBTakeCoverInfantry.h" +#include "../AIBotBehaviour/BBTriggerable.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollision2d.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollision3d.h" +#include "../AIBotBehaviourPattern/BBPAvoidCollisionInfantery.h" +#include "../AIBotBehaviourPattern/BBPBridgeRepair.h" +#include "../AIBotBehaviourPattern/BBPC4.h" +#include "../AIBotBehaviourPattern/BBPCallForMedic.h" +#include "../AIBotBehaviourPattern/BBPChange.h" +#include "../AIBotBehaviourPattern/BBPChangeLandingCraft.h" +#include "../AIBotBehaviourPattern/BBPChangeTeleport.h" +#include "../AIBotBehaviourPattern/BBPDefuseMines.h" +#include "../AIBotBehaviourPattern/BBPFire2d.h" +#include "../AIBotBehaviourPattern/BBPFire2dDriver.h" +#include "../AIBotBehaviourPattern/BBPFire3d.h" +#include "../AIBotBehaviourPattern/BBPFireInfantery.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypoints2d.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypoints3d.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypointsBoat.h" +#include "../AIBotBehaviourPattern/BBPGotoWaypointsInfantery.h" +#include "../AIBotBehaviourPattern/BBPHeliFire3d.h" +#include "../AIBotBehaviourPattern/BBPIdle2d.h" +#include "../AIBotBehaviourPattern/BBPIdle3d.h" +#include "../AIBotBehaviourPattern/BBPIdleInfantery.h" +#include "../AIBotBehaviourPattern/BBPMedicAssist.h" +#include "../AIBotBehaviourPattern/BBPRandom.h" +#include "../AIBotBehaviourPattern/BBPRevive.h" +#include "../AIBotBehaviourPattern/BBPRunOverSoldier.h" +#include "../AIBotBehaviourPattern/BBPSuicide.h" +#include "../AIBotBehaviourPattern/BBPTakeCover.h" +#include "../AIBotBehaviourPattern/BBPTakeCover3d.h" +#include "../AIBotBehaviourPattern/BBPTakeCoverInfantry.h" +#include "../AIBotBehaviourPattern/BBPTriggerable.h" namespace dice { namespace hfe { @@ -19,208 +79,208 @@ namespace { class BBCreateFunctionAvoid : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBMoveTo`. class BBCreateFunctionMoveTo : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBMoveToFixed`. class BBCreateFunctionMoveToFixed : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBMedicAssist`. class BBCreateFunctionMedicAssist : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBIdle`. class BBCreateFunctionIdle : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFire`. class BBCreateFunctionFire : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFire3d`. class BBCreateFunctionFire3d : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireInfantery`. class BBCreateFunctionFireInfantery : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireUnarmed`. class BBCreateFunctionFireUnarmed : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireLargeBore`. class BBCreateFunctionFireLargeBore : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTakeCover`. class BBCreateFunctionTakeCover : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTakeCoverInfantry`. class BBCreateFunctionTakeCoverInfantry : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBFireDriver`. class BBCreateFunctionFireDriver : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBChange`. class BBCreateFunctionChange : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBChangeLandingCraft`. class BBCreateFunctionChangeLandingCraft : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBChangeTeleport`. class BBCreateFunctionChangeTeleport : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBSuicide`. class BBCreateFunctionSuicide : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBCallForMedic`. class BBCreateFunctionCallForMedic : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBRevive`. class BBCreateFunctionRevive : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTakeCover3d`. class BBCreateFunctionTakeCover3d : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBC4`. class BBCreateFunctionC4 : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBRunOverSoldier`. class BBCreateFunctionRunOverSoldier : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBBridgeRepair`. class BBCreateFunctionBridgeRepair : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBDefuseMines`. class BBCreateFunctionDefuseMines : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBRandom`. class BBCreateFunctionRandom : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; // - builds one `BBTriggerable`. class BBCreateFunctionTriggerable : public BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights); + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights); }; } // anonymous namespace @@ -322,7 +382,7 @@ std::string BotBehaviourManager::getBehaviourName(int id) // Creates a named behavior through a registered factory. -int BotBehaviourManager::create(std::string behaviourName, std::string createFunctionName, +BotBehaviour* BotBehaviourManager::create(std::string behaviourName, std::string createFunctionName, std::string name, int mode, std::string urgeCurveName, float* weights, std::string& message) { @@ -368,190 +428,312 @@ std::string BotBehaviourManager::createUCXInverse(std::string& name, float numer return "UCXInverse created"; } -// The twenty-six frontier bodies. +// The twenty-six create functions (weak in the image, 0x3D4190..0x3D8DD0). Each compares the +// pattern name with its candidates in the image's order, builds the first match with the behaviour +// id, and builds the behaviour with (id, mode) narrowed to bytes (`movzbl`), the pattern (null when +// no name matches), the urge curve and the weights. Every allocation goes through checkPointer +// (the Debug(6, ..., 46, ...) "Allocation failed" branch after each `new`). namespace { -// Creation of BBAvoid and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionAvoid::operator()(int, std::string&, int, UrgeCurve*, float*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionAvoid::operator()"); +// ELF 0x3D4190. +BotBehaviour* BBCreateFunctionAvoid::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) +{ + BBPAvoidCollision* pattern = 0; + if (name.compare("BBPAvoidCollision2d") == 0) + pattern = checkPointer(new BBPAvoidCollision2d(behaviourId)); + else if (name.compare("BBPAvoidCollision3d") == 0) + pattern = checkPointer(new BBPAvoidCollision3d(behaviourId)); + else if (name.compare("BBPAvoidCollisionInfantery") == 0) + pattern = checkPointer(new BBPAvoidCollisionInfantery(behaviourId)); + return checkPointer(new BBAvoid(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBMoveTo and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionMoveTo::operator()(int, std::string&, int, UrgeCurve*, float*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionMoveTo::operator()"); -} +// ELF 0x3D4690. +BotBehaviour* BBCreateFunctionMoveTo::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) +{ + BBPGotoWaypoint* pattern = 0; + if (name.compare("BBPGotoWaypoint2d") == 0) + pattern = checkPointer(new BBPGotoWaypoint2d(behaviourId)); + else if (name.compare("BBPGotoWaypointBoat") == 0) + pattern = checkPointer(new BBPGotoWaypointBoat(behaviourId)); + else if (name.compare("BBPGotoWaypoint3d") == 0) + pattern = checkPointer(new BBPGotoWaypoint3d(behaviourId)); + else if (name.compare("BBPGotoWaypointInfantery") == 0) + pattern = checkPointer(new BBPGotoWaypointSoldier(behaviourId)); + return checkPointer(new BBMoveTo(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); +} -// Creation of BBMoveToFixed and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionMoveToFixed::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D4CC0. +BotBehaviour* BBCreateFunctionMoveToFixed::operator()(int behaviourId, std::string&, int mode, + UrgeCurve*, float*) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionMoveToFixed::operator()"); + return checkPointer(new BBMoveToFixed(static_cast(behaviourId), static_cast(mode))); } -// Creation of BBMedicAssist and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionMedicAssist::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5D90. +BotBehaviour* BBCreateFunctionMedicAssist::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionMedicAssist::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPMedicAssist") == 0) + pattern = checkPointer(new BBPMedicAssist(behaviourId)); + return checkPointer(new BBMedicAssist(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBIdle and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionIdle::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D4F80. +BotBehaviour* BBCreateFunctionIdle::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionIdle::operator()"); + BBPIdle* pattern = 0; + if (name.compare("BBPIdle2d") == 0) + pattern = checkPointer(new BBPIdle2d(behaviourId)); + else if (name.compare("BBPIdle3d") == 0) + pattern = checkPointer(new BBPIdle3d(behaviourId)); + else if (name.compare("BBPIdleInfantery") == 0) + pattern = checkPointer(new BBPIdleInfantery(behaviourId)); + return checkPointer(new BBIdle(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFire and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFire::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6030. +BotBehaviour* BBCreateFunctionFire::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFire::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire2d") == 0) + pattern = checkPointer(new BBPFire2d(behaviourId)); + else if (name.compare("BBPFireInfantery") == 0) + pattern = checkPointer(new BBPFireInfantery(behaviourId)); + return checkPointer(new BBFire(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFire3d and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFire3d::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6A80. +BotBehaviour* BBCreateFunctionFire3d::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFire3d::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire3d") == 0) + pattern = checkPointer(new BBPFire3d(behaviourId)); + else if (name.compare("BBPHeliFire3d") == 0) + pattern = checkPointer(new BBPHeliFire3d(behaviourId)); + return checkPointer(new BBFire3d(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFireInfantery and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireInfantery::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6E50. +BotBehaviour* BBCreateFunctionFireInfantery::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireInfantery::operator()"); + BBPFireInfantery* pattern = 0; + if (name.compare("BBPFireInfantery") == 0) + pattern = checkPointer(new BBPFireInfantery(behaviourId)); + return checkPointer(new BBFireInfantery(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFireUnarmed and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireUnarmed::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D4E20. +BotBehaviour* BBCreateFunctionFireUnarmed::operator()(int behaviourId, std::string&, int mode, + UrgeCurve*, float*) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireUnarmed::operator()"); + return checkPointer(new BBFireUnarmed(static_cast(behaviourId), static_cast(mode))); } -// Creation of BBFireLargeBore and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireLargeBore::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D6400. +BotBehaviour* BBCreateFunctionFireLargeBore::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireLargeBore::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire2d") == 0) + pattern = checkPointer(new BBPFire2d(behaviourId)); + else if (name.compare("BBPFireInfantery") == 0) + pattern = checkPointer(new BBPFireInfantery(behaviourId)); + return checkPointer(new BBFireLargeBore(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights, false)); } -// Creation of BBTakeCover and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTakeCover::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D70F0. +BotBehaviour* BBCreateFunctionTakeCover::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTakeCover::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTakeCover") == 0) + pattern = checkPointer(new BBPTakeCover(behaviourId)); + return checkPointer(new BBTakeCover(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBTakeCoverInfantry and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTakeCoverInfantry::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7390. +BotBehaviour* BBCreateFunctionTakeCoverInfantry::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTakeCoverInfantry::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTakeCoverInfantry") == 0) + pattern = checkPointer(new BBPTakeCoverInfantry(behaviourId)); + return checkPointer(new BBTakeCoverInfantry(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBFireDriver and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionFireDriver::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D67E0. +BotBehaviour* BBCreateFunctionFireDriver::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionFireDriver::operator()"); + BBPFire* pattern = 0; + if (name.compare("BBPFire2dDriver") == 0) + pattern = checkPointer(new BBPFire2dDriver(behaviourId)); + return checkPointer(new BBFireArtilleryDriver(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBChange and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionChange::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5480. +BotBehaviour* BBCreateFunctionChange::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionChange::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPChange") == 0) + pattern = checkPointer(new BBPChange(behaviourId)); + return checkPointer(new BBChange(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBChangeLandingCraft and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionChangeLandingCraft::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5720. +BotBehaviour* BBCreateFunctionChangeLandingCraft::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionChangeLandingCraft::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPChangeLandingCraft") == 0) + pattern = checkPointer(new BBPChangeLandingCraft(behaviourId)); + else if (name.compare("BBPChange") == 0) + pattern = checkPointer(new BBPChange(behaviourId)); + return checkPointer(new BBChangeLandingCraft(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBChangeTeleport and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionChangeTeleport::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D5AF0. +BotBehaviour* BBCreateFunctionChangeTeleport::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionChangeTeleport::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPChangeTeleport") == 0) + pattern = checkPointer(new BBPChangeTeleport(behaviourId)); + return checkPointer(new BBChangeTeleport(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBSuicide and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionSuicide::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7630. +BotBehaviour* BBCreateFunctionSuicide::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionSuicide::operator()"); + BBPSuicide* pattern = 0; + if (name.compare("BBPSuicide") == 0) + pattern = checkPointer(new BBPSuicide(behaviourId)); + return checkPointer(new BBSuicide(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBCallForMedic and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionCallForMedic::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D78D0. +BotBehaviour* BBCreateFunctionCallForMedic::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionCallForMedic::operator()"); + BBPCallForMedic* pattern = 0; + if (name.compare("BBPCallForMedic") == 0) + pattern = checkPointer(new BBPCallForMedic(behaviourId)); + return checkPointer(new BBCallForMedic(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBRevive and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionRevive::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7B70. +BotBehaviour* BBCreateFunctionRevive::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionRevive::operator()"); + BBPRevive* pattern = 0; + if (name.compare("BBPRevive") == 0) + pattern = checkPointer(new BBPRevive(behaviourId)); + return checkPointer(new BBRevive(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBTakeCover3d and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTakeCover3d::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D7E10. +BotBehaviour* BBCreateFunctionTakeCover3d::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTakeCover3d::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTakeCover3d") == 0) + pattern = checkPointer(new BBPTakeCover3d(behaviourId)); + return checkPointer(new BBTakeCover3d(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBC4 and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionC4::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D80B0. +BotBehaviour* BBCreateFunctionC4::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionC4::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPC4") == 0) + pattern = checkPointer(new BBPC4(behaviourId)); + return checkPointer(new BBC4(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBRunOverSoldier and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionRunOverSoldier::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8890. +BotBehaviour* BBCreateFunctionRunOverSoldier::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionRunOverSoldier::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPRunOverSoldier") == 0) + pattern = checkPointer(new BBPRunOverSoldier(behaviourId)); + return checkPointer(new BBRunOverSoldier(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBBridgeRepair and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionBridgeRepair::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8350. +BotBehaviour* BBCreateFunctionBridgeRepair::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionBridgeRepair::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPBridgeRepair") == 0) + pattern = checkPointer(new BBPBridgeRepair(behaviourId)); + return checkPointer(new BBBridgeRepair(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBDefuseMines and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionDefuseMines::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D85F0. +BotBehaviour* BBCreateFunctionDefuseMines::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionDefuseMines::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPDefuseMines") == 0) + pattern = checkPointer(new BBPDefuseMines(behaviourId)); + return checkPointer(new BBDefuseMines(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBRandom and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionRandom::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8B30. +BotBehaviour* BBCreateFunctionRandom::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionRandom::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPRandom") == 0) + pattern = checkPointer(new BBPRandom(behaviourId)); + return checkPointer(new BBRandom(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } -// Creation of BBTriggerable and registration with the behavior list remain unimplemented. -// [RETIRE-WHEN: aidll-02-skeleton] Replace the stop when this factory behavior is recovered. -int BBCreateFunctionTriggerable::operator()(int, std::string&, int, UrgeCurve*, float*) +// ELF 0x3D8DD0. +BotBehaviour* BBCreateFunctionTriggerable::operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) { - BF2_AI_FRONTIER("dice::hfe::ai::(anonymous namespace)::BBCreateFunctionTriggerable::operator()"); + PlanGenerator* pattern = 0; + if (name.compare("BBPTriggerable") == 0) + pattern = checkPointer(new BBPTriggerable(behaviourId)); + return checkPointer(new BBTriggerable(static_cast(behaviourId), + static_cast(mode), pattern, urgeCurve, weights)); } } // anonymous namespace diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h index f0d906ab4..c0439ec88 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BotBehaviourManager.h @@ -13,14 +13,17 @@ namespace dice { namespace hfe { namespace ai { +class BotBehaviour; class UrgeCurve; // Factory interface for constructing bot behaviors. class BBCreateFunction { public: - virtual int operator()(int behaviourId, std::string& name, int mode, - UrgeCurve* urgeCurve, float* weights) = 0; + // Returns the new behaviour (`movl %edi, %eax` after `new BB...`); an unknown pattern name + // still builds the behaviour, with a null pattern. + virtual BotBehaviour* operator()(int behaviourId, std::string& name, int mode, + UrgeCurve* urgeCurve, float* weights) = 0; }; class BotBehaviourManager @@ -41,7 +44,9 @@ class BotBehaviourManager // the factory dispatch // Called by `AIConsole::setVehicleBehaviour` , which is the `.ai` script binding. - int create(std::string behaviourName, std::string createFunctionName, std::string name, + // Returns the created behaviour, or null with `message` set (AIConsole::setVehicleBehaviour + // registers a non-null result). + BotBehaviour* create(std::string behaviourName, std::string createFunctionName, std::string name, int mode, std::string urgeCurveName, float* weights, std::string& message); // the urge-curve factories diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp index 09c95a1ad..030842cae 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp @@ -1,10 +1,20 @@ // Owns the bot pool and schedules sensing, decisions and plan execution. // Work is distributed across ticks according to per-bot update deadlines and detail level. +// static init: ELF 0x3E1470 (__tcf_0 0x3E14D0, _GLOBAL__I 0x3E1500): 's Init object only. +#include + +#include #include "BotManager.h" -#include "AIDllFrontier.h" +#include +#include "../AIBot/WPEmpty.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../../../AIInterface/BFKnowledge/BFGame.h" +#include "../../../../IO/File/FileManager.h" +#include "../../../../Game/Objects/IObject.h" +#include "../../../../Game/Objects/IObjectTemplate.h" #include "AIMain.h" // IAIMain::m_instance - cached at +60 #include "AISettingsInterfaces.h" // IAISettings::getMaxNBots #include "../AIBot/BotMain.h" // the preallocated pool @@ -28,12 +38,20 @@ #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // actionHearing's object list #include "../AIKnowledge/IPIPhysical.h" #include "../../../../IO/Input/PlayerInput.h" // actionExecutePlan presses a climber's inputs +#include "../../../AIInterface/BFKnowledge/IAIObject.h" // the object map, vehicle changes +#include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectPhysical::enablePhysics +#include "../AIBot/BotCallBack.h" // death and spawn reports +#include "../AIBot/BotSquad.h" // the order forwarders +#include "../../../AIInterface/BFKnowledge/IWeapon.h" // actionHearing namespace dice { namespace hfe { namespace ai { +int BotManager::s_tabLevel = 0; + // Runs the scheduled bot work within the supplied time budget. +// ELF 0x3DD580 void BotManager::action(const double& budget) { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -107,6 +125,7 @@ void BotManager::action(const double& budget) } // Applies accumulated bot damage once per tick. +// ELF 0x3E0AF0 void BotManager::updateDamages() { IAIGameEffector* const effector = @@ -140,6 +159,7 @@ void BotManager::updateDamages() // [INFERRED] Services one eligible bot's radio per tick, resuming from the saved cursor. // Skips dead, man-down, or navigation-blocked bots and makes at most one roster circuit. +// ELF 0x3DE360 void BotManager::actionComAgent() { const unsigned int start = m_comAgentCursor; @@ -174,6 +194,7 @@ static bool speedSquaredAtMost(const Vec3& speed, float limit) } // Executes plans for the scheduled portion of the roster and refills work queues within the budget. +// ELF 0x3DDA90 void BotManager::actionExecutePlan(const double& slice) { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -222,14 +243,14 @@ void BotManager::actionExecutePlan(const double& slice) { if (bot->getPlayer() && bot->getPlayer()->getCurrentVehicle()) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // Retail: `IAIObject* primary = getPlayer->getCurrentVehicle->getPrimaryObject; - // if (primary) { bot->setBotStuck(true); primary->setIsAllowedByBots(false); }` - // IAIObject slots ELF +0xFC / +0x9C (PE +0xF8 / +0x98), named from the engine's - // AIObjectReal table (bf2 ). IAIObject has no declaration in this tree. - IAIObject* const vehicle = bot->getPlayer()->getCurrentVehicle(); - (void)vehicle; - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::actionExecutePlan (IAIObject::getPrimaryObject)"); + // ELF 0x3DE2A7: IAIObject +0xFC getPrimaryObject; a stuck bot marks its vehicle's + // primary object as not allowed to bots (+0x9C), after Bot +0x148 setBotStuck. + IAIObject* const primary = bot->getPlayer()->getCurrentVehicle()->getPrimaryObject(); + if (primary) + { + bot->setBotStuck(true); + primary->setIsAllowedByBots(false); + } } bool onFoot = false; if (bot->getPlayer()) @@ -297,6 +318,7 @@ void BotManager::actionExecutePlan(const double& slice) // [INFERRED] Visits at most one roster circuit and refreshes at most size/16 + 1 active // navigations, skipping dead and man-down bots. Requires nonnull bot records: a null bot // does not advance the cursor and would loop indefinitely. +// ELF 0x3DD980 void BotManager::actionUpdateNavPoints() { if (m_botInfos.empty()) @@ -323,6 +345,7 @@ void BotManager::actionUpdateNavPoints() } // Schedules decisions using the interleave limits and each bot's detail level. +// ELF 0x3DE850 void BotManager::actionDecisionMaking(const double& slice) { unsigned int light = 0; @@ -426,6 +449,7 @@ void BotManager::actionDecisionMaking(const double& slice) } // Uses one tenth of the slice for bot path requests and the remainder for search processing. +// ELF 0x3DF7F0 void BotManager::actionPathfinding(const double& slice) { IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); @@ -475,8 +499,17 @@ void BotManager::actionPathfinding(const double& slice) } } -// Scans occupied world objects for hearing within the supplied slice. -// [FRONTIER] The object-query path remains incomplete. +// ELF 0x3DE440. Scans the occupied world objects round-robin from the last resume id. A sided +// object with an armament or a mobile plug-in gets a sound radius: the mobile's +// getSoundSphereRadius (IAIObjectMobile +0x40), or the last fired weapon's (IWeapon +0x10C) +// when that fired within 3.0f seconds (ELF 0x49CC90) and is larger. Without a mobile plug-in the +// ELF keeps the radius at its 0.0f start, so a weapon alone is never heard. A radius above 0.1f +// (ELF 0x49CC80) is heard by every live, standing enemy bot within it (squared distance against +// the float-rounded squared radius), through Bot +0x178 event_heardObject with the object's +// information for the bot's side (IAIObject +0xB4 forceGetInformation(side, false)). The slice +// deadline is tested only after such a pass. +// [PLATFORM] The ELF keeps the time difference and the distance sum in x87 extended precision; +// both are double here. void BotManager::actionHearing(const double& slice) { const double deadline = @@ -499,19 +532,54 @@ void BotManager::actionHearing(const double& slice) if (++next == m_occupiedObjects.end()) next = m_occupiedObjects.begin(); ++visited; - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // The body's first call is `object->getSide` (IAIObject ELF +0x12C / PE +0x128), and - // IAIObject has no declaration in this tree; see the outline above. - (void)object; - (void)gameTime; - (void)deadline; - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::actionHearing (IAIObject hearing query)"); + if (!object->getSide()) + continue; + IAIObjectArmament* const armament = object->getArmament(); + IAIObjectMobile* const mobile = object->getMobile(); + if (!armament && !mobile) + continue; + + float weaponRadius = 0.0f; + float radius = 0.0f; + if (armament) + { + IWeapon* const weapon = armament->getLastFiredWeapon(); + if (weapon && 3.0f > gameTime - weapon->getTimeOfFiring()) + weaponRadius = weapon->getSoundSphereRadius(); + } + if (mobile) + { + const float mobileRadius = mobile->getSoundSphereRadius(); + radius = weaponRadius > mobileRadius ? weaponRadius : mobileRadius; + } + if (radius <= 0.1f) + continue; + + const float radiusSquared = radius * radius; + const int side = object->getSide(); + const Vec3& position = object->getPosition(); + for (std::vector >::iterator it = m_occupiedObjects.begin(); + it != m_occupiedObjects.end(); ++it) + { + Bot* const bot = getBot(it->second); + if (!bot || bot->isDead() || bot->getManDown() || bot->getSide() == side) + continue; + const Vec3& other = it->second->getPosition(); + const double dx = static_cast(position.x) - other.x; + const double dy = static_cast(position.y) - other.y; + const double dz = static_cast(position.z) - other.z; + if (!((dx * dx + dy * dy) + dz * dz > radiusSquared)) + bot->event_heardObject(object->forceGetInformation(bot->getSide(), false)); + } + if (static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime() > deadline) + break; } if (count > 0) m_hearingResumeId = next->first; } // Processes at most two sensing updates per tick using the full-detail update rate. +// ELF 0x3DF180 void BotManager::actionSensing(const double& slice) { const double deadline = @@ -673,6 +741,7 @@ BotManager::BotManager() // These configuration methods remain virtual through IBotManagerModifier. +// ELF 0x3DAD20 void BotManager::setLodLevelTicks(unsigned full, unsigned medium, unsigned light) { m_lodLevelFullTicks = full; @@ -680,6 +749,7 @@ void BotManager::setLodLevelTicks(unsigned full, unsigned medium, unsigned light m_lodLevelLightTicks = light; } +// ELF 0x3DAD50 void BotManager::setLodLevelPriority(unsigned full, unsigned medium, unsigned light) { m_lodLevelFullPriority = full; @@ -709,6 +779,7 @@ void BotManager::setUnplannedDecisionMakingThreshold(const double& full, m_unplannedDecisionMakingThresholdLight = light < 0.0 ? -light : light; } +// ELF 0x3DAE30 void BotManager::setDecisionMakingInterleave(unsigned planned, unsigned unplanned) { m_plannedDecisionMakingInterleave = planned; @@ -717,6 +788,7 @@ void BotManager::setDecisionMakingInterleave(unsigned planned, unsigned unplanne // Normalizes two integer weights into complementary shares. Leaves both unchanged // when their unsigned sum is zero. +// ELF 0x3DAE50 void BotManager::setSensingQuotient(unsigned a, unsigned b) { if (a + b) @@ -729,6 +801,7 @@ void BotManager::setSensingQuotient(unsigned a, unsigned b) // Normalizes three weights but stores only the first two fractions. // Leaves existing shares unchanged when the unsigned total is zero. +// ELF 0x3DAEB0 void BotManager::setSystemQuotient(unsigned a, unsigned b, unsigned c) { const unsigned total = a + b + c; @@ -739,47 +812,48 @@ void BotManager::setSystemQuotient(unsigned a, unsigned b, unsigned c) } } -// [FRONTIER] Active-bot counting requires the remaining state predicates. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotManager operation. - -// [FRONTIER] Bot-manager destruction remains unimplemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when owned bot and scheduler teardown is recovered. +// ELF 0x3DA7A0 (D1; recovered on the client track, docs/macos-c-singleplayer.md): reset, then the +// three scheduling queues are deleted (reset has already replaced A and B with fresh ones). The +// containers and both interface bases follow as members. BotManager::~BotManager() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::~BotManager"); + reset(); + delete m_queuePriorityA; + delete m_queuePriorityB; + delete m_queueSensing; } -// [FRONTIER] Remaining bot-manager virtual operations stop visibly when reached. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace each stop when its corresponding behavior is recovered. - // - the vector's byte span shifted right by two, i.e. its element count. // It counts admitted records, including deactivated bots. The constructor only reserves capacity; // addUnspawnedBot appends a record after consuming or allocating a BotMain. +// ELF 0x3DB060 int BotManager::getBotCount() const { return static_cast(m_botInfos.size()); } // Reports the bot counts from the managed roster. +// ELF 0x3DB080 int BotManager::getNumberOfActiveBots() const { return static_cast(m_botInfos.size()) - static_cast(m_deactivatedBots.size()); } +// ELF 0x3DB0D0 int BotManager::getNumberOfDeactivedBots() const { return static_cast(m_deactivatedBots.size()); } // Returns the bot at index. The caller must supply a valid index and a live record. +// ELF 0x3DB100 Bot* BotManager::getBot(unsigned int index) const { return m_botInfos[index]->m_bot; } // Bot-ID lookup checks bounds; player lookup requires a valid association. +// ELF 0x3DB1A0 Bot* BotManager::getBotFromId(unsigned int id) const { if (id < m_botInfos.size()) @@ -794,6 +868,7 @@ Bot* BotManager::getBotFromId(unsigned int id) const } // no bounds check on `playerId` - see the block above. +// ELF 0x3E0A80 Bot* BotManager::getBotFromPlayerId(int playerId) const { if (m_botByPlayerId[playerId] == -1) @@ -803,9 +878,15 @@ Bot* BotManager::getBotFromPlayerId(int playerId) const return getBotFromId(static_cast(m_botByPlayerId[playerId])); } -Bot* BotManager::getBotFromName(const std::string&) const +// ELF 0x3DB1D0: the first record whose player's name (IAIPlayer +0x18) equals the argument. +Bot* BotManager::getBotFromName(const std::string& name) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getBotFromName"); + for (std::vector::const_iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + { + if ((*it)->m_bot->getPlayer()->getName() == name) + return (*it)->m_bot; + } + return 0; } // BotManager::BotInfo - inlined in ELF addUnspawnedBot at ; @@ -820,7 +901,89 @@ BotManager::BotInfo::BotInfo(Bot* bot) { } +// ELF 0x3DB2E0 +bool exitAddBot(int playerId) +{ + static_cast(CommonSingletonServer::m_iaiGameEffector)->terminatePlayer(playerId); + return false; +} + +// ELF 0x3DB320 +bool BotManager::addBot(int playerId, int side, float* personality, IAIObject* object) +{ + const std::size_t rosterSize = m_botInfos.size(); + if (rosterSize >= static_cast( + static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots())) + return exitAddBot(playerId); + if (m_botByPlayerId[playerId] != -1) + return exitAddBot(playerId); + + m_lastCreatedBot = 0; + IAIPlayer* const player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) + ->getPlayerFromId(playerId); + IAIGameEffector* const effector = static_cast(CommonSingletonServer::m_iaiGameEffector); + if (object) + { + IAIObject* const currentVehicle = player->getCurrentVehicle(); + if (currentVehicle != player->getDefaultVehicle()) + effector->exitVehicle(player); + if (!object->isUnit()) + return exitAddBot(playerId); + effector->enterVehicle(player, object); + } + IAIObject* const vehicle = player->getCurrentVehicle(); + if (!vehicle) + return exitAddBot(playerId); + vehicle->setSide(side); + + const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfBehaviours(); + BotMain* bot; + if (m_bots.empty()) + { + UrgencyGenerator** const generators = checkPointer(new UrgencyGenerator*[count]); + UrgencyMerger* const merger = checkPointer(new UrgencyMerger(count, personality, generators)); + float* const weights = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + weights[i] = 1.0f; + BotOrder* const order = checkPointer(new BotOrder(weights, static_cast( + BotBehaviourManager::m_instance->getBehaviourId("Idle")))); + player->setViewDistance(static_cast(CommonSingletonServer::m_iaiSettings)->getViewDistance()); + bot = checkPointer(new BotMain(player, static_cast(m_botInfos.size()), + personality, 1.0f, 1, order, new BotMemory(), 0, side, merger, generators)); + } + else + { + bot = static_cast(m_bots.front()); + bot->setPlayer(player); + bot->m_basicWeights = personality; + bot->setSide(side); + float* const weights = checkPointer(new float[count]); + for (int i = 0; i < count; ++i) + weights[i] = 1.0f; + BotOrder* const order = checkPointer(new BotOrder(weights, static_cast( + BotBehaviourManager::m_instance->getBehaviourId("Idle")))); + bot->recieveOrder(order); + m_bots.erase(m_bots.begin()); + } + + bot->updateBotVehicle(0); + bot->updateBot(); + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (!information) + return exitAddBot(playerId); + information->setStrength(information->getStrength() + 1.0f); + bot->setWaypoints(checkPointer(new WPEmpty(information->getPosition()))); + m_botInfos.push_back(checkPointer(new BotInfo(bot))); + // shipped defect: grows to playerId, then writes element playerId; the first lookup is unchecked too. + if (static_cast(m_botByPlayerId.size()) < playerId) + m_botByPlayerId.resize(playerId, -1); + m_botByPlayerId[playerId] = static_cast(bot->getBotId()); + m_lastCreatedBot = bot; + return true; +} + // Admits an unspawned player using the first available preallocated bot. +// ELF 0x3DC300 bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) { m_lastCreatedBot = 0; @@ -869,7 +1032,67 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) return true; } +// ELF 0x3DD240. Picks the first dead bot of the side, else the first bot of the side; with none +// the index stays 0 (the ELF's initial value) and record 0 is deactivated. Its name returns to +// the pool (IAISettingsModifier +0x94 setBotNameUnused), its id is queued first in the +// deactivated list, its player slot cleared, its player detached (IAIPlayer +0x14 setPlayer(0)) +// and the bot marked deactivated. Both list inserts are at end() (the list header itself). +int BotManager::deactivateBot(int side) +{ + unsigned int index = 0; + bool found = false; + for (unsigned int i = 0; i < m_botInfos.size(); ++i) + { + Bot* const bot = m_botInfos[i]->m_bot; + if (bot && bot->getSide() == side && bot->isDead()) + { + index = i; + found = true; + break; + } + } + if (!found) + { + for (unsigned int i = 0; i < m_botInfos.size(); ++i) + { + Bot* const bot = m_botInfos[i]->m_bot; + if (bot && bot->getSide() == side) + { + index = i; + break; + } + } + } + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBotNameUnused(m_botInfos[index]->m_bot->getPlayer()->getName()); + m_deactivatedBots.push_back(index); + m_botByPlayerId[m_botInfos[index]->m_bot->getPlayerId()] = -1; + m_botInfos[index]->m_bot->getPlayer()->setPlayer(static_cast(0)); + m_botInfos[index]->m_bot->setAsDeactivated(true); + return static_cast(index); +} + +// ELF 0x3DD450. The name goes back to the pool before the test; only a dead bot is then +// deactivated (a live one answers -1). +int BotManager::deactivateBotFromPlayerId(int playerId) +{ + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return -1; + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBotNameUnused(bot->getPlayer()->getName()); + const unsigned int botId = bot->getBotId(); + if (!bot->isDead()) + return -1; + m_deactivatedBots.push_back(botId); + bot->setAsDeactivated(true); + bot->getPlayer()->setPlayer(static_cast(0)); + m_botByPlayerId[playerId] = -1; + return static_cast(botId); +} + // Reactivates a retired bot for a player and restores it to the active roster. +// ELF 0x3DD040 bool BotManager::reactivateBot(int playerId, int side, const std::string& name) { if (m_deactivatedBots.empty()) @@ -902,300 +1125,578 @@ bool BotManager::reactivateBot(int playerId, int side, const std::string& name) return true; } -Bot* BotManager::getBot(IAIObject*) const +// ELF 0x3DB120: the object map's bot id, then that record's bot (a null record answers null). +Bot* BotManager::getBot(IAIObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getBot"); + const std::map::const_iterator it = m_vehicleBots.find(object); + if (it == m_vehicleBots.end()) + return 0; + BotInfo* const info = m_botInfos[it->second]; + return info ? info->m_bot : 0; } +// ELF 0x3E0C90 Bot* BotManager::getLastCreatedBot() const { // return [this+228]. PE uses the corresponding member at +276. return m_lastCreatedBot; } -void BotManager::updateBotVehicle(Bot*, IAIObject*) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::updateBotVehicle"); -} - -void BotManager::setBotChangedVehicle(int, IAIObject*) +// ELF 0x3E0100: drops the first map entry that carries this bot's id, then maps the object to +// it (insert_unique: an object already mapped keeps its old bot). +void BotManager::updateBotVehicle(Bot* bot, IAIObject* vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotChangedVehicle"); -} - -void BotManager::setBotIsDead(int) -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsDead"); + const unsigned int botId = bot->getBotId(); + for (std::map::iterator it = m_vehicleBots.begin(); it != m_vehicleBots.end(); ++it) + { + if (it->second == botId) + { + m_vehicleBots.erase(it); + break; + } + } + m_vehicleBots.insert(std::pair(vehicle, botId)); } -void BotManager::setBotIsAlive(int) +// ELF 0x3E0210. A physical vehicle first gets IAIObjectPhysical +0x74 enablePhysics(its own +// side) - the plug-in is fetched before the side. A bot outside its transition phase and alive +// then refreshes its vehicle (+0x2C, null out-flag) and itself (+0x30), drops its plan (+0x5C), +// and, with the SAI enabled, reports the equipment change to its side's SAI (+0x40, bot id +// read before the side). +void BotManager::setBotChangedVehicle(int playerId, IAIObject* vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsAlive"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + if (vehicle && vehicle->isPhysical()) + { + IAIObjectPhysical* const physical = vehicle->getPhysical(); + physical->enablePhysics(vehicle->getSide()); + } + if (bot->isInTransitionPhase()) + return; + if (bot->isDead()) + return; + bot->updateBotVehicle(0); + bot->updateBot(); + bot->invalidatePlan(); + if (m_aiMain->getSAIEnable()) + { + const unsigned int botId = bot->getBotId(); + m_aiMain->getSAI(bot->getSide())->setBotHasChangedEquipment(botId); + } } -void BotManager::setBotIsManDown(int, IAIObject*) +// ELF 0x3E0340. The first object-map entry whose bot id equals the player id is dropped (the +// ELF compares the mapped bot id with the player id). The bot leaves man-down, enters its +// transition phase, resets navigation and its assigned areas (BotMain +0x214, past the Bot +// interface), its record's +4 word becomes 1 and the bot resets; equipment is cleared (-1), +// placed C4 removed, and the death callback (+0x11C) reports. +// The side's SAI is fetched (IAIMain +0x3C) and not used, as in the ELF. +void BotManager::setBotIsDead(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsManDown"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + for (std::map::iterator it = m_vehicleBots.begin(); it != m_vehicleBots.end(); ++it) + { + if (it->second == static_cast(playerId)) + { + m_vehicleBots.erase(it); + break; + } + } + bot->setManDown(false); + bot->setIsInTransitionPhase(true); + bot->getBotNavigation()->resetAll(); + static_cast(bot)->resetAssignedAreas(); + BotInfo* const info = m_botInfos[bot->getBotId()]; + IAIMain::m_instance->getSAI(info->m_bot->getSide()); + info->m_word4 = 1; + info->m_bot->reset(); + bot->setCurrentEquipment(static_cast(-1)); + if (bot->isC4Placed()) + bot->removeC4(); + IBotDeathCallBack* const callBack = bot->getDeathCallBack(); + if (callBack) + callBack->reportDeath(); +} + +// ELF 0x3E0510. Only a bot in its transition phase: the phase ends, vehicle and bot refresh, +// the last change time becomes -1000000.0 (float constant, ELF 0x49CDA4), the record's +// priorities, +0x18 double and +0x14 flag clear, the spawn coordinate is taken from the +// bot's information (Information +0x30 getPosition) and the spawn callback reports. +void BotManager::setBotIsAlive(int playerId) +{ + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot || !bot->isInTransitionPhase()) + return; + bot->setIsInTransitionPhase(false); + bot->updateBotVehicle(0); + bot->updateBot(); + bot->setLastChangeTime(-1000000.0f); + BotInfo* const info = m_botInfos[bot->getBotId()]; + info->m_priority = 0; + info->m_double24 = 0.0f; + info->m_word4 = 0; + info->m_flag20 = false; + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + if (information) + static_cast(bot)->setSpawnCoord(information->getPosition()); + IBotSpawnCallBack* const callBack = bot->getSpawnCallBack(); + if (callBack) + callBack->reportSpawn(); +} + +// ELF 0x3E0640: the object is not read. +void BotManager::setBotIsManDown(int playerId, IAIObject*) +{ + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->setManDown(true); + bot->updateBot(); + bot->updateBotVehicle(0); + bot->invalidatePlan(); + bot->getBotNavigation()->resetAll(); } -void BotManager::setBotIsRevived(int, IAIObject*) +// ELF 0x3E06C0. The revived bot leaves man-down, refreshes, resets navigation (reset, not +// resetAll), drops its plan, queues radio message 8 on channel 6 (args 2, 1.0f - ELF +// 0x49CB2C - and -1), and with the SAI enabled reports an equipment change (bot id first). +void BotManager::setBotIsRevived(int playerId, IAIObject*) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotIsRevived"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->setManDown(false); + bot->updateBot(); + bot->getBotNavigation()->reset(); + bot->invalidatePlan(); + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(8), + static_cast(6), 2u, 1.0f, -1); + if (m_aiMain->getSAIEnable()) + { + const unsigned int botId = bot->getBotId(); + m_aiMain->getSAI(bot->getSide())->setBotHasChangedEquipment(botId); + } } -void BotManager::setBotReceivedRadioMessage(const AIRadioMessageSettings&, int, int) +// ELF 0x3E07C0: the third argument names the receiving player. +void BotManager::setBotReceivedRadioMessage(const AIRadioMessageSettings& settings, int a, int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotReceivedRadioMessage"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->getCommunicationAgent()->receiveRadioMessage(settings, a, false); // ELF 0x3E080E } -void BotManager::setBotRecievedAttackCommanderOrder(int) +// ELF 0x3E0820: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedAttackCommanderOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedAttackCommanderOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveAttackCommanderOrder(); } -void BotManager::setBotRecievedDefendCommanderOrder(int) +// ELF 0x3E0870: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedDefendCommanderOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedDefendCommanderOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveDefendCommanderOrder(); } -void BotManager::setBotRecievedMoveCommanderOrder(int) +// ELF 0x3E08C0: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedMoveCommanderOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedMoveCommanderOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveMoveCommanderOrder(); } -void BotManager::setBotRecievedAttackSquadOrder(int) +// ELF 0x3E0910: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedAttackSquadOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedAttackSquadOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveAttackSquadOrder(); } -void BotManager::setBotRecievedDefendSquadOrder(int) +// ELF 0x3E0960: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedDefendSquadOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedDefendSquadOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveDefendSquadOrder(); } -void BotManager::setBotRecievedMoveSquadOrder(int) +// ELF 0x3E09B0: the bot's squad (+0x34 getBotSquad) receives the order. +void BotManager::setBotRecievedMoveSquadOrder(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotRecievedMoveSquadOrder"); + Bot* const bot = getBotFromPlayerId(playerId); + if (bot) + bot->getBotSquad()->recieveMoveSquadOrder(); } -void BotManager::setBotTeamKilled(int, int) +// ELF 0x3E0A00: the second argument is not read. +void BotManager::setBotTeamKilled(int playerId, int) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setBotTeamKilled"); + Bot* const bot = getBotFromPlayerId(playerId); + if (!bot) + return; + bot->getCommunicationAgent()->enqueueRadioMessage(static_cast(9), + static_cast(6), 3u, 0.0f, -1); } -void BotManager::registerDamageOnBot(float, int, int) +// ELF 0x3E0AC0: unchecked index; updateDamages applies and clears the sum each tick. +void BotManager::registerDamageOnBot(float damage, int botIndex, int attackerIndex) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::registerDamageOnBot"); + m_botInfos[botIndex]->m_damage += damage; + m_botInfos[botIndex]->m_attackerIndex = attackerIndex; } +// ELF 0x3DAD10: `flds 0xE8(this)`. float BotManager::getVehicleBailValue() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getVehicleBailValue"); + return m_float232; } -void BotManager::removeMineTarget(unsigned int) +// ELF 0x3DB280: every bot targeting the mine (BotMain +0x1FC) gets target -1 (+0x1F8). +void BotManager::removeMineTarget(unsigned int handle) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::removeMineTarget"); + for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + { + BotMain* const bot = static_cast((*it)->m_bot); + if (bot->getMineTarget() == handle) + bot->setMineTarget(static_cast(-1)); + } } +// ELF 0x3DFCE0 (1056 B; recovered on the client track, docs/macos-c-singleplayer.md). Clears the +// plan cursor, deletes every bot record (its bot through the virtual deleting destructor, +4, +// then the record) and empties the record vector and the bot list; frees the two priority +// queues and empties the +56 list; re-applies the construction-time scheduling defaults through +// the virtual setters (+0x8C..+0xA4); allocates two empty priority queues; clears +188. +// The sensing queue is left alone. Returns 1. bool BotManager::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::reset"); + m_planCursor = 0; // +0x104 + for (std::vector::iterator info = m_botInfos.begin(); info != m_botInfos.end(); ++info) + { + if (*info) + { + if ((*info)->m_bot) + delete (*info)->m_bot; // virtual, slot +4 + delete *info; + } + } + m_botInfos.resize(0, 0); + m_bots.resize(0, 0); + delete m_queuePriorityA; + delete m_queuePriorityB; + m_list56.clear(); // +0x38 + setLodLevelTicks(3, 2, 1); // +0x8C + setLodLevelPriority(3, 2, 1); // +0x90 + setPlannedDecisionMakingThreshold(0.5, 1.0, 3.0); // +0x94 + setUnplannedDecisionMakingThreshold(0.3, 0.8, 2.0); // +0x98 + setDecisionMakingInterleave(2, 2); // +0x9C + setSensingQuotient(1, 1); // +0xA0 + setSystemQuotient(30, 40, 30); // +0xA4 + m_queuePriorityA = new BotQueue; + m_queuePriorityB = new BotQueue; + m_hearingResumeId = 0; // +0xBC + return true; } -void BotManager::setRenderBotSensing(bool) +// ELF 0x3E2CC0 (weak): `movb %dl, 0xEC(this)`. +void BotManager::setRenderBotSensing(bool render) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::setRenderBotSensing"); + m_flag236 = render; } +// ELF 0x3E2CE0 (weak): `movzbl 0xEC(this)`. bool BotManager::getRenderBotSensing() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getRenderBotSensing"); + return m_flag236; } +// ELF 0x3E0CA0 void BotManager::writeBotPlans() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::writeBotPlans"); + s_tabLevel = 0; + const std::string levelPath = static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); + io::IStream* file = io::fileManager->open(levelPath + "../../../AI/BotPlans.cpp", + static_cast(0), static_cast(2), 0); + for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + { + Bot* const bot = (*it)->m_bot; + if (bot->isDead()) + continue; + BotScript* const plan = bot->getPlan(); + if (!file) + continue; + Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); + std::ostringstream out; + out << "/*******************************************************/" << std::endl; + const std::string& name = bot->getPlayer()->getName(); + out << "/* Name: " << name << std::endl; + // shipped defect: a missing information record is dereferenced, and a null plan is not checked. + const std::string& equipment = information->getAIObject()->getObject()->getTemplate()->getName(); + out << "/* Equipment: " << equipment << " Pos: "; + const Vec3& position = information->getPosition(); + out << position.x << '/'; + out << position.y << '/'; + out << position.z << " */" << std::endl; + out << "/*******************************************************/" << std::endl; + out << *static_cast(plan) << std::endl; + const std::string lengthSource = out.str(); + const std::string text = out.str(); + file->write(text.c_str(), static_cast(lengthSource.size())); + } + if (file) + file->release(); } +// ELF 0x3E2CF0 / 0x3E2D10 (weak): `incl` / `decl` of the class static. void BotManager::increaseTabLevel() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::increaseTabLevel"); + ++s_tabLevel; } +// ELF 0x3E2D10 void BotManager::decreaseTabLevel() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::decreaseTabLevel"); + --s_tabLevel; } -void BotManager::tabulate(std::ostream&) +// ELF 0x3E1410 +void BotManager::tabulate(std::ostream& out) { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::tabulate"); + for (int i = 0; i < s_tabLevel; ++i) + out << '\t'; } +// ELF 0x3DAF10: `movl 0x84(this)`. unsigned BotManager::getLodLevelFullTicks() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelFullTicks"); + return m_lodLevelFullTicks; } +// ELF 0x3DAF20: `movl 0x88(this)`. unsigned BotManager::getLodLevelMediumTicks() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelMediumTicks"); + return m_lodLevelMediumTicks; } +// ELF 0x3DAF30: `movl 0x8C(this)`. unsigned BotManager::getLodLevelLightTicks() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelLightTicks"); + return m_lodLevelLightTicks; } +// ELF 0x3DAF40: `movl 0x40(this)`. unsigned BotManager::getLodLevelFullPriority() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelFullPriority"); + return m_lodLevelFullPriority; } +// ELF 0x3DAF50: `movl 0x44(this)`. unsigned BotManager::getLodLevelMediumPriority() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelMediumPriority"); + return m_lodLevelMediumPriority; } +// ELF 0x3DAF60: `movl 0x48(this)`. unsigned BotManager::getLodLevelLightPriority() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLodLevelLightPriority"); + return m_lodLevelLightPriority; } +// ELF 0x3DAF70: `fldl 0x54(this)`. double BotManager::getPlannedDecisionMakingThresholdFull() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdFull"); + return m_plannedDecisionMakingThresholdFull; } +// ELF 0x3DAF80: `fldl 0x5C(this)`. double BotManager::getPlannedDecisionMakingThresholdMedium() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdMedium"); + return m_plannedDecisionMakingThresholdMedium; } +// ELF 0x3DAF90: `fldl 0x64(this)`. double BotManager::getPlannedDecisionMakingThresholdLight() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingThresholdLight"); + return m_plannedDecisionMakingThresholdLight; } +// ELF 0x3DAFA0: `fldl 0x6C(this)`. double BotManager::getUnplannedDecisionMakingThresholdFull() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdFull"); + return m_unplannedDecisionMakingThresholdFull; } +// ELF 0x3DAFB0: `fldl 0x74(this)`. double BotManager::getUnplannedDecisionMakingThresholdMedium() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdMedium"); + return m_unplannedDecisionMakingThresholdMedium; } +// ELF 0x3DAFC0: `fldl 0x7C(this)`. double BotManager::getUnplannedDecisionMakingThresholdLight() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingThresholdLight"); + return m_unplannedDecisionMakingThresholdLight; } +// ELF 0x3DAFD0: `movl 0x4C(this)`. unsigned BotManager::getPlannedDecisionMakingInterleave() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlannedDecisionMakingInterleave"); + return m_plannedDecisionMakingInterleave; } +// ELF 0x3DAFE0: `movl 0x50(this)`. unsigned BotManager::getUnplannedDecisionMakingInterleave() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getUnplannedDecisionMakingInterleave"); + return m_unplannedDecisionMakingInterleave; } +// ELF 0x3DAFF0: `fldl 0xA0(this)`. double BotManager::getSensingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSensingQuotient"); + return m_sensingQuotient; } +// ELF 0x3DB000: `fldl 0xA8(this) - the sensing split's second share`. double BotManager::getMemoryUpdateQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getMemoryUpdateQuotient"); + return m_sensingQuotientInverse; } +// ELF 0x3DB010: `fldl 0x90(this)`. double BotManager::getSystemDecisionMakingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSystemDecisionMakingQuotient"); + return m_systemDecisionMakingQuotient; } +// ELF 0x3DB020: `fldl 0x98(this) - setSystemQuotient's second share`. double BotManager::getSystemPathfindingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSystemPathfindingQuotient"); + return m_systemQuotient2; } +// ELF 0x3DB030: the third share setSystemQuotient does not store, `1.0f - [0x98] - [0x90]` +// (1.0f at ELF 0x49CB2C, evaluated left to right in x87). double BotManager::getSystemSensingQuotient() const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSystemSensingQuotient"); + return (1.0f - m_systemQuotient2) - m_systemDecisionMakingQuotient; } +// ELF 0x3DFA80: every record's four counters (+0x20..+0x2C) and three run times (+0x30..+0x40). void BotManager::resetStatistics() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::resetStatistics"); + for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + { + BotInfo* const info = *it; + info->m_behaviourUpdateCount = 0; + info->m_word36 = 0; + info->m_word40 = 0; + info->m_word44 = 0; + info->m_double48 = 0.0f; + info->m_double56 = 0.0f; + info->m_double64 = 0.0f; + } } -void BotManager::resetStatistics(unsigned int) const +// ELF 0x3DFAF0: the same for one unchecked index (the records are reached through pointers). +void BotManager::resetStatistics(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::resetStatistics"); + BotInfo* const info = m_botInfos[index]; + info->m_behaviourUpdateCount = 0; + info->m_word36 = 0; + info->m_word40 = 0; + info->m_word44 = 0; + info->m_double48 = 0.0f; + info->m_double56 = 0.0f; + info->m_double64 = 0.0f; } -unsigned BotManager::getPlanExecutionUpdateCount(unsigned int) const +// ELF 0x3DFB50 (+0x24), unchecked index. +unsigned BotManager::getPlanExecutionUpdateCount(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlanExecutionUpdateCount"); + return m_botInfos[index]->m_word36; } -unsigned BotManager::getDecisionMakingUpdateCount(unsigned int) const +// ELF 0x3DFB70 (+0x28), unchecked index. +unsigned BotManager::getDecisionMakingUpdateCount(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getDecisionMakingUpdateCount"); + return m_botInfos[index]->m_word40; } -unsigned BotManager::getSensingUpdateCount(unsigned int) const +// ELF 0x3DFB90 (+0x2C), unchecked index. +unsigned BotManager::getSensingUpdateCount(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSensingUpdateCount"); + return m_botInfos[index]->m_word44; } -unsigned BotManager::getDecisionMakingBehaviourUpdateCount(unsigned int) const +// ELF 0x3DFCC0 (+0x20), unchecked index. +unsigned BotManager::getDecisionMakingBehaviourUpdateCount(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getDecisionMakingBehaviourUpdateCount"); + return m_botInfos[index]->m_behaviourUpdateCount; } -double BotManager::getPlanExecutionRunTime(unsigned int) const +// ELF 0x3DFBB0 (+0x30), unchecked index. +double BotManager::getPlanExecutionRunTime(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPlanExecutionRunTime"); + return m_botInfos[index]->m_double48; } -double BotManager::getDecisionMakingRunTime(unsigned int) const +// ELF 0x3DFBD0 (+0x38), unchecked index. +double BotManager::getDecisionMakingRunTime(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getDecisionMakingRunTime"); + return m_botInfos[index]->m_double56; } -double BotManager::getSensingRunTime(unsigned int) const +// ELF 0x3DFBF0 (+0x40), unchecked index. +double BotManager::getSensingRunTime(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getSensingRunTime"); + return m_botInfos[index]->m_double64; } -bool BotManager::isPathfinding(unsigned int) const +// ELF 0x3DFC10 (+0x14), unchecked index. +bool BotManager::isPathfinding(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::isPathfinding"); + return m_botInfos[index]->m_flag20; } -bool BotManager::getLastPathfindingSucceeded(unsigned int) const +// ELF 0x3DFC40 (+0x48), unchecked index. +bool BotManager::getLastPathfindingSucceeded(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLastPathfindingSucceeded"); + return m_botInfos[index]->m_flag72; } -bool BotManager::getPathfindingStall(unsigned int) const +// ELF 0x3DFC70 (+0x49), unchecked index. +bool BotManager::getPathfindingStall(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getPathfindingStall"); + return m_botInfos[index]->m_flag73; } -double BotManager::getLastPathfindingRunTime(unsigned int) const +// ELF 0x3DFCA0 (+0x4C), unchecked index. +double BotManager::getLastPathfindingRunTime(unsigned int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::getLastPathfindingRunTime"); + return m_botInfos[index]->m_double76; +} + +// ELF 0x3E0C40 +void BotManager::enableBotScriptDebugger(bool enable) +{ + for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + (*it)->m_bot->enableBotScriptDebugger(enable); } -void BotManager::enableBotScriptDebugger(bool) +// ELF 0x3E0AB0 +void BotManager::buildObjectMap() { - BF2_AI_FRONTIER("dice::hfe::ai::BotManager::enableBotScriptDebugger"); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotManager.h b/Code/BF2/AI/AIDLL/AI/Main/BotManager.h index 67d1f0a7c..c7d22f7a2 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BotManager.h @@ -106,7 +106,7 @@ class BotManager : public IBotManager, public IBotManagerModifier typedef BotPriorityQueue SensingQueue; BotManager(); - // Virtual destruction is inherited from both interfaces; ordered teardown remains a named stop. + // Virtual destruction is inherited from both interfaces. virtual ~BotManager(); // the tick @@ -197,14 +197,19 @@ class BotManager : public IBotManager, public IBotManagerModifier virtual void enableBotScriptDebugger(bool enable); // +0x128 // population, and not part of either base - // These five are absent from both vtables, so they are BotManager's own non-virtual API. - void addBot(int side, int id, float* weights, IAIObject* obj); + // These methods are absent from both vtables, so they are BotManager's own non-virtual API. + bool addBot(int playerId, int side, float* weights, IAIObject* object); + void buildObjectMap(); // Adds an unspawned bot for playerId and side using personality weights; returns true. bool addUnspawnedBot(int playerId, int side, float* personality); // Returns whether the player's bot was reactivated on the requested side. bool reactivateBot(int playerId, int side, const std::string& name); - void deactivateBot(int id); - void deactivateBotFromPlayerId(int playerId); // indexes m_botByPlayerId + // Both answer the deactivated bot's id, or -1 (ELF 0x3DD240 / 0x3DD450). + int deactivateBot(int side); + int deactivateBotFromPlayerId(int playerId); // indexes m_botByPlayerId + + // ELF .bss 0x4CE8F8 (4 bytes); increaseTabLevel / decreaseTabLevel step it. [INFERRED] type int. + static int s_tabLevel; private: // Three priority queues hold pending bot work. Native container sizes depend on the compiler ABI. @@ -254,8 +259,9 @@ class BotManager : public IBotManager, public IBotManagerModifier /* 192 */ void* m_ptr192; // = 0 /* 196 */ void* m_ptr196; // = 0 /* 200 */ void* m_ptr200; // = 0 - // [UNRESOLVED] Map key and value types; the declarations preserve the observed storage width. - /* 204 */ std::map m_map204; // +204 node, +208 count, +212 comparator + // Object -> bot id, std::map by the shipped instantiations + // (ELF getBot(IAIObject*) 0x3DB120 find, updateBotVehicle 0x3E0100 insert_unique). Name [INFERRED]. + /* 204 */ std::map m_vehicleBots; // +204 node, +208 count, +212 comparator // [INFERRED] Shared scratch selection, cleared and filled from queues by decision-making // and sensing passes before they process the selected bots. /* 216 */ std::vector m_selectedBots; diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.cpp new file mode 100644 index 000000000..527552196 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.cpp @@ -0,0 +1,96 @@ +// Registered bot placements and the retail console spawn operation. + +// static init: ELF 0x3E4B60, __tcf_0 0x3E4BF0, _GLOBAL__I 0x3E4C20: stream Init precedes the manager. +#include + +#include "BotPlacementManager.h" + +#include + +#include "../../../../Core/Debug.h" +#include "../AIBot/BotMain.h" +#include "IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +// static init: ELF 0x3E4B60 (_GLOBAL__I 0x3E4C20): `operator new(8)`, the constructor, then +// the store to m_instance - the manager exists from the moment the library is loaded. BF2AI::clear +// deletes it (ELF 0x3EE1D0, the last delete there); a fresh library load makes the next one. +BotPlacementManager* BotPlacementManager::m_instance = new BotPlacementManager(); + +// ELF 0x3E2D30: constructs the two empty team lists and nothing else; it does not touch +// m_instance. +BotPlacementManager::BotPlacementManager() +{ +} + +// ELF 0x3E2EF0 (D1): clears m_instance only when it names this object, then the two lists are +// destroyed in reverse order, each destroying its placements (three strings apiece). +BotPlacementManager::~BotPlacementManager() +{ + if (m_instance == this) + m_instance = 0; +} + +// ELF 0x3E2F60 +bool BotPlacementManager::addPlacement(const std::string& name, const Vec3& position, + const Vec3& rotation, const std::string& string1C, + int team, const std::string& string20) +{ + BotPlacement placement = {}; + placement.m_name = name; + placement.m_position = position; + placement.m_rotation = rotation; + placement.m_string1C = string1C; + placement.m_string20 = string20; + m_placements[team - 1].insert(m_placements[team - 1].end(), placement); + return true; +} + +// ELF 0x3E30E0 +bool BotPlacementManager::spawnBot(int team) +{ + std::stringstream command; + std::stringstream count; + std::string name; + BotPlacement placement = {}; + + Debug(DebugTypeError, "AI/AIDLL/AI/Main/BotPlacementManager.cpp", 90, "") + << "This does not work!"; + + if (m_placements[team - 1].empty()) + return false; + + const std::list::iterator it = m_placements[team - 1].begin(); + name = "FIXME"; + command << it->m_name << " " << it->m_position << " " << it->m_rotation << " " + << it->m_string1C << " " << team << " "; + command << name << " "; + command << it->m_string20; + + std::stringstream position; + std::stringstream rotation; + std::stringstream side; + position << it->m_position; + rotation << it->m_rotation; + side << team; + placement = *it; + m_placements[team - 1].erase(m_placements[team - 1].begin()); + + count << static_cast(IBotManager::instance->getBotCount()); + Bot* const bot = IBotManager::instance->getLastCreatedBot(); + if (bot) + { + // shipped defect: none of the command streams is executed, and the placeholder name + // is applied to the already existing last-created bot. + bot->setName(name); + return true; + } + return false; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.h b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.h new file mode 100644 index 000000000..2381acf5f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/BotPlacementManager.h @@ -0,0 +1,56 @@ +// Holds the per-team bot placements that console commands register and spawnBot consumes. +// Constructed when the DLL loads (this file's static initializer) and destroyed by BF2AI::clear. +// Source placement is attested by spawnBot's diagnostic path. + +#ifndef AI_AIDLL_AI_MAIN_BOTPLACEMENTMANAGER_H // [INFERRED] guard style +#define AI_AIDLL_AI_MAIN_BOTPLACEMENTMANAGER_H + +#include +#include + +#include "../../../../Math/Vec3.h" + +namespace dice { +namespace hfe { +namespace ai { + +// One registered placement. Retail element size is 0x24 (list node 0x2C): the list's __clear +// (0x3E4C40) destroys strings at +0x00, +0x1C and +0x20; +0x04..+0x1B hold no destructor and are +// filled from addPlacement's two Vec3 arguments. Field names [INFERRED] from addPlacement's +// parameter order (std::string const&, Vec3 const&, Vec3 const&, std::string const&, int, +// std::string const&); the int selects the team list and is not stored. +struct BotPlacement +{ + /* +0x00 */ std::string m_name; + /* +0x04 */ Vec3 m_position; + /* +0x10 */ Vec3 m_rotation; + /* +0x1C */ std::string m_string1C; // [UNRESOLVED] meaning + /* +0x20 */ std::string m_string20; // [UNRESOLVED] meaning +}; + +class BotPlacementManager +{ +public: + BotPlacementManager(); // ELF 0x3E2D30 (C2), 0x3E2E30 (C1) + ~BotPlacementManager(); // ELF 0x3E2E80 (D2), 0x3E2EF0 (D1) - not virtual + + // Appends a placement to team 1 or 2. The team index is unchecked. + bool addPlacement(const std::string& name, const Vec3& position, const Vec3& rotation, + const std::string& string1C, int team, const std::string& string20); + // Emits the retail error, then consumes one placement when available. If the error is + // filtered, the retail body only renames the last-created bot; it creates no new bot. + bool spawnBot(int team); + + static BotPlacementManager* m_instance; + +private: + // Retail size 8 (`operator new(8)` in the static initializer): two list heads, one per team, + // indexed team - 1 by addPlacement. The constructor and destructor walk them as an array. + /* +0x00 */ std::list m_placements[2]; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_MAIN_BOTPLACEMENTMANAGER_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp b/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp index da92ce876..3f8e3d314 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/CommonSingletonServer.cpp @@ -15,8 +15,14 @@ extern ClassManager* classManager; namespace ai { +// ELF 0x2EC020 / 0x2EC040; engine ELF 0x841BE50 / 0x841BE60. +ISingletonServerUpdater::ISingletonServerUpdater() +{ +} + // Shared out-of-line destructor used by engine and DLL updater classes. Keep it before // update in the interface: update occupies ELF +0x08 and PE +0x04. +// ELF 0x2EC060 / 0x2EC080 / 0x2EC0A0 ISingletonServerUpdater::~ISingletonServerUpdater() { } @@ -53,12 +59,14 @@ void* CommonSingletonServer::m_iAIMineManager = 0; // - a bare `ret`. See the header: the base publishes the entry point and does // nothing with it. AISingletonServer::updateStaticMethods is the one that is actually called. +// ELF 0x2EB570 void CommonSingletonServer::updateStaticMethods() { } // Refreshes all 28 singleton pointers in order. Missing names store null without logging // or reporting failure; callers must validate the interfaces they require. +// ELF 0x2EB580 void CommonSingletonServer::updateStaticMethodsInternal() { m_iAimerHelper = classManager->getSimpleSingleton("AimerHelper"); @@ -92,6 +100,7 @@ void CommonSingletonServer::updateStaticMethodsInternal() } // The same twenty-eight, same order, all nulled. +// ELF 0x2EB410 void CommonSingletonServer::clearAllStaticMethods() { m_iAimerHelper = 0; diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp index 49c8003b7..e0710fcc4 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp @@ -1,8 +1,34 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining CommunicationHub operations. +// [INFERRED] Source placement. + +// static init: ELF 0x3E5BD0 (__tcf_0 0x3E5C30, _GLOBAL__I 0x3E5C60): 's Init object only. +#include #include "CommunicationHub.h" -#include "AIDllFrontier.h" +#include +#include +#include +#include + +#include "../AIStrategicEntity/AIStrategicObjectManager.h" // reset: the area count +#include "../AIStrategicEntity/AIStrategicArea.h" // enemySpottedByAI: area centres + +#include "CommonSingletonServer.h" // enemySpottedByHuman's timer +#include "IBotManager.h" +#include "../AIBot/BotMain.h" +#include "../AIBot/CommunicationAgent.h" +#include "../AIKnowledge/Information.h" +#include "../AIKnowledge/IPIPhysical.h" +#include "../AIKnowledge/InformationManager.h" +#include "../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../AIInterface/BFKnowledge/BFTimer.h" +#include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer +#include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" // IAIPlayerFactory::getPlayerFromId +#include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::enemySpottedByAI +#include "../../../AIInterface/BFKnowledge/BFRadioComm.h" // IBFRadioComm::sendAIRadioMessage +#include "../../../AIInterface/Module/BFConsole.h" // IBFModuleCourier, AIRadioMessageSettings +#include "../../../../Math/Mat4.h" +#include "../../../../Math/Vec3.h" namespace dice { namespace hfe { @@ -28,34 +54,219 @@ CommunicationHub::~CommunicationHub() m_instance = 0; } -// [FRONTIER] Behavior methods stop until their strategic-object dependencies are implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// ELF 0x3E5170. The three timestamps go to -1000.0. Each side's strength vector gets one entry +// per strategic area: appended as {6, -1000.0} while side 0's vector is empty, otherwise the +// first areaCount entries of both are overwritten in place (sizes are not checked again). void CommunicationHub::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::reset"); + const double never = -1000.0; + m_type2SentTime[0] = never; + m_type2SentTime[1] = never; + m_time44 = never; + const int areas = static_cast(AIStrategicObjectManager::getInstance()->getStrategicAreas().size()); + if (m_combatStrength[0].empty()) + { + for (int i = 0; i < areas; ++i) + { + m_combatStrength[0].push_back(std::make_pair(static_cast(6), static_cast(-1000))); + m_combatStrength[1].push_back(std::make_pair(static_cast(6), static_cast(-1000))); + } + return; + } + for (int i = 0; i < areas; ++i) + { + m_combatStrength[0][i].first = static_cast(6); + m_combatStrength[1][i].first = static_cast(6); + m_combatStrength[0][i].second = never; + m_combatStrength[1][i].second = never; + } } -void CommunicationHub::enemySpottedByAI(IAIPlayer*, IAIObject*, int) +// ELF 0x3E57E0 (776 bytes). The side's information about the object must be primary (Information +// ::isPrimary is called on the lookup result without a null test) and have a physical plug-in. +// The object's XZ position is tested against every strategic area's centre (AIStrategicArea +// ::getCenterPosition), within 100 m for strength types 4 and 5, else 30 m. For the first area in +// range that has news the game is told (IAIGame +0x6C) and the scan ends: +// * types 4/5: more than 60 s since the last such report (+44, shared by both sides); +// * the area's entry for the side is older than 60 s: it takes the type and the time; +// * the entry holds type 0 or 1 and the enemy is type 2: it becomes 2 with the time. +// The object's world object is fetched before the bot's player, as shipped. +void CommunicationHub::enemySpottedByAI(IAIPlayer* player, IAIObject* object, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::enemySpottedByAI"); + Information* const information = informationManager->getInformation(object->getInformation(side)); + if (!information->isPrimary()) + return; + IPIPhysical* const physical = information->getPhysical(); + if (!physical) + return; + const int strengthType = physical->getStrengthType(); + const std::map& areas = + AIStrategicObjectManager::getInstance()->getStrategicAreas(); + const bool largeType = static_cast(strengthType - 4) <= 1; + const float rangeSq = largeType ? 10000.0f : 900.0f; + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + std::vector >& strengths = m_combatStrength[side - 1]; + + unsigned int index = 0; + for (std::map::const_iterator it = areas.begin(); it != areas.end(); + ++it, ++index) + { + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + vec3ToVec2XZ(object->getPosition(), position); + const Vec2& centre = it->second->getCenterPosition(); + const float dx = position.x - centre.x; + const float dy = position.y - centre.y; + if (!(rangeSq > dx * dx + dy * dy)) + continue; + if (largeType && now - m_time44 > 60.0f) + { + m_time44 = now; + break; + } + std::pair& entry = strengths[index]; + if (now - entry.second > 60.0f) + { + entry.first = static_cast(strengthType); + entry.second = now; + break; + } + if ((entry.first == 0 || entry.first == 1) && strengthType == 2) + { + strengths[index].first = static_cast(2); + strengths[index].second = now; + break; + } + } + if (index == areas.size()) + return; // no area had news: the shipped loop exit skips the report + + world::IObject* const spotted = object->getObject(); + world::IPlayer* const spotter = player->getPlayer(); + static_cast(CommonSingletonServer::m_iaiGame)->enemySpottedByAI(spotter, spotted); } -void CommunicationHub::enemySpottedByHuman(IAIObject*, unsigned char) const +// ELF 0x3E5AF0. The side's information about the object (IAIObject +0xB8 getInformation), +// else forced into existence (+0xB4 forceGetInformation(side, true)), is stamped with the game +// time (Information +0xC setTime). Neither lookup result is tested before the stamp. +void CommunicationHub::enemySpottedByHuman(IAIObject* object, unsigned char side) const { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::enemySpottedByHuman"); + Information* information = informationManager->getInformation(object->getInformation(side)); + if (!information) + information = informationManager->getInformation(object->forceGetInformation(side, true)); + information->setTime(static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); } -void CommunicationHub::filterAndSendAIRadioMessage(BotMain*, int, ChannelMessageType, - AIRadioChannelType, AIRadioMessageType, - unsigned char, int, unsigned char, - unsigned char) +// ELF 0x3E5330 (395 bytes). The game time is read first in every case. A type-2 message is sent +// only when more than 20 s have passed since the side's last one, whose time is then renewed from +// a second timer read. Inside the 20 s it is not sent: when `argument` names an AI player, the +// settings of message type 2 (IBFModuleCourier +0x1C, then +0x18; the voice lookup's result is +// not tested) go straight to filterAndReceiveAIRadioMessage(settings, playerId, argument, true). +// Everything else reaches IBFRadioComm +8 without the message type; its result is discarded. +void CommunicationHub::filterAndSendAIRadioMessage(BotMain*, int senderPlayerId, + ChannelMessageType channelMessage, + AIRadioChannelType channel, AIRadioMessageType type, + unsigned char voice, int playerId, unsigned char side, + unsigned char argument) { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::filterAndSendAIRadioMessage"); + const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (type == 2) + { + if (!(20.0f > now - m_type2SentTime[side - 1])) + { + m_type2SentTime[side - 1] = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + } + else + { + IAIPlayer* const receiver = + static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(argument); + if (!receiver || !receiver->getIsAIPlayer()) + return; + IBFModuleCourier* const courier = + static_cast(CommonSingletonServer::m_iBFModuleCourier); + int typeVoice; + courier->getVoiceFromAiMessageType(static_cast(2), typeVoice); + AIRadioMessageSettings settings; + courier->getAIMessageSettings(typeVoice, settings); + filterAndReceiveAIRadioMessage(settings, playerId, argument, true); + return; + } + } + static_cast(CommonSingletonServer::m_iBFRadioComm) + ->sendAIRadioMessage(senderPlayerId, channelMessage, channel, voice, playerId, side, argument); } -void CommunicationHub::filterAndReceiveAIRadioMessage(const AIRadioMessageSettings&, int, int, bool) +// ELF 0x3E54C0 (795 bytes). The receiver is IBotManager +0x1C getBotFromPlayerId(receiver), used +// without a null test; its own messages (BotMain +0xB4 getPlayerId == sender) are dropped. A +// message of type 0, 1 or 2 (settings +0) whose sender is a human player (IAIPlayerFactory +0x20, +// IAIPlayer +0x88 false) is filtered first; an unknown or AI sender is not: +// * type 2 is dropped when the receiver's current equipment lies more than 90 degrees off the +// human's camera forward axis (row 2), seen from the camera position (row 3). The direction +// is normalised as shipped: kept when |d.d - 1| < FLT_EPSILON, zero when |d.d| < FLT_EPSILON. +// The equipment information is not null-tested; +// * types 1 and 0 set the human's current vehicle's primary object allowed (1) or not allowed +// (0) for bots (IAIObject +0xFC, +0x9C); the vehicle itself is not null-tested. +// Then CommunicationAgent::receiveRadioMessage(settings, sender, flag) files it. +// [CHOSEN, not recovered] x87 extended intermediates are carried in double here. +void CommunicationHub::filterAndReceiveAIRadioMessage(const AIRadioMessageSettings& settings, + int senderPlayerId, int receiverPlayerId, bool flag) { - BF2_AI_FRONTIER("dice::hfe::ai::CommunicationHub::filterAndReceiveAIRadioMessage"); + Bot* const bot = IBotManager::instance->getBotFromPlayerId(receiverPlayerId); + if (senderPlayerId == bot->getPlayerId()) + return; + int type; + std::memcpy(&type, settings.m_opaque0, sizeof(type)); // +0, opaque in BFConsole.h + IAIPlayerFactory* const players = static_cast(CommonSingletonServer::m_iaiPlayerFactory); + if (type == 0 || type == 1) + { + IAIPlayer* const sender = players->getPlayerFromId(senderPlayerId); + if (sender && !sender->getIsAIPlayer()) + { + if (IAIObject* const primary = sender->getCurrentVehicle()->getPrimaryObject()) + primary->setIsAllowedByBots(type == 1); + } + } + else if (type == 2) + { + IAIPlayer* const sender = players->getPlayerFromId(senderPlayerId); + if (sender && !sender->getIsAIPlayer()) + { + const Mat4& camera = *static_cast(sender->getCameraTransformation()); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + const Vec3& target = equipment->getPosition(); + Vec3 direction; + direction.x = target.x - camera.m[12]; + direction.y = target.y - camera.m[13]; + direction.z = target.z - camera.m[14]; + const double lengthSq = static_cast(direction.x) * direction.x + + static_cast(direction.y) * direction.y + + static_cast(direction.z) * direction.z; + if (!(std::fabs(lengthSq - 1.0f) < 1.1920928955078125e-07f)) + { + if (!(std::fabs(static_cast(lengthSq)) < 1.1920928955078125e-07f)) + { + const double scale = 1.0f / std::sqrt(lengthSq); + direction.x = static_cast(direction.x * scale); + direction.y = static_cast(direction.y * scale); + direction.z = static_cast(direction.z * scale); + } + else + direction.x = direction.y = direction.z = 0.0f; + } + const Mat4& view = *static_cast(sender->getCameraTransformation()); + double cosine = static_cast(view.m[8]) * direction.x + + static_cast(view.m[9]) * direction.y + + static_cast(view.m[10]) * direction.z; + if (-1.0f > cosine) + cosine = -1.0f; + else if (cosine > 1.0f) + cosine = 1.0f; + if (std::acos(static_cast(cosine)) > 1.5707963705062866f) + return; + } + } + bot->getCommunicationAgent()->receiveRadioMessage(settings, senderPlayerId, flag); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h index ff066edbf..c61287fcc 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h +++ b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h @@ -1,6 +1,4 @@ // Filters and distributes bot radio messages and enemy sightings. -// [FRONTIER] Remaining message behavior requires implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_COMMUNICATIONHUB_H @@ -32,26 +30,36 @@ enum CombatStrengthType : int; class CommunicationHub { public: - CommunicationHub(); // 0x??, - virtual ~CommunicationHub(); // 0x??, - (vtable slots 0 and 1) + CommunicationHub(); // ELF 0x3E4F10 (C1), 0x3E4EB0 (C2) + virtual ~CommunicationHub(); // ELF 0x3E5010 (D1), 0x3E4F70 (D2), 0x3E50B0 (D0) - void reset(); - void enemySpottedByAI(IAIPlayer *, IAIObject *, int); - void enemySpottedByHuman(IAIObject *, unsigned char) const; - void filterAndSendAIRadioMessage(BotMain *, int, ChannelMessageType, - AIRadioChannelType, AIRadioMessageType, - unsigned char, int, unsigned char, unsigned char); - void filterAndReceiveAIRadioMessage(const AIRadioMessageSettings&, int, int, bool); + void reset(); // ELF 0x3E5170 + // ELF 0x3E57E0: reports a bot's sighting of `object` to the game (IAIGame +0x6C) when it is + // new for one of `side`'s strategic areas. + void enemySpottedByAI(IAIPlayer* player, IAIObject* object, int side); + void enemySpottedByHuman(IAIObject *, unsigned char) const; // ELF 0x3E5AF0 + // ELF 0x3E5330: hands a bot's message to the engine radio (IBFRadioComm +8). The BotMain + // argument is not read. A type-2 message within 20 s of the side's last one is not sent; + // it is delivered to `argument` directly when that player is a bot. + void filterAndSendAIRadioMessage(BotMain* bot, int senderPlayerId, ChannelMessageType channelMessage, + AIRadioChannelType channel, AIRadioMessageType type, + unsigned char voice, int playerId, unsigned char side, + unsigned char argument); + // ELF 0x3E54C0: files `settings` with the bot of `receiverPlayerId` (unless it sent it). + // Messages of types 0..2 from a human sender are filtered first; see the .cpp. + void filterAndReceiveAIRadioMessage(const AIRadioMessageSettings& settings, int senderPlayerId, + int receiverPlayerId, bool flag); // Offsets describe the original ELF layout. STL sizes and double alignment depend on // the target compiler; do not treat 52 bytes as a portable object size. // These timestamps are uninitialized until reset is called. - /* +4 */ double m_time4; // [UNRESOLVED] - reset puts -1000.0 here - /* +12 */ double m_time12; // [UNRESOLVED] - likewise + // Game time of each side's last sent type-2 message (indexed side - 1); reset: -1000.0. + /* +4 */ double m_type2SentTime[2]; // Two per-side combat-strength vectors. Each original ELF element occupies 12 bytes. /* +20 */ std::vector > m_combatStrength[2]; - /* +44 */ double m_time44; // [UNRESOLVED] - reset puts -1000.0 here too + // enemySpottedByAI: last report of a strength-type 4/5 enemy, either side; reset: -1000.0. + /* +44 */ double m_time44; // first wins here (`if (!m_instance)`), and the destructor does test `== this` - the opposite // discipline from `AerialHeightMap`, one step earlier in the same init sequence. diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp index 8466be28f..9d6a5ce3a 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp @@ -1,6 +1,14 @@ - +#include #include "IAIPathfinding.h" +namespace { +// The two original translation units are combined here; local object names are [INFERRED]. +// static init: ELF 0x3E6990 (__tcf_0 0x3E69F0, _GLOBAL__I 0x3E6A20), IAIPathfinding.cpp. +std::ios_base::Init pathfindingStreamInit; +// static init: ELF 0x3E6B40 (__tcf_0 0x3E6BA0, _GLOBAL__I 0x3E6BD0), IAIPathfindingSetup.cpp. +std::ios_base::Init pathfindingSetupStreamInit; +} + namespace dice { namespace hfe { namespace ai { diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h index bd35c7875..3d002389c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.h @@ -28,6 +28,18 @@ struct triple C third; }; +// Attested as `ai::make_triple` (ELF), the triple counterpart of +// std::make_pair. +template +triple make_triple(const A& first, const B& second, const C& third) +{ + triple result; + result.first = first; + result.second = second; + result.third = third; + return result; +} + namespace astar { // `setStatus`'s second argument and `getStatus`'s result. [UNRESOLVED] enumerators. enum Status : int; @@ -59,28 +71,28 @@ class IAIPathfinding virtual bool isValidPosition(int, int, const Vec3&, unsigned int, bool) const = 0; virtual bool isValidPosition(int, int, const Vec3&, unsigned int, unsigned int, bool) const = 0; // Appends pointers to const vertices through a mutable output vector. - virtual int getPolygon(std::vector&, int, const Vec3&, int) const = 0; - virtual int getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const = 0; - virtual int getPolygon(std::vector&, int, unsigned int, unsigned int) const = 0; + virtual bool getPolygon(std::vector&, int, const Vec3&, int) const = 0; + virtual bool getPolygon(std::vector&, int, const Vec3&, unsigned int&, unsigned int&, int) const = 0; + virtual bool getPolygon(std::vector&, int, unsigned int, unsigned int) const = 0; // Returns whether a polygon was found; invalid map indices return false. // [INFERRED] The second overload's bool result follows the first overload's contract. virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, int) const = 0; virtual bool getPolygon(const Vec3&, int, unsigned int&, unsigned int&, unsigned int, unsigned int, int) const = 0; virtual void getPolygonsInRadius(std::list&, int, unsigned int, unsigned int, const Vec3&, float) const = 0; virtual void getPolygonsInTriangle(std::list&, int, unsigned int, unsigned int, const Vec3&, const Vec3&, const Vec3&) const = 0; - virtual int getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const = 0; + virtual bool getPolygonFromIsland(const Vec3&, int, unsigned int&, unsigned int, int) const = 0; virtual bool getMaterial(const Vec3&, int, int, unsigned char&) const = 0; virtual bool getMaterial(int, unsigned int, unsigned int, unsigned char&) const = 0; - virtual void setMaterial(int, unsigned int, unsigned int, unsigned char) const = 0; // const, and mutates + virtual bool setMaterial(int, unsigned int, unsigned int, unsigned char) const = 0; // const, and mutates virtual void* getQuadTree(int, unsigned int) const = 0; virtual void* getClusterGraph(int, unsigned int) const = 0; virtual void getPolygonCentre(Vec3&, int, unsigned int, unsigned int) const = 0; - virtual void getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const = 0; + virtual bool getEdge(Vec3&, Vec3&, int, unsigned int, unsigned int, unsigned int) const = 0; virtual bool getLineIntersectionWithPolygon(Vec3&, int, unsigned int, unsigned int, const Vec3&, const Vec3&) const = 0; virtual void drawPolygon(int, unsigned int, unsigned int, float *, float) const = 0; // const, and draws virtual int getClusterOfPolygon(int, unsigned int, unsigned int) const = 0; virtual bool areNeighbouringClusters(int, unsigned int, unsigned short, unsigned short) const = 0; - virtual void updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short) = 0; + virtual bool updateClusterPortalCosts(unsigned int&, triple&, int, unsigned int, unsigned short) = 0; virtual bool trace(int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const = 0; virtual bool trace(unsigned int, unsigned int, int, const Vec3&, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const = 0; virtual bool trace(BotNavigation *, bool, const Vec3&, Vec3&, unsigned int&, int, int, float, unsigned char, unsigned char *) const = 0; @@ -111,14 +123,16 @@ class IAIPathfinding virtual void restoreMapPart(int) = 0; virtual void resetOriginalMaterialOfDestroyableMapPart(int) = 0; virtual void searchPointSelected(bool) = 0; - virtual bool tryPath(const Vec3&, const Vec3&) = 0; - virtual bool tryClusterPath(const Vec3&, const Vec3&) = 0; + virtual void tryPath(const Vec3&, const Vec3&) = 0; + virtual void tryClusterPath(const Vec3&, const Vec3&) = 0; virtual void setClusterSearch(bool) = 0; virtual bool getClusterSearch() const = 0; virtual void setActivatePathfindingDebugTool(bool) = 0; virtual bool getActivatePathfindingDebugTool() const = 0; virtual void setPathfindingDebugToolVehicle(const std::string&) = 0; - virtual void* getPathfindingDebugToolVehicle() const = 0; + // ELF 0x3A53E0 returns IAISettings +0x50 getVehicle(int) unchanged; ConsoleClass540 assigns it + // to a std::string, so the borrowed reference is the result [INFERRED spelling]. + virtual const std::string& getPathfindingDebugToolVehicle() const = 0; virtual void setPathfindingDebugToolVehicleId(int) = 0; virtual int getClusterCostType(int, unsigned int) const = 0; @@ -138,24 +152,24 @@ class IAIPathfindingSetup IMapContainer(); virtual ~IMapContainer(); // slots 0, 1 - virtual const std::string& getName() = 0; // 2 - virtual int getMinPolygonsInLeaf() = 0; // 3 + virtual const std::string& getName() const = 0; // 2 + virtual int getMinPolygonsInLeaf() const = 0; // 3 virtual void setMinPolygonsInLeaf(int) = 0; // 4 - virtual int getMaxDepthInTree() = 0; // 5 + virtual int getMaxDepthInTree() const = 0; // 5 virtual void setMaxDepthInTree(int) = 0; // 6 - virtual float getMaxSlope() = 0; // 7 + virtual float getMaxSlope() const = 0; // 7 virtual void setMaxSlope(float) = 0; // 8 virtual void setHeadClearance(float) = 0; // 9 - virtual float getHeadClearance() = 0; // 10 + virtual float getHeadClearance() const = 0; // 10 virtual void setRadius(float) = 0; // 11 - virtual float getRadius() = 0; // 12 + virtual float getRadius() const = 0; // 12 virtual void setAllowedHeightDiff(float) = 0; // 13 - virtual float getAllowedHeightDiff() = 0; // 14 - virtual void draw() = 0; // 15 - virtual void undraw() = 0; // 16 - virtual void drawCluster() = 0; // 17 - virtual void undrawCluster() = 0; // 18 - virtual void drawClusterNeighbourIndices(const Vec3&) = 0; // 19 + virtual float getAllowedHeightDiff() const = 0; // 14 + virtual void draw() const = 0; // 15 + virtual void undraw() const = 0; // 16 + virtual void drawCluster() const = 0; // 17 + virtual void undrawCluster() const = 0; // 18 + virtual void drawClusterNeighbourIndices(const Vec3&) const = 0; // 19 virtual void loadGTSDebugMeshes() = 0; // 20 virtual void buildDebugMeshes() = 0; // 21 virtual void unloadDebugMeshes() = 0; // 22 @@ -204,4 +218,4 @@ class IAIPathfindingSetup } // namespace hfe } // namespace dice -#endif // AI_AIDLL_AI_MAIN_IAIPATHFINDING_H \ No newline at end of file +#endif // AI_AIDLL_AI_MAIN_IAIPATHFINDING_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h index 812bd06bc..5adc9a14c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.h @@ -12,7 +12,7 @@ namespace dice { namespace hfe { namespace ai { -class AIRadioMessageSettings; +struct AIRadioMessageSettings; class Bot; class IAIObject; diff --git a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp index 7328a6be1..0fff5d82e 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.cpp @@ -1,8 +1,18 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining StrategyManager operations. +// static init: ELF 0x3EAC80 (__tcf_0 0x3EACE0, _GLOBAL__I 0x3EAD10): 's Init object only. +#include #include "StrategyManager.h" -#include "AIDllFrontier.h" +#include "../../../../Core/Debug.h" +#include "../AIUtils/checkPointer.h" +#include "../AIStrategic/Strategy.h" +#include "../AIStrategic/StrategyPrerequisite.h" +#include "../AIStrategic/SCConstant.h" +#include "../AIStrategic/SCHomogeneous.h" +#include "../AIStrategic/SCHeterogeneous.h" +#include "../AIStrategic/SCArea.h" +#include "../AIStrategicEntity/AIStrategicObjectManager.h" +#include "../AIStrategicEntity/AIStrategicArea.h" namespace dice { namespace hfe { @@ -10,7 +20,7 @@ namespace ai { StrategyManager* StrategyManager::m_instance = 0; -// Initializes strategy collections and installs the singleton when none exists. +// ELF 0x3E7A60 / 0x3E7D40. Initializes collections and installs the first singleton. StrategyManager::StrategyManager() : m_activeStrategy(0) , m_activePrerequisite(0) @@ -26,7 +36,7 @@ StrategyManager::StrategyManager() m_instance = this; } -// Resets strategy state and releases the owned collections. +// ELF 0x3E7F70 / 0x3E8160. Resets state and releases the owned collections. StrategyManager::~StrategyManager() { reset(); @@ -35,45 +45,51 @@ StrategyManager::~StrategyManager() m_instance = 0; } -// Static access to the concrete strategy manager, whose destructor is nonvirtual. +// ELF 0x3E8350. Static access to the manager, whose destructor is nonvirtual. StrategyManager* StrategyManager::getInstance() { return m_instance; } +// ELF 0x3E8370. void StrategyManager::setInstance(StrategyManager* instance) { m_instance = instance; } +// ELF 0x3EA7B0. bool StrategyManager::getEnableDebug() { return m_enableDebug; } -void StrategyManager::setEnableDebug(bool on) +// ELF 0x3EA790. The stored byte is explicitly returned in EAX. +bool StrategyManager::setEnableDebug(bool on) { m_enableDebug = on; + return on; } +// ELF 0x3E8730. Strategy* StrategyManager::getActiveStrategy() { return m_activeStrategy; } -// by value - the shipped function is `__stdcall` with a hidden return slot, i.e. it copies the +// ELF 0x3E8740. The shipped function has a hidden return slot, i.e. it copies the // member rather than handing back a reference to it. std::string StrategyManager::getActiveStrategyName() { return m_activeStrategyName; } +// ELF 0x3E9410. StrategyPrerequisite* StrategyManager::getActivePrerequisite() { return m_activePrerequisite; } -// the cursor is checked before it is dereferenced, and a miss returns null rather than a sentinel. +// ELF 0x3EA3B0. A missing active condition returns null. StrategyCondition* StrategyManager::getActiveCondition() { if (m_activeCondition == m_conditions.end()) @@ -81,136 +97,378 @@ StrategyCondition* StrategyManager::getActiveCondition() return m_activeCondition->second; } -// 1-based, and unclamped - see the member note in the header. `team == 0` reads the dword that +// ELF 0x3EA770. 1-based and unclamped. `team == 0` reads the dword that // holds `m_enableDebug`. Strategy* StrategyManager::getForcedStrategy(int team) { return m_forcedStrategy[team - 1]; } -// [FRONTIER] Remaining strategy-management operations require strategy and condition behavior. -// reset is also reached by destruction. -// [RETIRE-WHEN: aidll-02-skeleton] Replace each stop when its corresponding behavior is recovered. -void StrategyManager::reset() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::reset"); -} - +// ELF 0x3EA7D0 (1192 B; recovered on the client track, docs/macos-c-singleplayer.md). Clears the +// forced strategies and the debug flag, then empties the three owning maps one node at a time: +// value deleted first (Strategy and StrategyPrerequisite through their nonvirtual destructors, +// conditions through the virtual deleting destructor, vtable +4), then the node erased. The +// active name/pointer pairs are reset from a temporary {name, 0}; the shipped strategy text is +// "No Strategiws" (sic, the constructor says "No Strategies"). The modifier and area lists are +// left alone. Returns 1 (`mov eax, 1` at 0x3EAB7C). +bool StrategyManager::reset() +{ + m_forcedStrategy[0] = 0; // +0x48 + m_forcedStrategy[1] = 0; // +0x4C + m_enableDebug = false; // +0x44 + + std::map::iterator strategy = m_strategies.begin(); + while (strategy != m_strategies.end()) + { + delete strategy->second; + m_strategies.erase(strategy++); + } + m_activeStrategyName = std::string("No Strategiws"); // +0x04 + m_activeStrategy = 0; // +0x08 + + std::map::iterator prerequisite = m_prerequisites.begin(); + while (prerequisite != m_prerequisites.end()) + { + delete prerequisite->second; + m_prerequisites.erase(prerequisite++); + } + m_activePrerequisiteName = std::string("No Prerequisites"); // +0x1C + m_activePrerequisite = 0; // +0x20 + + std::map::iterator condition = m_conditions.begin(); + while (condition != m_conditions.end()) + { + delete condition->second; // virtual, slot +4 + m_conditions.erase(condition++); + } + m_activeCondition = m_conditions.end(); // +0x30 + return true; +} + +// ELF 0x3EA7C0: `movzbl 0x44(this)`, the same body as getEnableDebug. bool StrategyManager::isDebugEnabled() { - // twelve bytes, the same size as `getEnableDebug`, so it is almost certainly the identical - // body under a second name - but it was not read, and a size coincidence is not a reading. - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::isDebugEnabled"); + return m_enableDebug; } +// ELF 0x3E9420: a copy of the +0x1C string. std::string StrategyManager::getActivePrerequisiteName() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getActivePrerequisiteName"); + return m_activePrerequisiteName; } +// ELF 0x3EA3D0: the active condition's key, or "" (the empty tail of a string literal at +// ELF GOT-0xFD12) while the iterator is end(). std::string StrategyManager::getActiveConditionName() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getActiveConditionName"); -} - -Strategy* StrategyManager::getStrategy(std::string) -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getStrategy"); + if (m_activeCondition == m_conditions.end()) + return ""; + return m_activeCondition->first; } -StrategyCondition* StrategyManager::getCondition(std::string) +// ELF 0x3E8930: map find, null when absent. +Strategy* StrategyManager::getStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getCondition"); + const std::map::iterator it = m_strategies.find(name); + return it == m_strategies.end() ? 0 : it->second; } -StrategyPrerequisite* StrategyManager::getPrerequisite(std::string) +// ELF 0x3EA4C0: map find, null when absent. +StrategyCondition* StrategyManager::getCondition(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::getPrerequisite"); + const std::map::iterator it = m_conditions.find(name); + return it == m_conditions.end() ? 0 : it->second; } -void StrategyManager::setActiveStrategy(std::string) +// ELF 0x3E9610: map find, null when absent. +StrategyPrerequisite* StrategyManager::getPrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setActiveStrategy"); + const std::map::iterator it = m_prerequisites.find(name); + return it == m_prerequisites.end() ? 0 : it->second; } -void StrategyManager::setActivePrerequisite(std::string) +// ELF 0x3E8780. Both images explicitly return the selected pointer. +Strategy* StrategyManager::setActiveStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setActivePrerequisite"); + const std::map::iterator it = m_strategies.find(name); + const std::pair active = it == m_strategies.end() + ? std::pair("NULL", 0) + : std::pair(it->first, it->second); + m_activeStrategyName = active.first; + m_activeStrategy = active.second; + return m_activeStrategy; } -void StrategyManager::setActiveCondition(std::string) +// ELF 0x3E9460. +StrategyPrerequisite* StrategyManager::setActivePrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setActiveCondition"); + const std::map::iterator it = m_prerequisites.find(name); + const std::pair active = it == m_prerequisites.end() + ? std::pair("", 0) + : std::pair(it->first, it->second); + m_activePrerequisiteName = active.first; + m_activePrerequisite = active.second; + return m_activePrerequisite; } -void StrategyManager::setPrerequisite(std::string) +// ELF 0x3EA440. +StrategyCondition* StrategyManager::setActiveCondition(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::setPrerequisite"); + m_activeCondition = m_conditions.find(name); + // shipped defect: a missing condition leaves end(), which is still dereferenced. + return m_activeCondition->second; } -void StrategyManager::forceStrategy(std::string, int) +// ELF 0x3E8A50: the named prerequisite (null when unknown) goes to the active strategy; with +// none an Error debug (line 182) is raised. +void StrategyManager::setPrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::forceStrategy"); -} - -void StrategyManager::createStrategy(std::string) + if (!m_activeStrategy) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/StrategyManager.cpp", 182, "") + << "Cannot set prerequisite " << name << " - there is no active strategy."; + return; + } + m_activeStrategy->setPrerequisite(getPrerequisite(name)); +} + +// ELF 0x3EA650. +std::string StrategyManager::forceStrategy(std::string name, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::createStrategy"); + std::string result; + if (side != 1 && side != 2) + { + result += "Side must be 1 or 2, current side: "; + // shipped defect: append the side as one character, rather than a decimal number. + result += static_cast(side); + return result; + } + const std::map::iterator it = m_strategies.find(name); + if (it == m_strategies.end()) + { + m_forcedStrategy[side - 1] = 0; + result += "No active strategy chosen : "; + } + else + { + m_forcedStrategy[side - 1] = it->second; + result += "Strategy is activated : "; + } + result += name; + return result; } -void StrategyManager::createPrerequisite(std::string) +// ELF 0x3E8390. An existing name clears the active strategy (name "NULL") and answers false; +// otherwise the new strategy is registered and becomes active. +bool StrategyManager::createStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::createPrerequisite"); + if (m_strategies.find(name) != m_strategies.end()) + { + m_activeStrategyName.assign("NULL"); + m_activeStrategy = 0; + return false; + } + Strategy* const strategy = checkPointer(new Strategy(name)); + m_strategies[name] = strategy; + m_activeStrategyName = name; + m_activeStrategy = strategy; + return true; } -void StrategyManager::addCondition(std::string) +// ELF 0x3E90C0: the createStrategy shape for prerequisites; an existing name answers false and +// leaves the active prerequisite as it is. +bool StrategyManager::createPrerequisite(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addCondition"); + if (m_prerequisites.find(name) != m_prerequisites.end()) + return false; + StrategyPrerequisite* const prerequisite = checkPointer(new StrategyPrerequisite(name)); + m_prerequisites[name] = prerequisite; + m_activePrerequisiteName = name; + m_activePrerequisite = prerequisite; + return true; } -void StrategyManager::addCondition(std::string, float) +// ELF 0x3E97C0: weight 1.0f (ELF 0x49CB2C). Neither overload tests the active prerequisite. +void StrategyManager::addCondition(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addCondition"); + m_activePrerequisite->addCondition(getCondition(name), 1.0f); } -void StrategyManager::addSpecificObjectModifier(std::string, float) +// ELF 0x3E9730. +void StrategyManager::addCondition(std::string name, float weight) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addSpecificObjectModifier"); + m_activePrerequisite->addCondition(getCondition(name), weight); } -void StrategyManager::addRequiredPrecedingStrategy(std::string) +// ELF 0x3E8F20. The active strategy is recorded unchecked and resolved against an area later. +bool StrategyManager::addSpecificObjectModifier(std::string name, float modifier) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addRequiredPrecedingStrategy"); + ObjectStrategyModifierTuple tuple; + tuple.m_objectName = name; + tuple.m_strategy = m_activeStrategy; + tuple.m_modifier = modifier; + m_objectModifiers.insert(m_objectModifiers.end(), tuple); + return true; } -void StrategyManager::addProhibitedPrecedingStrategy(std::string) +// ELF 0x3E8BE0. +bool StrategyManager::addRequiredPrecedingStrategy(std::string name) { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::addProhibitedPrecedingStrategy"); -} - + if (!m_activeStrategy) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/StrategyManager.cpp", 193, "") + << "Cannot add required preceding strategy " << name << " - there is no active strategy."; + return false; + } + return m_activeStrategy->addRequiredPrecedingStrategy(getStrategy(name)); +} + +// ELF 0x3E8D80. +bool StrategyManager::addProhibitedPrecedingStrategy(std::string name) +{ + if (!m_activeStrategy) + { + Debug(DebugTypeError, "AI/AIDLL/AI/Main/StrategyManager.cpp", 204, "") + << "Cannot add prohibited preceding strategy " << name << " - there is no active strategy."; + return false; + } + return m_activeStrategy->addProhibitedPrecedingStrategy(getStrategy(name)); +} + +// ELF 0x3E8FD0. Retains the tuples and leaves the last area selected. void StrategyManager::completeStrategies() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::completeStrategies"); + AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); + for (std::list::iterator it = m_objectModifiers.begin(); + it != m_objectModifiers.end(); ++it) + { + manager->setActive(it->m_objectName); + AIStrategicArea* const area = manager->getActiveArea(); + if (area) + it->m_strategy->setSpecificStrategicObjectModifier(area->m_index, it->m_modifier); + } } +// ELF 0x3EA5E0. The singleton lookup is retained even for an empty list. void StrategyManager::completeConditions() { - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::completeConditions"); -} - -void StrategyManager::listStrategies() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::listStrategies"); -} - -void StrategyManager::listPrerequisites() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::listPrerequisites"); -} - -void StrategyManager::listConditions() -{ - BF2_AI_FRONTIER("dice::hfe::ai::StrategyManager::listConditions"); + AIStrategicObjectManager::getInstance(); + for (std::list::iterator it = m_areas.begin(); it != m_areas.end(); ++it) + (*it)->updateArea(); +} + +// ELF 0x3E89A0. +std::string StrategyManager::listStrategies() +{ + std::string result; + for (std::map::iterator it = m_strategies.begin(); + it != m_strategies.end(); ++it) + { + result += it->first; + result += "\n"; + } + return result; +} + +// ELF 0x3E9680. +std::string StrategyManager::listPrerequisites() +{ + std::string result; + for (std::map::iterator it = m_prerequisites.begin(); + it != m_prerequisites.end(); ++it) + { + result += it->first; + result += "\n"; + } + return result; +} + +// ELF 0x3EA530. +std::string StrategyManager::listConditions() +{ + std::string result; + for (std::map::iterator it = m_conditions.begin(); + it != m_conditions.end(); ++it) + { + result += it->first; + result += "\n"; + } + return result; +} + +// ELF 0x3E9850. The target value starts at 0.0f (ELF 0x49CB34); a new condition becomes the +// active one (the insert's iterator). +bool StrategyManager::createConstantCondition(std::string name, + StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional conditional, + float constant) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + StrategyCondition* const condition = checkPointer( + new SCConstant(name, compareType, compare, side, conditional, constant, 0.0f)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + return true; +} + +// ELF 0x3E9B20 +bool StrategyManager::createHomogenousCondition(std::string name, + StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::Conditional conditional) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + StrategyCondition* const condition = checkPointer( + new SCHomogeneous(name, compareType, compare, conditional, 0.0f)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + return true; +} + +// ELF 0x3E9DE0 +bool StrategyManager::createHeterogeneousCondition(std::string name, + StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional first, + StrategyCondition::Conditional second) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + StrategyCondition* const condition = checkPointer( + new SCHeterogeneous(name, compareType, compare, side, first, second, 0.0f)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + return true; +} + +// ELF 0x3EA0B0 +bool StrategyManager::createAreaCondition(std::string name, std::string areaName, + StatusMap::Status status) +{ + if (m_conditions.find(name) != m_conditions.end()) + { + m_activeCondition = m_conditions.end(); + return false; + } + SCArea* const condition = checkPointer(new SCArea(name, areaName, -1, status)); + m_activeCondition = + m_conditions.insert(std::pair(name, condition)).first; + m_areas.insert(m_areas.end(), condition); + return true; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h index 24d835063..37e37cde1 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/StrategyManager.h @@ -1,6 +1,4 @@ // Owns strategies and their conditions. -// [FRONTIER] Operations with unresolved nested parameter types remain undeclared. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. #ifndef AI_AIDLL_AI_MAIN_STRATEGYMANAGER_H #define AI_AIDLL_AI_MAIN_STRATEGYMANAGER_H @@ -10,6 +8,8 @@ #include #include "AIDllTypes.h" +#include "../AIStrategic/StrategyCondition.h" // the condition creators' enum parameters +#include "../AIStrategic/StatusMap.h" namespace dice { namespace hfe { @@ -27,19 +27,27 @@ class StrategyManager class ObjectStrategyModifierTuple { public: - char m_opaque[12]; // [UNRESOLVED] fields; size attested + // ELF 0x3E8F20 constructs these in order; names are [INFERRED]. + /* +0 */ std::string m_objectName; + /* +4 */ Strategy* m_strategy; + /* +8 */ float m_modifier; }; - StrategyManager(); // 0x?? / - ~StrategyManager(); // 0x??, - not virtual + StrategyManager(); + ~StrategyManager(); // nonvirtual - virtual void reset(); // the only virtual, vtable slot 0 + // The only virtual, vtable slot 0. ELF 0x3EA7D0 materializes `mov eax, 1` before its return, + // so it is not void; its direct callers (the D1/D2 destructors, ELF 0x3E7F95 / 0x3E8185) drop + // the value. The mangled name carries no return type: bool is [INFERRED] from the sibling + // sole-virtual resets (AIConsole, AIStrategicObjectManager, AILandingZoneManager, + // BotBehaviourManager), not from the PE. + virtual bool reset(); static StrategyManager* getInstance(); static void setInstance(StrategyManager *); bool getEnableDebug(); - void setEnableDebug(bool); + bool setEnableDebug(bool); bool isDebugEnabled(); Strategy* getActiveStrategy(); @@ -53,23 +61,41 @@ class StrategyManager Strategy* getStrategy(std::string); StrategyCondition* getCondition(std::string); StrategyPrerequisite* getPrerequisite(std::string); - void setActiveStrategy(std::string); - void setActivePrerequisite(std::string); - void setActiveCondition(std::string); + Strategy* setActiveStrategy(std::string); + StrategyPrerequisite* setActivePrerequisite(std::string); + // The shipped setter dereferences the resulting iterator even when the name is absent. + StrategyCondition* setActiveCondition(std::string); void setPrerequisite(std::string); - void forceStrategy(std::string, int); - void createStrategy(std::string); - void createPrerequisite(std::string); + std::string forceStrategy(std::string, int); // ConsoleClass407 assigns the string + bool createStrategy(std::string); // ELF 0x3E8390: false when the name exists + bool createPrerequisite(std::string); // ELF 0x3E90C0: likewise void addCondition(std::string); void addCondition(std::string, float); - void addSpecificObjectModifier(std::string, float); - void addRequiredPrecedingStrategy(std::string); - void addProhibitedPrecedingStrategy(std::string); + bool addSpecificObjectModifier(std::string, float); // ConsoleClass381 stores the bool + bool addRequiredPrecedingStrategy(std::string); // ConsoleClass376 stores the bool + bool addProhibitedPrecedingStrategy(std::string); // ConsoleClass377 stores the bool void completeStrategies(); void completeConditions(); - void listStrategies(); - void listPrerequisites(); - void listConditions(); + // ConsoleClass368/388/394 assign the strings. + std::string listStrategies(); + std::string listPrerequisites(); + std::string listConditions(); + + // ELF 0x3E9850: false (and the active condition cleared) when the name exists. + bool createConstantCondition(std::string name, StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional conditional, float constant); + // Each creator clears the active condition and returns false for a duplicate name. + bool createHomogenousCondition(std::string name, StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::Conditional conditional); + bool createHeterogeneousCondition(std::string name, StrategyCondition::CompareType compareType, + StrategyCondition::Compare compare, + StrategyCondition::ConditionSide side, + StrategyCondition::Conditional first, + StrategyCondition::Conditional second); + bool createAreaCondition(std::string name, std::string areaName, StatusMap::Status status); // the layout, from the 545-byte constructor cross-checked against the destructor // the three registries each come as A (name, active-pointer, map) triple, in the same order. diff --git a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp index 53c8a165a..5983eecc9 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp @@ -1,8 +1,9 @@ -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining UserOrderManager operations. +// static init: ELF 0x3521D0 (__tcf_0 0x352230, _GLOBAL__I 0x352260): 's Init object only. +#include #include "UserOrderManager.h" -#include "AIDllFrontier.h" +#include "../AIUtils/checkPointer.h" #include "../AIStrategicEntity/GuardPosition.h" #include "../AIStrategicEntity/PatrolPath.h" @@ -13,7 +14,7 @@ namespace ai { // ds:, plain .bss. UserOrderManager* UserOrderManager::m_instance = 0; -// Initializes patrol-path and guard-position maps and registers the order manager. +// ELF 0x351510 / 0x351690. Initializes maps and registers the first order manager. UserOrderManager::UserOrderManager() : m_activePatrolPath(0) , m_patrolCursor(m_patrolPaths.end()) @@ -26,7 +27,7 @@ UserOrderManager::UserOrderManager() m_instance = this; } -// Deletes owned patrol paths before guard positions, advancing iterators after deletion +// ELF 0x351750 / 0x351900. Deletes patrol paths before guard positions, advancing after deletion // and re-reading end(). Clears a matching singleton after pointee cleanup; map members // then release their nodes in reverse declaration order. UserOrderManager::~UserOrderManager() @@ -46,54 +47,85 @@ UserOrderManager::~UserOrderManager() // the four accessors, 10- each // Each hands out a reference or a raw pointer straight into a member, with no copy and no guard. +// ELF 0x351D30. PatrolPath* UserOrderManager::getActivePatrolPath() const { return m_activePatrolPath; } +// ELF 0x351FE0. GuardPosition* UserOrderManager::getActiveGuardPosition() const { // Indeterminate until something assigns it - see the constructor. return m_activeGuardPosition; } +// ELF 0x3520F0. const std::map& UserOrderManager::getPatrolPaths() const { return m_patrolPaths; } +// ELF 0x351FD0. const std::map& UserOrderManager::getGuardPositions() const { return m_guardPositions; } -// [FRONTIER] Advances one patrol path or guard position per tick, with an idle phase between sweeps. -// The current body stops because PatrolPath::update and GuardPosition::update remain unimplemented. -// [UNRESOLVED] Purpose of the idle phase. -// [RETIRE-WHEN: aidll-02-skeleton] Implement and validate both dependent updates before enabling the cursor. +// ELF 0x352100. Each phase resets its exhausted cursor before advancing to the next phase. void UserOrderManager::update() { - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::update"); + switch (m_updatePhase) + { + case 0: + if (m_patrolCursor == m_patrolPaths.end()) + { + m_patrolCursor = m_patrolPaths.begin(); + m_updatePhase = 1; + } + else + { + m_patrolCursor->second->update(); + ++m_patrolCursor; + } + break; + case 1: + if (m_guardCursor == m_guardPositions.end()) + { + m_updatePhase = 2; + m_guardCursor = m_guardPositions.begin(); + } + else + { + m_guardCursor->second->update(); + ++m_guardCursor; + } + break; + case 2: + m_updatePhase = 0; + break; + } } -// [FRONTIER] the two creation bodies. `createPatrolPath` and `createGuardPosition` -// build the objects the two maps hold; their construction and behaviour remain unwritten. -// [RETIRE-WHEN: aidll-02-skeleton] -void UserOrderManager::createPatrolPath(const std::string&, CombatStrengthType, int) +// ELF 0x351AB0. A duplicate name still replaces the active pointer and leaks the new path. +void UserOrderManager::createPatrolPath(const std::string& name, CombatStrengthType strength, int side) { - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::createPatrolPath"); + m_activePatrolPath = checkPointer(new PatrolPath(strength, side)); + m_patrolPaths.insert(std::pair(name, m_activePatrolPath)); } -void UserOrderManager::createGuardPosition(const std::string&, const Vec2&, CombatStrengthType, - int, int) +// ELF 0x351D40. Duplicate names likewise leave an unregistered active position. +void UserOrderManager::createGuardPosition(const std::string& name, const Vec2& position, + CombatStrengthType strength, int side, int kit) { - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::createGuardPosition"); + m_activeGuardPosition = checkPointer(new GuardPosition(position, strength, side, kit)); + m_guardPositions.insert(std::pair(name, m_activeGuardPosition)); } -// Guard positions take priority over patrol paths; each map is traversed in key order. +// ELF 0x351FF0. Guard positions take priority over patrol paths; maps are traversed in key order. // Preserve short-circuit predicate order and reload end after each rejected entry. // Only exhausted maps return false. Retail's selected arm calls recruit(bot) and returns true -// independent of that call's result; its callback/plan dependencies remain unrecovered here. +// independent of that call's result. bool UserOrderManager::recruitBot(Bot* bot, int side) { for (std::map::iterator i = m_guardPositions.begin(); @@ -102,9 +134,8 @@ bool UserOrderManager::recruitBot(Bot* bot, int side) GuardPosition* const position = i->second; if (position->active() && position->getSide() == side && position->needBot()) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // ELF GuardPosition::recruit ; bot is passed unchanged. - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::recruitBot (GuardPosition::recruit)"); + position->recruit(bot); + return true; } } @@ -114,9 +145,8 @@ bool UserOrderManager::recruitBot(Bot* bot, int side) PatrolPath* const path = i->second; if (path->active() && path->getSide() == side && path->neededResources() > 0) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] - // ELF PatrolPath::recruit ; bot is passed unchanged. - BF2_AI_FRONTIER("dice::hfe::ai::UserOrderManager::recruitBot (PatrolPath::recruit)"); + path->recruit(bot); + return true; } } return false; diff --git a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h b/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h index 81ce26e88..33d9c3694 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h @@ -1,5 +1,4 @@ // Owns patrol paths and guard positions and assigns bots to user orders. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_MAIN_USERORDERMANAGER_H @@ -39,11 +38,10 @@ class UserOrderManager // the round-robin tick void update(); - // [FRONTIER] + // Creation selects the new object even if a duplicate name prevents its registration. void createPatrolPath(const std::string&, CombatStrengthType, int); void createGuardPosition(const std::string&, const Vec2&, CombatStrengthType, int, int); - // Returns false when the bot should fall back to its side's SAI. Selection is implemented; - // eligible guard/path recruitment still stops at the missing operation. + // Returns false when no eligible guard or patrol accepts this side, allowing fallback to SAI. bool recruitBot(Bot* bot, int side); // First-wins, set by the constructor; `BF2AI::clear` deletes through it. diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h index 5b63f1a65..a47ed7343 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h @@ -43,7 +43,17 @@ class AIObjectPredicate virtual bool predicate(IAIObject* object) = 0; // +0x00, both images }; -class DestroyableObject; // BFObjectEnvironment::getAllDestroyableObjects, by value in a vector +// Object-local navigation bounds and transformation, returned by getAllDestroyableObjects. +// ELF bf2 0x8401390 writes the byte, both vectors and the complete matrix; libaidll's +// drawDynamicAIObjects consumes a 92-byte element. Member names are [INFERRED]. +class DestroyableObject +{ +public: + /* +0x00 */ bool initiallyWalkable; + /* +0x04 */ Vec3 min; + /* +0x10 */ Vec3 max; + /* +0x1C */ Mat4 transform; +}; class TargetData; // BFObjectEnvironment::getTargetObjects, likewise class IWeapon; // BFObjectEnvironment::hasIndirectLineOfFire class IKitTemplate; // KitTemplateManager's two containers diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp index 65f86d55e..3fe2fa5b2 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.cpp @@ -1,12 +1,7 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-07-knowledge] Complete and validate the remaining AIObjectMobile operations. - #include "AIObjectMobile.h" #include -#include "AIFrontier.h" #include "AITemplateMobile.h" #include "../SingletonServer.h" // BFSingletonServer::m_iInformationFactory @@ -16,6 +11,8 @@ #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/Ids.h" +#include "../../../Core/Debug.h" +#include "../../../Scene/Object/WorldObjTemplPortal/PortalEvent.h" #include "../../../Game/Objects/IObject.h" #include "../../../Game/Objects/ISoldier.h" #include "../../../Game/Objects/ObjectLayoutAccess.h" // IObject +0x44, the physics node @@ -229,14 +226,16 @@ float AIObjectMobile::getSprintStamina() const return 0.0f; } -// read: type 0 stores the event's portal id in -// the owner's m_lastPassedPortal, type 1 stores -1, and anything else is retail's -// Debug(Error, "AI/AIInterface/BFKnowledge/AIObjectMobile.cpp", 57) "Unwanted event sent to -// callback". It needs world::PortalEvent::getType / getPortalId, which this tree does not declare. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -void AIObjectMobile::PortalEventCallback::handleEvent(world::PortalEvent* /*event*/) +// ELF 0x8417450. Preserve the repeated type query before the leave-sector branch. +void AIObjectMobile::PortalEventCallback::handleEvent(world::PortalEvent* event) { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectMobile::PortalEventCallback::handleEvent (world::PortalEvent)"); + if (event->getType() == world::PORTAL_EVENT_ENTER_SECTOR) + m_owner->m_lastPassedPortal = static_cast(event->getPortalId()); + else if (event->getType() == world::PORTAL_EVENT_LEAVE_SECTOR) + m_owner->m_lastPassedPortal = -1; + else + Debug(DebugTypeError, "AI/AIInterface/BFKnowledge/AIObjectMobile.cpp", 57) + << "Unwanted event sent to callback"; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h index 524e15817..f571cf47a 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectMobile.h @@ -25,7 +25,7 @@ class AIObjectMobile : public IAIObjectMobile { public: explicit PortalEventCallback(AIObjectMobile* owner) : m_owner(owner) {} - virtual void handleEvent(world::PortalEvent* event); // [FRONTIER] + virtual void handleEvent(world::PortalEvent* event); private: /* +0x04 */ AIObjectMobile* m_owner; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp index 3e750de93..3faf7c3b6 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.cpp @@ -1,12 +1,8 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-07-knowledge] Complete and validate the remaining AIObjectPhysical operations. #include "AIObjectPhysical.h" -#include "AIFrontier.h" +#include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "AITemplatePhysical.h" #include "BFGame.h" // IAIGame::getIsPrecaching (+0x68) @@ -18,15 +14,18 @@ #include "../../../Core/Ids.h" #include "../../../Game/Objects/DestroyableObjectTemplate.h" // usedByAi / initiallyWalkable / corners #include "../../../Game/Objects/GameLogicComp/IArmorGLComp.h" +#include "../../../Game/Objects/GameLogicComp/ArmorGLCompTemplate.h" // getTimeToStayAsWreck #include "../../../Game/Objects/IObject.h" #include "../../../Game/Objects/IObjectTemplate.h" #include "../../../Game/Objects/IPlayer.h" #include "../../../Game/Objects/ObjectLayoutAccess.h" #include "../../../Math/LocalBoundingBox.h" +#include "../../../Math/BoundingBox.h" #include "../../../Physics/ICollisionMesh.h" #include "../../../Physics/IPhysicsNode.h" #include "../../../Physics/IResponsePhysics.h" #include "../../../Physics/PhysicsUtil.h" // hfe::resetPhysics +#include "../../../Physics/SoldierResponse.h" // m_byteFA (+0xFA), a friend #include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" namespace dice { @@ -56,12 +55,14 @@ world::IResponsePhysics* responsePhysics(world::IObject* object) } // anonymous namespace // . +0x0C is left unwritten. +// ELF 0x8419940 / 0x8419980. AIObjectPhysical::AIObjectPhysical(IAIObject* object, AITemplatePhysical* aiTemplate) : IAIObjectPhysical(object), m_template(aiTemplate), m_physicsNode(0), m_mapPosId(-1) { } // A pathfinding-relevant object gives its map entry back. +// ELF 0x8419AD0 / 0x8419B30 / 0x8419B90. AIObjectPhysical::~AIObjectPhysical() { if (m_template->m_affectsPathfinding) @@ -69,12 +70,14 @@ AIObjectPhysical::~AIObjectPhysical() m_mapPosId, m_object); // +0xC4 } +// ELF 0x8419D00. int AIObjectPhysical::getId() const { return AIOFPhysical; } // - the factory's three-argument request under this plug-in's own id. +// ELF 0x8419BF0. void AIObjectPhysical::createInformationPlugIn(unsigned int handle, bool real) { informationFactory()->requestInformationPlugin(handle, getId(), real); // +0x20 @@ -87,6 +90,7 @@ void AIObjectPhysical::createInformationPlugIn(unsigned int handle, bool real) // announces itself as a bridge. // The template is cast to DestroyableObjectTemplate unchecked - only such templates can set // m_affectsPathfinding (AITemplatePhysical::initFromObject). +// ELF 0x84199C0. void AIObjectPhysical::init() { m_maxHealth = m_template->m_maxHealth; @@ -109,11 +113,13 @@ void AIObjectPhysical::init() } // empty. +// ELF 0x841A740. void AIObjectPhysical::update() { } // Returns 1,000,000 when there is no armour component. +// ELF 0x841A170. float AIObjectPhysical::getHealth() { world::IArmorGLComp* const armor = @@ -124,32 +130,38 @@ float AIObjectPhysical::getHealth() } // / - template reads. +// ELF 0x8419C40. float AIObjectPhysical::getMaxHealth() const { return m_template->m_maxHealth; } +// ELF 0x8419C50. float AIObjectPhysical::getMass() const { return m_template->m_mass; } +// ELF 0x8419CC0. float AIObjectPhysical::getVolume() const { return m_template->m_volume; } +// ELF 0x8419CE0. float AIObjectPhysical::getBestArmour() const { return m_template->m_bestArmour; } +// ELF 0x8419CF0. int AIObjectPhysical::getStrType() const { return m_template->m_strType; } // a constant, whatever the direction. +// ELF 0x8419CD0. float AIObjectPhysical::getArmour(const Vec3& /*direction*/) const { return 1.0f; @@ -157,6 +169,7 @@ float AIObjectPhysical::getArmour(const Vec3& /*direction*/) const // an object without collision LOD 1 calls abort - retail's own, not a // frontier. Otherwise the collision mesh's LOD-1 box. +// ELF 0x841A1A0. const LocalBoundingBox* AIObjectPhysical::getLocalBoundingBox() const { if (!m_object->getObject()->hasCollisionLod(1)) // +0xCC @@ -164,21 +177,33 @@ const LocalBoundingBox* AIObjectPhysical::getLocalBoundingBox() const return collisionMesh(m_object->getObject())->getBoundingBox(1); // +0x58 } -// `new BoundingBox` (0x60 B, eight zeroed corners), initWithLocalBoundingBox( -// getLocalBoundingBox), transform(object->getAbsoluteTransformation), checkPointer'd. The -// BoundingBox class is not in this tree. +// ELF 0x841A280. Allocation precedes the virtual queries; initialization follows them. BoundingBox* AIObjectPhysical::getCurrentBoundingBox() { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getCurrentBoundingBox (BoundingBox)"); + BoundingBox* const box = new BoundingBox; + const LocalBoundingBox* const local = getLocalBoundingBox(); + const Mat4& transformation = m_object->getObject()->getAbsoluteTransformation(); + for (int i = 0; i < 8; ++i) + box->m_corners[i] = Vec3{ 0.0f, 0.0f, 0.0f }; + box->initWithLocalBoundingBox(*local); + box->transform(transformation); + return checkPointer(box); } -// the same with the caller's transformation. -BoundingBox* AIObjectPhysical::getBoundingBox(const Mat4& /*transformation*/) +// ELF 0x841A400. +BoundingBox* AIObjectPhysical::getBoundingBox(const Mat4& transformation) { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getBoundingBox (BoundingBox)"); + BoundingBox* const box = new BoundingBox; + const LocalBoundingBox* const local = getLocalBoundingBox(); + for (int i = 0; i < 8; ++i) + box->m_corners[i] = Vec3{ 0.0f, 0.0f, 0.0f }; + box->initWithLocalBoundingBox(*local); + box->transform(transformation); + return checkPointer(box); } // The collision mesh's LOD-1 radius, 0 without that LOD. +// ELF 0x8419C60. float AIObjectPhysical::getRadius() const { if (!m_object->getObject()->hasCollisionLod(1)) // +0xCC @@ -188,6 +213,7 @@ float AIObjectPhysical::getRadius() const // The box centre, recomputed first when stale - through a const pointer, as // retail does (the derived data is cached state). +// ELF 0x841A200. Vec3 AIObjectPhysical::getSphereLocalOffset() const { LocalBoundingBox* const box = const_cast(getLocalBoundingBox()); // +0x30 @@ -197,6 +223,7 @@ Vec3 AIObjectPhysical::getSphereLocalOffset() const } // the radius about the centre. +// ELF 0x841A250. float AIObjectPhysical::getSmallestRadius() const { LocalBoundingBox* const box = const_cast(getLocalBoundingBox()); @@ -205,33 +232,89 @@ float AIObjectPhysical::getSmallestRadius() const return box->m_radiusFromCentre; } -// the LOD-1 box's longer horizontal side split into equal circles along its middle -// (pushed into `out` as Vec2), the step returned. Read; not yet transcribed. -float AIObjectPhysical::getSubSpheres2d(std::vector& /*out*/) const +// ELF 0x8419E50. Appends circles along the longer horizontal side; returns their spacing. +float AIObjectPhysical::getSubSpheres2d(std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getSubSpheres2d"); + const LocalBoundingBox* const minimum = getLocalBoundingBox(); + const LocalBoundingBox* const maximum = getLocalBoundingBox(); + const float minX = minimum->m_min.x; + const float minZ = minimum->m_min.z; + const float width = maximum->m_max.x - minX; + const float depth = maximum->m_max.z - minZ; + if (depth > width) + { + if (width != 0.0f) + { + const float count = depth / width; + if (count > 1.0f) + { + Vec2 position = { minX + width * 0.5f, minZ }; + const float step = depth / (count + 1.0f); + for (int i = 0; static_cast(i) < count; ++i) + { + position.y += step; + out.push_back(position); + } + return step; + } + } + } + else if (width > depth && depth != 0.0f) + { + const float count = width / depth; + if (count > 1.0f) + { + Vec2 position = { minX, minZ + depth * 0.5f }; + const float step = width / (count + 1.0f); + for (int i = 0; static_cast(i) < count; ++i) + { + position.x += step; + out.push_back(position); + } + return step; + } + } + // shipped defect: both coordinates use x, with two independent virtual queries. + const float x = getSphereLocalOffset().x; + const float z = getSphereLocalOffset().x; + out.push_back(Vec2{ x, z }); + return getSmallestRadius(); } +// ELF 0x841A090. bool AIObjectPhysical::isTouchingTerrain(Vec3& out) const { return responsePhysics(m_object->getObject())->getIsIntersectingTerrain(out); // +0x7C } -// false while the physics node sleeps; a soldier answers the negation of a raw -// byte at +0xFA of its response physics (the soldier physics' ground flag - no class for it in this -// tree); anything else asks the node's getIsInAir (+0x1B0). +// bf2 0x841A0C0 (ELF listing). The ISoldier query comes first; then false while the physics node +// sleeps (+0x11C); a soldier answers the negation of its response physics' ground-contact byte +// (SoldierResponsePhysics +0xFA, the object asked for again); anything else asks the node's +// getIsInAir (+0x1B0). bool AIObjectPhysical::isInAir() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::isInAir (soldier response physics +0xFA)"); + void* const soldier = m_object->getObject()->queryInterface(world::IID_ISoldier); // +0x0C + if (m_physicsNode->getIsSleeping()) // +0x11C + return false; + if (soldier) + { + const world::SoldierResponsePhysics* const response = + static_cast( + world::object_detail::LayoutAccess::responsePhysics(m_object->getObject())); + return !response->m_byteFA; + } + return m_physicsNode->getIsInAir(); // +0x1B0 } // strictly above zero (`setnbe` after fucomip - unordered is false). +// ELF 0x841A140. bool AIObjectPhysical::isInWater() const { return m_physicsNode->getUnderWater() > 0.0f; // +0x10C } // The engine object is asked for and discarded; the answer is always 0. +// ELF 0x841A560. int AIObjectPhysical::getMaterial() const { m_object->getObject(); @@ -240,6 +323,7 @@ int AIObjectPhysical::getMaterial() const // The occupying player's man-down clock, when it has a // control object, an occupant, and that occupant is down. The occupant is asked for twice. +// ELF 0x841A580. float AIObjectPhysical::getManDownTimeLeft() const { world::IPlayerControlObject* const pco = static_cast( @@ -252,14 +336,21 @@ float AIObjectPhysical::getManDownTimeLeft() const return player->getManDownTimeLeft(); // +0xF8 } -// the ArmorGLCompTemplate component's +0x110 accessor (not declared in this tree) -// 1.0 without the component. +// bf2 0x841A5F0 (ELF listing). The object's template component of class ArmorGLCompTemplate +// (IObjectTemplate +0x60, getComponentFromClassID) answers its +0x110 slot, which the ELF primary +// vtable (_ZTVN4dice3hfe5world19ArmorGLCompTemplateE) holds as getTimeToStayAsWreck; 1.0 without +// the component. float AIObjectPhysical::getMaxManDownTime() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIObjectPhysical::getMaxManDownTime (ArmorGLCompTemplate +0x110)"); + world::ArmorGLCompTemplate* const armorTemplate = static_cast( + m_object->getObject()->getTemplate()->getComponentFromClassID(world::CID_ArmorGLCompTemplate)); + if (!armorTemplate) + return 1.0f; + return armorTemplate->getTimeToStayAsWreck(); // +0x110 } // status 1 on the armour component. +// ELF 0x841A640. bool AIObjectPhysical::getManDown() const { world::IArmorGLComp* const armor = @@ -269,11 +360,13 @@ bool AIObjectPhysical::getManDown() const return false; } +// ELF 0x841A680. bool AIObjectPhysical::doesAffectPathfinding() const { return m_template->m_affectsPathfinding; } +// ELF 0x841A730. int AIObjectPhysical::getMapPosId() const { return m_mapPosId; @@ -283,6 +376,7 @@ int AIObjectPhysical::getMapPosId() const // physics node and the response physics of the node's object are switched together, and an enable // resets the object's physics (hfe::resetPhysics, player control objects included). Both answer // true for the owning side whether or not anything changed. +// ELF 0x8419D90. bool AIObjectPhysical::enablePhysics(int side) { if (side != m_object->getSide()) // +0x12C @@ -296,6 +390,7 @@ bool AIObjectPhysical::enablePhysics(int side) return true; } +// ELF 0x8419D10. bool AIObjectPhysical::disablePhysics(int side) { if (side != m_object->getSide()) @@ -308,6 +403,7 @@ bool AIObjectPhysical::disablePhysics(int side) return true; } +// ELF 0x8419E30. bool AIObjectPhysical::hasPhysicsEnabled() { return m_physicsNode->getEnabled(); // +0x1C diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h index 4be6d8c5b..9e047183f 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIObjectPhysical.h @@ -34,19 +34,20 @@ class AIObjectPhysical : public IAIObjectPhysical virtual float getArmour(const Vec3& direction) const; // +0x28 virtual float getBestArmour() const; // +0x2C virtual const LocalBoundingBox* getLocalBoundingBox() const; // +0x30 - virtual BoundingBox* getCurrentBoundingBox(); // +0x34, [FRONTIER] - virtual BoundingBox* getBoundingBox(const Mat4& transformation); // +0x38, [FRONTIER] + // Returns a new transformed box; the caller owns it. + virtual BoundingBox* getCurrentBoundingBox(); // +0x34 + virtual BoundingBox* getBoundingBox(const Mat4& transformation); // +0x38 virtual float getRadius() const; // +0x3C virtual Vec3 getSphereLocalOffset() const; // +0x40 virtual float getSmallestRadius() const; // +0x44 - virtual float getSubSpheres2d(std::vector& out) const; // +0x48, [FRONTIER] + virtual float getSubSpheres2d(std::vector& out) const; // +0x48 virtual int getStrType() const; // +0x4C virtual bool isTouchingTerrain(Vec3& out) const; // +0x50 - virtual bool isInAir() const; // +0x54, [FRONTIER] + virtual bool isInAir() const; // +0x54 virtual bool isInWater() const; // +0x58 virtual int getMaterial() const; // +0x5C virtual float getManDownTimeLeft() const; // +0x60 - virtual float getMaxManDownTime() const; // +0x64, [FRONTIER] + virtual float getMaxManDownTime() const; // +0x64 virtual bool getManDown() const; // +0x68 virtual bool doesAffectPathfinding() const; // +0x6C virtual int getMapPosId() const; // +0x70 diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp index 47adedbd5..3b5e8dbc9 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.cpp @@ -1,10 +1,10 @@ // Engine implementation of the AI player interface. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #include "AIPlayer.h" -#include "AIFrontier.h" +#include +#include #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/AIUtils/checkPointer.h" @@ -12,10 +12,14 @@ #include "../../../Game/GameLogic/Player.h" // world::IPlayer - every forward's target #include "../../../Game/Objects/IObject.h" // getTemplate #include "../../../Game/Objects/IObjectTemplate.h" // getClassID +#include "../../../Game/Objects/ICameraObject.h" // getCameraTransformation #include "../../../Math/Mat4.h" // the lazily built identity matrix #include "../../../Scene/Object/PlayerManager.h" // the `playerManager` global #include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" -#include "AIPlayerFactory.h" // the id-to-player mapping pair +#include "AIPlayerFactory.h" +#include "../../../Game/IGameLogic.h" // gameLogic - removePlayerFromGame +#include "../AIInstance.h" // the AI instance test in the destructor +#include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // setBotNameUnused // the id-to-player mapping pair namespace dice { namespace hfe { @@ -25,11 +29,12 @@ namespace ai { Mat4* AIPlayer::identityMatrix = 0; // The interface destructor has no additional cleanup. +// ELF 0x83FCB40 / 0x83FCB50. IAIPlayer::~IAIPlayer() { } -// Wraps the supplied player and initializes view distance from its current value. +// ELF 0x83FBA60 / 0x83FBC30. Wraps the supplied player and initializes view distance from its current value. // The player is borrowed and must outlive this wrapper. AIPlayer::AIPlayer(world::IPlayer* player) : m_player(player) @@ -40,42 +45,61 @@ AIPlayer::AIPlayer(world::IPlayer* player) if (!identityMatrix) { - Mat4* const matrix = checkPointer(new Mat4); + Mat4* const matrix = new Mat4{{ + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f + }}; + identityMatrix = checkPointer(matrix); // Preserves the repeated identity-matrix stores, including diagonal indices 0, 5, 10, and 15. matrix->m[0] = 1.0f; matrix->m[1] = 0.0f; matrix->m[2] = 0.0f; matrix->m[3] = 0.0f; matrix->m[4] = 0.0f; matrix->m[5] = 1.0f; matrix->m[6] = 0.0f; matrix->m[7] = 0.0f; matrix->m[8] = 0.0f; matrix->m[9] = 0.0f; matrix->m[10] = 1.0f; matrix->m[11] = 0.0f; matrix->m[12] = 0.0f; matrix->m[13] = 0.0f; matrix->m[14] = 0.0f; matrix->m[15] = 1.0f; - - identityMatrix = matrix; } } -// - eight bytes longer than the `(IPlayer*)` form and not read. -// The extra length is presumably the null player it starts from; nothing in this tree calls it. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] +// ELF 0x83FBE00 / 0x83FBFD0. An unattached wrapper shares the same lazy identity matrix. AIPlayer::AIPlayer() + : m_player(0) + , m_i8(0) + , m_viewDistance(0.0f) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::AIPlayer()"); + if (!identityMatrix) + { + Mat4* const matrix = new Mat4{{ + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f + }}; + identityMatrix = checkPointer(matrix); + matrix->m[0] = 1.0f; matrix->m[1] = 0.0f; matrix->m[2] = 0.0f; matrix->m[3] = 0.0f; + matrix->m[4] = 0.0f; matrix->m[5] = 1.0f; matrix->m[6] = 0.0f; matrix->m[7] = 0.0f; + matrix->m[8] = 0.0f; matrix->m[9] = 0.0f; matrix->m[10] = 1.0f; matrix->m[11] = 0.0f; + matrix->m[12] = 0.0f; matrix->m[13] = 0.0f; matrix->m[14] = 0.0f; matrix->m[15] = 1.0f; + } } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Destruction remains unimplemented; AIPlayerFactory::destroy reaches this boundary. +// bf2 0x83FC280: while the AI instance (0x8AC37F8) exists and is not shutting down, a bot's +// name goes back to the pool (IAISettingsModifier +0x94 setBotNameUnused). +// ELF 0x83FC1A0 / 0x83FC210 / 0x83FC280. AIPlayer::~AIPlayer() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::~AIPlayer"); + if (g_aiInstance && !aiInstance()->isShuttingDown() && m_player && getIsAIPlayer()) + static_cast(CommonSingletonServer::m_iaiSettingsModifier) + ->setBotNameUnused(m_player->getName()); } // Delegates to the wrapped engine player through the typed interface. // - and it resets the one field that is genuinely this object's, not the // player's. A recycled `AIPlayer` therefore keeps its view distance; only +8 is cleared. +// ELF 0x83FC300. void AIPlayer::reset() { m_i8 = 0; } +// ELF 0x83FC440. world::IPlayer* AIPlayer::getPlayer() const { return m_player; @@ -83,6 +107,7 @@ world::IPlayer* AIPlayer::getPlayer() const // it resolves the ID and then calls its own virtual slot +0x14 - a virtual // self-call, not a direct one, so an override of the pointer form would catch this path too. +// ELF 0x83FC310. void AIPlayer::setPlayer(int playerId) { setPlayer(world::playerManager->getPlayerFromId(playerId)); @@ -90,6 +115,7 @@ void AIPlayer::setPlayer(int playerId) // Replaces the factory id mapping when the player changes. Seeds view distance only // when its current value equals zero; NaN is left unchanged. +// ELF 0x83FC350. void AIPlayer::setPlayer(world::IPlayer* player) { IAIPlayerFactory* const factory = @@ -108,12 +134,14 @@ void AIPlayer::setPlayer(world::IPlayer* player) } // - IPlayer +0x24. +// ELF 0x83FC450. const std::string& AIPlayer::getName() const { return m_player->getName(); } // - IPlayer +0x54. +// ELF 0x83FC4C0. int AIPlayer::getId() const { return m_player->getId(); @@ -121,30 +149,35 @@ int AIPlayer::getId() const // - IPlayer +0x50. A different number from `getId`, and the two slots are // adjacent on both classes; do not collapse them. +// ELF 0x83FC4E0. int AIPlayer::getInputId() const { return m_player->getInputId(); } // - IPlayer +0x6C, narrowed with `movzx`. +// ELF 0x83FC500. bool AIPlayer::getIsAlive() const { return m_player->getIsAlive(); } // - IPlayer +0x68. +// ELF 0x83FC520. void AIPlayer::setIsAlive(bool alive) { m_player->setIsAlive(alive); } // - IPlayer +0x100. +// ELF 0x83FC550. bool AIPlayer::isManDown() const { return m_player->getIsManDown(); } // Checks the current vehicle template to identify ladder and parachute states. +// ELF 0x83FC570. bool AIPlayer::isClimbingLadder() const { world::IObject* const vehicle = m_player->getVehicle(); @@ -155,6 +188,7 @@ bool AIPlayer::isClimbingLadder() const return vehicle->getTemplate()->getClassID() == world::CID_LadderContainerTemplate; } +// ELF 0x83FC5B0. bool AIPlayer::isParachuting() const { world::IObject* const vehicle = m_player->getVehicle(); @@ -166,6 +200,7 @@ bool AIPlayer::isParachuting() const } // - IPlayer +0x154. +// ELF 0x83FC610. void AIPlayer::setSpawnGroup(int group) { m_player->setSpawnGroup(group); @@ -173,6 +208,7 @@ void AIPlayer::setSpawnGroup(int group) // forward the selected kit unchanged to // IPlayer::setKit (ELF +0x16C / PE +0x168), with no player-null guard or validation. +// ELF 0x83FC640. void AIPlayer::setSpawnKit(int kit) { m_player->setKit(kit); @@ -180,6 +216,7 @@ void AIPlayer::setSpawnKit(int kit) // - IPlayer +0x90, `getFov`. this is what corrected the declared return type: // the body materialises nothing in eax and leaves the player's float in st0. +// ELF 0x83FC880. float AIPlayer::getFieldOfView() { return m_player->getFov(); @@ -187,41 +224,82 @@ float AIPlayer::getFieldOfView() // - IPlayer +0x9C, `getAIPlayerInput`. the player has A separate input block // for AI, and this is the slot that hands it over; the name on the player side says so outright. +// ELF 0x83FC5F0. const void* AIPlayer::getPlayerInput() const { return m_player->getAIPlayerInput(); } -// [FRONTIER] Unimplemented player queries and actions stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding AIPlayer operation. - +// ELF 0x83FC670. int AIPlayer::getSpawnGroup() const { // IPlayer virtual +0x158/+0x154, without a null guard or value conversion. return m_player->getSpawnGroup(); } +// ELF 0x83FC690. int AIPlayer::getSpawnKit() const { // IPlayer virtual +0x170/+0x16C, with no null guard or value conversion. return m_player->getKit(); } +// bf2 0x83FC6B0. Without a vehicle -1. Otherwise the first player control object on the +// vehicle's parent chain (queryInterface IID_IPlayerControlObject, then IObject +0x28) answers +// its PCO id (+0x30). Ladder, parachute, zipline and rope containers first hop to the object +// their control object occupies (+0x14) and search from there. A chain without one reads +// through a null pointer, as the ELF does. +namespace { +world::IPlayerControlObject* findControlObject(world::IObject* object) +{ + for (; object; object = object->getParent()) + { + world::IPlayerControlObject* const control = static_cast( + object->queryInterface(world::IID_IPlayerControlObject)); + if (control) + return control; + } + return 0; +} +} // anonymous namespace + +// ELF 0x83FC6B0. unsigned int AIPlayer::getPlayerControlObjectId() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getPlayerControlObjectId"); + // The ELF reads the template before its null test (a null vehicle faults there); testing + // first keeps the C++ defined. [CHOSEN, not recovered] ordering only. + world::IObject* const vehicle = m_player->getVehicle(); + if (!vehicle) + return static_cast(-1); + const unsigned int classId = vehicle->getTemplate()->getClassID(); + if (classId == world::CID_LadderContainerTemplate || classId == world::CID_ParachuteTemplate || + classId == world::CID_ZiplineContainerTemplate || + classId == world::CID_GrapplingHookRopeContainerTemplate) + { + world::IObject* const occupied = findControlObject(vehicle)->getOccupingObject(); + return static_cast(findControlObject(occupied)->getPcoId()); + } + return static_cast(findControlObject(vehicle)->getPcoId()); } +// bf2 0x83FC7C0: the default vehicle's AI component; a player without one aborts (the ELF +// calls abort directly - an inlined assertion). +// ELF 0x83FC7C0. IAIObject* AIPlayer::getSoldier() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getSoldier"); + if (!m_player->getDefaultVehicle()) + std::abort(); + return static_cast(m_player->getDefaultVehicle()->getAIComponent()); } +// bf2 0x83FC7A0: IPlayer +0xA4, then the object's cached AI component (+0x34), unchecked. +// ELF 0x83FC7A0. IAIObject* AIPlayer::getDefaultVehicle() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getDefaultVehicle"); + return static_cast(m_player->getDefaultVehicle()->getAIComponent()); } +// ELF 0x83FC800. IAIObject* AIPlayer::getCurrentVehicle() { // One vehicle lookup; no template/occupant guards. @@ -243,28 +321,51 @@ IAIObject* AIPlayer::getCurrentVehicle() return static_cast(vehicle->getAIComponent()); } +// bf2 0x83FC8B0. Without a camera (IPlayer +0x180) 1.0. Otherwise cot(fov / 2) scaled by a +// function static cot(0.6f) built on first use (0x8AC3310 flag, 0x8AC3318 value, 1.0f / tan). +// [PLATFORM] the ELF keeps the quotients in x87 extended precision. +// ELF 0x83FC8B0. float AIPlayer::getFieldOfViewModifier() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getFieldOfViewModifier"); + if (!m_player->getCamera()) + return 1.0f; + static bool s_initialised = false; + static float s_standardCotangent; + if (!s_initialised) + { + const float standard = 0.6f; + s_initialised = true; + s_standardCotangent = 1.0f / (sinf(standard) / cosf(standard)); + } + const float half = m_player->getFov() * 0.5f; + return (cosf(half) / sinf(half)) * s_standardCotangent; } +// bf2: `flds` of the 1.2f constant at 0x889AA58. +// ELF 0x83FC8A0. float AIPlayer::getStandardFieldOfView() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getStandardFieldOfView" - " - eleven bytes, one float constant at ds:0x889AA58, not yet read"); + return 1.2f; } +// bf2 0x83FC960: a fifth of the stored distance (0.2f at 0x8899EF0) on night maps +// (IPlayer +0x2FC), reached through this wrapper's own getPlayer (+0x0C). +// ELF 0x83FC960. float AIPlayer::getViewDistance() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getViewDistance"); + if (getPlayer()->isPlayerInNightMap()) + return 0.2f * m_viewDistance; + return m_viewDistance; } -void AIPlayer::setViewDistance(float) +// bf2: a plain store to +0x0C. +// ELF 0x83FC9A0. +void AIPlayer::setViewDistance(float distance) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::setViewDistance" - " - fourteen bytes; AISettings::setViewDistance reaches it once per live bot"); + m_viewDistance = distance; } +// ELF 0x83FC9B0. int AIPlayer::getSide() { // unchecked IPlayer::getTeam forward. @@ -273,49 +374,76 @@ int AIPlayer::getSide() // forward the side and false to // IPlayer::setTeam (ELF +0xE4 / PE +0xE0), with no player-null guard. +// ELF 0x83FC9D0. void AIPlayer::setSide(int side) { m_player->setTeam(side, false); } +// bf2 0x83FCA00 (seven bytes, `xor %eax,%eax`): always 0; the weapon is not read. +// ELF 0x83FCA00. int AIPlayer::getNumShotsFired(IWeapon*) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getNumShotsFired" - " - seven bytes, so it returns a constant and ignores the weapon"); + return 0; } +// bf2 0x83FC3D0 (recovered on the client track, docs/macos-c-singleplayer.md). The singleton at +// ds:0x8AC37F8 is AIInstanceServer::m_iAI (g_aiInstance here); +0x20 is isShuttingDown. While the +// AI is not shutting down, a live player (IPlayer +0x6C) is killed through the game logic +// (ds:0x8ACBFA0, IGameLogic +0x6C, killPlayer(player, true, false)). The instance is not null- +// tested, as shipped. +// ELF 0x83FC3D0. void AIPlayer::removePlayerFromGame() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::removePlayerFromGame" - " - read except for the singleton at ds:0x8AC37F8"); + if (aiInstance()->isShuttingDown()) + return; + if (m_player && m_player->getIsAlive()) + gameLogic->killPlayer(m_player, true, false); } -void AIPlayer::setName(const std::string&) +// bf2 0x83FCA10: IPlayer +0x20. +// ELF 0x83FCA10. +void AIPlayer::setName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::setName"); + m_player->setName(name); } +// bf2 0x83FCA40: the first int of the player's score data (IPlayer +0x174), 0 without one. +// [UNRESOLVED] PlayerScoreData's layout; only its leading score word is read here. +// ELF 0x83FCA40. int AIPlayer::getScore() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getScore"); + world::PlayerScoreData* const data = m_player->getScoreData(); + return data ? *reinterpret_cast(data) : 0; } -void AIPlayer::setIsAIPlayer(bool) +// bf2 0x83FCA70: IPlayer +0x60. +// ELF 0x83FCA70. +void AIPlayer::setIsAIPlayer(bool isAI) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::setIsAIPlayer"); + m_player->setIsAIPlayer(isAI); } // forward the player's // Boolean query through IPlayer (+0x64 / +0x60), with no null guard. +// ELF 0x83FCAA0. bool AIPlayer::getIsAIPlayer() { return m_player->getIsAIPlayer(); } +// bf2 0x83FC470: the player's camera (IPlayer +0x180 getCamera) as a world::IObject +// (queryInterface(IID_IObject), +0x0C) gives its absolute transformation (IObject +0x84); without +// a camera the shared identity matrix. The result is the Mat4's address. +// ELF 0x83FC470. const void* AIPlayer::getCameraTransformation() const { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayer::getCameraTransformation" - " - read in outline; the camera object's transform slot is not confirmed"); + world::ICameraObject* const camera = m_player->getCamera(); + if (!camera) + return identityMatrix; + const world::IObject* const object = + static_cast(camera->queryInterface(world::IID_IObject)); + return &object->getAbsoluteTransformation(); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h index 632ef4a6a..879cb8a1f 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayer.h @@ -1,6 +1,5 @@ // AI view of an engine player, implemented by AIPlayer in the executable. // [INFERRED] Return types are derived from implementations; preserve virtual declaration order. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIINTERFACE_BFKNOWLEDGE_AIPLAYER_H // [INFERRED] guard style @@ -66,13 +65,12 @@ class IAIPlayer // Forwards player state and actions to a borrowed world::IPlayer. // The wrapped player must outlive this object. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. class AIPlayer : public IAIPlayer { public: explicit AIPlayer(world::IPlayer* player); - AIPlayer(); // [FRONTIER] - virtual ~AIPlayer(); // [FRONTIER] + AIPlayer(); + virtual ~AIPlayer(); virtual void reset(); virtual world::IPlayer* getPlayer() const; @@ -90,24 +88,24 @@ class AIPlayer : public IAIPlayer virtual void setSpawnKit(int kit); virtual int getSpawnGroup() const; virtual int getSpawnKit() const; // forwards getKit - virtual unsigned int getPlayerControlObjectId(); // [FRONTIER] - virtual IAIObject* getSoldier(); // [FRONTIER] - virtual IAIObject* getDefaultVehicle(); // [FRONTIER] + virtual unsigned int getPlayerControlObjectId(); + virtual IAIObject* getSoldier(); + virtual IAIObject* getDefaultVehicle(); virtual IAIObject* getCurrentVehicle(); virtual float getFieldOfView(); - virtual float getFieldOfViewModifier(); // [FRONTIER] - virtual float getStandardFieldOfView(); // [FRONTIER] - virtual float getViewDistance(); // [FRONTIER] - virtual void setViewDistance(float distance); // [FRONTIER] + virtual float getFieldOfViewModifier(); + virtual float getStandardFieldOfView(); + virtual float getViewDistance(); + virtual void setViewDistance(float distance); virtual int getSide(); - virtual void setSide(int side); // [FRONTIER] - virtual int getNumShotsFired(IWeapon* weapon); // [FRONTIER] - virtual void removePlayerFromGame(); // [FRONTIER] - virtual void setName(const std::string& name); // [FRONTIER] - virtual int getScore(); // [FRONTIER] - virtual void setIsAIPlayer(bool isAI); // [FRONTIER] + virtual void setSide(int side); + virtual int getNumShotsFired(IWeapon* weapon); + virtual void removePlayerFromGame(); // bf2 0x83FC3D0 + virtual void setName(const std::string& name); + virtual int getScore(); + virtual void setIsAIPlayer(bool isAI); virtual bool getIsAIPlayer(); - virtual const void* getCameraTransformation() const; // [FRONTIER] + virtual const void* getCameraTransformation() const; virtual const void* getPlayerInput() const; // ds: - one `Mat4`, allocated by whichever `AIPlayer` is constructed first and never diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp index 96e77d1eb..08e34364a 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.cpp @@ -1,19 +1,17 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining AIPlayerFactory operations. #include "AIPlayerFactory.h" - -#include "AIFrontier.h" +#include #include "AIPlayer.h" // the concrete wrapper this creates +#include "IAIObject.h" // isOccupiedObject +#include "IAIObjectPlugIn.h" // IAIObjectUnit::isOccupied #include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../../Game/GameLogic/Player.h" // world::IPlayer::getId #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" +#include "../../../Scene/Object/PlayerManager.h" // the player lookups #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods namespace dice { @@ -23,7 +21,30 @@ extern ClassManager* classManager; namespace ai { +// bf2 0x842B700. The primary object's unit is tested first (null unit: false); the secondary +// objects' units are not null-checked (`call *0x48(%eax)` straight after getUnit), as in the image. +bool isOccupiedObject(IAIObject* object, IAIObject* exclude) +{ + IAIObject* const primary = object->getPrimaryObject(); // +0xFC + IAIObjectUnit* const unit = primary->getUnit(); // +0x98 + if (!unit) + return false; + if (exclude != primary && unit->isOccupied()) // IAIObjectUnit +0x48 + return true; + int iterator; + for (IAIObject* secondary = primary->getFirstSecondaryObject(iterator); // +0x11C + secondary; + secondary = primary->getSecondaryObject(iterator)) // +0x114 + { + IAIObjectUnit* const secondaryUnit = secondary->getUnit(); + if (exclude != secondary && secondaryUnit->isOccupied()) + return true; + } + return false; +} + // First wins in, exact match out. +// ELF 0x842DDA0 / 0x842DE30. IAIPlayerFactory::IAIPlayerFactory() { if (!CommonSingletonServer::m_iaiPlayerFactory) @@ -34,6 +55,7 @@ IAIPlayerFactory::IAIPlayerFactory() } } +// ELF 0x842DEC0 / 0x842DF40 / 0x842DFC0. IAIPlayerFactory::~IAIPlayerFactory() { if (CommonSingletonServer::m_iaiPlayerFactory == this) @@ -47,34 +69,43 @@ IAIPlayerFactory::~IAIPlayerFactory() // The ELF's _M_fill_insert / erase pair on an empty vector is `resize(256, 0)` - libstdc++ 3.x // expands resize into exactly that branch. 256 is the player-id space, so the vector is an // id-indexed table from the first instruction. +// ELF 0x842B7B0 / 0x842B850. AIPlayerFactory::AIPlayerFactory() { m_players.resize(256, 0); } +// ELF 0x842B8F0 / 0x842B970 / 0x842B9F0. AIPlayerFactory::~AIPlayerFactory() { } -// Creation overloads identify unsupported paths by their argument types in frontier diagnostics. - +// ELF 0x842BA80. Creates an unattached wrapper without inserting it into the id table. IAIPlayer* AIPlayerFactory::create() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::create()"); + return checkPointer(new AIPlayer()); } +// bf2 0x842BBA0: the player manager's player by id, wrapped through this factory's own +// create(IPlayer*) (+0x14); null for an unknown id. +// ELF 0x842BBA0. IAIPlayer* AIPlayerFactory::create(int id) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::create(int)"); + world::IPlayer* const player = world::playerManager->getPlayerFromId(id); + return player ? create(player) : 0; } +// bf2 0x842BBE0: the same by name (+0x1C getPlayerFromName). +// ELF 0x842BBE0. IAIPlayer* AIPlayerFactory::create(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::create(const std::string&)"); + world::IPlayer* const player = world::playerManager->getPlayerFromName(name); + return player ? create(player) : 0; } // Wraps a player and stores it at its player id. The caller must size m_players first; // this function neither grows the vector nor checks the index. +// ELF 0x842BC20. IAIPlayer* AIPlayerFactory::create(world::IPlayer* player) { AIPlayer* const created = checkPointer(new AIPlayer(player)); @@ -85,14 +116,32 @@ IAIPlayer* AIPlayerFactory::create(world::IPlayer* player) return created; } +// bf2 0x842BDC0: the table slot is cleared by id while the wrapper has a player, else by +// searching for the pointer; the wrapper is then deleted (null tolerated by the test before the +// deleting destructor). +// ELF 0x842BDC0. void AIPlayerFactory::destroy(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::destroy"); + if (player->getPlayer()) + { + m_players[player->getId()] = 0; + } + else + { + const std::vector::iterator it = std::find(m_players.begin(), m_players.end(), player); + if (it != m_players.end()) + *it = 0; + } + if (player) + delete player; } +// bf2: the named player's id (IPlayer +0x54), or -1. +// ELF 0x842BE80. int AIPlayerFactory::getPlayerIdFromName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::getPlayerIdFromName"); + world::IPlayer* const player = world::playerManager->getPlayerFromName(name); + return player ? player->getId() : -1; } // IAIPlayerFactory's ELF slot +0x20 @@ -107,25 +156,32 @@ IAIPlayer* AIPlayerFactory::getPlayerFromId(int id) return m_players[id]; } +// bf2: unchecked store at the wrapper's id (IAIPlayer +0x1C). +// ELF 0x842BD60. void AIPlayerFactory::setIdToPlayerMapping(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::setIdToPlayerMapping"); + m_players[player->getId()] = player; } +// ELF 0x842BD90. void AIPlayerFactory::removeIdToPlayerMapping(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::removeIdToPlayerMapping"); + m_players[player->getId()] = 0; } // - a bare member load, so it hands back the vector itself. +// ELF 0x842BE70. const std::vector& AIPlayerFactory::getAllPlayers() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::getAllPlayers"); + return m_players; } +// bf2: the local human (+0x30 getLocalHumanPlayer) looked up by id, null without one. +// ELF 0x842BEC0. IAIPlayer* AIPlayerFactory::getPlayerFromLocalHumanPlayer() { - BF2_AI_FRONTIER("dice::hfe::ai::AIPlayerFactory::getPlayerFromLocalHumanPlayer"); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + return player ? m_players[player->getId()] : 0; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h index 1ad3a814b..af39dcff7 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIPlayerFactory.h @@ -20,6 +20,13 @@ class IBase; namespace ai { +class IAIObject; + +// bf2 0x842B700, the first function of AIPlayerFactory.cpp's text (exported, `T`): whether any +// unit of the object's primary object or of its secondary objects other than `exclude` is +// occupied. AIEventListener's vehicle-exit arm uses it. +bool isOccupiedObject(IAIObject* object, IAIObject* exclude); + class IAIPlayerFactory { public: diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp index b5d43811d..c4370fa5b 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp @@ -1,12 +1,7 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFCollisionHandler operations. #include "BFCollisionHandler.h" -#include "AIFrontier.h" #include "../../../Game/Objects/IObject.h" // getAbsolutePosition, the +0x6C / +0x68 slot #include "../../AIDLL/AI/Main/CommonSingletonServer.h" @@ -14,6 +9,23 @@ #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods #include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings::getMaxNBots - slot +0 +#include "../../AIDLL/AI/Main/AICollisionHandler.h" // IAICollisionHandler +0x14 - handleProjectileDamage +#include "IAIObject.h" +#include "IAIObjectPlugIn.h" // IAIObjectArmament / IAIObjectPhysical +#include "WeaponTemplateManager.h" +#include "WeaponTemplate.h" +#include "../../../Game/Objects/IObjectTemplate.h" +#include "../../../Game/Objects/IPlayer.h" +#include "../../../Game/Objects/Base/SimpleObjectTemplate.h" // m_aiTemplate (+0x128), friended +#include "../../../Game/Objects/ObjectLayoutAccess.h" // IObject +0x34, the AI object +#include "../../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" +#include "../../../Scene/Object/PlayerManager.h" +#include "../../../Core/Ids.h" // CID_SimpleObjectTemplate +#include "../../../Game/Objects/IObjectTemplateComponent.h" // getClassID +0x10 +#include "../../../Game/Objects/Projectiles/GenericProjectile.h" // IProjectileObject's implementor +#include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" +#include "../../AIDLL/AI/Main/AIMineManager.h" // minePlaced +0x18 / mineRemoved +0x14 +#include namespace dice { namespace hfe { @@ -90,68 +102,329 @@ static bool botProjectileShortOfTarget(const Vec3& start, const Vec3& position, return dx * dx + dz * dz < passDistanceSq; } +// bf2 0x83FD2F0: every record is deleted, then the array - with scalar delete although the +// constructor allocated it with new[] (a shipped defect, kept: the element type is a plain +// pointer, so no array cookie is involved). The count is read live; with no bots (-1) the loop +// does not run and the null array is deleted. BFCollisionHandler::~BFCollisionHandler() { + for (int i = 0; i < m_count; ++i) + delete m_projectiles[i]; + delete m_projectiles; } +// bf2 0x83FD3F0: every bot's record is deleted and replaced by a fresh one (checkPointer on the +// allocation). [CHOSEN, not recovered] The ELF's inline construction clears only the +4 flag byte +// and the four Vec3s; the shared constructor also clears the +5 flag, which no path reads before +// botProjectilePassedPoint sets it. void BFCollisionHandler::removeAllProjectiles() { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::removeAllProjectiles"); + for (int i = 0; i < m_count; ++i) + { + delete m_projectiles[i]; + m_projectiles[i] = checkPointer(new BotProjectile()); + } +} + +namespace { + +// [INFERRED] local helper: handleCollision and handleProjectileMiss end in the same inlined block. +// A round that shows a mine icon is reported to the mine manager: radius-trigger type 2 as type 1 +// with radius 9, otherwise, when the template's detonation component is the default one, as type 0 +// with radius 7.5. The template's component query is not null-tested, as compiled. +void reportPlacedMine(world::IObject* object, unsigned int objectId) +{ + world::IProjectileDetonationComp* detonation = static_cast( + object->queryComponent(world::IID_IProjectileDetonationComp, + world::IID_IProjectileDetonationComp)); // +0x5C + if (!detonation || !detonation->getShowMineIndicationIcon()) // +0x74 + return; + detonation = static_cast( + object->queryComponent(world::IID_IProjectileDetonationComp, + world::IID_IProjectileDetonationComp)); // asked again + IAIMineManager* const mines = static_cast(CommonSingletonServer::m_iAIMineManager); + if (detonation->getRadiusTriggerType() == 2) // +0x78 + { + mines->minePlaced(static_cast(1), objectId, + object->getAbsoluteTransformation(), 9.0f); // +0x18 + return; + } + // [CHOSEN, not recovered] const_cast: the template's queryComponent (+0x5C) is not const. + world::IObjectTemplate* const objectTemplate = + const_cast(object->getTemplate()); // +0x14 + if (objectTemplate->queryComponent(world::IID_IProjectileDetonationCompTemplate)->getClassID() + != world::CID_DefaultDetonationCompTemplate) + return; + mines->minePlaced(static_cast(0), objectId, + object->getAbsoluteTransformation(), 7.5f); +} + +// GenericProjectile is IProjectileObject's only implementor (see world::projectileOwner in +// GenericProjectile.cpp); the typed downcast is the retail subtable dispatch minus the thunk. +inline world::GenericProjectile* asGenericProjectile(world::IProjectileObject* projectile) +{ + return static_cast(projectile); +} + +inline IAIObject* aiObjectOf(world::IObject* object) +{ + return static_cast(world::object_detail::LayoutAccess::aiObject(object)); // +0x34 } -void BFCollisionHandler::handleCollision(world::IObject* a, world::IObject* b, const Vec3& at) +} // namespace + +// handleCollision - bf2 0x83FD5C0, 1118 B (objdump, 2026-11-01). GameLogicCollision's object hit: +// `projectile` hit `hitObject` at `at`. A round fired from a vehicle with an AI object tells the AI +// collision handler about the victim (victimUpdate +0x1C, the victim's player id from the nearest +// player-control object up the hit object's chain) and, when that answers true, the shooter +// (shooterUpdate +0x20); then the indirect hit (+0x2C) is reported with the victim's player id +// (-1 without one). The mine block follows for every hit. Without a hit object the indirect hit +// is reported with a null player, AI object and projectile: the next two slots then dereference +// the null player, as compiled (GameLogicCollision never passes a null hit object). +void BFCollisionHandler::handleCollision(world::IObject* projectile, world::IObject* hitObject, const Vec3& at) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleCollision"); + if (!hitObject) + { + world::IProjectileObject* const proj = projectile + ? static_cast(projectile->queryInterface(world::IID_IProjectileObject)) + : 0; + if (!proj) + return; + world::IPlayer* const player = asGenericProjectile(proj)->getPlayer(); // +0x54 + if (!player) + return; + world::IObject* const vehicle = player->getVehicle(); // +0x48 + if (!vehicle || !aiObjectOf(vehicle)) + return; + handleIndirectProjectileHit(0, 0, static_cast(0), projectile, -1); // +0x2C + return; + } + if (!projectile) + return; + + world::IProjectileObject* const proj = + static_cast(projectile->queryInterface(world::IID_IProjectileObject)); + world::IPlayer* const player = proj ? asGenericProjectile(proj)->getPlayer() : 0; + world::IObject* const vehicle = player ? player->getVehicle() : 0; + IAIObject* const shooter = vehicle ? aiObjectOf(vehicle) : 0; + if (shooter) + { + int victimPlayerId = -1; + IAIObject* const victim = aiObjectOf(world::getRootParent(hitObject)); + if (victim) + { + world::IPlayerControlObject* pco = 0; + for (world::IObject* o = hitObject; o; o = o->getParent()) + { + pco = static_cast( + o->queryInterface(world::IID_IPlayerControlObject)); + if (pco) + break; + } + world::IPlayer* const victimPlayer = pco ? pco->getOccupingPlayer() : 0; // +0x10 + if (victimPlayer) + { + victimPlayerId = victimPlayer->getId(); // +0x54 + const Vec3& position = projectile->getAbsolutePosition(); // +0x6C + IAICollisionHandler* const ai = + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)); + if (ai->victimUpdate(victimPlayerId, projectile->getObjectId(), position, victim, shooter)) + static_cast(CommonSingletonServer::m_iAICollisionHandler) + ->shooterUpdate(asGenericProjectile(proj)->getPlayer()->getId(), + projectile->getObjectId(), hitObject, victim, at); + } + } + handleIndirectProjectileHit(player, shooter, proj, projectile, victimPlayerId); // +0x2C + } + reportPlacedMine(projectile, projectile->getObjectId()); } +// handleProjectileTimeout - bf2 0x83FDA30, 483 B. GenericProjectile's reset and detonate: the +// owner's AI hears the round's object id, the owner's id, the round's position and whether its +// template carries a sticky-collision component (+0x24). A round that shows a mine icon is +// removed from the mine manager (+0x14). +// [CHOSEN, not recovered] the return value: the image sets none; both callers discard it. int BFCollisionHandler::handleProjectileTimeout(world::IProjectileObject* projectile, world::IObject* owner) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileTimeout"); + world::IPlayer* const player = asGenericProjectile(projectile)->getPlayer(); // +0x54 + if (player) + { + const int playerId = player->getId(); + const unsigned int objectId = owner->getObjectId(); + bool sticky = false; + const world::IObjectTemplate* const objectTemplate = owner->getTemplate(); + if (objectTemplate && objectTemplate->getComponentFromClassID(world::CID_StickyCollisionCompTemplate)) // +0x60 + sticky = true; + const Vec3& position = owner->getAbsolutePosition(); + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileTimeout(static_cast(objectId), playerId, position, sticky); // +0x24 + } + world::IProjectileDetonationComp* const detonation = static_cast( + owner->queryComponent(world::IID_IProjectileDetonationComp, world::IID_IProjectileDetonationComp)); + if (detonation && detonation->getShowMineIndicationIcon()) + static_cast(CommonSingletonServer::m_iAIMineManager)->mineRemoved(owner->getObjectId()); + return 0; } -int BFCollisionHandler::handleProjectileFire(const Vec3& from, world::IProjectileObject* projectile, world::IObject* weapon, world::IPlayer* player) +// handleProjectileFire - bf2 0x83FDF80, 501 B. `object` is the fired round (GenericFireArm / +// MultiFireComp pass it as the second argument of the short form); `projectile` is not read. A +// player in a vehicle with an AI object reports the shot to the AI collision handler (+0x08: the +// start point, the round, its transformation and object id, the AI object of the shooter's root, +// the player's id and team) and marks the vehicle's last fired weapon (armament +0x28). +// [CHOSEN, not recovered] the return value: the image sets none; the caller discards it. +int BFCollisionHandler::handleProjectileFire(const Vec3& from, world::IProjectileObject* /*projectile*/, + world::IObject* object, world::IPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileFire"); + world::IObject* const vehicle = player->getVehicle(); // +0x48 + IAIObject* const shooter = vehicle ? aiObjectOf(vehicle) : 0; + if (!shooter) + return 0; + world::IObject* const shooterObject = shooter->getObject(); // +0x20 + const int team = player->getTeam(); // +0xE8 + const int playerId = player->getId(); // +0x54 + IAIObject* const root = aiObjectOf(world::getRootParent(shooterObject)); + const unsigned int objectId = object->getObjectId(); + const Mat4& transformation = object->getAbsoluteTransformation(); // +0x84 + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileFire(from, object, transformation, static_cast(objectId), root, + playerId, team); // +0x08 + if (IAIObjectArmament* const armament = shooter->getArmament()) // +0x84 + armament->setLastFiredWeapon(); // +0x28 + return 0; } -void BFCollisionHandler::handleProjectileFire(world::IProjectileObject* projectile, world::IObject* weapon) +// handleProjectileFire - bf2 0x83FDF10, 106 B. A round with an owner is reported with its start +// point (IProjectileObject +0x6C) through the long form (+0x14). +void BFCollisionHandler::handleProjectileFire(world::IProjectileObject* projectile, world::IObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileFire"); + if (!projectile) + return; + world::IPlayer* const player = asGenericProjectile(projectile)->getPlayer(); // +0x54 + if (!player) + return; + const Vec3 from = asGenericProjectile(projectile)->getStartPos(); // +0x6C + handleProjectileFire(from, projectile, object, player); // +0x14 } -void BFCollisionHandler::handleProjectileDamage(world::IObject* target, float amount, int type, unsigned int id, Vec3 at) +// handleProjectileDamage - ELF 0x83FE410, 651 B (read with objdump/rea, 2026-11-01). Called by +// GameLogicDamage::serverGiveDamage after the damage is applied, result unused. `id` is the weapon's +// template id, `type` the player id: the AI weapon template is looked up by the weapon template's +// m_aiTemplate name (a copied string, as compiled), then the shooter is that player's current +// vehicle's AI object and the victim the target's; the strength row is the weapon template's +// m_strengths for the victim's combat-strength type. Every lookup that fails returns silently. +// The handler goes through checkPointer (a null one is logged, then called, as shipped). +// `amount` and `at` are not read. +void BFCollisionHandler::handleProjectileDamage(world::IObject* target, float /*amount*/, int type, + unsigned int id, Vec3 /*at*/) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileDamage"); + if (id == static_cast(-1)) + return; + world::IObjectTemplate* const objectTemplate = world::objectTemplateManager->getTemplate(id); // +0x60 + if (!objectTemplate) + return; + world::SimpleObjectTemplate* const simple = static_cast( + objectTemplate->queryImplementation(world::CID_SimpleObjectTemplate)); // +0x50 + if (!simple) + return; + WeaponTemplate* weapon; + { + const std::string aiTemplate(simple->m_aiTemplate); // +0x128 + weapon = WeaponTemplateManager::m_instance->getTemplate(aiTemplate); + } + if (!weapon) + return; + + world::IPlayer* const player = world::playerManager->getPlayerFromId(type); // +0x20 + if (!player) + return; + world::IObject* const vehicle = player->getVehicle(); // +0x48 + if (!vehicle) + return; + IAIObject* const shooter = static_cast( + world::object_detail::LayoutAccess::aiObject(vehicle)); // +0x34 + if (!shooter) + return; + IAIObjectArmament* const armament = shooter->getArmament(); // +0x84 + if (!armament) + return; + IAIObject* const victim = static_cast( + world::object_detail::LayoutAccess::aiObject(target)); // +0x34 + if (!victim) + return; + IAIObjectPhysical* const physical = victim->getPhysical(); // +0x94 + if (!physical) + return; + const int weaponIndex = armament->getWeaponIdFromActivationId(weapon->m_weaponActivate, // +0x34 + weapon->m_weaponFire); + if (weaponIndex == -1) + return; + const int strength = weapon->m_strengths[physical->getStrType()]; // +0x4C + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileDamage(shooter, victim, strength, weaponIndex); // +0x14 } -void BFCollisionHandler::handleExplosionDamage(world::IObject* target, float amount, int type, unsigned int id, Vec3 at) + +// handleExplosionDamage - bf2 0x83FE180, 651 B: GameLogicExplosion's queued damage. It compiles to +// the same instructions as handleProjectileDamage (register choice in the checkPointer diagnostic +// aside); [CHOSEN, not recovered] the body is shared through a non-virtual call. +void BFCollisionHandler::handleExplosionDamage(world::IObject* target, float amount, int type, + unsigned int id, Vec3 at) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleExplosionDamage"); + BFCollisionHandler::handleProjectileDamage(target, amount, type, id, at); } +// handleIndirectProjectileHit - bf2 0x83FDC70, 325 B: the player's team, then the AI collision +// handler's short form (+0x10). Returns its answer. int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, const Vec3& at, int a) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleIndirectProjectileHit"); + const int team = player->getTeam(); // +0xE8 + return checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleIndirectProjectileHit(team, object, at, a); // +0x10 } +// handleIndirectProjectileHit - bf2 0x83FDDC0, 332 B: the player's team, then the long form (+0x0C). int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, int a, const Vec3& at, int b) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleIndirectProjectileHit"); + const int team = player->getTeam(); // +0xE8 + return checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleIndirectProjectileHit(team, object, a, at, b); // +0x0C } -int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, world::IProjectileObject* projectile, world::IObject* weapon, int a) +// handleIndirectProjectileHit - bf2 0x83FDC20, 76 B: the round's object id and position, through +// the (int, Vec3) form (+0x28). `projectile` is not read. +int BFCollisionHandler::handleIndirectProjectileHit(world::IPlayer* player, IAIObject* object, + world::IProjectileObject* /*projectile*/, + world::IObject* weapon, int a) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleIndirectProjectileHit"); + const Vec3& position = weapon->getAbsolutePosition(); // +0x6C + return handleIndirectProjectileHit(player, object, static_cast(weapon->getObjectId()), + position, a); // +0x28 } -int BFCollisionHandler::handleProjectileMiss(int a, world::IObject* object, int b, const Vec3& at) +// handleProjectileMiss - bf2 0x83FE6A0, 586 B. GameLogicCollision's terrain hit: `playerId` is the +// round's owner (-1 without one), `objectId` the round's object id. The owner's vehicle's AI +// object reports the miss (+0x18); the mine block follows with that id. +// [CHOSEN, not recovered] the return value: the image sets none; the caller discards it. +int BFCollisionHandler::handleProjectileMiss(int playerId, world::IObject* object, int objectId, const Vec3& at) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::handleProjectileMiss"); + if (world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId)) // +0x20 + { + world::IObject* const vehicle = player->getVehicle(); // +0x48 + IAIObject* const shooter = vehicle ? aiObjectOf(vehicle) : 0; + if (shooter) + checkPointer(static_cast(CommonSingletonServer::m_iAICollisionHandler)) + ->handleProjectileMiss(shooter, playerId, objectId, at); // +0x18 + } + reportPlacedMine(object, static_cast(objectId)); + return 0; } +// reset - bf2 0x83FEB80, 45 B: every bot's projectile record is removed (+0x40); the count is +// read live. void BFCollisionHandler::reset() { - BF2_AI_FRONTIER("dice::hfe::ai::BFCollisionHandler::reset"); + for (int id = 0; id < m_count; ++id) + removeBotProjectile(id); } // Every live, unpassed round is sampled once per AI tick: its highest Y is kept, and it is diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp index 42e800c37..f3c4bba08 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.cpp @@ -1,12 +1,21 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFCommander operations. #include "BFCommander.h" -#include "AIFrontier.h" +#include "IAIObject.h" +#include "AIPlayer.h" +#include "../../../IO/Network/INetworkable.h" +#include "../../../Game/Objects/IObject.h" +#include "../../../Game/GameLogic/SquadManager/SquadOrder.h" +#include "../../../Game/Objects/Game/ArtilleryHandler.h" // the two artillery queries +#include "../../../Game/GameEvents/ArtilleryEvent.h" // fireArtillery +#include "../../../Game/GameEvents/UAVEvent.h" +#include "../../../Game/GameEvents/SupplyDropEvent.h" +#include "../../../Game/GameEvents/DropVehicleEvent.h" +#include "../../../Game/GameLogic/GameLogic.h" +#include "../../../Game/GameLogic/VoiceMessages.h" +#include "../../../Game/GameLogic/SquadManager/ISquadManager.h" +#include "../../../Core/EventManager.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" @@ -16,9 +25,29 @@ namespace dice { namespace hfe { extern ClassManager* classManager; +extern IBase* squadManager; // ds:0x8ACBFA4 - Core/Globals.cpp namespace ai { +namespace { +// Shared spelling of the lookup/play sequence in ELF 0x840F7F0..0x8410463. +void playCommanderMessage(int team, const char* name) +{ + int messageId = 0, voiceId = 0, filterId = 0; + bool found; + { + const std::string filter(""); + const std::string voice("commander"); + const std::string message(name); + found = static_cast(gameLogic)->getVoiceMessages()->namesToIds( + &messageId, &voiceId, &filterId, message, voice, filter); + } + if (found) + static_cast(gameLogic)->getVoiceMessages()->playRadioMessage( + team, messageId, voiceId, filterId); +} +} + // First wins in, exact match out. IBFCommander::IBFCommander() { @@ -48,95 +77,177 @@ BFCommander::~BFCommander() { } +// bf2 ELF 0x840F340: ISquadManager::applyForCommander(side +0x6C, id +0x1C) (+0x58). +// [CHOSEN] The image returns whatever the void call leaves in eax; 0 here (callers discard it). int BFCommander::applyAsCommander(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::applyAsCommander"); + const int id = player->getId(); + static_cast(squadManager)->applyForCommander(player->getSide(), id); + return 0; } +// bf2 ELF 0x840F390: ISquadManager::resignCommander(side) (+0x68). Return as above. int BFCommander::retireAsCommander(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::retireAsCommander"); + static_cast(squadManager)->resignCommander(player->getSide()); + return 0; } +// bf2 ELF 0x840F3C0 / 0x840F400 / 0x840F440: giveOrder with order type 5 / 4 / 6. The image +// tail-returns giveOrder's leftover eax; 0 here ([CHOSEN], CommanderInterface discards it). int BFCommander::giveAttackOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::giveAttackOrder"); + giveOrder(position, a, b, target, static_cast(5)); + return 0; } int BFCommander::giveMoveOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::giveMoveOrder"); + giveOrder(position, a, b, target, static_cast(4)); + return 0; } int BFCommander::giveDefendOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::giveDefendOrder"); + giveOrder(position, a, b, target, static_cast(6)); + return 0; } -void BFCommander::sendAttackMessage(int a, int b) +// bf2 ELF 0x840F740: a commander order {type, target network id or 0, points = {position, 0, 0}, +// flag2C false} for (team, squad) through ISquadManager::issueCommanderOrder (+0x48, last +// argument false). The target's id is its object's networkable id (IObjectComponent +0x20, +// IObject::getNetworkable slot 54, ushort at +4). +void BFCommander::giveOrder(const Vec3& position, int squadId, int team, IAIObject* target, SquadOrderType type) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::sendAttackMessage"); + SquadOrder order; + for (int i = 0; i < 3; ++i) + { + order.points[i].x = 0.0f; + order.points[i].y = 0.0f; + order.points[i].z = 0.0f; + } + order.flag2C = false; + order.orderId = type; + order.points[0] = position; + order.targetNetId = 0; + if (target) + { + io::INetworkable* const networkable = target->getObject()->getNetworkable(); + if (networkable) + order.targetNetId = static_cast(networkable->m_networkableId); + } + static_cast(squadManager)->issueCommanderOrder(team, squadId, order, false); } -void BFCommander::sendDefendMessage(int a, int b) +// ELF 0x840F7F0. The squad argument is unused. +void BFCommander::sendAttackMessage(int team, int /*squadId*/) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::sendDefendMessage"); + playCommanderMessage(team, "attack_position"); } -int BFCommander::fireArtillery(int a, int b, Vec2 position) +// ELF 0x840F980. +void BFCommander::sendDefendMessage(int team, int /*squadId*/) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::fireArtillery"); + playCommanderMessage(team, "defend"); +} + +// bf2 0x840F480. Queues a request-fire ArtilleryEvent (type 1, the team in the byte at +0x14, +// GameLogic category, id 15) for the next update. A squad id other than -1 also marks that +// squad's order accepted (ISquadManager +0x24: false, order type 2, squad order type 0, false). +// [CHOSEN, not recovered] The ELF leaves the last call's EAX; no caller reads it, 0 here. +int BFCommander::fireArtillery(int team, int squadId, Vec2 position) +{ + ArtilleryEvent* const event = new ArtilleryEvent(); + event->m_target = position; + event->m_artilleryType = ArtilleryEvent::ArtilleryTypeRequestFire; + event->m_team = static_cast(team); + eventManager->postEventNextUpdate(ECGameLogic, 15, static_cast(event)); + if (squadId != -1) + { + static_cast(squadManager) + ->setIsAccepted(team, squadId, false, static_cast(2), + static_cast(0), false); + } + return 0; } -int BFCommander::sendUav(int a, int b, Vec2 position) +// ELF 0x840F530. Unlike fireArtillery, these producers do not guard squadId == -1. +void BFCommander::sendUav(int team, int squadId, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::sendUav"); + UAVEvent* const event = new UAVEvent(position.x, position.y, team, false); + eventManager->postEventNextUpdate(ECGameLogic, 15, event); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(1), false); } -int BFCommander::dropSupply(int a, int b, Vec2 position) +// ELF 0x840F5E0. +void BFCommander::dropSupply(int team, int squadId, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::dropSupply"); + SupplyDropEvent* const event = new SupplyDropEvent(position.x, position.y, team); + eventManager->postEventNextUpdate(ECGameLogic, 15, event); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(3), false); } -int BFCommander::dropVehicle(int a, int b, Vec2 position) +// ELF 0x840F690. The producer deliberately leaves the trailing event byte untouched. +void BFCommander::dropVehicle(int team, int squadId, Vec2 position) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::dropVehicle"); + DropVehicleEvent* const event = new DropVehicleEvent(team, position); + eventManager->postEventNextUpdate(ECGameLogic, 15, event); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(2), false); } -int BFCommander::denyArtilleryRequest(int a, int b) +// ELF 0x840FB10. Acceptance state is cleared even when message lookup fails. +void BFCommander::denyArtilleryRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denyArtilleryRequest"); + playCommanderMessage(team, "artillery_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(0), false); } +// bf2 0x840FCE0: the team's handler (one-based, unchecked) has any artillery piece registered. bool BFCommander::gameHasArtillery(int team) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::gameHasArtillery"); + return world::artilleryManager->getHandler(static_cast(team))->hasArtilleryPieces(); } +// bf2 0x840FD00: the handler's haveAnyArtillery (pieces that still have an owner object). bool BFCommander::anyArtilleryPiecesLeft(int team) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::anyArtilleryPiecesLeft"); + return world::artilleryManager->getHandler(static_cast(team))->haveAnyArtillery(); } -// dice's capital A. Frozen - it is the mangled name. -int BFCommander::ArtilleryUnavailable(int a, int b) +// ELF 0x840FD30. The capital A is attested by the mangled name. +void BFCommander::ArtilleryUnavailable(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::ArtilleryUnavailable"); + playCommanderMessage(team, "artillery_unavailable"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(0), false); } -int BFCommander::denySupplyRequest(int a, int b) +// ELF 0x840FF00. +void BFCommander::denySupplyRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denySupplyRequest"); + playCommanderMessage(team, "supply_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(3), false); } -int BFCommander::denyVehicleDropRequest(int a, int b) +// ELF 0x84100D0. +void BFCommander::denyVehicleDropRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denyVehicleDropRequest"); + playCommanderMessage(team, "vehicledrop_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(2), false); } -int BFCommander::denyUavRequest(int a, int b) +// ELF 0x84102A0. +void BFCommander::denyUavRequest(int team, int squadId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFCommander::denyUavRequest"); + playCommanderMessage(team, "uav_deny"); + static_cast(squadManager)->setIsAccepted( + team, squadId, false, static_cast(2), static_cast(1), false); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h index 64968a541..df9b1036a 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFCommander.h @@ -17,6 +17,7 @@ namespace dice { namespace hfe { class IBase; +enum SquadOrderType : int; // Game/GameLogic/SquadManager/ISquadInfo.h namespace ai { @@ -34,16 +35,16 @@ class IBFCommander virtual void sendAttackMessage(int a, int b) = 0; virtual void sendDefendMessage(int a, int b) = 0; virtual int fireArtillery(int a, int b, Vec2 position) = 0; - virtual int sendUav(int a, int b, Vec2 position) = 0; - virtual int dropSupply(int a, int b, Vec2 position) = 0; - virtual int dropVehicle(int a, int b, Vec2 position) = 0; - virtual int denyArtilleryRequest(int a, int b) = 0; + virtual void sendUav(int a, int b, Vec2 position) = 0; + virtual void dropSupply(int a, int b, Vec2 position) = 0; + virtual void dropVehicle(int a, int b, Vec2 position) = 0; + virtual void denyArtilleryRequest(int a, int b) = 0; virtual bool gameHasArtillery(int team) = 0; virtual bool anyArtilleryPiecesLeft(int team) = 0; - virtual int ArtilleryUnavailable(int a, int b) = 0; - virtual int denySupplyRequest(int a, int b) = 0; - virtual int denyVehicleDropRequest(int a, int b) = 0; - virtual int denyUavRequest(int a, int b) = 0; + virtual void ArtilleryUnavailable(int a, int b) = 0; + virtual void denySupplyRequest(int a, int b) = 0; + virtual void denyVehicleDropRequest(int a, int b) = 0; + virtual void denyUavRequest(int a, int b) = 0; }; class BFCommander : public IBFCommander @@ -60,16 +61,20 @@ class BFCommander : public IBFCommander virtual void sendAttackMessage(int a, int b); virtual void sendDefendMessage(int a, int b); virtual int fireArtillery(int a, int b, Vec2 position); - virtual int sendUav(int a, int b, Vec2 position); - virtual int dropSupply(int a, int b, Vec2 position); - virtual int dropVehicle(int a, int b, Vec2 position); - virtual int denyArtilleryRequest(int a, int b); + virtual void sendUav(int a, int b, Vec2 position); + virtual void dropSupply(int a, int b, Vec2 position); + virtual void dropVehicle(int a, int b, Vec2 position); + virtual void denyArtilleryRequest(int a, int b); virtual bool gameHasArtillery(int team); virtual bool anyArtilleryPiecesLeft(int team); - virtual int ArtilleryUnavailable(int a, int b); - virtual int denySupplyRequest(int a, int b); - virtual int denyVehicleDropRequest(int a, int b); - virtual int denyUavRequest(int a, int b); + virtual void ArtilleryUnavailable(int a, int b); + virtual void denySupplyRequest(int a, int b); + virtual void denyVehicleDropRequest(int a, int b); + virtual void denyUavRequest(int a, int b); + +private: + // bf2 ELF 0x840F740: the shared body of the three give*Order methods. + void giveOrder(const Vec3& position, int squadId, int team, IAIObject* target, SquadOrderType type); }; } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp index 1f9c6ea57..e3c8c5f66 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp @@ -8,8 +8,14 @@ #include "../../../Core/Debug.h" // the no-settings report #include "AIFrontier.h" +#include "../../../Game/Objects/ISpawnPoint.h" // getSpawnPointPositions +#include "../../../Game/Objects/IObject.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings, the menu arm's override +#include "../../../Game/GeneralSettings.h" // IGeneralSettings, the menu arm +#include "../../../Game/LocalProfileManager.h" // ILocalProfileManager, the menu arm +#include "../../../Core/StringUtil.h" // compareIgnoreCase (0x431950) #include "../../../Core/ClassManager.h" #include "../../../Game/GameServer/ServerSettings.h" #include "../../../Game/IGame.h" // the `game` global and queryInterface (+0x0C) @@ -23,6 +29,16 @@ #include "../../../Game/GameLogic/SpawnSystem/SpawnManager.h" #include "../../../Game/GameLogic/SpawnSystem/SpawnGroup.h" +#include "../../../Game/Objects/Projectiles/IProjectileObject.h" +#include "../../../Game/Objects/Projectiles/GenericProjectile.h" // getTeam, IProjectileDetonationComp +#include "../../../Game/Objects/ObjectLayoutAccess.h" // IObject +0x34, the AI object +#include "../../../Game/Objects/IPlayer.h" // getCloseMines, getId +#include "../../../IO/Network/INetworkable.h" // m_networkableId +#include "../../../Math/Vec3.h" // vec3ToVec2XZ, insideCentreBox +#include "AIPlayer.h" +#include "IAIObject.h" + +#include // std::find over the ignore list #include // the control-point map's own type namespace dice { @@ -65,14 +81,54 @@ int BFGame::getMaxNumberOfPlayers() const } // Copies game settings into the AI configuration, including bot population and team balance. -// [RETIRE-WHEN: aidll-01-adapters] Remove when the corresponding implementation is complete and validated. +// BF2.exe 0x815C50 (530 B, RET 0xC). With a "GeneralSettings" singleton (the client hosting a game +// from the menu) the values come from the profile's GeneralSettings; otherwise from serverSettings. +// The menu arm, in order: +// 1. "LocalProfileManager" (string 0x87FD98) must exist and have a current profile (+0x44); +// otherwise return false (0x815DB4) and leave a/b/c alone. +// 2. settings +0x40 stringGet("GSGameMode", "gpm_cq") (0x880688 / 0x89B4D0); when it equals +// "sp1" (0x89B200, compareIgnoreCase 0x431950), the bot count is forced: 16, or +// IAISettings (CommonSingletonServer, 0xA3867C) slot 0 getMaxNBots when IAISettings exists +// and its slot +0xB8 overrideMenuSettings() answers true; then GeneralSettings +0xB4 +// setMaxBots(count). +// 3. a = +0xB0 getMaxBots, b = +0xB8 getMaxBotsIncludeHumans, c = +0xC0 getBotSkill (stored +// through the x87 stack as a float); return true. int BFGame::getAISettingsFromGame(int& a, bool& b, float& c) const { - if (classManager->getSingleton(std::string("GeneralSettings"))) + IBase* general = classManager->getSingleton(std::string("GeneralSettings")); +#if DEDICATED + // The dedicated images declare no GeneralSettings (Game/GeneralSettings.h is client-only), and + // no dedicated module registers the singleton, so this arm cannot be reached there. + if (general) { BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getAISettingsFromGame" - " - the MENU arm; this image has no GeneralSettings slots"); + " - the MENU arm in a dedicated image (no GeneralSettings interface)"); + } +#else + if (general) + { + IGeneralSettings* generalSettings = static_cast(general); + ILocalProfileManager* profiles = static_cast( + classManager->getSingleton(std::string("LocalProfileManager"))); + if (!profiles || !profiles->getCurrentProfile()) // +0x44 + return 0; + const std::string gameMode(settings->stringGet(std::string("GSGameMode"), // +0x40 + std::string("gpm_cq"))); + if (compareIgnoreCase(gameMode, std::string("sp1")) == 0) + { + int count = 16; + const IAISettings* aiSettings = + static_cast(CommonSingletonServer::m_iaiSettings); + if (aiSettings && aiSettings->overrideMenuSettings()) // +0xB8 + count = aiSettings->getMaxNBots(); // +0x00 + generalSettings->setMaxBots(count); // +0xB4 + } + a = generalSettings->getMaxBots(); // +0xB0 + b = generalSettings->getMaxBotsIncludeHumans(); // +0xB8 + c = generalSettings->getBotSkill(); // +0xC0 + return 1; } +#endif // no settings and no menu is A reported failure, not A silent zero - and the caller honours // the false by leaving the script's values alone. @@ -107,9 +163,71 @@ int BFGame::getTickets(int team) const return static_cast(world::scoreManager)->getTeamScore(team)->m_tickets; } +// bf2 0x83FF9B0 (ELF listing, Ghidra pseudo-code as cross-check). Walks the player's close mines +// (IPlayer +0x32C) for at most 100 entries, counting skipped ones. A mine counts when its +// projectile team (IProjectileObject +0x64) differs from the bot's side (IAIPlayer +0x6C) and its +// object id is not in `ignore`; the nearest by squared distance wins. For each new best, in this +// order: id, position (IObject +0x6C), normal = the transformation's third row (+0x84, bytes +// 0x20..0x28), found = true, then found = false when the detonation component's +// getRadiusTriggerType (+0x78) is 2. Neither the projectile face nor the component is null-tested. +// The return value is whether any mine was taken (a byte; the caller tests %al). int BFGame::getClosestHostileMine(IAIPlayer* player, Vec3 from, bool& found, Vec3& position, Vec3& normal, unsigned int& id, std::vector& ignore) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getClosestHostileMine"); + bool any = false; + world::IPlayer* const owner = player->getPlayer(); // +0x0C + const int side = player->getSide(); // +0x6C + std::vector mines; + owner->getCloseMines(mines); // +0x32C + int count = 0; + Vec3 minePosition; + minePosition.x = 0.0f; + minePosition.y = 0.0f; + minePosition.z = 0.0f; + float best = 3.4028235e38f; + if (!mines.empty()) + { + for (std::vector::iterator it = mines.begin(); it != mines.end(); ++it) + { + if (++count > 100) + break; + world::IObject* const mine = *it; + // GenericProjectile is IProjectileObject's only implementor; the typed downcast is the + // retail +0x64 subtable dispatch (thunk _ZThn316_ ... getTeam at vtable +0x37C). + world::GenericProjectile* const projectile = static_cast( + static_cast( + mine->queryInterface(world::IID_IProjectileObject))); // +0x0C + if (projectile->getTeam() == side) // +0x64 + continue; + const unsigned int mineId = mine->getObjectId(); // +0x10 + if (std::find(ignore.begin(), ignore.end(), mineId) != ignore.end()) + continue; + minePosition = mine->getAbsolutePosition(); // +0x6C + const Vec3 at = from; + const float dx = at.x - minePosition.x; + const float dy = at.y - minePosition.y; + const float dz = at.z - minePosition.z; + const float distance = dx * dx + dy * dy + dz * dz; + if (distance < best) + { + any = true; + id = mineId; + best = distance; + position = minePosition; + const float* const m = mine->getAbsoluteTransformation().m; // +0x84 + normal.x = m[8]; + normal.y = m[9]; + normal.z = m[10]; + world::IProjectileDetonationComp* const detonation = + static_cast( + mine->queryComponent(world::IID_IProjectileDetonationComp, + world::IID_IProjectileDetonationComp)); // +0x5C + found = true; + if (detonation->getRadiusTriggerType() == 2) // +0x78 + found = false; + } + } + } + return any; } // Only gameLogic is guarded. @@ -189,12 +307,25 @@ bool BFGame::getControlPointInfo(unsigned int index, Vec3& position, float& radi return active; } -// [FRONTIER] Finds a control point within the horizontal box defined by a and b. -// [RETIRE-WHEN: aidll-01-adapters] Implement and validate insideCentreBox before enabling this query. +// bf2 0x83FF350. The id of the first control point (key order) whose XZ position lies in the box +// insideCentreBox(position, a, b) (bf2 0x83F7A20, same code as the AI image's) describes; -1 when +// there is none or no game logic. The Vec2 scratch is zeroed once, before the walk. int BFGame::findControlPoint(const Vec2& a, const Vec2& b) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::findControlPoint" - " - the walk is read; dice::hfe::insideCentreBox is not"); + Vec2 position; + position.x = 0.0f; + position.y = 0.0f; + if (!gameLogic) + return -1; + typedef std::map ControlPointMap; + ControlPointMap* const points = gameLogic->getControlPointMap(); // +0x174 + for (ControlPointMap::iterator it = points->begin(); it != points->end(); ++it) + { + vec3ToVec2XZ(it->second->getAbsolutePosition(), position); // +0x6C + if (insideCentreBox(position, a, b)) + return static_cast(it->first); + } + return -1; } // The returned list is @@ -219,14 +350,43 @@ int BFGame::getControlPointId(int index) const return static_cast(static_cast(spawnManager)->getSpawnGroup(index)->getControlPointId()); } -int BFGame::getSpawnPointPositions(std::vector& out, unsigned char team) const +// bf2 0x83FF800. Every group's spawn points (copied vector, ISpawnGroup +0x40) that are neither +// AI-enter-on-spawn (+0x24), enter-on-spawn (+0x20) nor human-only (+0x50) add their spawn +// position (+0x34, checkAI true, from a zero Vec3). The team is not read. +// [CHOSEN, not recovered] The ELF leaves the last call's EAX; no caller reads it, 0 here. +int BFGame::getSpawnPointPositions(std::vector& out, unsigned char) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getSpawnPointPositions"); + const std::map& groups = + static_cast(spawnManager)->getSpawnGroups(); + for (std::map::const_iterator group = groups.begin(); + group != groups.end(); ++group) + { + const std::vector points = group->second->getSpawnPoints(); + for (std::vector::const_iterator it = points.begin(); it != points.end(); ++it) + { + ISpawnPoint* const point = *it; + if (point->getAIEnterOnSpawn() || point->getEnterOnSpawn() || point->getOnlyForHuman()) + continue; + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + point->getSpawnPosition(position, true); + out.push_back(position); + } + } + return 0; } -void BFGame::getControlPointPositions(std::vector& out, unsigned char team) const +// bf2 0x83FFCB0: every control point's absolute position (IObject +0x6C), from the game logic's +// control-point map (IGameLogic +0x174); nothing without a game logic. The team is not read. +void BFGame::getControlPointPositions(std::vector& out, unsigned char) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getControlPointPositions"); + if (!gameLogic) + return; + std::map* const points = gameLogic->getControlPointMap(); + for (std::map::iterator it = points->begin(); it != points->end(); ++it) + out.push_back(it->second->getAbsolutePosition()); } // Capture team before @@ -250,14 +410,37 @@ bool BFGame::isEligibleSpawnpoint(int team, int groupId) const return active; } +// bf2 0x83FF530. Group 0 or an unknown group is false; otherwise the group's AI spawn point +// (ISpawnGroup +0x44, true) answers enter-on-spawn (+0x20) or AI-enter-on-spawn (+0x24). The +// returned point is not null-tested. bool BFGame::isEnterOnSpawnSpawnpoint(int index) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::isEnterOnSpawnSpawnpoint"); + if (index == 0) + return false; + ISpawnGroup* const group = static_cast(spawnManager)->getSpawnGroup(index); // +0x28 + if (!group) + return false; + ISpawnPoint* const point = group->getSpawnPoint(true); // +0x44 + return point->getEnterOnSpawn() || point->getAIEnterOnSpawn(); // +0x20 / +0x24 } +// bf2 0x83FF5B0. 0 for group 0 or an unknown group; otherwise the AI spawn point's object to +// enter (ISpawnPoint +0x28, (true, side)) and that object's AI object (IObject +0x34): -1 without +// one, else its getInformation(side) (IAIObject +0xB8). Neither the point nor the object is +// null-tested. int BFGame::getEnterOnSpawnSpawnpointObject(int a, int b) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getEnterOnSpawnSpawnpointObject"); + if (a == 0) + return 0; + ISpawnGroup* const group = static_cast(spawnManager)->getSpawnGroup(a); // +0x28 + if (!group) + return 0; + world::IObject* const object = group->getSpawnPoint(true)->getObjectToEnter(true, b); // +0x44, +0x28 + IAIObject* const aiObject = + static_cast(world::object_detail::LayoutAccess::aiObject(object)); // +0x34 + if (!aiObject) + return -1; + return static_cast(aiObject->getInformation(b)); // +0xB8 } // Returns the level directory joined with the configured level name. @@ -329,9 +512,25 @@ bool BFGame::getIsPrecaching() const return m_isPrecaching; } +// bf2 0x83FFE30. Without a game nothing happens. Otherwise the spotted object's networkable id +// (IObject +0xD8, the u16 at +0x04; 0 without one) goes out as a spotted message with a zero Vec2 +// and vehicle type 26 (IGame +0xD0), and the game's spotted text for that id (+0xCC) is sent as a +// team radio message from the player (+0x58, (TCTeam, text, player id, 0, false, false)). +// [UNRESOLVED] the name of VehicleType 26. void BFGame::enemySpottedByAI(world::IPlayer* player, world::IObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFGame::enemySpottedByAI"); + if (!game) + return; + unsigned short networkableId = 0; + if (io::INetworkable* const networkable = object->getNetworkable()) // +0xD8 + networkableId = networkable->m_networkableId; + Vec2 zero; + zero.x = 0.0f; + zero.y = 0.0f; + game->sendSpottedMessage(player, networkableId, zero, static_cast(26)); // +0xD0 + const unsigned int playerId = static_cast(player->getId()); // +0x54 + const std::string message = game->getSpottedMessage(networkableId); // +0xCC + game->radioMessageFromPlayer(TCTeam, message, playerId, 0, false, false); // +0x58 } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp index 097f837ac..e49be6613 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.cpp @@ -1,13 +1,7 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFGameEffector operations. #include "BFGameEffector.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings::getBotName #include "../../../Core/ClassManager.h" @@ -15,60 +9,88 @@ #include "../../../Game/IGame.h" // the `game` global #include "../../../Game/IGameServer.h" // createPlayer, slot +0x20 #include "../../../Scene/Object/PlayerManager.h" // the `playerManager` global +#include "../../../Game/IGameLogic.h" // the `gameLogic` global +#include "../../../Game/GameLogic/ServerGameLogic.h" // forceSpawnBot +#include "../../../Core/SettingsRepostitory.h" // the `settings` global +#include "../../../Physics/MaterialManager.h" +#include "AIPlayer.h" +#include "IAIObject.h" namespace dice { namespace hfe { extern ClassManager* classManager; +namespace world { extern IBase* materialManager; } namespace ai { // First wins in, exact match out. +// ELF 0x840E1E0 / 0x840E260. IAIGameEffector::IAIGameEffector() { if (!CommonSingletonServer::m_iaiGameEffector) classManager->registerSimpleSingleton(std::string("IAIGameEffector"), this); } +// ELF 0x840E2E0 / 0x840E360 / 0x840E3E0. IAIGameEffector::~IAIGameEffector() { if (CommonSingletonServer::m_iaiGameEffector == this) classManager->unregisterSimpleSingleton(std::string("IAIGameEffector")); } +// ELF 0x8400300 / 0x8400340. BFGameEffector::BFGameEffector() - : m_unknown04(0) - , m_unknown08(0) - , m_unknown0C(0) { } +// ELF 0x8400380 / 0x84003E0 / 0x8400440. BFGameEffector::~BFGameEffector() { } +// bf2 0x84004B0: IGame +0xA4 enterVehicle(player, the vehicle's engine object, false); the +// vehicle's object (IObjectComponent +0x20) is read before the player. +// ELF 0x84004B0. int BFGameEffector::enterVehicle(IAIPlayer* player, IAIObject* vehicle) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::enterVehicle"); + world::IObject* const object = vehicle->getObject(); + return game->enterVehicle(player->getPlayer(), object, false); } +// bf2 0x8400500: IGame +0xA8 exitVehicle(player, true, true). +// ELF 0x8400500. int BFGameEffector::exitVehicle(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::exitVehicle"); + return game->exitVehicle(player->getPlayer(), true, true); } // Includes the overload arguments in the terminatePlayer frontier diagnostic. +// bf2 0x8400720: the player manager's player (+0x20) goes to IGameServer +0x28 destroyPlayer +// (the server is queried from `game`, which is not tested before the query's own null arm). +// [CHOSEN, not recovered] destroyPlayer is void; the ELF answers its leftover AL. 0 here. int BFGameEffector::terminatePlayer(int playerId) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::terminatePlayer(int)"); + world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId); + IGameServer* const server = + game ? static_cast(game->queryInterface(IID_IGameServer)) : 0; + server->destroyPlayer(player); + return 0; } +// bf2 0x8400780: the same for the wrapper's player. +// ELF 0x8400780. int BFGameEffector::terminatePlayer(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::terminatePlayer(IAIPlayer*)"); + world::IPlayer* const target = player->getPlayer(); + IGameServer* const server = + game ? static_cast(game->queryInterface(IID_IGameServer)) : 0; + server->destroyPlayer(target); + return 0; } // Creates an AI player through the game server and returns its player ID. +// ELF 0x8400540. int BFGameEffector::addBot(int& a, int& b, std::string& name) { if (name.empty()) @@ -99,35 +121,74 @@ int BFGameEffector::addBot(int& a, int& b, std::string& name) return 0; } +// bf2 0x8400620: IGameLogic +0x70 reSpawnPlayer. +// ELF 0x8400620. int BFGameEffector::respawnBot(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::respawnBot"); + return gameLogic->reSpawnPlayer(player->getPlayer()); } +// bf2 0x8400650: only on a server (setting "GSIsServer", default false), the server game logic +// spawns the player at (position, rotation). +// ELF 0x8400650. void BFGameEffector::forceSpawnBot(IAIPlayer* player, const Vec3& position, const Vec3& rotation) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::forceSpawnBot"); + if (!settings->boolGet(std::string("GSIsServer"), false)) + return; + std::pair at(position, rotation); + static_cast(gameLogic)->spawnPlayer(player->getPlayer(), &at); } +// bf2 0x84007D0: IGameLogic +0xE4 giveDamage on the target's engine object with no victim +// list, weapon or projectile objects, a zero position and an up (0, 1, 0) direction, -1 and the +// flags false, true, false. The int is the damage type slot. +// ELF 0x84007D0. int BFGameEffector::giveDamage(IAIObject* target, world::IPlayer* from, int type, float amount) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::giveDamage"); + world::IObject* const object = target->getObject(); + Vec3 position; + position.x = 0.0f; + position.y = 0.0f; + position.z = 0.0f; + Vec3 direction; + direction.x = 0.0f; + direction.y = 1.0f; + direction.z = 0.0f; + return gameLogic->giveDamage(object, amount, from, 0, 0, type, 0, 0, position, direction, -1, + false, true, false); +} + +// ELF 0x8400880. The final engine effect call has no return value. +void BFGameEffector::playEffect(const Vec3& position, int a, int b) +{ + queueSoundEffect(position, a, b); + const Vec3 up = { 0.0f, 1.0f, 0.0f }; + const world::IObjectTemplate* const effect = static_cast( + static_cast(world::materialManager) + ->getEffectTemplate(static_cast(a), static_cast(b), 0)); + const Vec3 point = position; + gameLogic->playEffect(point, effect, up); } -int BFGameEffector::playEffect(const Vec3& position, int a, int b) +// ELF 0x8400920. The dedicated ELF ships an empty body. +void BFGameEffector::playSoundEffects(double) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::playEffect"); } -// 5 bytes - A bare ret. dice's own empty body, not a gap. -void BFGameEffector::playSoundEffects(double dt) +// ELF 0x8400930. The dedicated ELF ships an empty body. +void BFGameEffector::queueSoundEffect(const Vec3&, int, int) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::playSoundEffects"); } +// bf2 0x8400940: this effector's own giveDamage (+0x24) of 1e8f on the player's soldier, from +// the player, typed with its side; side, player and soldier are read in that order. +// ELF 0x8400940. int BFGameEffector::suicide(IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFGameEffector::suicide"); + const int side = player->getSide(); + world::IPlayer* const from = player->getPlayer(); + IAIObject* const soldier = player->getSoldier(); + return giveDamage(soldier, from, side, 1e8f); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h index 452eb7f32..e17850424 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGameEffector.h @@ -34,7 +34,7 @@ class IAIGameEffector virtual int respawnBot(IAIPlayer* player) = 0; virtual void forceSpawnBot(IAIPlayer* player, const Vec3& position, const Vec3& rotation) = 0; virtual int giveDamage(IAIObject* target, world::IPlayer* from, int type, float amount) = 0; - virtual int playEffect(const Vec3& position, int a, int b) = 0; + virtual void playEffect(const Vec3& position, int a, int b) = 0; virtual void playSoundEffects(double dt) = 0; virtual int suicide(IAIPlayer* player) = 0; }; @@ -53,15 +53,22 @@ class BFGameEffector : public IAIGameEffector virtual int respawnBot(IAIPlayer* player); virtual void forceSpawnBot(IAIPlayer* player, const Vec3& position, const Vec3& rotation); virtual int giveDamage(IAIObject* target, world::IPlayer* from, int type, float amount); - virtual int playEffect(const Vec3& position, int a, int b); + virtual void playEffect(const Vec3& position, int a, int b); virtual void playSoundEffects(double dt); virtual int suicide(IAIPlayer* player); private: + void queueSoundEffect(const Vec3& position, int a, int b); + + // [INFERRED] Element name. Both ELF destructors iterate in 20-byte steps. + // [UNRESOLVED] Entry fields: the ELF queue/play methods are empty, so no writer exists. + struct SoundEffect + { + unsigned char unread[20]; + }; + /* +0x00 */ // vptr - /* +0x04 */ int m_unknown04; // [UNRESOLVED] - the constructor zeroes all three - /* +0x08 */ int m_unknown08; - /* +0x0C */ int m_unknown0C; + /* +0x04 */ std::vector m_soundEffects; // [INFERRED] name; native STL layout }; } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp index 65255ce12..4e56dc3b0 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp @@ -9,6 +9,7 @@ #include "AIFrontier.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h" #include "../../../Core/ClassManager.h" namespace dice { @@ -46,7 +47,7 @@ IBFGraph* BFGraphCreator::createGraph() void BFGraphCreator::destroyGraph(IBFGraph* graph) { - // ELF: `if (graph) graph->[vtable +0x04]` - Itanium's deleting destructor, which is what + // ELF 0x842E610: `if (graph) graph->[vtable +0x04]` - Itanium's deleting destructor, which is what // `delete` compiles to. The null guard is dice's and is kept. if (graph) delete graph; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp index 7dcf62585..516321c09 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp @@ -6,9 +6,13 @@ #include "AIFrontier.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/AIUtils/IAimerHelper.h" #include "../../../Core/ClassManager.h" #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods #include +#include +#include "IAIObject.h" +#include "IAIObjectPlugIn.h" // IAIObjectUnit::isOccupied #include "../../../Scene/Object/PlayerManager.h" // isValidPlayerId's one call #include "../../../Core/Ids.h" // the four container CIDs, IID_IPlayerControlObject #include "../../../Game/Objects/IObject.h" // getTemplate, getAIComponent @@ -19,15 +23,376 @@ #include "../../../Game/IGameLogic.h" // gameLogic: getPcoMap, giveDamage #include "../../../Game/Objects/GameLogicComp/IArmorGLComp.h" // getHitPoints / getMaxHitPoints #include "../../../Game/Objects/GameLogicComp/ArmorGLCompTemplate.h" // getCanBeDestroyed +#include "../../../Scene/Object/ObjectManager.h" // getObjectFromName +#include "BFTerrain.h" // IAITerrain::intersectTerrain (+0x64) #include "BFTimer.h" // IBFTimer::getGameTime +#include "../../../Game/GameLogic/CombatArea.h" // getAiCombatAreaLayer +#include "../../../Game/GameLogic/CombatAreaManager.h" +#include "../../../Game/Objects/DestroyableObjectTemplate.h" +#include "../../../Game/Objects/ObjectSpawnerTemplate.h" +#include "../../../Game/Objects/Game/TargetObject.h" +#include "../../../Scene/Object/ObjectTypes/Base/ObjectTemplateManager.h" +#include "../../../Game/IGame.h" +#include "../../../Core/Debug.h" +#include "../../../Math/LocalBoundingBox.h" +#include "AITemplate.h" +#include "AITemplateManager.h" +#include +#include "IWeapon.h" // hasIndirectLineOfFire's weapon reads +#include "BFPhysics.h" // IAIPhysics::getGravity +#include "../../../Core/Random.h" // g_random (ELF dice::hfe::Rand) +#include "../../../Game/Objects/Game/Soldier.h" // Soldier::getCameras +#include "../../../Game/Objects/ICameraObject.h" +#include "../../../Game/Objects/ObjectLayoutAccess.h" // the cached collision mesh (+0x40) +#include "../../../Physics/ICollisionMesh.h" // the sense mesh's faces and vertices +#include "../../../Physics/MaterialManager.h" // RayCastStopPredicate::predicateSurface +#include "../../../Physics/IPhysicsNode.h" // isAsleep +#include "../../../Physics/Material.h" +#include "../../../Scene/Object/ObjectPredicator.h" +#include namespace dice { namespace hfe { extern ClassManager* classManager; +namespace world { extern IBase* materialManager; } // ds:0x8AD2820 - Core/Globals.cpp + namespace ai { +// ELF 0x8400A30 / 0x8400A50. +TargetData::TargetData(unsigned int idValue, const Vec3& positionValue, IAIObject* objectValue) + : id(idValue), position(positionValue), object(objectValue) +{ +} + +// ELF 0x8400A70 / 0x8400A90. +TargetData::TargetData(const TargetData& other) + : id(other.id), position(other.position), object(other.object) +{ +} + +// ELF 0x8400AB0. The error can be filtered; then only id and object are copied. +TargetData& TargetData::operator=(const TargetData& other) +{ + Debug(DebugTypeError, "AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp", 75) + << "This does not work!"; + id = other.id; + object = other.object; + return *this; +} + +namespace { + +// ELF 0x840B200, 0x840B260, 0x840B270. +class DestroyableObjectsPredicate : public world::ObjectPredicator +{ +public: + virtual bool predicate(world::IObject* object) + { + world::IObjectTemplate* const objectTemplate = static_cast( + object->getTemplate()->queryInterface(world::IID_IObjectTemplate)); + return objectTemplate && objectTemplate->getClassID() == world::CID_DestroyableObjectTemplate + && static_cast(objectTemplate)->usedByAi; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } +}; + +// ELF 0x840B4F0, 0x840B540, 0x840B550 (the AI TU's predicate). +class NoMobilePredicate : public world::ObjectPredicator +{ +public: + virtual bool predicate(world::IObject* object) + { + if (!object->hasCollisionLod(0)) + return false; + world::IPhysicsNode* const node = static_cast( + world::object_detail::LayoutAccess::physicsNode(object)); + return !node || !node->getIsMobile(); + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } +}; + +// ELF 0x840B560, 0x840B590, 0x840B5A0. +class ObjectSpawnerPredicate : public world::ObjectPredicator +{ +public: + virtual bool predicate(world::IObject* object) + { + return object->getTemplate()->getClassID() == world::CID_ObjectSpawnerTemplate; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } +}; + +// ELF 0x840A1A0's inlined comparison orders only the signed endpoint pair. +struct Edge +{ + int first, second, index; + bool operator<(const Edge& other) const + { + return first == other.first ? second < other.second : first < other.first; + } +}; + +// bf2 0x8400BC0. The object's cached AI component; failing that, for the four container templates +// the occupying object's. The four tests are independent ifs, each overwriting the answer when its +// occupying object exists, as the image runs them in sequence. The parachute's +// IPlayerControlObject is used unchecked. +IAIObject* getIAIObject(world::IObject* object) +{ + IAIObject* aiObject = static_cast(object->getAIComponent()); // +0x34 + if (aiObject) + return aiObject; + + if (object->getTemplate()->getClassID() == world::CID_LadderContainerTemplate) + { + world::IObject* const occupying = + static_cast(object)->getOccupingObject(); // +0x18C + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (object->getTemplate()->getClassID() == world::CID_ParachuteTemplate) + { + world::IPlayerControlObject* const control = static_cast( + object->queryInterface(world::IID_IPlayerControlObject)); + world::IObject* const occupying = control->getOccupingObject(); // +0x14 + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (object->getTemplate()->getClassID() == world::CID_ZiplineContainerTemplate) + { + world::IObject* const occupying = + static_cast(object)->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (object->getTemplate()->getClassID() == world::CID_GrapplingHookRopeContainerTemplate) + { + world::IObject* const occupying = + static_cast(object)->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + return aiObject; +} + +// The TU's own one-slot object filter (typeinfo without a base, vtable of one entry). +class IObjectPredicate +{ +public: + virtual bool predicate(world::IObject* object) = 0; // +0x00 +}; + +// bf2 0x840B1D0 (vtable 0x88D75F8): objects with a collision LOD 0 (IObject slot 51). +class CollisionPredicate : public IObjectPredicate +{ +public: + virtual bool predicate(world::IObject* object) { return object->hasCollisionLod(0); } +}; + +// bf2 0x840B450. Pre-order: the object itself when the predicate (if any) takes it, then every +// object down its getChild chain (IObject +0xF0, read literally: the chain is followed through +// getChild, not the sibling link), each recursively. +void getAllChildren(world::IObject* object, std::vector& out, IObjectPredicate* filter) +{ + if (!filter || filter->predicate(object)) + out.push_back(object); + for (world::IObject* child = object->getChild(); child; child = child->getChild()) + getAllChildren(child, out, filter); +} + +// bf2 0x840B310 / 0x840B360 (vtable 0x88D75B0): the line test's stop filter. Objects whose AI +// object is in `ignore` do not stop the line; any other object is remembered for predicateSurface. +// With `seeThroughStops` a see-through surface (material +0x7C) does not stop the line either, but +// it records the squared distance from `from` to that object's position when nearer than the best +// so far; every other surface stops it. +class RayCastStopPredicate : public world::ObjectPredicator +{ +public: + RayCastStopPredicate(const std::vector& ignore, bool seeThroughStops, const Vec3& from) + : m_ignore(&ignore) + , m_seeThroughStops(seeThroughStops) + , m_nearestSeeThroughSq(FLT_MAX) + , m_from(from) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (aiObject) + { + for (std::vector::const_iterator it = m_ignore->begin(); it != m_ignore->end(); ++it) + if (aiObject == *it) + return false; + } + m_object = object; + return true; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + virtual bool predicateSurface(int surface) + { + world::Material* const material = static_cast(world::materialManager) + ->getMaterialPtr(static_cast(surface)); // +0x24 + if (!m_seeThroughStops || !material->getIsSeeThrough()) // +0x7C + return true; + const Vec3& position = m_object->getAbsolutePosition(); // +0x6C + Vec3 delta; + delta.x = m_from.x - position.x; + delta.y = m_from.y - position.y; + delta.z = m_from.z - position.z; + const float distanceSq = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + if (m_nearestSeeThroughSq > distanceSq) + m_nearestSeeThroughSq = distanceSq; + return false; + } + + /* +0x04 */ const std::vector* m_ignore; + /* +0x08 */ bool m_seeThroughStops; + /* +0x0C */ world::IObject* m_object; // left unset until predicate takes an object + /* +0x10 */ float m_nearestSeeThroughSq; + /* +0x14 */ Vec3 m_from; +}; + +// bf2 0x840B280 (vtable 0x88D75C8): the sphere pass's filter. Objects without an AI object pass; +// an object whose AI object is the primary object (IAIObject +0xFC) of a non-null `ignore` entry +// is refused. The flag is stored and never read. +class SphereExcludeFilter : public world::ObjectPredicator +{ +public: + SphereExcludeFilter(const std::vector& ignore, bool flag) + : m_ignore(&ignore) + , m_flag(flag) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (!aiObject) + return true; + for (std::vector::const_iterator it = m_ignore->begin(); it != m_ignore->end(); ++it) + { + if (*it && (*it)->getPrimaryObject() == aiObject) + return false; + } + return true; + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + + /* +0x04 */ const std::vector* m_ignore; + /* +0x08 */ bool m_flag; +}; + +// bf2 0x840B0C0 (vtable 0x88D7620): an engine-side wrapper of an AI filter. Objects without an AI +// object answer `noAIObject`; with one, the filter (if any) decides. +class AIPredWrapper : public world::ObjectPredicator +{ +public: + AIPredWrapper(AIObjectPredicate* filter, bool noAIObject) + : m_filter(filter) + , m_noAIObject(noAIObject) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (!aiObject) + return m_noAIObject; + if (!m_filter) + return true; + return m_filter->predicate(aiObject); + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + + /* +0x04 */ AIObjectPredicate* m_filter; + /* +0x08 */ bool m_noAIObject; +}; + +// bf2 0x840B130 / 0x840B180 (vtable 0x88D7608): AIPredWrapper's test, and see-through surfaces +// (material +0x7C) do not stop a line. +class AISeeingPredWrapper : public world::ObjectPredicator +{ +public: + AISeeingPredWrapper(AIObjectPredicate* filter, bool noAIObject) + : m_filter(filter) + , m_noAIObject(noAIObject) + { + } + + virtual bool predicate(world::IObject* object) + { + IAIObject* const aiObject = getIAIObject(object); + if (!aiObject) + return m_noAIObject; + if (!m_filter) + return true; + return m_filter->predicate(aiObject); + } + virtual unsigned int getFlags() const { return 0x1000000; } + virtual bool performCulling(world::IObject*) { return true; } + virtual bool predicateSurface(int surface) + { + world::Material* const material = static_cast(world::materialManager) + ->getMaterialPtr(static_cast(surface)); // +0x24 + return !material->getIsSeeThrough(); // +0x7C + } + + /* +0x04 */ AIObjectPredicate* m_filter; + /* +0x08 */ bool m_noAIObject; +}; + +// The image's inlined uniform draw, 2^-24 * ((((raw >> 7) | 1) + 1)), and the rounded index pick +// built on it: lo + (hi - lo) * draw + 0.5, truncated. [CHOSEN] helper spellings for inlined code. +inline float randomUnit() +{ + return static_cast(static_cast(((g_random.getRaw() >> 7) | 1u) + 1u)) * 5.9604645e-08f; +} + +inline unsigned int randomIndex(float hi) +{ + const float lo = 0.0f; + return static_cast(static_cast(lo + (hi - lo) * randomUnit() + 0.5f)); +} + +// Row-vector point transform, p * m (m[12..14] the translation). [CHOSEN] spelling of the inlined +// operator. +inline Vec3 transformPoint(const Vec3& p, const Mat4& m) +{ + Vec3 out; + out.x = p.x * m.m[0] + p.y * m.m[4] + p.z * m.m[8] + m.m[12]; + out.y = p.x * m.m[1] + p.y * m.m[5] + p.z * m.m[9] + m.m[13]; + out.z = p.x * m.m[2] + p.y * m.m[6] + p.z * m.m[10] + m.m[14]; + return out; +} + +// Common topology in ELF 0x8405F70 and 0x8407300. IDs are relative to zero even on append. +void appendBoxTopology(IAIObjectEnvironment::Mesh& mesh) +{ + static const std::pair edges[] = { + {0, 1}, {0, 2}, {0, 4}, {0, 6}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, + {2, 6}, {2, 7}, {3, 5}, {3, 7}, {4, 5}, {4, 6}, {4, 7}, {5, 7}, {6, 7} + }; + static const triple faces[] = { + {12, 10, 8}, {10, 17, 9}, {9, 3, 1}, {3, 14, 2}, {2, 6, 0}, {13, 7, 6}, + {17, 15, 14}, {15, 16, 13}, {16, 12, 11}, {11, 5, 7}, {8, 4, 5}, {4, 1, 0} + }; + mesh.edges.reserve(18); + for (unsigned int i = 0; i < 18; ++i) + mesh.edges.push_back(edges[i]); + for (unsigned int i = 0; i < 12; ++i) + mesh.faces.push_back(make_triple(faces[i].first, faces[i].second, faces[i].third)); +} + +} // namespace + // First wins in, exact match out. IAIObjectEnvironment::IAIObjectEnvironment() { @@ -49,47 +414,143 @@ IAIObjectEnvironment::~IAIObjectEnvironment() } } -// Zeroes the opaque vector storage, flag, and severe-damage timestamp separately. +// bf2 0x8400CA0: the three vectors default-constructed, the flag and severe-damage timestamp zeroed. // Leaves padding at +0x29..+0x2B untouched. BFObjectEnvironment::BFObjectEnvironment() { - std::memset(m_opaque, 0, sizeof(m_opaque)); // +0x04 .. +0x27, the three vectors m_byte28 = 0; // +0x28, a byte m_lastSevereDamageTime = 0.0; // +0x2C, a double } +// bf2 0x8400DA0: the members' destructors (the three vectors, last first). BFObjectEnvironment::~BFObjectEnvironment() { } +// bf2 0x8400F50 (Hex-Rays; listing for the call). The frustum query (object manager +0x50, flag +// true, 0.0, 0.0) into the scratch list through AIPredWrapper(filter, false), then each AI object. void BFObjectEnvironment::getWorldFrustumObjects(std::vector& out, const Frustum& frustum, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldFrustumObjects"); + std::vector& objects = const_cast&>(m_senseObjects); + objects.resize(0); + AIPredWrapper wrapper(filter, false); + world::objectManager->getObjectsFromGrid(frustum, objects, &wrapper, true, 0.0f, 0.0f); // +0x50 + pushAIObjects(out, objects); } +// bf2 0x84010C0 (Hex-Rays). As getWorldFrustumObjects with the sphere query (+0x40). void BFObjectEnvironment::getWorldSphereObjects(std::vector& out, const Vec3& centre, float radius, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldSphereObjects"); + std::vector& objects = const_cast&>(m_senseObjects); + objects.resize(0); + AIPredWrapper wrapper(filter, false); + world::objectManager->getObjectsFromGrid(centre, radius, objects, &wrapper); // +0x40 + pushAIObjects(out, objects); } +// bf2 0x8401230 (Hex-Rays). As getWorldFrustumObjects with the whole-grid query (+0x3C). void BFObjectEnvironment::getAllWorldObjects(std::vector& out, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllWorldObjects"); + std::vector& objects = const_cast&>(m_senseObjects); + objects.resize(0); + AIPredWrapper wrapper(filter, false); + world::objectManager->getObjectsFromGrid(objects, &wrapper); // +0x3C + pushAIObjects(out, objects); } void BFObjectEnvironment::getAllDestroyableObjects(std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllDestroyableObjects"); + // ELF 0x8401390. This query does not clear the scratch vector before dispatch. + DestroyableObjectsPredicate predicate; + std::vector& objects = const_cast&>(m_senseObjects); + world::objectManager->getObjectsFromGrid(objects, &predicate); + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + world::DestroyableObjectTemplate* const objectTemplate = + static_cast(static_cast( + (*it)->getTemplate()->queryInterface(world::IID_IObjectTemplate))); + DestroyableObject entry; + entry.initiallyWalkable = objectTemplate->initiallyWalkable; + entry.min = Vec3{objectTemplate->minCorner[0], objectTemplate->minCorner[1], objectTemplate->minCorner[2]}; + entry.max = Vec3{objectTemplate->maxCorner[0], objectTemplate->maxCorner[1], objectTemplate->maxCorner[2]}; + entry.transform = (*it)->getAbsoluteTransformation(); + out.push_back(entry); + } } +// bf2 0x8401670: every player in the player manager's list (+0x3C), its id (IPlayer +0x54). void BFObjectEnvironment::getWorldPlayerIds(std::vector& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldPlayerIds"); + const std::list& players = world::playerManager->getPlayers(); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + out.push_back((*it)->getId()); } +// bf2 0x8401700. Every alive, not man-down player with a vehicle contributes its vehicle's AI +// object (for ladder, zipline and grappling-hook containers the occupying object's, for a +// parachute the IPlayerControlObject's occupying object's, unchecked). A primary object (+0xF8) +// is taken directly (through the filter, if any); any other object contributes its primary object +// (+0xFC) to a set, and each set member whose unit is not occupied (IAIObjectUnit +0x48) is +// taken afterwards, also through the filter. void BFObjectEnvironment::getWorldPlayerOccupiedObjects(std::vector& out, AIObjectPredicate* filter) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getWorldPlayerOccupiedObjects"); + const std::list& players = world::playerManager->getPlayers(); + std::set primaries; + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + world::IPlayer* const player = *it; + if (!player || !player->getIsAlive() || player->getIsManDown() || !player->getVehicle()) + continue; + + IAIObject* aiObject = static_cast(player->getVehicle()->getAIComponent()); + if (!aiObject) + { + const unsigned int classId = player->getVehicle()->getTemplate()->getClassID(); + if (classId == world::CID_LadderContainerTemplate) + { + world::IObject* const occupying = + static_cast(player->getVehicle())->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + else if (player->getVehicle()->getTemplate()->getClassID() == world::CID_ParachuteTemplate) + { + world::IPlayerControlObject* const control = static_cast( + player->getVehicle()->queryInterface(world::IID_IPlayerControlObject)); + aiObject = static_cast(control->getOccupingObject()->getAIComponent()); + } + else if (player->getVehicle()->getTemplate()->getClassID() == world::CID_ZiplineContainerTemplate + || player->getVehicle()->getTemplate()->getClassID() + == world::CID_GrapplingHookRopeContainerTemplate) + { + world::IObject* const occupying = + static_cast(player->getVehicle())->getOccupingObject(); + if (occupying) + aiObject = static_cast(occupying->getAIComponent()); + } + if (!aiObject) + continue; + } + + if (aiObject->isPrimary()) + { + if (!filter || filter->predicate(aiObject)) + out.push_back(aiObject); + } + else + { + primaries.insert(aiObject->getPrimaryObject()); + } + } + + for (std::set::const_iterator it = primaries.begin(); it != primaries.end(); ++it) + { + IAIObject* const primary = *it; + if (primary->getUnit()->isOccupied()) + continue; + if (!filter || filter->predicate(primary)) + out.push_back(primary); + } } // Collects AI objects matching the supplied predicate within the requested region. @@ -146,29 +607,70 @@ void BFObjectEnvironment::getWorldPlayerOccupiedObjectsWithIds(std::vectorgetLocalHumanPlayer(); // +0x30 + if (!player) + return 0; + world::IObject* const vehicle = player->getVehicle(); // +0x48 + return vehicle ? static_cast(vehicle->getAIComponent()) : 0; } +// bf2 0x8403320 (Hex-Rays): the translation of the local human player's camera (IPlayer +0x180, +// as an IObject, unchecked). bool BFObjectEnvironment::getLocalPlayerPosition(Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getLocalPlayerPosition"); + if (!world::playerManager) + return false; + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + if (!player) + return false; + world::ICameraObject* const camera = player->getCamera(); // +0x180 + if (!camera) + return false; + world::IObject* const object = static_cast(camera->queryInterface(world::IID_IObject)); + const Mat4& transform = object->getAbsoluteTransformation(); + position.x = transform.m[12]; + position.y = transform.m[13]; + position.z = transform.m[14]; + return true; } +// bf2 0x84033A0 (Hex-Rays): the local human player's camera transformation (no player-manager +// null test here). bool BFObjectEnvironment::getLocalPlayerCameraTransformation(Mat4& transform) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getLocalPlayerCameraTransformation"); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + if (!player) + return false; + world::ICameraObject* const camera = player->getCamera(); + if (!camera) + return false; + world::IObject* const object = static_cast(camera->queryInterface(world::IID_IObject)); + transform = object->getAbsoluteTransformation(); + return true; } +// bf2 0x8403490 (Hex-Rays): the local human player's id, 0 without one. int BFObjectEnvironment::getLocalPlayerId() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getLocalPlayerId"); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + return player ? player->getId() : 0; } +// bf2 0x84034C0 (Hex-Rays): the ids of connected human players, rebuilt in the member list. const std::vector& BFObjectEnvironment::getActivePlayerIds() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getActivePlayerIds"); + const std::list& players = world::playerManager->getPlayers(); // +0x3C + std::vector& ids = const_cast&>(m_activePlayerIds); + ids.resize(0); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + if (!(*it)->getIsAIPlayer() && (*it)->getIsConnected()) // +0x64, +0x78 + ids.push_back((*it)->getId()); + } + return m_activePlayerIds; } // Returns whether PlayerManager resolves the id to a player. @@ -177,105 +679,613 @@ bool BFObjectEnvironment::isValidPlayerId(int id) const return world::playerManager->getPlayerFromId(id) != 0; } +// bf2 0x8403600. The player after `id` (+0x24 getNextPlayerFromId) is answered when it is a +// connected human; AI players and disconnected ones are skipped by asking again with the same +// id, which returns the same player, so the loop ends at -1. Read literally. int BFObjectEnvironment::getNextPlayerId(int id) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getNextPlayerId"); + world::IPlayer* const first = world::playerManager->getNextPlayerFromId(id); + if (!first) + return -1; + world::IPlayer* player = first; + do + { + if (!player->getIsAIPlayer() && player->getIsConnected()) + return player->getId(); + player = world::playerManager->getNextPlayerFromId(id); + } + while (player != first); + return -1; } +// bf2 0x8401DD0 (ELF listing, Ghidra cross-check). The terrain first (IAITerrain +0x64 +// intersectTerrain into zeroed scratch); a terrain hit is a hit. Otherwise the answer is the +// object test (this +0x90, collideLineWithObjects) with every argument forwarded. The image also +// computes `to - from` into a local that nothing reads; it is left out. bool BFObjectEnvironment::collideLineWithWorld(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::collideLineWithWorld"); + Vec3 terrainHit; + terrainHit.x = 0.0f; + terrainHit.y = 0.0f; + terrainHit.z = 0.0f; + Vec3 terrainNormal; + terrainNormal.x = 0.0f; + terrainNormal.y = 0.0f; + terrainNormal.z = 0.0f; + float distance; + if (static_cast(CommonSingletonServer::m_iaiTerrain) + ->intersectTerrain(from, to, terrainHit, distance, terrainNormal)) // +0x64 + return true; + return collideLineWithObjects(from, to, ignore, a, b, c, hit) != 0; // +0x90 } +// bf2 0x8401FF0 (listing). Objects first: intersectLine (+0x68, flags 1, 0, 0, 1, mask 0) along +// `to - from` through AISeeingPredWrapper(filter, true), or no predicate at all without a filter; +// then the terrain (IAITerrain +0x64). The hit point goes to `hit`, or a local when it is null. bool BFObjectEnvironment::collideLineWithWorld(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, Vec3* hit) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::collideLineWithWorld"); + Vec3 localHit; + localHit.x = 0.0f; + localHit.y = 0.0f; + localHit.z = 0.0f; + Vec3& hitPoint = hit ? *hit : localHit; + Vec3 normal; + normal.x = 0.0f; + normal.y = 0.0f; + normal.z = 0.0f; + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + AISeeingPredWrapper wrapper(filter, true); + world::IObject* hitObject; + int hitPart; + if (world::objectManager->intersectLine(hitObject, hitPoint, normal, hitPart, from, direction, + filter ? &wrapper : 0, true, false, false, true, 0)) // +0x68 + return true; + float distance; + return static_cast(CommonSingletonServer::m_iaiTerrain) + ->intersectTerrain(from, to, hitPoint, distance, normal) != 0; // +0x64 } +// bf2 0x8401EC0 (Hex-Rays; listing for the calls). The first object hit along `to - from` +// (AIPredWrapper(filter, true), or none without a filter), else the terrain hit; `height` is that +// point's y. False when neither is hit (height untouched). bool BFObjectEnvironment::getMaxHeight(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, float& height) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getMaxHeight"); + AIPredWrapper wrapper(filter, true); + Vec3 hitPoint; + hitPoint.x = 0.0f; + hitPoint.y = 0.0f; + hitPoint.z = 0.0f; + Vec3 normal; + normal.x = 0.0f; + normal.y = 0.0f; + normal.z = 0.0f; + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + world::IObject* hitObject; + int hitPart; + float distance; + if (world::objectManager->intersectLine(hitObject, hitPoint, normal, hitPart, from, direction, + filter ? &wrapper : 0, true, false, false, true, 0) + || static_cast(CommonSingletonServer::m_iaiTerrain) + ->intersectTerrain(from, to, hitPoint, distance, normal)) + { + height = hitPoint.y; + return true; + } + return false; } +// Engine ELF 0x84022F0 (amd-64 0x7715E0). Tests both segments through the helper's apex. +// shipped defect: this calls pure IAimerHelper slot 2, not AimerHelper's by-value-float slot 3. +// No AimerHelper is constructed in either AI image; no null guard is added to the retail call. bool BFObjectEnvironment::hasIndirectLineOfFire(IWeapon* weapon, const Vec3& from, const Vec3& to, const std::vector& ignore) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::hasIndirectLineOfFire"); + static Vec3 zero = { 0.0f, 0.0f, 0.0f }; + (void)zero; + const float gravity = static_cast(CommonSingletonServer::m_iaiPhysics)->getGravity(); // +0x08 + Vec3 predictedTarget = {0.0f, 0.0f, 0.0f}; + Vec3 velocity = {0.0f, 0.0f, 0.0f}; + Vec3 apex = {0.0f, 0.0f, 0.0f}; + const Vec3& weaponPosition = weapon->getPosition(); // +0x5C + Vec3 delta; + delta.x = to.x - from.x; + delta.y = to.y - from.y; + delta.z = to.z - from.z; + const float scaledGravity = weapon->getGravityModifier() * gravity; // +0x80 + const float drag = weapon->getDrag(); // +0x7C + const float exitVelocity = weapon->getExitVelocity(); // +0x84 + if (!static_cast(CommonSingletonServer::m_iAimerHelper)->unimplementedAimerSlot2( + &exitVelocity, &drag, &scaledGravity, &delta, &weaponPosition, &predictedTarget, &velocity, &apex)) + return false; + bool hit; + return !collideLineWithWorld(from, apex, ignore, false, 0.0f, false, hit) + && !collideLineWithWorld(apex, to, ignore, false, 0.0f, false, hit); } -void BFObjectEnvironment::pickRandomSensePosition(Vec3& position, Vec3& normal, Vec3 hint, IAIObject* object) +// bf2 0x84024B0 (ELF listing; Hex-Rays cross-check). A random point on the object's collision +// surface, in world space (`position`) and in the root object's frame (`localPosition`). The +// scratch list is the root and its getChild chain with a collision LOD 0. While no mesh is found +// and there is more than one candidate, a random candidate's collision mesh (IObject +0x40) is +// taken when it has LOD 0; failing that the first candidate's, unchecked. With faces, a random +// face and a uniform point in it (the u + v > 1 half folded back); with vertices only, a random +// vertex; with neither (or no candidates) the object's position and a zero local point. `hint` is +// not read. The object's bounding radius is fetched and discarded on the fallback path. +void BFObjectEnvironment::pickRandomSensePosition(Vec3& position, Vec3& localPosition, Vec3 hint, IAIObject* object) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::pickRandomSensePosition"); + world::IObject* const root = object->getObject(); // +0x20 + m_senseObjects.resize(0); + + CollisionPredicate collision; + getAllChildren(root, m_senseObjects, &collision); + + if (!m_senseObjects.empty()) + { + Mat4 rootInverse = root->getAbsoluteTransformation(); // slot 33 + const Mat4 rootTransform = rootInverse; + rootInverse.setInverse(rootTransform); + + world::ICollisionMesh* mesh = 0; + world::IObject* chosen = 0; + while (!mesh && m_senseObjects.size() > 1) + { + chosen = m_senseObjects[randomIndex(static_cast(m_senseObjects.size()) - 1.0f)]; + if (chosen->hasCollisionLod(0)) + mesh = static_cast(world::object_detail::LayoutAccess::collisionMesh(chosen)); + } + if (!mesh) + { + chosen = m_senseObjects[0]; + if (chosen->hasCollisionLod(0)) + mesh = static_cast(world::object_detail::LayoutAccess::collisionMesh(chosen)); + } + + const unsigned int faceCount = static_cast(mesh->getFaceCount(0)); // slot 19 + const unsigned int vertexCount = mesh->getVertexCount(0); // slot 16 + Vec3 world; + if (faceCount) + { + const unsigned int face = randomIndex(static_cast(faceCount) - 1.0f); + float u = randomUnit(); + float v = randomUnit(); + if (u + v > 1.0f) + { + u = 1.0f - u; + v = 1.0f - v; + } + const unsigned short* const faces = static_cast(mesh->getFaceVector(0)); // slot 20 + const Vec3* const vertices = static_cast(mesh->getVertexVector(0)); // slot 17 + const unsigned short* const f = faces + face * 4; // 8-byte faces + const Vec3& p0 = vertices[f[0]]; + Vec3 edge1; + edge1.x = vertices[f[1]].x - p0.x; + edge1.y = vertices[f[1]].y - p0.y; + edge1.z = vertices[f[1]].z - p0.z; + Vec3 edge2; + edge2.x = vertices[f[2]].x - p0.x; + edge2.y = vertices[f[2]].y - p0.y; + edge2.z = vertices[f[2]].z - p0.z; + localPosition.x = p0.x + edge1.x * u + edge2.x * v; + localPosition.y = p0.y + edge1.y * u + edge2.y * v; + localPosition.z = p0.z + edge1.z * u + edge2.z * v; + world = transformPoint(localPosition, chosen->getAbsoluteTransformation()); + } + else if (vertexCount) + { + const unsigned int vertex = randomIndex(static_cast(vertexCount - 1)); + localPosition = static_cast(mesh->getVertexVector(0))[vertex]; + world = transformPoint(localPosition, chosen->getAbsoluteTransformation()); + } + else + { + // The same fallback as an empty list (the image shares the block). + object->getBoundingRadius(); // +0xE8, unused + localPosition.x = 0.0f; + localPosition.y = 0.0f; + localPosition.z = 0.0f; + position = object->getPosition(); // +0xD4 + return; + } + position = world; + localPosition = transformPoint(world, rootInverse); + return; + } + + object->getBoundingRadius(); // +0xE8, unused + localPosition.x = 0.0f; + localPosition.y = 0.0f; + localPosition.z = 0.0f; + position = object->getPosition(); // +0xD4 } -bool BFObjectEnvironment::pickSoldierRandomSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int& part) +// bf2 0x8403010 (listing; Hex-Rays cross-check), byte-identical to getSoldierSensePosition: for a +// soldier (object with an IObject, IAIObject +0xA4 isOfType(ITSoldier), template implementing +// CID_SoldierTemplate) the first camera of Soldier::getCameras (the map's leftmost entry, unchecked) +// as an IObject: its absolute position and its relative position. `part` is neither read nor written. +bool BFObjectEnvironment::pickSoldierRandomSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int& part) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::pickSoldierRandomSensePosition"); + if (!object->getObject() || !object || !object->isOfType(ITSoldier)) // +0x20, +0xA4 + return false; + world::IObject* const soldier = object->getObject(); + if (!const_cast(soldier->getTemplate()) + ->queryImplementation(world::CID_SoldierTemplate)) // +0x50 + return false; + + world::ICameraObject* const camera = + static_cast(soldier)->getCameras()->begin()->second; // +0x1A4 + world::IObject* cameraObject = 0; + if (camera) + cameraObject = static_cast(camera->queryInterface(world::IID_IObject)); + position = cameraObject->getAbsolutePosition(); // +0x6C + localPosition = cameraObject->getRelativePosition(); // +0xE0 + return true; } -bool BFObjectEnvironment::getSoldierSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int part) +// bf2 0x8403100 (listing; Hex-Rays cross-check). See pickSoldierRandomSensePosition; `part` unused. +bool BFObjectEnvironment::getSoldierSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int part) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getSoldierSensePosition"); + if (!object->getObject() || !object || !object->isOfType(ITSoldier)) // +0x20, +0xA4 + return false; + world::IObject* const soldier = object->getObject(); + if (!const_cast(soldier->getTemplate()) + ->queryImplementation(world::CID_SoldierTemplate)) // +0x50 + return false; + + world::ICameraObject* const camera = + static_cast(soldier)->getCameras()->begin()->second; // +0x1A4 + world::IObject* cameraObject = 0; + if (camera) + cameraObject = static_cast(camera->queryInterface(world::IID_IObject)); + position = cameraObject->getAbsolutePosition(); // +0x6C + localPosition = cameraObject->getRelativePosition(); // +0xE0 + return true; } +// bf2 0x84031F0 (listing). `slope` is the physical plug-in's smallest radius (+0x94, +0x44); +// height and normal are the terrain's at the position's x/z (IAITerrain +0x28). The object's +// position and an isOfType(ITSoldier) answer are fetched, and a probe segment from radius above +// the object's height down by 2 * radius is built, but none of them is used. Returns 0. int BFObjectEnvironment::getHeightAndNormalForObject(IAIObject* object, const Vec3& position, float& height, Vec3& normal, float& slope) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getHeightAndNormalForObject"); + const float radius = object->getPhysical()->getSmallestRadius(); + slope = radius; + const Vec3 objectPosition = object->getPosition(); // +0xD4 + object->isOfType(ITSoldier); // +0xA4, unused + Vec3 probeFrom; + probeFrom.x = position.x; + probeFrom.y = radius + objectPosition.y; + probeFrom.z = position.z; + Vec3 probeDelta; + probeDelta.x = 0.0f; + probeDelta.y = radius * -2.0f; + probeDelta.z = 0.0f; + (void)probeFrom; + (void)probeDelta; + Vec3 terrainNormal; + terrainNormal.x = 0.0f; + terrainNormal.y = 0.0f; + terrainNormal.z = 0.0f; + unsigned char material; + height = static_cast(CommonSingletonServer::m_iaiTerrain) + ->getHeightAndNormal(position.x, position.z, terrainNormal, material); // +0x28 + normal = terrainNormal; + return 0; } -void BFObjectEnvironment::getVehicleSpawnerPositions(std::vector& out, unsigned char team) const +// ELF 0x8403770. The team parameter is unused; the object map is copied before iteration. +void BFObjectEnvironment::getVehicleSpawnerPositions(std::vector& out, unsigned char /*team*/) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getVehicleSpawnerPositions"); + const std::map objects = world::objectManager->getAllObjectsFromGrid(); + for (std::map::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + world::IObject* const object = it->second; + if (object->getNotInAI() || object->getTemplate()->getClassID() != world::CID_ObjectSpawnerTemplate) + continue; + const world::ObjectSpawnerTemplate* const spawner = + static_cast(object->getTemplate()); + for (unsigned int slot = 0; slot <= 2; ++slot) + { + const std::string name = spawner->getObjectTemplate(slot); + world::IObjectTemplate* const objectTemplate = world::objectTemplateManager->getTemplate(name); + if (!objectTemplate) + break; + world::SimpleObjectTemplate* const simple = static_cast( + objectTemplate->queryImplementation(world::CID_SimpleObjectTemplate)); + if (simple) + { + const std::string aiName = simple->m_aiTemplate; + if (!aiName.empty()) + { + AITemplate* const aiTemplate = AITemplateManager::m_instance->getTemplate(aiName); + if (aiTemplate && !(aiTemplate->m_types & 4) && aiTemplate->isMobile()) + out.push_back(object->getAbsolutePosition()); + } + } + } + } } +// bf2 0x8403680: the object manager's name lookup (+0x24), its cached AI component (+0x34). IAIObject* BFObjectEnvironment::getObjectFromName(const std::string& name) { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getObjectFromName"); + world::IObject* const object = world::objectManager->getObjectFromNameHash(name); + return object ? static_cast(object->getAIComponent()) : 0; } -int BFObjectEnvironment::getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const +// bf2 0x84036B0 (Hex-Rays; listing). The boundary query (+0x6C) over the primary terrain's +// extent (IAITerrain +0x54 .. +0x60, as floats). +bool BFObjectEnvironment::getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllStaticCollisionMeshes"); + IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); + Vec2 min; + min.x = static_cast(terrain->getPrimaryWorldMinX()); + min.y = static_cast(terrain->getPrimaryWorldMinZ()); + Vec2 max; + max.x = static_cast(terrain->getPrimaryWorldMaxX()); + max.y = static_cast(terrain->getPrimaryWorldMaxZ()); + return getAllStaticCollisionMeshesWithinBoundary(min, max, meshes, water, addOns, more, bounds, team); } -int BFObjectEnvironment::getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const +bool BFObjectEnvironment::getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAllStaticCollisionMeshesWithinBoundary"); + // ELF 0x8403B20. The team parameter does not participate in this query. + (void)team; + std::vector objects; + Vec3 boxMin = {0.0f, 0.0f, 0.0f}, boxMax = {0.0f, 0.0f, 0.0f}; + NoMobilePredicate noMobile; + ObjectSpawnerPredicate spawners; + vec2ToVec3XZ(min, boxMin); + vec2ToVec3XZ(max, boxMax); + world::objectManager->getObjectsInBoxFromGrid(boxMin, boxMax, objects, &noMobile); + world::objectManager->getObjectsInBoxFromGrid(boxMin, boxMax, objects, &spawners); + std::pair combatBounds; + combatBounds.first = Vec2{0.0f, 0.0f}; + combatBounds.second = Vec2{0.0f, 0.0f}; + createBoundingBoxFromCombatAreas(combatBounds); + bounds = combatBounds; + + for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) + { + world::IObject* const object = *it; + world::IObjectTemplate* const objectTemplate = static_cast( + object->getTemplate()->queryInterface(world::IID_IObjectTemplate)); + if (!objectTemplate) + continue; + const std::string& name = objectTemplate->getName(); + objectTemplate->getClassID(); // The shipped body discards this query. + if (object->getNotInAI()) + continue; + if (object->getTemplate()->getClassID() != world::CID_ObjectSpawnerTemplate) + { + if (hasOnlyInfantryCollMesh(object) || !objectOverlapsCombatAreas(object, bounds)) + continue; + const Mat4& transform = object->getAbsoluteTransformation(); + if (object->hasCollisionLod(3)) + { + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(object)); + if (objectTemplate->getClassID() == world::CID_DestroyableObjectTemplate) + { + world::DestroyableObjectTemplate* const destroyable = + static_cast(objectTemplate); + if (destroyable->usedByAi) + { + DestroyableAddOnMesh entry; + entry.name = object->getTemplate()->getName(); + entry.initiallyWalkable = destroyable->initiallyWalkable; + const Vec3 low = {destroyable->minCorner[0], destroyable->minCorner[1], destroyable->minCorner[2]}; + const Vec3 high = {destroyable->maxCorner[0], destroyable->maxCorner[1], destroyable->maxCorner[2]}; + createBoundingBoxFromLocalCoordinates(low, high, transform, entry.mesh); + const IAIObject* const aiObject = static_cast(object->getAIComponent()); + addOns.insert(std::make_pair(aiObject, entry)); + } + if (!destroyable->initiallyWalkable) + continue; + } + const bool ladder = objectTemplate->getClassID() == world::CID_LadderTemplate; + std::list& output = ladder ? more : meshes; + { + MeshAndBoundingBox entry; + entry.name = name; + // shipped defect: the owner is copied before it is assigned below. + output.push_back(entry); + } + MeshAndBoundingBox& entry = output.back(); + entry.object = static_cast(object->getAIComponent()); + createMeshFromObject(collision, 3, transform, entry.mesh); + const LocalBoundingBox* const box = collision->getBoundingBox(3); + createBoundingBoxFromLocalCoordinates(box->m_min, box->m_max, transform, entry.boundingBox); + } + else if (object->hasCollisionLod(0)) + { + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(object)); + std::vector>* const materials = objectTemplate->getMaterialVector(); + const int count = static_cast(materials->size()); + bool hasWater = false; + for (int i = 0; i < count; ++i) + { + world::Material* const material = static_cast(world::materialManager) + ->getMaterialPtr((*materials)[i].second); + if (material->getHasWaterPhysics()) + { + hasWater = true; + break; + } + } + if (hasWater) + { + WaterMesh entry; // The retail name stays empty. + createMeshFromObject(collision, 0, transform, entry.mesh); + water.push_back(entry); + } + } + continue; + } + + const world::ObjectSpawnerTemplate* const spawner = + static_cast(object->getTemplate()); + bool valid[3] = {false, false, false}; + Mesh slotMeshes[3]; + bool rejected = false; + for (unsigned int slot = 0; slot <= 2; ++slot) + { + const std::string templateName = spawner->getObjectTemplate(slot); + world::IObjectTemplate* const spawnedTemplate = world::objectTemplateManager->getTemplate(templateName); + if (!spawnedTemplate) + continue; + const Vec3 rotation = Vec3::getZero(); + const Vec3 position = Vec3::getZero(); + world::IObject* const spawned = gameLogic->spawnObject(spawnedTemplate, position, rotation, 0); + if (spawned->queryInterface(world::IID_IPlayerControlObject)) + { + world::IPhysicsNode* const node = static_cast( + world::object_detail::LayoutAccess::physicsNode(spawned)); + if (node && node->getIsMobile()) + { + game->destroyObject(spawned); + rejected = true; + break; + } + } + world::IObjectTemplate* const spawnedObjectTemplate = static_cast( + spawned->getTemplate()->queryInterface(world::IID_IObjectTemplate)); + if (spawnedObjectTemplate->getClassID() == world::CID_DestroyableObjectTemplate + && static_cast(spawnedObjectTemplate)->usedByAi) + { + game->destroyObject(spawned); + rejected = true; + break; + } + const Mat4& transform = object->getAbsoluteTransformation(); + if (spawned->hasCollisionLod(3)) + { + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(spawned)); + const LocalBoundingBox* const box = collision->getBoundingBox(3); + createBoundingBoxFromLocalCoordinates(box->m_min, box->m_max, transform, slotMeshes[slot]); + game->destroyObject(spawned); + valid[slot] = true; + } + else + game->destroyObject(spawned); + } + if (rejected || (!valid[0] && !valid[1] && !valid[2])) + continue; + { + MeshAndBoundingBox entry; + entry.name = name; + meshes.push_back(entry); + } + MeshAndBoundingBox& entry = meshes.back(); + entry.object = 0; + Vec3 low = {100000.0f, 100000.0f, 100000.0f}; + Vec3 high = {-100000.0f, -100000.0f, -100000.0f}; + for (unsigned int slot = 0; slot <= 2; ++slot) + { + if (!valid[slot]) + continue; + for (unsigned int i = 0; i < slotMeshes[slot].vertices.size(); ++i) + { + const Vec3& p = slotMeshes[slot].vertices[i]; + if (low.x > p.x) low.x = p.x; + if (low.y > p.y) low.y = p.y; + if (low.z > p.z) low.z = p.z; + if (p.x > high.x) high.x = p.x; + if (p.y > high.y) high.y = p.y; + if (p.z > high.z) high.z = p.z; + } + } + createBoundingBoxFromWorldCoordinates(low, high, entry.boundingBox); + createBoundingBoxFromWorldCoordinates(low, high, entry.mesh); + } + bounds.first.x -= 3.0f; + bounds.first.y -= 3.0f; + bounds.second.x += 3.0f; + bounds.second.y += 3.0f; + return true; } +// bf2 0x8405840 (Hex-Rays): an object in the grid (object manager +0x30) without a physics node, +// or whose node sleeps (+0x11C). Unknown ids are not asleep. bool BFObjectEnvironment::isAsleep(unsigned int id) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::isAsleep"); + world::IObject* const object = world::objectManager->getObjectFromGrid(id); + if (!object) + return false; + world::IPhysicsNode* const node = + static_cast(world::object_detail::LayoutAccess::physicsNode(object)); // +0x44 + return !node || node->getIsSleeping(); } -int BFObjectEnvironment::getTargetObjects(std::vector& out, int team) const +// ELF 0x8405740. The target map's owning player determines the team filter. +void BFObjectEnvironment::getTargetObjects(std::vector& out, int team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getTargetObjects"); + const std::map* const objects = + static_cast*>(gameLogic->getTargetObjectMap()); + for (std::map::const_iterator it = objects->begin(); it != objects->end(); ++it) + { + world::IObject* const object = it->second; + world::IPlayer* const player = world::playerManager->getPlayerFromId( + static_cast(object)->getTargetPlayerId()); + if (player && player->getTeam() == team) + { + IAIObject* const aiObject = static_cast(world::getRootParent(object)->getAIComponent()); + const Vec3& position = object->getAbsolutePosition(); + out.push_back(TargetData(it->first, position, aiObject)); + } + } } -// ELF, 10 bytes. Empty in the dedicated image. -void BFObjectEnvironment::loadOvergrowthCollision(const std::string& path) const +// bf2 0x8405890, 10 bytes: `mov eax, 1` and return; the materialised 1 is why the declaration +// returns bool (the mangled name carries no return type). +bool BFObjectEnvironment::loadOvergrowthCollision(const std::string& path) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::loadOvergrowthCollision"); + return true; } bool BFObjectEnvironment::initAiCombatAreas() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::initAiCombatAreas"); + // ELF 0x84058A0. Capture the singleton before resizing the vector. + CombatAreaManager* const manager = CombatAreaManager::getInstance(); + std::vector& areas = const_cast&>(m_combatAreas); + areas.resize(0); + return manager->getAiCombatAreas(areas); } bool BFObjectEnvironment::isAiPositionInsideCombatArea(const Vec3& position) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::isAiPositionInsideCombatArea"); + // ELF 0x8405930. + return CombatAreaManager::getInstance()->isAiPositionInside(position, m_combatAreas); } +// bf2 0x8405960 (Hex-Rays; listing): the first AI combat area's layer, read as a byte (movzbl +// of +0x30), or 255 without one. int BFObjectEnvironment::getAiCombatAreaLayer() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAiCombatAreaLayer"); + int layer = 255; + if (m_combatAreas.size()) + layer = *reinterpret_cast(&m_combatAreas[0]->m_layer); + return layer; } -int BFObjectEnvironment::getAICombatArea(std::list& out) const +// ELF 0x8405990. Always clear the output, then orient the first area's polygon clockwise. +void BFObjectEnvironment::getAICombatArea(std::list& out) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::getAICombatArea"); + out.clear(); + if (m_combatAreas.empty()) + return; + const CombatArea* const area = m_combatAreas[0]; + if (area->isClockwise()) + for (std::vector::const_iterator it = area->m_points.begin(); it != area->m_points.end(); ++it) + out.push_back(*it); + else + for (std::vector::const_reverse_iterator it = area->m_points.rbegin(); it != area->m_points.rend(); ++it) + out.push_back(*it); } // Updates the AI object environment during the simulation tick. @@ -336,9 +1346,224 @@ void BFObjectEnvironment::damageSeverelyDamagedVehicles() } } -int BFObjectEnvironment::collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit) +// bf2 0x8402130 (listing; Hex-Rays cross-check). The object line test from `from` along +// `to - from`: without spheres the object manager's intersectLine (+0x68, flags 1, 0, 0, 1, mask 0) +// through a RayCastStopPredicate; with spheres intersectLineWithSpheres (+0x70) with a +// SphereExcludeFilter first and the stop predicate second, `sphereRadius` last. `hitBeyondSeeThrough` +// is whether the hit point lies farther from `from` than the nearest see-through surface the stop +// predicate skipped (always false when none was). Returns the intersection's answer. +// bf2 0x8408350 (Hex-Rays). Reserves for the new objects, then appends each object's AI object +// (getIAIObject), skipping objects without one. `objects` is taken by value. +void BFObjectEnvironment::pushAIObjects(std::vector& out, std::vector objects) const +{ + out.reserve(objects.size() + out.size()); + for (std::vector::iterator it = objects.begin(); it != objects.end(); ++it) + { + IAIObject* const aiObject = getIAIObject(*it); + if (aiObject) + out.push_back(aiObject); + } +} + +int BFObjectEnvironment::collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool useSpheres, float sphereRadius, bool seeThroughStops, bool& hitBeyondSeeThrough) +{ + Vec3 hitPoint; + hitPoint.x = 0.0f; + hitPoint.y = 0.0f; + hitPoint.z = 0.0f; + Vec3 hitNormal; + hitNormal.x = 0.0f; + hitNormal.y = 0.0f; + hitNormal.z = 0.0f; + Vec3 unused; // a third zeroed Vec3 (-0x38), never passed + unused.x = 0.0f; + unused.y = 0.0f; + unused.z = 0.0f; + (void)unused; + RayCastStopPredicate stop(ignore, seeThroughStops, from); + world::IObject* hitObject; + int hitPart; + bool result; + if (useSpheres) + { + SphereExcludeFilter exclude(ignore, seeThroughStops); + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + result = world::objectManager->intersectLineWithSpheres(hitObject, hitPoint, hitNormal, hitPart, + from, direction, &exclude, &stop, + sphereRadius); // +0x70 + } + else + { + Vec3 direction; + direction.x = to.x - from.x; + direction.y = to.y - from.y; + direction.z = to.z - from.z; + result = world::objectManager->intersectLine(hitObject, hitPoint, hitNormal, hitPart, from, + direction, &stop, true, false, false, true, 0); // +0x68 + } + const float dx = hitPoint.x - from.x; + const float dy = hitPoint.y - from.y; + const float dz = hitPoint.z - from.z; + hitBeyondSeeThrough = dx * dx + dy * dy + dz * dz > stop.m_nearestSeeThroughSq; + return result; +} + +// ELF 0x8405C30. Each face contributes undirected edges, stored once in insertion order. +void BFObjectEnvironment::createMeshFromObject(world::ICollisionMesh* collision, int lod, + const Mat4& transform, Mesh& mesh) const +{ + const Vec3* const vertices = static_cast(collision->getVertexVector(lod)); + const int vertexCount = static_cast(collision->getVertexCount(lod)); + mesh.vertices.reserve(static_cast(vertexCount)); + for (int i = 0; i < vertexCount; ++i) + mesh.vertices.push_back(transformPoint(vertices[i], transform)); + + std::set uniqueEdges; + const int faceCount = collision->getFaceCount(lod); + // Three unsigned 16-bit indices in an eight-byte record; the last word is not read here. + struct ExportFace { unsigned short indices[3]; unsigned char unread[2]; }; + const ExportFace* const faces = static_cast(collision->getFaceVector(lod)); + for (int i = 0; i < faceCount; ++i) + { + int previous = faces[i].indices[2]; + triple triangle; + for (int j = 0; j <= 2; ++j) + { + const int current = faces[i].indices[j]; + const Edge edge = {previous < current ? previous : current, + current < previous ? previous : current, + static_cast(mesh.edges.size())}; + const std::pair::iterator, bool> inserted = uniqueEdges.insert(edge); + if (inserted.second) + mesh.edges.push_back(std::make_pair(inserted.first->first, inserted.first->second)); + // ELF 0x840A100: insert_in_triple(triangle, 2 - j, index). + if (j == 0) triangle.third = inserted.first->index; + else if (j == 1) triangle.second = inserted.first->index; + else triangle.first = inserted.first->index; + previous = current; + } + mesh.faces.push_back(triangle); + } +} + +// ELF 0x8405F70. Corner ordering uses x/y/z bits 4/2/1, then the shared box topology. +void BFObjectEnvironment::createBoundingBoxFromLocalCoordinates(const Vec3& min, const Vec3& max, + const Mat4& transform, Mesh& mesh) const +{ + mesh.vertices.reserve(8); + for (unsigned int i = 0; i < 8; ++i) + { + const Vec3 corner = {(i & 4) ? max.x : min.x, (i & 2) ? max.y : min.y, (i & 1) ? max.z : min.z}; + mesh.vertices.push_back(transformPoint(corner, transform)); + } + appendBoxTopology(mesh); +} + +// ELF 0x8407300. +void BFObjectEnvironment::createBoundingBoxFromWorldCoordinates(const Vec3& min, const Vec3& max, Mesh& mesh) const +{ + mesh.vertices.reserve(8); + for (unsigned int i = 0; i < 8; ++i) + { + const Vec3 corner = {(i & 4) ? max.x : min.x, (i & 2) ? max.y : min.y, (i & 1) ? max.z : min.z}; + mesh.vertices.push_back(corner); + } + appendBoxTopology(mesh); +} + +// ELF 0x84083F0. Every area's vertices participate, including exclusions. +void BFObjectEnvironment::createBoundingBoxFromCombatAreas(std::pair& bounds) const +{ + Vec2 low = {100000.0f, 100000.0f}; + Vec2 high = {-100000.0f, -100000.0f}; + for (unsigned int i = 0; i < m_combatAreas.size(); ++i) + { + const std::vector& points = m_combatAreas[i]->m_points; + for (unsigned int j = 0; j < points.size(); ++j) + { + if (low.x > points[j].x) low.x = points[j].x; + if (low.y > points[j].y) low.y = points[j].y; + if (points[j].x > high.x) high.x = points[j].x; + if (points[j].y > high.y) high.y = points[j].y; + } + } + bounds.first = low; + bounds.second = high; +} + +// ELF 0x8408500. Walk each transformed bottom edge in unit XZ steps until an AI area accepts it. +bool BFObjectEnvironment::objectOverlapsCombatAreas(const world::IObject* object, + std::pair& bounds) const +{ + if (!object->hasCollisionLod(3)) + return false; + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(const_cast(object))); + const LocalBoundingBox* const box = collision->getBoundingBox(3); + CombatAreaManager* const manager = CombatAreaManager::getInstance(); + const Mat4& transform = object->getAbsoluteTransformation(); + std::vector points; + const Vec3 corners[4] = { + transformPoint(Vec3{box->m_min.x, box->m_min.y, box->m_min.z}, transform), + transformPoint(Vec3{box->m_max.x, box->m_min.y, box->m_min.z}, transform), + transformPoint(Vec3{box->m_max.x, box->m_min.y, box->m_max.z}, transform), + transformPoint(Vec3{box->m_min.x, box->m_min.y, box->m_max.z}, transform) + }; + for (unsigned int i = 0; i < 4; ++i) + points.push_back(corners[i]); + for (unsigned int i = 0; i < 4; ++i) + { + const Vec3& a = points[i]; + const Vec3& b = points[(i + 1) & 3]; + Vec3 direction = {b.x - a.x, 0.0f, b.z - a.z}; + const float length = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + const float lengthSq = direction.x * direction.x + direction.y * direction.y + direction.z * direction.z; + if (!(FLT_EPSILON > std::fabs(lengthSq - 1.0f))) + { + if (!(FLT_EPSILON > std::fabs(lengthSq))) + { + const float scale = 1.0f / std::sqrt(lengthSq); + direction.x *= scale; + direction.y *= scale; + direction.z *= scale; + } + else + direction.x = direction.y = direction.z = 0.0f; + } + const int count = static_cast(length) + 1; + Vec3 position = points[i]; + for (int sample = 0; sample < count; ++sample) + { + if (manager->isAiPositionInside(position, m_combatAreas)) + { + for (unsigned int j = 0; j < 4; ++j) + { + if (bounds.first.x > points[j].x) bounds.first.x = points[j].x; + if (bounds.first.y > points[j].z) bounds.first.y = points[j].z; + if (points[j].x > bounds.second.x) bounds.second.x = points[j].x; + if (points[j].z > bounds.second.y) bounds.second.y = points[j].z; + } + return true; + } + position.x = direction.x + position.x; + position.y = direction.y + position.y; + position.z = direction.z + position.z; + } + } + return false; +} + +// ELF 0x8408C00. +bool BFObjectEnvironment::hasOnlyInfantryCollMesh(world::IObject* object) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFObjectEnvironment::collideLineWithObjects"); + world::ICollisionMesh* const collision = static_cast( + world::object_detail::LayoutAccess::collisionMesh(object)); + if (!collision || object->hasCollisionLod(1) || !object->hasCollisionLod(2)) + return false; + return !collision->sameInstance(0, 2, 0, 3); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h index aea65fe37..fc6d286e0 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.h @@ -11,22 +11,61 @@ #include #include "AIAdapterTypes.h" +#include "../../AIDLL/AI/Main/IAIPathfinding.h" // Complete triple elements in the mesh face lists. namespace dice { namespace hfe { class IBase; +class CombatArea; +namespace world { class IObject; class ICollisionMesh; } namespace ai { +// A borrowed target position; assignment keeps the destination's existing reference. +class TargetData +{ +public: + TargetData(unsigned int id, const Vec3& position, IAIObject* object); + TargetData(const TargetData& other); + TargetData& operator=(const TargetData& other); + + // Member spellings are [INFERRED]; ELF constructors establish their order. + unsigned int id; // x86 +0x00 + const Vec3& position; // x86 +0x04 + IAIObject* object; // x86 +0x08 +}; + class IAIObjectEnvironment { public: - // [FRONTIER] These nested mesh types belong to IAIObjectEnvironment. - // Their member layouts are not yet known. - struct MeshAndBoundingBox; - struct WaterMesh; - struct DestroyableAddOnMesh; + // Mesh data exchanged with the offline navigation exporter. Field names are [INFERRED]. + // ELF MeshAndBoundingBox/WaterMesh list destruction and Mesh copy construction attest + // these source-level containers; their native STL layouts are compiler-dependent. + struct Mesh + { + std::vector vertices; + std::vector> edges; + std::list> faces; + }; + struct MeshAndBoundingBox + { + std::string name; + IAIObject* object; // x86 +0x04; assigned after insertion from the object's cached AI component. + Mesh boundingBox; + Mesh mesh; + }; + struct WaterMesh + { + std::string name; + Mesh mesh; + }; + struct DestroyableAddOnMesh + { + std::string name; + bool initiallyWalkable; + Mesh mesh; + }; IAIObjectEnvironment(); virtual ~IAIObjectEnvironment(); @@ -55,15 +94,15 @@ class IAIObjectEnvironment virtual int getHeightAndNormalForObject(IAIObject* object, const Vec3& position, float& height, Vec3& normal, float& slope) = 0; virtual void getVehicleSpawnerPositions(std::vector& out, unsigned char team) const = 0; virtual IAIObject* getObjectFromName(const std::string& name) = 0; - virtual int getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; - virtual int getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; + virtual bool getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; + virtual bool getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const = 0; virtual bool isAsleep(unsigned int id) const = 0; - virtual int getTargetObjects(std::vector& out, int team) const = 0; - virtual void loadOvergrowthCollision(const std::string& path) const = 0; + virtual void getTargetObjects(std::vector& out, int team) const = 0; + virtual bool loadOvergrowthCollision(const std::string& path) const = 0; virtual bool initAiCombatAreas() const = 0; virtual bool isAiPositionInsideCombatArea(const Vec3& position) const = 0; virtual int getAiCombatAreaLayer() const = 0; - virtual int getAICombatArea(std::list& out) const = 0; + virtual void getAICombatArea(std::list& out) const = 0; virtual void damageSeverelyDamagedVehicles() = 0; virtual int collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit) = 0; }; @@ -92,28 +131,41 @@ class BFObjectEnvironment : public IAIObjectEnvironment virtual bool collideLineWithWorld(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, Vec3* hit); virtual bool getMaxHeight(const Vec3& from, const Vec3& to, AIObjectPredicate* filter, float& height); virtual bool hasIndirectLineOfFire(IWeapon* weapon, const Vec3& from, const Vec3& to, const std::vector& ignore); - virtual void pickRandomSensePosition(Vec3& position, Vec3& normal, Vec3 hint, IAIObject* object); - virtual bool pickSoldierRandomSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int& part); - virtual bool getSoldierSensePosition(Vec3& position, Vec3& normal, IAIObject* object, unsigned int part); + virtual void pickRandomSensePosition(Vec3& position, Vec3& localPosition, Vec3 hint, IAIObject* object); + virtual bool pickSoldierRandomSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int& part); + virtual bool getSoldierSensePosition(Vec3& position, Vec3& localPosition, IAIObject* object, unsigned int part); virtual int getHeightAndNormalForObject(IAIObject* object, const Vec3& position, float& height, Vec3& normal, float& slope); virtual void getVehicleSpawnerPositions(std::vector& out, unsigned char team) const; virtual IAIObject* getObjectFromName(const std::string& name); - virtual int getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; - virtual int getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; + virtual bool getAllStaticCollisionMeshes(std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; + virtual bool getAllStaticCollisionMeshesWithinBoundary(const Vec2& min, const Vec2& max, std::list& meshes, std::list& water, std::map& addOns, std::list& more, std::pair& bounds, unsigned char team) const; virtual bool isAsleep(unsigned int id) const; - virtual int getTargetObjects(std::vector& out, int team) const; - virtual void loadOvergrowthCollision(const std::string& path) const; + virtual void getTargetObjects(std::vector& out, int team) const; + virtual bool loadOvergrowthCollision(const std::string& path) const; virtual bool initAiCombatAreas() const; virtual bool isAiPositionInsideCombatArea(const Vec3& position) const; virtual int getAiCombatAreaLayer() const; - virtual int getAICombatArea(std::list& out) const; + virtual void getAICombatArea(std::list& out) const; virtual void damageSeverelyDamagedVehicles(); virtual int collideLineWithObjects(const Vec3& from, const Vec3& to, const std::vector& ignore, bool a, float b, bool c, bool& hit); private: + void createMeshFromObject(world::ICollisionMesh* collision, int lod, const Mat4& transform, Mesh& mesh) const; + void createBoundingBoxFromLocalCoordinates(const Vec3& min, const Vec3& max, const Mat4& transform, Mesh& mesh) const; + void createBoundingBoxFromWorldCoordinates(const Vec3& min, const Vec3& max, Mesh& mesh) const; + void createBoundingBoxFromCombatAreas(std::pair& bounds) const; + bool objectOverlapsCombatAreas(const world::IObject* object, std::pair& bounds) const; + bool hasOnlyInfantryCollMesh(world::IObject* object) const; + + void pushAIObjects(std::vector& out, std::vector objects) const; + /* +0x00 */ // vptr - // [UNRESOLVED] Three pointer-vector fields remain opaque. The trailing clock value is a double. - /* +0x04 */ unsigned char m_opaque[0x24]; // three std::vector members, zeroed as retail does + // The element types come from the std::vector instantiations each member's users call + // (erase / _M_fill_insert / _M_insert_aux); the destructor frees the three in reverse order. + // [CHOSEN] member names. + /* +0x04 */ std::vector m_senseObjects; // pickRandomSensePosition's scratch + /* +0x10 */ std::vector m_activePlayerIds; // getActivePlayerIds' answer + /* +0x1C */ std::vector m_combatAreas; // the AI combat-area set /* +0x28 */ unsigned char m_byte28; // [UNRESOLVED] ctor 0 /* +0x2C */ double m_lastSevereDamageTime; // [CHOSEN] name; ELF +0x2C / PE +0x38, ctor 0.0 }; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp index c8f74877e..e0d1e1b36 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFPhysics.cpp @@ -1,15 +1,10 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFPhysics operations. #include "BFPhysics.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" +#include "../../../Physics/BasicPhysicsSystem.h" // IPhysicsSystem::getGravity (+0x20) namespace dice { namespace hfe { @@ -19,31 +14,36 @@ extern ClassManager* classManager; namespace ai { // First wins in, exact match out. +// ELF 0x840E790 / 0x840E810. IAIPhysics::IAIPhysics() { if (!CommonSingletonServer::m_iaiPhysics) classManager->registerSimpleSingleton(std::string("IAIPhysics"), this); } +// ELF 0x840E890 / 0x840E910 / 0x840E990. IAIPhysics::~IAIPhysics() { if (CommonSingletonServer::m_iaiPhysics == this) classManager->unregisterSimpleSingleton(std::string("IAIPhysics")); } +// ELF 0x840B740 / 0x840B770. BFPhysics::BFPhysics() { } +// ELF 0x840B7A0 / 0x840B7C0 / 0x840B7E0. BFPhysics::~BFPhysics() { } -// - world::basicPhysicsSystem (ds:) vtable +0x20. -// The whole class is a one-call forwarder; four bytes, one virtual. +// bf2 0x840B810: a forwarder to world::basicPhysicsSystem's getGravity (IPhysicsSystem +0x20), +// no null guard. +// ELF 0x840B810. float BFPhysics::getGravity() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFPhysics::getGravity"); + return static_cast(world::basicPhysicsSystem)->getGravity(); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp index 18efbb0d2..ebc9504df 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFRadioComm.cpp @@ -1,15 +1,14 @@ -// [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFRadioComm operations. +// Placement attested by the ELF's "AI/AIInterface/BFKnowledge/BFRadioComm.cpp" __FILE__ string. #include "BFRadioComm.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" +#include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../../Core/ClassManager.h" +#include "../../../Core/Debug.h" +#include "../../../Core/EventManager.h" +#include "../../../Game/IEventListener.h" // ECNetwork +#include "../../../Game/GameEvents/RadioMessageEvent.h" // RadioMessageReceivedEvent namespace dice { namespace hfe { @@ -39,10 +38,36 @@ BFRadioComm::~BFRadioComm() { } -// - the single virtual, and the AI's only way to speak. +// bf2 0x840B900: the AI's only way to speak. The AI channel is mapped to the engine channel +// 0..8 -> 6, 7, 8, 3, 2, 4, 10, 11, 14 (an unknown one reports an Error and becomes 19), and a +// RadioMessageReceivedEvent {connection = playerId, message = a, sender = b, team = c, flags = d, +// that channel, type = channel} is posted as ECNetwork event at time 0 (EventManager +0x10). +// The allocation goes through checkPointer (its "AI/AIDLL/AI/AIUtils/checkPointer.h" Debug block +// is inlined here). [INFERRED] int: the value is the postEvent result left in eax; the only +// caller (CommunicationHub::filterAndSendAIRadioMessage) discards it. int BFRadioComm::sendAIRadioMessage(int playerId, ChannelMessageType channel, AIRadioChannelType type, unsigned char a, int b, unsigned char c, unsigned char d) { - BF2_AI_FRONTIER("dice::hfe::ai::BFRadioComm::sendAIRadioMessage"); + int engineChannel; + switch (static_cast(type)) + { + case 0: engineChannel = 6; break; + case 1: engineChannel = 7; break; + case 2: engineChannel = 8; break; + case 3: engineChannel = 3; break; + case 4: engineChannel = 2; break; + case 5: engineChannel = 4; break; + case 6: engineChannel = 10; break; + case 7: engineChannel = 11; break; + case 8: engineChannel = 14; break; + default: + engineChannel = 19; + Debug(DebugTypeError, __FILE__, 77, "") << "Unknown AI radio channel number " + << static_cast(type); // line 0x4D + break; + } + EventNode* const event = checkPointer(new RadioMessageReceivedEvent( + playerId, a, static_cast(b), c, d, engineChannel, static_cast(channel))); + return static_cast(eventManager->postEvent(ECNetwork, event, 0.0f)); } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp index 14e6822bd..6daf5ed65 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp @@ -12,6 +12,13 @@ #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" #include "../../../Game/GameLogic/SquadManager/ISquadManager.h" +#include "../../../Game/GameLogic/SquadManager/ISquadInfo.h" +#include "../../../Game/GameLogic/SquadManager/SquadOrder.h" +#include "../../../Game/GameEvents/RequestEvent.h" +#include "../../../Game/Objects/IObject.h" +#include "../../../IO/Network/NetworkManager.h" +#include "../../../IO/Network/INetworkable.h" +#include "IAIObject.h" #include "../SingletonServer.h" // BFSingletonServer::updateStaticMethods namespace dice { @@ -51,9 +58,10 @@ BFSquad::~BFSquad() { } +// bf2 0x84108F0: ISquadManager +0x40 getFirstUnusedSquad. int BFSquad::getNextEmptySquad(int team) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::getNextEmptySquad"); + return static_cast(squadManager)->getFirstUnusedSquad(team); } // Preserve id-before-side virtual calls. @@ -64,9 +72,14 @@ bool BFSquad::joinSquad(int squad, IAIPlayer* player) return static_cast(squadManager)->addToSquad(side, squad, playerId); } +// ELF 0x8410960: id, then side, then ISquadManager +0x34 removeFromSquad(side, squad, id, false). +// The ELF answers the zero-extended low byte of that void call; nothing reads it, 0 is answered. int BFSquad::exitSquad(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::exitSquad"); + const int playerId = player->getId(); + const int side = player->getSide(); + static_cast(squadManager)->removeFromSquad(side, squad, playerId, false); + return 0; } bool BFSquad::isSquadLeader(int squad, IAIPlayer* player) @@ -84,86 +97,169 @@ bool BFSquad::isSquadLeader(int squad, IAIPlayer* player) return playerId == leader; } +// bf2 0x8410A10: id, then side, then ISquadManager +0x38 setSquadLeader(side, squad, id, false). +// The ELF answers the low byte of that void call; nothing reads it, 0 is answered. int BFSquad::assignAsSquadLeader(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::assignAsSquadLeader"); + const int playerId = player->getId(); + const int side = player->getSide(); + static_cast(squadManager)->setSquadLeader(side, squad, playerId, false); + return 0; } +// bf2 0x8410A70: a player who is not the leader answers 1; the leader is replaced by -1 +// (setSquadLeader(side, squad, -1, false), whose void low byte the ELF answers; 0 here). int BFSquad::retireAsSquadLeader(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::retireAsSquadLeader"); + const int playerId = player->getId(); + if (playerId != static_cast(squadManager)->getSquadLeader(player->getSide(), squad)) + return 1; + static_cast(squadManager)->setSquadLeader(player->getSide(), squad, -1, false); + return 0; } +// bf2 0x8410B00: issueOrder with squad order type 5. int BFSquad::issueSquadAttackOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::issueSquadAttackOrder"); + return issueOrder(position, a, b, target, 5); } +// bf2 0x8410B30: issueOrder with squad order type 4. int BFSquad::issueSquadMoveOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::issueSquadMoveOrder"); + return issueOrder(position, a, b, target, 4); } +// bf2 0x8410B60: issueOrder with squad order type 6. int BFSquad::issueSquadDefendOrder(const Vec3& position, int a, int b, IAIObject* target) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::issueSquadDefendOrder"); + return issueOrder(position, a, b, target, 6); } // 5 bytes - a bare ret. Empty, like its decline twin. -void BFSquad::acceptSquadOrder(int squad, IAIPlayer* player) +// bf2 0x8410C70 and 0x8410C80 are bare `ret`s. +void BFSquad::acceptSquadOrder(int, IAIPlayer*) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptSquadOrder"); } // ELF, - empty. -void BFSquad::declineSquadOrder(int squad, IAIPlayer* player) +void BFSquad::declineSquadOrder(int, IAIPlayer*) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineSquadOrder"); } int BFSquad::acceptCommanderAttackOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptCommanderAttackOrder"); + return acceptCommanderOrder(squad, player, 5); } int BFSquad::acceptCommanderDefendOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptCommanderDefendOrder"); + return acceptCommanderOrder(squad, player, 6); } int BFSquad::acceptCommanderMoveOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::acceptCommanderMoveOrder"); + return acceptCommanderOrder(squad, player, 4); } int BFSquad::declineCommanderAttackOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineCommanderAttackOrder"); + return declineCommanderOrder(squad, player, 5); } int BFSquad::declineCommanderDefendOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineCommanderDefendOrder"); + return declineCommanderOrder(squad, player, 6); } int BFSquad::declineCommanderMoveOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::declineCommanderMoveOrder"); + return declineCommanderOrder(squad, player, 4); } +// bf2 0x8410F30: for a human only, a RequestEvent (side, squad, type 1) executed on the server +// for the player's id (GameEvent +0x28) and released. +// [CHOSEN, not recovered] The ELF leaves the last call's EAX; no caller reads it, 0 here. int BFSquad::requestNewCommanderOrder(int squad, IAIPlayer* player) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::requestNewCommanderOrder"); + if (player->getIsAIPlayer()) + return 0; + RequestEvent* const event = + new RequestEvent(player->getSide(), squad, static_cast(1)); + event->executeServer(player->getId()); + event->release(); + return 0; +} + +// bf2 0x8410FB0: the squad's commander order (ISquadInfo +0x14) gives the position (its first +// point) and the target through the network id. The target argument is not read. +world::IObject* BFSquad::getCommanderOrder(int a, int b, Vec3& position, IAIObject*) +{ + SquadOrder* const order = static_cast(squadManager)->getSquadInfo(a, b)->getCommanderOrders(); + position = order->points[0]; + return io::networkManager->getObject(order->targetNetId); +} + +// bf2 0x8411020: the same for the squad order (ISquadInfo +0x10). +world::IObject* BFSquad::getSquadOrder(int a, int b, Vec3& position, IAIObject*) +{ + SquadOrder* const order = static_cast(squadManager)->getSquadInfo(a, b)->getSquadOrders(); + position = order->points[0]; + return io::networkManager->getObject(order->targetNetId); +} + +// bf2 0x8410BC0. The order: the type, the target's network id (0 without a target or a +// networkable), the position as the first of three points (the other two zero); the flag at +// +0x2C is left unset as in the ELF. ISquadManager +0x44 issueSquadOrder(b, a, order, false). +int BFSquad::issueOrder(const Vec3& position, int a, int b, IAIObject* target, int orderType) +{ + SquadOrder order; + for (int i = 0; i < 3; ++i) + { + order.points[i].x = 0.0f; + order.points[i].y = 0.0f; + order.points[i].z = 0.0f; + } + order.orderId = orderType; + order.points[0] = position; + order.targetNetId = 0; + if (target) + { + io::INetworkable* const networkable = target->getObject()->getNetworkable(); + if (networkable) + order.targetNetId = networkable->m_networkableId; + } + static_cast(squadManager)->issueSquadOrder(b, a, order, false); + return 0; } -world::IObject* BFSquad::getCommanderOrder(int a, int b, Vec3& position, IAIObject* target) +// bf2 0x8410D20 / 0x8410E70. The order is marked accepted (or not) for the player's side +// (ISquadManager +0x24: accepted, OrderType 1, the squad order type, false); a human's +// acceptance (RequestEvent type 2) or decline (type 3) is executed for the player and released. +int BFSquad::acceptCommanderOrder(int squad, IAIPlayer* player, int orderType) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::getCommanderOrder"); + static_cast(squadManager)->setIsAccepted(player->getSide(), squad, true, static_cast(1), + static_cast(orderType), false); + if (player->getIsAIPlayer()) + return 0; + RequestEvent* const event = + new RequestEvent(player->getSide(), squad, static_cast(2)); + event->executeServer(player->getId()); + event->release(); + return 0; } -world::IObject* BFSquad::getSquadOrder(int a, int b, Vec3& position, IAIObject* target) +int BFSquad::declineCommanderOrder(int squad, IAIPlayer* player, int orderType) { - BF2_AI_FRONTIER("dice::hfe::ai::BFSquad::getSquadOrder"); + static_cast(squadManager)->setIsAccepted(player->getSide(), squad, false, static_cast(1), + static_cast(orderType), false); + if (player->getIsAIPlayer()) + return 0; + RequestEvent* const event = + new RequestEvent(player->getSide(), squad, static_cast(3)); + event->executeServer(player->getId()); + event->release(); + return 0; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h index ea7e9df4c..c1fa61de9 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.h @@ -74,6 +74,12 @@ class BFSquad : public IBFSquad virtual int requestNewCommanderOrder(int squad, IAIPlayer* player); virtual world::IObject* getCommanderOrder(int a, int b, Vec3& position, IAIObject* target); virtual world::IObject* getSquadOrder(int a, int b, Vec3& position, IAIObject* target); + +private: + // Non-virtual ELF helpers (0x8410BC0, 0x8410D20, 0x8410E70); the int is a SquadOrderType value. + int issueOrder(const Vec3& position, int a, int b, IAIObject* target, int orderType); + int acceptCommanderOrder(int squad, IAIPlayer* player, int orderType); + int declineCommanderOrder(int squad, IAIPlayer* player, int orderType); }; } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp index 200a91f4f..1b3d8f2d7 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.cpp @@ -1,12 +1,14 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFTerrain operations. #include "BFTerrain.h" -#include "AIFrontier.h" +#include "../../../Core/Debug.h" +#include "../../AIDLL/AI/Main/IAIPathfinding.h" +#include +#include +#include "AIPlayer.h" +#include "../../../Physics/Heightmap.h" +#include "../../../Game/GameLogic/CombatAreaManager.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" @@ -100,35 +102,55 @@ float BFTerrain::getTerrainAltitude(float x, float z) const return water; } -unsigned char BFTerrain::getMaterial(float x, float z) const +// ELF 0x840C000. The shipped method reports its own unimplemented operation. +unsigned char BFTerrain::getMaterial(float /*x*/, float /*z*/) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getMaterial"); + Debug(DebugTypeError, "AI/AIInterface/BFKnowledge/BFTerrain.cpp", 111) << "Not implemented"; + return 0; } // ELF, - a constant. +// bf2 0x840C0F0: `mov eax, -1`. int BFTerrain::getMaterialToGiveDamage() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getMaterialToGiveDamage"); + return -1; } +// bf2 0x840DEB0: the combat area manager (unchecked) tests the wrapper's player. bool BFTerrain::isInsideCombatArea(IAIPlayer* player) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::isInsideCombatArea"); + return CombatAreaManager::getInstance()->isPlayerInside(player->getPlayer()); } +// bf2 0x840C100: IHeightmapCluster +0x7C getNormalInWorldCoords. void BFTerrain::getNormal(float x, float z, Vec3& normal) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getNormal"); + static_cast(m_heightmapCluster)->getNormalInWorldCoords(x, z, normal); } -void BFTerrain::getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const +// bf2 0x840C130: IHeightmapCluster +0x84 getHeightAndNormalInWorldCoords, its float passed on +// (the caller pops it from st0, hence the float return the port's declaration lacked). +float BFTerrain::getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getHeightAndNormal"); + return static_cast(m_heightmapCluster) + ->getHeightAndNormalInWorldCoords(x, z, normal, material); } +// bf2 0x840C170: acos of the terrain normal's y (IHeightmapCluster +0x7C into a zeroed Vec3), +// clamped to [-1, 1]. float BFTerrain::getSlope(float x, float z) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getSlope"); + Vec3 normal; + normal.x = 0.0f; + normal.y = 0.0f; + normal.z = 0.0f; + static_cast(m_heightmapCluster)->getNormalInWorldCoords(x, z, normal); + float y = normal.y; + if (-1.0f > y) + y = -1.0f; + else if (y > 1.0f) + y = 1.0f; + return std::acos(y); } // slot 12 - the second half of `getTerrainAltitude`, and the same one-line @@ -139,14 +161,38 @@ float BFTerrain::getWaterLevel(float x, float z) const ->getWaterLevelInWorldCoords(x, z); } +// bf2 0x840C210: the primary heightmap's sea level (IHeightmap +0x68). float BFTerrain::getSeaWaterLevel() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getSeaWaterLevel"); + return static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getSeaWaterLevel(); } -bool BFTerrain::findTerrainPoint(const Vec3& from, const Vec3& to, float step, Vec3& hit) const +// ELF 0x840C230. The second vector is a direction, normalized before scaling by step. +bool BFTerrain::findTerrainPoint(const Vec3& from, const Vec3& direction, float step, Vec3& hit) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::findTerrainPoint"); + Vec3 unit = direction; + const float lengthSq = unit.x * unit.x + unit.y * unit.y + unit.z * unit.z; + if (!(FLT_EPSILON > std::fabs(lengthSq - 1.0f))) + { + if (!(FLT_EPSILON > std::fabs(lengthSq))) + { + const float scale = 1.0f / std::sqrt(lengthSq); + unit.x *= scale; + unit.y *= scale; + unit.z *= scale; + } + else + unit.x = unit.y = unit.z = 0.0f; + } + Vec3 to; + to.x = step * unit.x + from.x; + to.y = step * unit.y + from.y; + to.z = step * unit.z + from.z; + Vec3 normal = {0.0f, 0.0f, 0.0f}; + float distance; + unsigned char material; + return static_cast(m_heightmapCluster) + ->intersectRayInWorldCoords(from, to, hit, distance, normal, material, true); } // ELF, - a bare member load. All ten of these are. @@ -186,49 +232,224 @@ int BFTerrain::getWorldMaxZ() const return m_worldMaxZ; } +// bf2 0x840C420: floor of the primary heightmap's getLowBoundaryX (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMinX() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMinX"); + return static_cast(static_cast( + std::floor(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getLowBoundaryX())))); } +// bf2 0x840C460: floor of the primary heightmap's getLowBoundaryZ (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMinZ() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMinZ"); + return static_cast(static_cast( + std::floor(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getLowBoundaryZ())))); } +// bf2 0x840C4A0: ceil of the primary heightmap's getHighBoundaryX (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMaxX() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMaxX"); + return static_cast(static_cast( + std::ceil(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getHighBoundaryX())))); } +// bf2 0x840C4E0: ceil of the primary heightmap's getHighBoundaryZ (as double), stored to float, then truncated. int BFTerrain::getPrimaryWorldMaxZ() const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getPrimaryWorldMaxZ"); + return static_cast(static_cast( + std::ceil(static_cast(static_cast(m_heightmapCluster)->getPrimaryHeightmap()->getHighBoundaryZ())))); } +// bf2 0x840C520: the heightmap cluster's intersectRayInWorldCoords (+0x90, verified in the ELF +// primary vtable), two-sided, into a discarded material byte. bool BFTerrain::intersectTerrain(const Vec3& from, const Vec3& to, Vec3& hit, float& distance, Vec3& normal) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::intersectTerrain"); + unsigned char material; + return static_cast(m_heightmapCluster) + ->intersectRayInWorldCoords(from, to, hit, distance, normal, material, true); } +// ELF 0x840C580. Output references are forwarded in their original order. bool BFTerrain::getTriangle(const Vec3& position, Vec3& a, Vec3& b, Vec3& c, Vec3& normal, unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getTriangle"); + return static_cast(m_heightmapCluster) + ->getTriangleAndNormalAndMaterialInWorldCoords(position.x, position.z, a, b, c, normal, material); } +// ELF 0x840C5E0. Sample just beyond the selected edge, away from the opposite vertex. bool BFTerrain::getTriangleNeighbour(const Vec3& a, const Vec3& b, const Vec3& c, unsigned int edge, Vec3& na, Vec3& nb, Vec3& nc, Vec3& normal, unsigned char& material) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getTriangleNeighbour"); + const Vec3 *first, *second, *opposite; + switch (edge) + { + case 0: first = &b; second = &a; opposite = &c; break; + case 1: first = &c; second = &b; opposite = &a; break; + case 2: first = &a; second = &c; opposite = &b; break; + default: return false; + } + Vec3 midpoint; + midpoint.x = (first->x + second->x) * 0.5f; + midpoint.y = (first->y + second->y) * 0.5f; + midpoint.z = (first->z + second->z) * 0.5f; + Vec3 position; + position.x = (midpoint.x - opposite->x) * 0.2f + midpoint.x; + position.y = (midpoint.y - opposite->y) * 0.2f + midpoint.y; + position.z = (midpoint.z - opposite->z) * 0.2f + midpoint.z; + return getTriangle(position, na, nb, nc, normal, material); +} + +// ELF 0x840C7B0. +void BFTerrain::getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +{ + world::IHeightmap* const heightmap = + static_cast(m_heightmapCluster)->getPrimaryHeightmap(); + Vec2 max; + max.x = heightmap->getHighBoundaryX(); + max.y = heightmap->getHighBoundaryZ(); + Vec2 min; + min.x = heightmap->getLowBoundaryX(); + min.y = heightmap->getLowBoundaryZ(); + getAllTerrainPolygonsWithinBoundary(bounds, min, max, vertices, edges, triangles); +} + +// ELF 0x840C880. +void BFTerrain::getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +{ + world::IHeightmap* const heightmap = + static_cast(m_heightmapCluster)->getPrimaryHeightmap(); + const Vec3& scale = heightmap->getScale(); + const float maxX = std::ceil(max.x / scale.x) * scale.x; + const float maxZ = std::ceil(max.y / scale.z) * scale.z; + const float minX = std::floor(min.x / scale.x) * scale.x; + const float minZ = std::floor(min.y / scale.z) * scale.z; + const int countX = static_cast((maxX - minX) / scale.x) + 1; + const int countZ = static_cast((maxZ - minZ) / scale.z) + 1; + const unsigned int count = static_cast(countX * countZ); + + // [CHOSEN, not recovered] The shared CRT heap policy has no per-allocation cap: + // https://github.com/B2BF/OpenBF2/issues/7 (docs/architecture.md, Images and boundaries). + // Retail Memory.cpp set_max_alloc_size/reset_max_alloc_size calls are omitted here and + // in checkUnconnectedMeshData; no ineffectual replacement setters are published. + vertices.reserve(count); + std::vector vertexMap; + vertexMap.reserve(count); + int nextVertex = 0; + for (float x = minX; maxX >= x; x += scale.x) + { + for (float z = minZ; maxZ >= z; z += scale.z) + { + Vec3 position; + position.x = x; + position.y = heightmap->getHeightInWorldCoords(x, z); + position.z = z; + if (pointInsideBbox(position, bounds)) + { + vertices.push_back(position); + vertexMap.push_back(nextVertex++); + } + else + vertexMap.push_back(-1); + } + } + + // ELF 0x840C860: edgesSize(countX, countZ). + const int edgeCount = (countZ - 1) * (countX - 1) + (countZ - 1) * countX + countZ * (countX - 1); + edges.reserve(static_cast(edgeCount)); + std::vector edgeMap; + edgeMap.reserve(static_cast(3 * countZ * countX)); + int nextEdge = 0; + for (int x = 0; x < countX; ++x) + { + for (int z = 0; z < countZ - 1; ++z) + { + const int a = vertexMap[x * countZ + z]; + const int b = vertexMap[x * countZ + z + 1]; + if (a >= 0 && b >= 0) + { + edges.push_back(std::make_pair(a, b)); + edgeMap.push_back(nextEdge++); + } + else + edgeMap.push_back(-1); + } + } + for (int x = 0; x < countX - 1; ++x) + { + for (int z = 0; z < countZ; ++z) + { + const int a = vertexMap[x * countZ + z]; + const int b = vertexMap[(x + 1) * countZ + z]; + if (a >= 0 && b >= 0) + { + edges.push_back(std::make_pair(a, b)); + edgeMap.push_back(nextEdge++); + } + else + edgeMap.push_back(-1); + } + } + for (int x = 0; x < countX - 1; ++x) + { + for (int z = 1; z < countZ; ++z) + { + const int a = vertexMap[x * countZ + z]; + const int b = vertexMap[(x + 1) * countZ + z - 1]; + if (a >= 0 && b >= 0) + { + edges.push_back(std::make_pair(a, b)); + edgeMap.push_back(nextEdge++); + } + else + edgeMap.push_back(-1); + } + } + const int horizontalCount = (countZ - 1) * countX; + const int diagonalStart = horizontalCount + countZ * (countX - 1); + for (int x = 0; x < countX - 1; ++x) + { + for (int z = 0; z < countZ - 1; ++z) + { + const int horizontal = x * (countZ - 1) + z; + const int vertical = horizontalCount + countZ * x + z; + const int diagonal = diagonalStart + x * (countZ - 1) + z; + if (edgeMap[horizontal] >= 0 && edgeMap[diagonal] >= 0 && edgeMap[vertical] >= 0) + triangles.push_back(make_triple(edgeMap[horizontal], edgeMap[diagonal], edgeMap[vertical])); + if (edgeMap[vertical + 1] >= 0 && edgeMap[(x + 1) * (countZ - 1) + z] >= 0 && edgeMap[diagonal] >= 0) + triangles.push_back(make_triple(edgeMap[vertical + 1], edgeMap[(x + 1) * (countZ - 1) + z], edgeMap[diagonal])); + } + } + // shipped defect: output is appended, but generated vertex and edge IDs start at zero. + checkUnconnectedMeshData(vertices, edges, triangles); } -int BFTerrain::getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +// ELF 0x840D470. The retail trailing scans do not remove or remap any mesh data. +void BFTerrain::checkUnconnectedMeshData(std::vector& vertices, + std::vector>& edges, + std::list>& triangles) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getAllTerrainPolygons"); + std::vector usedVertices(vertices.size(), false); + std::vector usedEdges(edges.size(), false); + for (std::list>::const_iterator it = triangles.begin(); it != triangles.end(); ++it) + { + usedVertices[edges[it->first].first] = true; + usedVertices[edges[it->first].second] = true; + usedVertices[edges[it->second].first] = true; + usedVertices[edges[it->second].second] = true; + usedVertices[edges[it->third].first] = true; + usedVertices[edges[it->third].second] = true; + usedEdges[it->first] = true; + usedEdges[it->second] = true; + usedEdges[it->third] = true; + } + for (unsigned int i = 0; i < usedVertices.size(); ++i) {} + for (unsigned int i = 0; i < usedEdges.size(); ++i) {} } -void BFTerrain::getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const +// ELF 0x840DE60. Ordered comparisons reject NaN in either coordinate or boundary. +bool BFTerrain::pointInsideBbox(const Vec3& position, const std::pair& bounds) const { - BF2_AI_FRONTIER("dice::hfe::ai::BFTerrain::getAllTerrainPolygonsWithinBoundary"); + return position.x >= bounds.first.x && position.z >= bounds.first.y + && bounds.second.x >= position.x && bounds.second.y >= position.z; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h index c0a85b8c6..e601bdedb 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTerrain.h @@ -33,7 +33,7 @@ class IAITerrain virtual int getMaterialToGiveDamage() const = 0; virtual bool isInsideCombatArea(IAIPlayer* player) const = 0; virtual void getNormal(float x, float z, Vec3& normal) const = 0; - virtual void getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const = 0; + virtual float getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const = 0; virtual float getSlope(float x, float z) const = 0; virtual float getWaterLevel(float x, float z) const = 0; virtual float getSeaWaterLevel() const = 0; @@ -51,7 +51,7 @@ class IAITerrain virtual bool intersectTerrain(const Vec3& from, const Vec3& to, Vec3& hit, float& distance, Vec3& normal) const = 0; virtual bool getTriangle(const Vec3& position, Vec3& a, Vec3& b, Vec3& c, Vec3& normal, unsigned char& material) const = 0; virtual bool getTriangleNeighbour(const Vec3& a, const Vec3& b, const Vec3& c, unsigned int edge, Vec3& na, Vec3& nb, Vec3& nc, Vec3& normal, unsigned char& material) const = 0; - virtual int getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const = 0; + virtual void getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const = 0; virtual void getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const = 0; }; @@ -69,7 +69,7 @@ class BFTerrain : public IAITerrain virtual int getMaterialToGiveDamage() const; virtual bool isInsideCombatArea(IAIPlayer* player) const; virtual void getNormal(float x, float z, Vec3& normal) const; - virtual void getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const; + virtual float getHeightAndNormal(float x, float z, Vec3& normal, unsigned char& material) const; virtual float getSlope(float x, float z) const; virtual float getWaterLevel(float x, float z) const; virtual float getSeaWaterLevel() const; @@ -87,10 +87,14 @@ class BFTerrain : public IAITerrain virtual bool intersectTerrain(const Vec3& from, const Vec3& to, Vec3& hit, float& distance, Vec3& normal) const; virtual bool getTriangle(const Vec3& position, Vec3& a, Vec3& b, Vec3& c, Vec3& normal, unsigned char& material) const; virtual bool getTriangleNeighbour(const Vec3& a, const Vec3& b, const Vec3& c, unsigned int edge, Vec3& na, Vec3& nb, Vec3& nc, Vec3& normal, unsigned char& material) const; - virtual int getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const; + virtual void getAllTerrainPolygons(std::pair bounds, std::vector& vertices, std::vector >& edges, std::list >& triangles) const; virtual void getAllTerrainPolygonsWithinBoundary(std::pair bounds, const Vec2& min, const Vec2& max, std::vector& vertices, std::vector >& edges, std::list >& triangles) const; private: + bool pointInsideBbox(const Vec3& position, const std::pair& bounds) const; + void checkUnconnectedMeshData(std::vector& vertices, std::vector>& edges, + std::list>& triangles) const; + /* +0x00 */ // vptr /* +0x04 */ IBase* m_heightmapCluster; // getSingleton("HeightmapCluster") /* +0x08 */ int m_worldSizeX; // heightmapCluster vtable +0x30 diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp index edef8a9ce..64561cde0 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.cpp @@ -1,13 +1,7 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFTimer operations. #include "BFTimer.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" #include "../../../Core/System.h" // namespace WorldPref @@ -25,29 +19,32 @@ extern ClassManager* classManager; namespace ai { // First wins in, exact match out. +// ELF 0x841C100 / 0x841C180. IBFTimer::IBFTimer() { if (!CommonSingletonServer::m_iBFTimer) classManager->registerSimpleSingleton(std::string("IBFTimer"), this); } +// ELF 0x841C200 / 0x841C280 / 0x841C300. IBFTimer::~IBFTimer() { if (CommonSingletonServer::m_iBFTimer == this) classManager->unregisterSimpleSingleton(std::string("IBFTimer")); } +// ELF 0x841BEB0 / 0x841BF00. BFTimer::BFTimer() - : m_paused(false) - , m_resetMark(0.0) - , m_wallClock(new BFTimerWallClock) { - bfTimerNow(m_wallClock); + BFTimerWallClock* const clock = new BFTimerWallClock; + bfTimerNow(clock); + m_wallClock = clock; reset(); } // the vptr reset, `operator delete` on the wall // clock, then the base destructor. It really does free the eight bytes the ctor allocated. +// ELF 0x841BF50 / 0x841BF80 / 0x841BFB0. BFTimer::~BFTimer() { delete m_wallClock; @@ -58,18 +55,21 @@ BFTimer::~BFTimer() // - `push ebp / mov ebp, esp / pop ebp / jmp WorldPref::getWorldTime`. A tail // jump: the timer owns no game clock, it forwards to WorldPref. +// ELF 0x841BFF0. double BFTimer::getGameTime() const { return WorldPref::getWorldTime(); } // - the same shape, to WorldPref::getTickTime. +// ELF 0x841C000. double BFTimer::getTimeIncrease() const { return WorldPref::getTickTime(); } // Returns elapsed wall-clock time in seconds, including the microsecond fraction. +// ELF 0x841C010. double BFTimer::getUpdateTime() const { BFTimerWallClock now; @@ -79,12 +79,14 @@ double BFTimer::getUpdateTime() const } // Returns the system wall-clock time. +// ELF 0x841C0E0. double BFTimer::getWallClockTime() const { return g_system->getWallClockTime(); } // - two tail jumps, one per branch. +// ELF 0x841C060. void BFTimer::setPause(bool paused) { if (paused) @@ -94,11 +96,13 @@ void BFTimer::setPause(bool paused) } // - `movzx eax, byte ptr [eax+4]`. +// ELF 0x841C080. bool BFTimer::getPause() { return m_paused; } +// ELF 0x841C0B0. void BFTimer::reset() { m_paused = false; @@ -108,11 +112,13 @@ void BFTimer::reset() // each. not virtual - absent from the vtable, and setPause is // their only caller. +// ELF 0x841C090. void BFTimer::pause() { m_paused = true; } +// ELF 0x841C0A0. void BFTimer::unpause() { m_paused = false; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h index cc5d58cf0..fc18ae80d 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFTimer.h @@ -18,7 +18,8 @@ namespace hfe { namespace ai { // Stored wall-clock value used by the AI timer. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the corresponding BFTimer operation. +// [RETIRE-WHEN: aidll-01-adapters] Confirm and validate the Win32 clock route against the +// original Win32 image before retiring that chosen route; the ELF timeval calls are verified. struct BFTimerWallClock { long tv_sec; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp index cdabb140c..6f5030446 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp @@ -40,16 +40,20 @@ DebugRenderer::~DebugRenderer() { } -// 5 bytes - a bare ret. Empty in the dedicated image. +// ELF 0x842E780: shipped dedicated no-op. The client body remains unrecovered. void DebugRenderer::drawAll() { +#if !DEDICATED BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawAll"); +#endif } -// - likewise empty. +// ELF 0x842E790: shipped dedicated no-op. The client body remains unrecovered. void DebugRenderer::reset() { +#if !DEDICATED BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::reset"); +#endif } int DebugRenderer::drawLine(const std::vector& points, unsigned int colour, float width) const @@ -57,7 +61,7 @@ int DebugRenderer::drawLine(const std::vector& points, unsigned int colour BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawLine"); } -int DebugRenderer::drawCircle(const Vec3& centre, const Vec3& normal, float radius, unsigned int colour, bool filled, int segments) const +int DebugRenderer::drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool filled, int segments) const { BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawCircle"); } diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h index 3e408e663..17fc8ceb1 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h @@ -29,7 +29,7 @@ class IDebugRenderer virtual void drawAll() = 0; virtual void reset() = 0; virtual int drawLine(const std::vector& points, unsigned int colour, float width) const = 0; - virtual int drawCircle(const Vec3& centre, const Vec3& normal, float radius, unsigned int colour, bool filled, int segments) const = 0; + virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool filled, int segments) const = 0; virtual int drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const = 0; virtual int draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const = 0; virtual int drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const = 0; @@ -45,7 +45,7 @@ class DebugRenderer : public IDebugRenderer virtual void drawAll(); virtual void reset(); virtual int drawLine(const std::vector& points, unsigned int colour, float width) const; - virtual int drawCircle(const Vec3& centre, const Vec3& normal, float radius, unsigned int colour, bool filled, int segments) const; + virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool filled, int segments) const; virtual int drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const; virtual int draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const; virtual int drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp index 5e7d86d72..a9e4a193b 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.cpp @@ -1,36 +1,193 @@ // [INFERRED] Source placement. +// static init: ELF 0x36A780 (__tcf_0 0x36A7E0, _GLOBAL__I 0x36A810): 's Init object only. +#include + #include "PlanePolygon.h" -#include "AIFrontier.h" +#include "../../../Math/BoundingBox.h" +#include +#include namespace dice { namespace hfe { -// an empty list, or a copy of the caller's. +// ELF 0x83F81F0 / 0x83F82D0 (bf2); 0x3688C0 / 0x3689C0 (libaidll.so). PlanePolygon::PlanePolygon() { } +// ELF 0x83F8300 / 0x83F8360 (bf2); 0x368A10 / 0x368A80 (libaidll.so). PlanePolygon::PlanePolygon(const std::list& vertices) : m_vertices(vertices) { } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -// Paired ABI evidence fixes this signature (, ELF imported symbol), but the 2,037-byte -// PE body and BoundingBox surface are not recovered. IPICover's physical fallback now stops at the -// exact callee instead of fabricating an outline. -PlanePolygon::PlanePolygon(BoundingBox* /*box*/, const Mat4& /*transformation*/) +// ELF 0x83F83C0 / 0x83F89E0 (bf2); 0x368AF0 / 0x369150 (libaidll.so). +PlanePolygon::PlanePolygon(BoundingBox* box, const Mat4& transformation) { - BF2_AI_FRONTIER("dice::hfe::PlanePolygon::PlanePolygon(BoundingBox*, const Mat4&)"); + Mat4 inverse = {}; + inverse.m[0] = inverse.m[5] = inverse.m[10] = inverse.m[15] = 1.0f; + inverse.setInverse(transformation); + Vec2* outline = new Vec2[4](); + Vec3* corners = new Vec3[8](); + for (int i = 0; i < 8; ++i) + { + const Vec3& p = box->m_corners[i]; + corners[i].x = inverse.m[0] * p.x + inverse.m[4] * p.y + inverse.m[8] * p.z + inverse.m[12]; + corners[i].y = inverse.m[1] * p.x + inverse.m[5] * p.y + inverse.m[9] * p.z + inverse.m[13]; + corners[i].z = p.x * inverse.m[2] + p.y * inverse.m[6] + p.z * inverse.m[10] + inverse.m[14]; + } + + int* indices = new int[4]; + float* heights = new float[4]; + indices[0] = 0; + heights[0] = corners[0].y; + for (int i = 1; i < 4; ++i) + { + float height = corners[i].y; + int index = i; + // shipped defect: compares the uninitialized heights[i], with bound 3-i. + for (int j = 0; j < 3 - i; ++j) + { + if (heights[i] > height) + { + std::swap(height, heights[j]); + std::swap(index, indices[j]); + } + } + heights[i] = height; + // shipped defect: the displaced index is discarded. + indices[i] = i; + } + for (int i = 4; i < 8; ++i) + { + const float height = corners[i].y; + // shipped defect: this bound is negative, so corners 4..7 never enter the set. + for (int j = 0; j < 3 - i; ++j) + { + if (heights[i] > height) + { + heights[j] = height; + indices[j] = i; + } + } + } + + unsigned int mask = 0; + for (int i = 0; i < 4; ++i) + mask |= 1U << indices[i]; + switch (mask) + { + case 0x0F: + vec3ToVec2XZ(corners[2], outline[0]); + vec3ToVec2XZ(corners[3], outline[1]); + vec3ToVec2XZ(corners[1], outline[2]); + vec3ToVec2XZ(corners[0], outline[3]); + break; + case 0x33: + vec3ToVec2XZ(corners[0], outline[0]); + vec3ToVec2XZ(corners[4], outline[1]); + vec3ToVec2XZ(corners[5], outline[2]); + vec3ToVec2XZ(corners[1], outline[3]); + break; + case 0x55: + vec3ToVec2XZ(corners[0], outline[0]); + vec3ToVec2XZ(corners[4], outline[1]); + vec3ToVec2XZ(corners[6], outline[2]); + vec3ToVec2XZ(corners[2], outline[3]); + break; + case 0xAA: + vec3ToVec2XZ(corners[7], outline[0]); + vec3ToVec2XZ(corners[3], outline[1]); + vec3ToVec2XZ(corners[1], outline[2]); + vec3ToVec2XZ(corners[5], outline[3]); + break; + case 0xCC: + vec3ToVec2XZ(corners[7], outline[0]); + vec3ToVec2XZ(corners[3], outline[1]); + vec3ToVec2XZ(corners[2], outline[2]); + vec3ToVec2XZ(corners[6], outline[3]); + break; + case 0xF0: + vec3ToVec2XZ(corners[4], outline[0]); + vec3ToVec2XZ(corners[5], outline[1]); + vec3ToVec2XZ(corners[7], outline[2]); + vec3ToVec2XZ(corners[6], outline[3]); + break; + } + for (int i = 0; i < 4; ++i) + m_vertices.push_back(outline[i]); + + // shipped defect: scalar deletes for arrays; the transformed corners are leaked. + ::operator delete(indices); + ::operator delete(heights); + ::operator delete(outline); } -// the list's own destructor. +// ELF 0x83F9000 / 0x83F93E0 (bf2); 0x3697B0 / 0x369BE0 (libaidll.so). +PlanePolygon::PlanePolygon(const Vec3& direction, BoundingBox* box) +{ + Vec3* highest = new Vec3[4](); + Vec2* outline = new Vec2[4](); + highest[0] = box->m_corners[0]; + float lowest = highest[0].y; + for (int i = 1; i < 8; ++i) + { + Vec3 candidate = box->m_corners[i]; + if (i < 4 && lowest > candidate.y) + lowest = candidate.y; + for (int j = 0; j < 4; ++j) + { + if (i == j) + { + highest[i] = candidate; + break; + } + if (highest[j].y < candidate.y) + { + // shipped defect: takes the displaced value from the original box. + const Vec3 displaced = box->m_corners[j]; + highest[j] = candidate; + candidate = displaced; + } + } + } + (void)lowest; + for (int i = 0; i < 4; ++i) + vec3ToVec2XZ(highest[i], outline[i]); + const Vec2 normal = { -direction.z, direction.x }; + int minIndex = 0; + int maxIndex = 0; + float minimum = normal.x * outline[0].x + normal.y * outline[0].y; + float maximum = minimum; + for (int i = 1; i < 4; ++i) + { + const float projection = normal.x * outline[i].x + normal.y * outline[i].y; + if (minimum > projection) + { + minimum = projection; + minIndex = i; + } + else if (maximum < projection) + { + maximum = projection; + maxIndex = i; + } + } + m_vertices.push_back(outline[maxIndex]); + m_vertices.push_back(outline[minIndex]); + // shipped defect: arrays are released with scalar delete. + ::operator delete(highest); + ::operator delete(outline); +} + +// ELF 0x83F97C0 / 0x83F9800 / 0x83F9840 (bf2); 0x36A010 / 0x36A070 / 0x36A0D0 (libaidll.so). PlanePolygon::~PlanePolygon() { } +// ELF 0x83F9890 (bf2); 0x36A140 (libaidll.so). // Each corner goes XZ -> Vec3 (y = 0), through the transformation // as a point (row vector: x' = m0*x + m4*y + m8*z + m12, and so on), and back to XZ, appended to a // temporary list; a new empty PlanePolygon then takes that list through its own setVertices slot. @@ -69,19 +226,20 @@ IPlanePolygon* PlanePolygon::fromTransform(const Mat4& transformation) const return polygon; } -// cleared, then refilled from the caller's list. +// ELF 0x83F9A10 (bf2); 0x36A300 (libaidll.so). Clears, then refills from the caller's list. void PlanePolygon::setVertices(std::list& vertices) { m_vertices.clear(); m_vertices.assign(vertices.begin(), vertices.end()); } +// ELF 0x83F9A70 (bf2); 0x36A370 (libaidll.so). const std::list& PlanePolygon::getVertices() const { return m_vertices; } -// `out` cleared, then each corner scaled per axis and appended. +// ELF 0x83F9A80 (bf2); 0x36A380 (libaidll.so). Clears out, then appends each corner scaled per axis. void PlanePolygon::getScaledVertices(std::list& out, const Vec2& scale) const { Vec2 scaled; @@ -96,16 +254,64 @@ void PlanePolygon::getScaledVertices(std::list& out, const Vec2& scale) co } } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -bool PlanePolygon::intersects(const Vec2& /*a*/, const Vec2& /*b*/) const +// ELF 0x83F9B10 (bf2); 0x36A430 (libaidll.so). +bool PlanePolygon::intersects(const Vec2& a, const Vec2& b) const { - BF2_AI_FRONTIER("dice::hfe::PlanePolygon::intersects"); + Vec2 normal = { 0.0f, 0.0f }; + getNormal(a, normal); + // shipped defect: dereferences end() for the initial edge endpoint. + const Vec2& last = *m_vertices.end(); + float previous = (last.x - b.x) * normal.x + (last.y - b.y) * normal.y; + std::list::const_iterator it = m_vertices.begin(); + float current = (it->x - b.x) * normal.x + (it->y - b.y) * normal.y; + // Unordered previous values follow the negative arm in both ELF builds. + if (previous >= 0.0f ? current <= 0.0f : current >= 0.0f) + return true; + previous = current; + for (++it; it != m_vertices.end(); ++it) + { + current = (it->x - b.x) * normal.x + (it->y - b.y) * normal.y; + if (!(previous >= 0.0f)) + { + // shipped defect: tests the untouched zero vector instead of current. + if (normal.x * 0.0f + normal.y * 0.0f >= 0.0f) + return true; + } + else if (current <= 0.0f) + return true; + previous = current; + } + return false; } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-07-knowledge] -bool PlanePolygon::isInside(const Vec2& /*a*/, const Vec2& /*b*/) const +// ELF 0x83F9CF0 (bf2); 0x36A640 (libaidll.so). +bool PlanePolygon::isInside(const Vec2& a, const Vec2& b) const { - BF2_AI_FRONTIER("dice::hfe::PlanePolygon::isInside"); + const Vec2 normal = { -a.y, a.x }; + int crossings = 0; + std::list::const_iterator last = m_vertices.end(); + --last; + for (std::list::const_iterator it = m_vertices.begin(); it != last; ++it) + { + std::list::const_iterator next = it; + ++next; + // shipped defect: adds b, omits the closing edge, and accepts even crossing counts. + const float first = (it->x + b.x) * normal.x + (it->y + b.y) * normal.y; + const float second = (next->x + b.x) * normal.x + (next->y + b.y) * normal.y; + if (first > 0.0f) + { + if (second <= 0.0f) + ++crossings; + } + else if (first < 0.0f) + { + if (second >= 0.0f) + ++crossings; + } + else if (second == 0.0f) + ++crossings; + } + return (crossings & 1) == 0; } } // namespace hfe diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h index 15dff818e..1398b90d7 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/PlanePolygon.h @@ -1,9 +1,5 @@ // Planar polygon geometry and transforms. -// [FRONTIER] Intersection and containment operations remain incomplete. // [INFERRED] Source placement. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-07-knowledge] Complete and validate the remaining PlanePolygon operations. #ifndef AI_AIINTERFACE_BFKNOWLEDGE_PLANEPOLYGON_H #define AI_AIINTERFACE_BFKNOWLEDGE_PLANEPOLYGON_H @@ -38,15 +34,16 @@ class PlanePolygon : public IPlanePolygon public: PlanePolygon(); explicit PlanePolygon(const std::list& vertices); - PlanePolygon(BoundingBox* box, const Mat4& transformation); // [FRONTIER] + PlanePolygon(BoundingBox* box, const Mat4& transformation); + PlanePolygon(const Vec3& direction, BoundingBox* box); virtual ~PlanePolygon(); virtual IPlanePolygon* fromTransform(const Mat4& transformation) const; virtual void setVertices(std::list& vertices); virtual const std::list& getVertices() const; virtual void getScaledVertices(std::list& out, const Vec2& scale) const; - virtual bool intersects(const Vec2& a, const Vec2& b) const; // [FRONTIER] - virtual bool isInside(const Vec2& a, const Vec2& b) const; // [FRONTIER] + virtual bool intersects(const Vec2& a, const Vec2& b) const; + virtual bool isInside(const Vec2& a, const Vec2& b) const; private: /* +0x04 */ std::list m_vertices; diff --git a/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp b/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp index 81754e555..2858d7dbd 100644 --- a/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp +++ b/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp @@ -1,6 +1,7 @@ #include "AIEventListener.h" +#include #include #include #include @@ -10,7 +11,11 @@ #include "../../../Game/Objects/IPlayer.h" // world::IPlayer::getId / getIsAIPlayer #include "../SingletonServer.h" // BFSingletonServer::m_iaiEventCourier #include "../BFKnowledge/BFGame.h" // IAIGame::setIsPrecaching / isPlaying -#include "../BFKnowledge/AIPlayerFactory.h" // IAIPlayerFactory +#include "../BFKnowledge/AIPlayerFactory.h" // IAIPlayerFactory, isOccupiedObject +#include "../BFKnowledge/IAIObject.h" // the vehicle and armament arms +#include "../BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit / IAIObjectPhysical +#include "../Module/BFConsole.h" // BFConsole::getAIMessageSettings (radio) +#include "../../AIDLL/AI/AIKnowledge/BFInformationCourier.h" // IAIInformationCourier armament #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/Main/AIEventCourier.h" // IAIEventCourier - 55 named slots #include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings::getDraw @@ -75,17 +80,90 @@ void AIEventListener::registerEvents() namespace { -// [FRONTIER] [TEMP] [CHOSEN, not recovered] - one per unwritten arm, each naming its own -// (category, id) so the next person knows exactly which dispatch entry is wanted rather than only -// that `handleEvent` was reached. [RETIRE-WHEN: aidll-01-adapters] -void unwrittenArm(const char* what, int category, unsigned int id) +// Category 3 id 0x16 (enemy spotted): SpottedEvent::executeServer's eight-byte stack block, an AI +// object pointer followed by the low byte of the team. The x86 layout is retail's (team at +4); +// the struct keeps the team after the full pointer on native x64. +struct SpottedPayload { - std::fprintf(stderr, - "[FRONTIER] dice::hfe::ai::AIEventListener::handleEvent - %s" "\n" - " category=%d id=%u" "\n", - what, category, id); - std::fflush(stderr); - std::abort(); + IAIObject* aiObject; // +0x00 + unsigned char team; // +0x04 +}; +#if defined(_M_IX86) +static_assert(offsetof(SpottedPayload, team) == 4, "retail spotted-event team byte"); +#endif + +// Category 3 ids 1 and 2 (seat entered / left): the five-dword block Soldier::enter posts +// (Soldier.cpp SoldierAiSeatPayload). The arms read +0x10 as a byte (`cmpb $0x0, 0x10(%esi)`). +struct SeatPayload +{ + IAIObject* object; // +0x00 the entered object (id 1) / the leaving soldier (id 2) + IAIObject* other; // +0x04 id 1: the armament lender; id 2: the vehicle left + int team; // +0x08 + int playerId; // +0x0C + int flag; // +0x10 low byte tested +}; + +// Category 3 id 0 (player killed): two ints, then the object whose borrowed armament is returned. +struct KilledPayload +{ + int a; // +0x00 eventPlayerKilled's second argument + int b; // +0x04 its first + IAIObject* object; // +0x08 +}; + +// Category 3 ids 6 / 7 (man down / revived): Soldier.cpp SoldierAiPlayerPayload. +struct ObjectPlayerPayload +{ + IAIObject* object; // +0x00 + int playerId; // +0x04 +}; + +// Category 3 ids 3 and 17: an int followed by an object. +struct IntObjectPayload +{ + int value; // +0x00 id 3: eventPlayerExitVehicle's int; id 17: the bridge's int + IAIObject* object; // +0x04 +}; + +// Category 3 id 10 (radio): the message key and two ints, all forwarded. +struct RadioPayload +{ + int message; // +0x00 BFConsole::getAIMessageSettings key + int a; // +0x04 + int b; // +0x08 +}; + +// Category 3 id 15 (commander request), 68 bytes copied to the stack whole (bf2 0x842FE75). +// Only +0x00 (type), +0x30, +0x34 and +0x38 are read; the rest is [UNRESOLVED]. +struct CommanderRequestPayload +{ + int type; // +0x00 0 artillery, 1 UAV, 2 vehicle drop, 3 supply + unsigned short unknown04; // +0x04 + Vec3 unknown08[3];// +0x08 + unsigned char unknown2C; // +0x2C + int a; // +0x30 + int b; // +0x34 + Vec3 position; // +0x38 +}; +static_assert(sizeof(CommanderRequestPayload) == 0x44, "retail 68-byte commander request"); + +#if defined(_M_IX86) +static_assert(sizeof(SeatPayload) == 20 && offsetof(KilledPayload, object) == 8 + && offsetof(IntObjectPayload, object) == 4, "retail ECAI payloads"); +#endif + +IAIInformationCourier* informationCourier() +{ + return static_cast(CommonSingletonServer::m_iaiInformationCourier); +} + +// The armament hand-back of ids 0, 2 and 14 once the unit must borrow armament: reset it, and the +// information courier resets both sides' handles (1 then 2). +void returnArmament(IAIObject* object) +{ + object->resetArmament(); // +0x80 + informationCourier()->resetArmament(object->getHandle(1)); // +0x30 + informationCourier()->resetArmament(object->getHandle(2)); } } // anonymous namespace @@ -253,9 +331,9 @@ void AIEventListener::handleEvent(EventCategory category, case 0x16u: { - // The payload is an object pointer followed by a team byte at offset 4. - const unsigned char* const bytes = static_cast(userData); - courier->event_enemySpotted(*static_cast(userData), bytes[4]); + // The payload is an object pointer followed by a team byte (offset 4 on x86). + const SpottedPayload* const payload = static_cast(userData); + courier->event_enemySpotted(payload->aiObject, payload->team); } return; @@ -263,56 +341,179 @@ void AIEventListener::handleEvent(EventCategory category, courier->event_isRepaired(*static_cast(userData)); return; - // the arms that dereference the payload as a world::IObject - // Each of these walks a vehicle or a pathfinding map through `world::IObject` vtable slots - // this tree does not name yet (decimal +116, +124, +128, +148, +152, +200, +204, +208, +252 - // and +296). Naming them is a `world::IObject` slot-map job, not an AI one, and guessing - // them would put ten wrong method names in the tree. Each stop below says which arm it is. + // bf2 0x842F7BE: the kill, then a non-null unit object's borrowed armament goes back + // (isUnit +0x74 gates the getUnit dereference). case 0u: - unwrittenArm("category 3 id 0 - player killed, plus the vehicle's armament release", - (int)category, id); + { + const KilledPayload* const p = static_cast(userData); + courier->eventPlayerKilled(p->b, p->a); + IAIObject* const object = p->object; + if (object && object->isUnit() // no getUnit null test here + && object->getUnit()->mustBorrowArmament(object)) + returnArmament(object); + } return; + + // bf2 0x842F870: entering a seat. The entered object takes the team (setSide +0x128), its + // primary object's physics are enabled for that team (IAIObjectPhysical +0x74), a unit that + // must borrow armament borrows the lender's (+0x7C) and the information courier links both + // sides' handles (+0x2C lender, borrower), the lender leaves the grid (+0xC8), and the AI + // hears eventPlayerEnterVehicle(playerId, object, lender). case 1u: - unwrittenArm("category 3 id 1 - player entered vehicle (and the 'not prepared for use" - " with AI' Debug at line 166)", (int)category, id); + { + const SeatPayload* const p = static_cast(userData); + IAIObject* const object = p->object; + if (!object) + { + if (static_cast(p->flag)) + return; + // The image logs and carries on into the null object (line 166). + Debug(DebugTypeError, "AI/AIInterface/Main/AIEventListener.cpp", 166, "") + << "You have tried to enter a vehicle that is not prepared for use with AI." + " Game will crash."; + } + IAIObject* const primary = object->getPrimaryObject(); + IAIObject* const lender = p->other; + object->setSide(p->team); + if (primary) + { + IAIObjectPhysical* const physical = primary->getPhysical(); + if (physical) + physical->enablePhysics(p->team); + } + if (lender && object->getUnit() && object->getUnit()->mustBorrowArmament(object)) + { + object->borrowArmament(lender); + { + const unsigned int borrower = object->getHandle(1); + informationCourier()->borrowArmament(lender->getHandle(1), borrower); + } + { + const unsigned int borrower = object->getHandle(2); + informationCourier()->borrowArmament(lender->getHandle(2), borrower); + } + } + if (p->other) + p->other->removeFromGrid(); + courier->eventPlayerEnterVehicle(p->playerId, p->object, p->other); + } return; + + // bf2 0x842FAB0: leaving a seat. The vehicle left returns borrowed armament and, when + // nobody else occupies it, goes neutral (setSide 0); the soldier re-enters the grid. case 2u: - unwrittenArm("category 3 id 2 - player exited vehicle", (int)category, id); + { + const SeatPayload* const p = static_cast(userData); + if (static_cast(p->flag)) + return; + IAIObject* const vehicle = p->other; + IAIObject* const soldier = p->object; + if (vehicle) + { + if (vehicle->getUnit() && vehicle->getUnit()->mustBorrowArmament(vehicle)) + returnArmament(vehicle); + if (!isOccupiedObject(vehicle, vehicle)) + vehicle->setSide(0); + } + if (soldier) + soldier->reInsertInGrid(); // +0xCC + } return; + + // bf2 0x842FB84. case 3u: - unwrittenArm("category 3 id 3 - eventPlayerExitVehicle", (int)category, id); + { + const IntObjectPayload* const p = static_cast(userData); + courier->eventPlayerExitVehicle(p->object, p->value); + } return; + + // bf2 0x842FBE9: the payload is the AI object (Soldier's kit pick-up); update +0x4C. case 5u: - unwrittenArm("category 3 id 5 - object slot +76", (int)category, id); + static_cast(userData)->update(); return; + + // bf2 0x842FBF6. case 6u: - unwrittenArm("category 3 id 6 - man down", (int)category, id); + { + const ObjectPlayerPayload* const p = static_cast(userData); + courier->eventManDown(p->playerId, p->object); + } return; + + // bf2 0x842FC16: the object is updated first. case 7u: - unwrittenArm("category 3 id 7 - revived", (int)category, id); + { + const ObjectPlayerPayload* const p = static_cast(userData); + p->object->update(); + courier->eventRevived(p->playerId, p->object); + } return; + + // bf2 0x842FD3F: a known message (BFConsole::m_instance, read directly) is forwarded. case 0xAu: - unwrittenArm("category 3 id 10 - radio message (needs BFConsole::getAIMessageSettings," - " itself a frontier)", (int)category, id); + { + const RadioPayload* const p = static_cast(userData); + AIRadioMessageSettings settings; + if (BFConsole::m_instance->getAIMessageSettings(p->message, settings)) + courier->eventRadioMessage(settings, p->a, p->b); + } return; + + // bf2 0x842FDF7: armament release of a non-null object. case 0xEu: - unwrittenArm("category 3 id 14 - vehicle armament release", (int)category, id); + { + IAIObject* const object = static_cast(userData); + if (object && object->getUnit() && object->getUnit()->mustBorrowArmament(object)) + returnArmament(object); + } return; + + // bf2 0x842FE75: the commander's requests by type; others are logged at line 449. case 0xFu: - unwrittenArm("category 3 id 15 - commander request (artillery/uav/supply/vehicle drop)," - " a 68-byte payload struct", (int)category, id); + { + const CommanderRequestPayload request = *static_cast(userData); + switch (request.type) + { + case 0: courier->event_receivedArtilleryRequest(request.a, request.b, request.position); break; + case 1: courier->event_receivedUavRequest(request.a, request.b, request.position); break; + case 2: courier->event_receivedVehicleDropRequest(request.a, request.b, request.position); break; + case 3: courier->event_receivedSupplyRequest(request.a, request.b, request.position); break; + default: + Debug(DebugTypeError, "AI/AIInterface/Main/AIEventListener.cpp", 449, "") + << "AI received unknown request type: " << request.type; + break; + } + } return; + + // bf2 0x84301D9: while playing (IAIGame +0x60), the bridge's map position id is destroyed + // (with a null object) and the bridge reported destroyed. case 0x11u: - unwrittenArm("category 3 id 17 - bridge destroyed", (int)category, id); + if (static_cast(CommonSingletonServer::m_iaiGame)->isPlaying()) + { + const IntObjectPayload* const p = static_cast(userData); + IAIObject* const bridge = p->object; + courier->event_pathfindingMapIdDestroyed(bridge->getPhysical()->getMapPosId(), 0); + courier->event_bridgeDestroyed(bridge, p->value); + } return; + + // bf2 0x843023F: the payload is the AI object (ArmorGLComp's repair post). case 0x12u: - unwrittenArm("category 3 id 18 - bridge repaired", (int)category, id); + { + IAIObject* const bridge = static_cast(userData); + courier->event_pathfindingMapIdRestored(bridge->getPhysical()->getMapPosId()); + courier->event_bridgeRepaired(bridge); + } return; + + // bf2 0x8430280 / 0x843028A: the payload is the AI object. case 0x13u: - unwrittenArm("category 3 id 19 - object slot +204", (int)category, id); + static_cast(userData)->reInsertInGrid(); return; case 0x14u: - unwrittenArm("category 3 id 20 - object slot +200", (int)category, id); + static_cast(userData)->removeFromGrid(); return; default: diff --git a/Code/BF2/AI/AIInterface/Module/BFConsole.cpp b/Code/BF2/AI/AIInterface/Module/BFConsole.cpp index 5caa0cf25..1fd9352c2 100644 --- a/Code/BF2/AI/AIInterface/Module/BFConsole.cpp +++ b/Code/BF2/AI/AIInterface/Module/BFConsole.cpp @@ -1,12 +1,13 @@ #include "BFConsole.h" -#include // the [FRONTIER] stops - stderr, not Debug; see the note at the first one -#include // std::abort - same +#include #include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" +#include "../../../Core/Debug.h" +#include "../../../Core/Ids.h" #include "../AIInstance.h" #include "../SingletonServer.h" #include "../Main/AIEventListener.h" @@ -48,13 +49,23 @@ #include "../BFKnowledge/WeaponTemplateManager.h" #include "../../../Core/ConsoleObjectMacro.h" #include "../../../Core/StringUtil.h" - +#include "../../../Game/IGameLogic.h" // addAIRadioMessage: gameLogic +#include "../../../Game/IGame.h" +#include "../../../Game/Objects/IPlayer.h" +#include "../../../Scene/Object/PlayerManager.h" +#include "../../../Game/GameLogic/ScoreSystem/ScoreManager.h" +#include "../../../Physics/BasicPhysicsSystem.h" +#include "../../../Game/GameLogic/GameLogic.h" // getVoiceMessages +#include "../../../Game/GameLogic/VoiceMessages.h" // namesToIds + +#include #include namespace dice { namespace hfe { extern ClassManager* classManager; +namespace world { extern IBase* scoreManager; } namespace ai { @@ -130,7 +141,7 @@ KitTemplate* getActiveKitTemplate() namespace { // [CHOSEN] native list key. Retail pushes every generated binding of this TU onto one list -// this tree's recovered subset - aiTemplate, aiTemplatePlugIn and kitTemplate so far +// this tree's recovered subset - aiTemplate, aiTemplatePlugIn, kitTemplate and aiComm so far // shares this one. const char* const kKitTemplateConsoleTag = "hfe.ai.kitTemplate"; @@ -655,6 +666,18 @@ BF2_CONSOLE_METHOD_2_STATIC_ACTIVE(setBattleStrength, consoleKitTemplateSetBattl getActiveKitTemplate() != 0, CombatStrengthType, int, kKitTemplateConsoleTag) #pragma pop_macro("BF2_CC_CONVERT") +// aiComm (ConsoleClass262, bf2 0x887E470): access 2, category 0; active while the console exists. +// The executor copies the name and forwards the three floats to the console instance. +namespace { +void consoleAddAIRadioMessage(std::string name, float modifier, float maxSendPeriod, float receiveTimeToLive) +{ + BFConsole::m_instance->addAIRadioMessage(name, modifier, maxSendPeriod, receiveTimeToLive); +} +} // namespace +BF2_CONSOLE_OBJECT("aiComm", 2, 0) +BF2_CONSOLE_METHOD_4_STATIC_ACTIVE(addAIRadioMessage, consoleAddAIRadioMessage, BFConsole::m_instance != 0, + std::string, float, float, float, kKitTemplateConsoleTag) + ConsoleObjectList& kitTemplateConsoleObjects() { return consoleBindingList(kKitTemplateConsoleTag); @@ -665,6 +688,7 @@ ConsoleObjectList& kitTemplateConsoleObjects() BFConsole* BFConsole::m_instance = 0; // Initializes console state and registers the AI adapter types. Registration keeps the first singleton. +// ELF 0x887ED00 / 0x887F790. BFConsole::BFConsole() : m_skipBulkClear(false) , m_singletonsCreated(false) @@ -694,6 +718,7 @@ BFConsole::BFConsole() } // Unregisters this console instance when it is the active singleton. +// ELF 0x8880190 / 0x88802C0. BFConsole::~BFConsole() { if (m_instance == this) @@ -701,12 +726,14 @@ BFConsole::~BFConsole() } // Returns null in this build. +// ELF 0x8881B50. void* BFConsole::getSinglePlayerInstance() { return 0; } // Constructs the engine-side AI adapters and refreshes cached singleton interfaces. +// ELF 0x88803F0. void BFConsole::createSingletons() { if (!m_singletonsCreated) @@ -761,6 +788,7 @@ void BFConsole::createSingletons() // Destroys the engine-side AI adapters and refreshes cached interfaces. // m_skipBulkClear suppresses one clearing pass. +// ELF 0x8881300. void BFConsole::clearSingletons() { if (m_skipBulkClear) @@ -815,8 +843,7 @@ void BFConsole::clearSingletons() } // Initializes the AI adapters needed for a game. -// [FRONTIER] [TEMP] [CHOSEN, not recovered] -// [RETIRE-WHEN: aidll-01-adapters] Replace remaining adapter stops with validated implementations. +// ELF 0x8881430. void BFConsole::aiMainInit() { // the two world adapters - see the block above. @@ -842,21 +869,66 @@ void BFConsole::aiMainInit() AITemplateManager::m_instance->createWreckTemplates(); } +// bf2 0x88816E0 (1135 B; recovered on the client track, docs/macos-c-singleplayer.md). The +// collision handler drops every tracked projectile (+0x08); the three template managers are +// deleted (nonvirtual destructors) and the kit manager through its deleting destructor (+0x10); +// all four are built again (their constructors install the singletons), each allocation checked +// like createSingletons (the Debug arms log and carry on); finally the AI game is told it is +// precaching (IAIGame +0x64, true). +// ELF 0x88816E0. void BFConsole::reset() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::ai::BFConsole::reset reached\n"); - std::fflush(stderr); - std::abort(); -} - -void BFConsole::addAIRadioMessage(const std::string& /*name*/, float, float, float) -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::ai::BFConsole::addAIRadioMessage reached\n"); - std::fflush(stderr); - std::abort(); + if (CommonSingletonServer::m_iBFCollisionHandler) + static_cast(CommonSingletonServer::m_iBFCollisionHandler)->removeAllProjectiles(); + if (AITemplateManager::m_instance) + delete AITemplateManager::m_instance; + if (AITemplatePlugInManager::m_instance) + delete AITemplatePlugInManager::m_instance; + if (WeaponTemplateManager::m_instance) + delete WeaponTemplateManager::m_instance; + if (KitTemplateManager::m_instance) + delete static_cast(KitTemplateManager::m_instance); + + AITemplateManager* templateManager = new AITemplateManager; // 0x24 + checkPointer(templateManager); + AITemplatePlugInManager* plugInManager = new AITemplatePlugInManager; // 0x20 + checkPointer(plugInManager); + WeaponTemplateManager* weaponTemplates = new WeaponTemplateManager(6); // 0x24 + checkPointer(weaponTemplates); + KitTemplateManager* kitTemplates = new KitTemplateManager; // 0x2C + checkPointer(kitTemplates); + + if (CommonSingletonServer::m_iaiGame) + static_cast(CommonSingletonServer::m_iaiGame)->setIsPrecaching(true); +} + +// bf2 0x8881BE0 (Hex-Rays; called only by the aiComm.addAIRadioMessage executor, ConsoleClass262). +// The voice message id comes from GameLogic's VoiceMessages (no voice, no filter); the radio +// message type from the name table the constructor filled, read without an end() test (an +// unknown name reads the header node, as shipped). Both maps keep an existing entry +// (insert_unique): settings[(unsigned char)id] = {type, modifier, max send period, receive time to +// live}, voices[type] = (unsigned char)id. AIRadioMessages.ai calls it once per message. +// ELF 0x8881B60. +void BFConsole::addAIRadioMessage(const std::string& name, float modifier, float maxSendPeriod, + float receiveTimeToLive) +{ + int messageId; + const std::string filter; + const std::string voice; + static_cast(gameLogic)->getVoiceMessages()->namesToIds(&messageId, 0, 0, name, voice, filter); + const AIRadioMessageType type = m_radioMessageTypes.find(name)->second; + AIRadioMessageSettings settings; + const int typeWord = static_cast(type); + std::memcpy(settings.m_opaque0, &typeWord, sizeof(typeWord)); + settings.m_modifier = modifier; + settings.m_maxSendPeriod = maxSendPeriod; + settings.m_receiveTimeToLive = receiveTimeToLive; + m_messageSettings.insert(std::make_pair(static_cast(messageId), settings)); + m_messageVoices.insert(std::make_pair(type, static_cast(messageId))); } // Resolves radio-message identifiers through the module courier. +// ELF 0x8881D90. bool BFConsole::getAIMessageSettings(int voiceId, AIRadioMessageSettings& settings) { // The key is the low byte - see the block above. @@ -870,6 +942,7 @@ bool BFConsole::getAIMessageSettings(int voiceId, AIRadioMessageSettings& settin return true; } +// ELF 0x8881E00. bool BFConsole::getVoiceFromAiMessageType(AIRadioMessageType type, int& voice) { std::map::const_iterator it = m_messageVoices.find(type); @@ -880,11 +953,101 @@ bool BFConsole::getVoiceFromAiMessageType(AIRadioMessageType type, int& voice) return true; } -void BFConsole::code(const std::string&) +// ELF 0x8881E50. ConsoleClass268's returned-string assignment also attests the result type. +std::string BFConsole::code(const std::string& command) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::ai::BFConsole::code reached\n"); - std::fflush(stderr); - std::abort(); + std::stringstream result; + world::IScoreManager* const scores = static_cast(world::scoreManager); + world::IPlayer* const player = world::playerManager->getLocalHumanPlayer(); + Debug(DebugTypeError, "AI/AIInterface/Module/BFConsole.cpp", 322, "") << "Does not work"; + if (!player) + { + result << "Error, could not find local player."; + return result.str(); + } + + const unsigned int team = static_cast(player->getTeam()); + const int tickets = scores->getTeamScore(team)->m_tickets; + float fraction = 0.0f; + bool reduceTickets = true; + if (equalsIgnoreCase(std::string(command.c_str()), std::string("Tobias.Karlsson"))) + { + if (game) + game->queryInterface(IID_IGameServer); + else + result << "Error, no game server active."; + // shipped defect: the failed server lookup does not prevent the ticket change. + fraction = 0.25f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("Jonathan.Gustavsson"))) + { + if (gameLogic->getGameStatus() == 1) + result << "Error, no active BotManager found."; + else + result << "Error, game must be running for this command."; + return result.str(); + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("Thomas.Skoldenborg")) || + equalsIgnoreCase(std::string(command.c_str()), std::string("Thomas.Sk\xF6ldenborg"))) + { + fraction = 0.33f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("TheAllSeeingEyeOfTheAIProgrammer"))) + { + fraction = 0.5f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("BotsCanCheatToo"))) + { + result << "The bots are CHEATING now, be aware."; + fraction = 0.75f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("ChallengeMyComputer"))) + { + result << "There goes the FRAME RATE."; + fraction = 0.75f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("EarthWalk"))) + { + static_cast(world::basicPhysicsSystem)->setGravity(-10.0f); + result << "GRAVITY set to EARTH. Home sweet home."; + reduceTickets = false; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("MoonWalk"))) + { + static_cast(world::basicPhysicsSystem)->setGravity(-1.67f); + result << "GRAVITY set to MOON. Let's dance!"; + fraction = 0.75f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("SpaceWalk"))) + { + static_cast(world::basicPhysicsSystem)->setGravity(-0.1f); + result << "GRAVITY set to SPACE. Better hold on tight!"; + fraction = 0.5f; + } + else if (equalsIgnoreCase(std::string(command.c_str()), std::string("FUBAR"))) + { + result << "QWERTY!"; + reduceTickets = false; + } + else + { + result << "Trying to cheat? \nShame on you! \n Feel my Wrath."; + const int remaining = tickets < 2 ? tickets : 1; + scores->getTeamScore(team)->setTickets(remaining); + reduceTickets = false; + } + + if (reduceTickets) + { + world::TeamScore* const score = scores->getTeamScore(team); + const float remaining = static_cast(tickets) * fraction; + score->setTickets(static_cast(remaining)); + } + // shipped defect: a busy loop only polls tickets and increments a local counter. + for (int i = 0; i < tickets - scores->getTeamScore(team)->m_tickets; ++i) + { + } + return result.str(); } // Registers the module courier interface for access through the singleton registry. diff --git a/Code/BF2/AI/AIInterface/Module/BFConsole.h b/Code/BF2/AI/AIInterface/Module/BFConsole.h index cb86ab276..daa07a74d 100644 --- a/Code/BF2/AI/AIInterface/Module/BFConsole.h +++ b/Code/BF2/AI/AIInterface/Module/BFConsole.h @@ -18,7 +18,7 @@ std::list& kitTemplateConsoleObjects(); class AIEventListener; // Radio-message values are four-byte integers; the constructor maps names to values -// 0..4 and 6..17. [FRONTIER] Enumerator names are unknown, so the enum remains opaque. +// 0..4 and 6..17. [UNRESOLVED] Enumerator names are unknown, so the enum remains opaque. enum AIRadioMessageType : int; // Settings for an AI radio message; preserve the field order used by the courier. @@ -36,15 +36,15 @@ class BFConsole BFConsole(); ~BFConsole(); - void createSingletons(); // [FRONTIER] - void clearSingletons(); // [FRONTIER] | - void aiMainInit(); // [FRONTIER] - void reset(); // [FRONTIER] + void createSingletons(); + void clearSingletons(); + void aiMainInit(); + void reset(); void addAIRadioMessage(const std::string& name, float a, float b, float c); - // [FRONTIER] - bool getAIMessageSettings(int, AIRadioMessageSettings&); // [FRONTIER] - bool getVoiceFromAiMessageType(AIRadioMessageType, int&); // [FRONTIER] - void code(const std::string&); // [FRONTIER] + bool getAIMessageSettings(int, AIRadioMessageSettings&); + bool getVoiceFromAiMessageType(AIRadioMessageType, int&); + // Emits the retail error diagnostic, then processes a legacy single-player code. + std::string code(const std::string& command); // Always returns null. static void* getSinglePlayerInstance(); diff --git a/Code/BF2/AI/AIInterface/SingletonServer.h b/Code/BF2/AI/AIInterface/SingletonServer.h index 4eb40ae2b..d537e85ec 100644 --- a/Code/BF2/AI/AIInterface/SingletonServer.h +++ b/Code/BF2/AI/AIInterface/SingletonServer.h @@ -14,6 +14,7 @@ class IAIEventCourier; class ISingletonServerUpdater { public: + ISingletonServerUpdater(); virtual ~ISingletonServerUpdater(); virtual void update() = 0; }; From cc1bf5e73c61477df2536107517a81bdb4b94f24 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Tue, 3 Nov 2026 19:02:07 +0100 Subject: [PATCH 04/71] AI: build manifests for the Windows AIDLL and the native Linux AI library One AIDLL source manifest, Code/Build/aidll_sources.txt, feeds both CMake and aidll.cmd. It lists the units in the retail link order, which is also the static-initialisation order, read from the .ctors table of libaidll.so. The engine image excludes every AIDLL-only unit by a directory rule (AI/AIDLL minus the shared CommonSingletonServer, plus three units outside it), so bf2_w32ded.exe never links them. syntaxcheck.cmd covers every AI unit. The linux-x64 preset builds a native libaidll.so with an export map (AidllAbi); this native library is a native-port design, not retail. AIDLL test fixtures are updated for the retired stops. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: OpenAI Codex --- CMakeLists.txt | 254 +--- Code/AidllAbi/aidll-posix.map | 5 + Code/Build/aidll.cmd | 122 +- Code/Build/aidll_sources.txt | 471 ++++++++ Code/Build/build.cmd | 86 +- Code/Tests/aidll/navmesh_loader_runtime.cpp | 2 +- Code/Tests/aidll/posix_loader.cpp | 42 + Code/Tests/syntaxcheck.cmd | 1186 +++++++++++++++---- 8 files changed, 1555 insertions(+), 613 deletions(-) create mode 100644 Code/AidllAbi/aidll-posix.map create mode 100644 Code/Build/aidll_sources.txt create mode 100644 Code/Tests/aidll/posix_loader.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 87b445db0..df809763e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -138,89 +138,16 @@ list(SORT bf2_engine_headers) # Its AIDLL-only half WAS SPLIT OUT on 2026-09-08 into AI/AIDLL/AI/Main/AISingletonServer.cpp, which # this list excludes - `AISingletonServer` exists only in libaidll.so. The side-DLL target that the # old note was waiting for is Code/Build/aidll.cmd plus bf2_aidll below. -set(bf2_aidll_only_sources +# AIDLL_w32ded.dll / libaidll owns every TU under AI/AIDLL except the shared singleton bridge +# (the same directory rule as Code/Build/build.cmd), plus three units outside it. This list is an +# exclusion set for the engine image only, so its order is irrelevant; the DLL's own link order is +# the explicit bf2_aidll_sources manifest below. +file(GLOB_RECURSE bf2_aidll_only_sources CONFIGURE_DEPENDS "${BF2_ROOT}/AI/AIDLL/*.cpp") +list(REMOVE_ITEM bf2_aidll_only_sources "${BF2_ROOT}/AI/AIDLL/AI/Main/CommonSingletonServer.cpp") +list(APPEND bf2_aidll_only_sources "${BF2_ROOT}/Core/DllModule.cpp" "${BF2_ROOT}/Core/DllGlobals.cpp" # the side-DLL image's globals TU - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotNavigation.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSquad.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSenses.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/Information.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmamentReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPICover.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AICollisionHandler.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIEventCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMineManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPlayerCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp" # libaidll materialId parser - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp" # libaidll only - chunk 04 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp" # libaidll only - live polygon query - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp" # libaidll only - chunk 04 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadFormation.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadMember.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMemory.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSubObjects.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIConsole.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategic/SAI.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotBehaviourManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/CommunicationHub.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/StrategyManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPathfinding.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/IAIPathfinding.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/UserOrderManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIModule.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIRandom.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/AILODManager.cpp" # libaidll only - chunk 02 - "${BF2_ROOT}/AI/AIDLL/AI/Main/IBotManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISettings.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISingletonServer.cpp" # libaidll only - see the split, below - "${BF2_ROOT}/AI/AIDLL/AI/Main/BF2AI.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotManager.cpp" + "${BF2_ROOT}/Math/DoubleVec3.cpp" ) list(REMOVE_ITEM bf2_engine_sources ${bf2_aidll_only_sources}) @@ -1077,9 +1004,8 @@ endif() # BF2_BUILD_LINUX / MSVC link contracts # ================================================================================================= # bf2_aidll - THE BOT-AI SIDE-DLL IMAGE. -# The native-x64 profile is intentionally dedicated-only. Do not let it emit x64 binaries under -# the shipped x86 AIDLL/BF2 names; those ports require separate targets and ABI validation. -if(NOT BF2_BUILD_X64) +# Windows x64 remains dedicated-only; Linux builds its own native libaidll.so. +if(NOT BF2_BUILD_X64 OR BF2_BUILD_LINUX) # # AIDLL_w32ded.dll is a THIRD server-side image built from this same tree: bf2_w32ded.exe loads it # through ai::AIConnection::init -> LoadLibraryBf -> the exported initDll, and reaches it afterwards @@ -1094,8 +1020,8 @@ if(NOT BF2_BUILD_X64) # in step; aidll.cmd is the one the harness and every gate use. # # EXCLUDE_FROM_ALL, and /FORCE for the same reason bf2_w32ded is: every unwritten function links at -# RVA 0 and faults BY NAME on the path that reaches it. The only unresolved symbol today is -# ai::informationManager, the InformationManager frontier BF2AI.cpp declares and chunk 02 fills. +# RVA 0 and faults BY NAME on the path that reaches it. +# Any remaining unresolved symbol must be reported by the strict-link gate. # # OUTPUT: /AIDLL_w32ded.dll - the build tree's bin/, NEVER the game folder. # "D:/B2BF Launcher/Battlefield2/AIDLL_w32ded.dll" is the REFERENCE binary. The server reaches the @@ -1105,109 +1031,54 @@ if(NOT BF2_BUILD_X64) set(BF2_AIDLL_OUTPUT_DIR "${CMAKE_BINARY_DIR}/bin" CACHE PATH "Where AIDLL_w32ded.dll is written (NOT the game folder - the original lives there)") -add_library(bf2_aidll SHARED EXCLUDE_FROM_ALL - # group 1 - the module entry point; engine code compiled into every side-DLL, never into the exe - "${BF2_ROOT}/Core/DllModule.cpp" - "${BF2_ROOT}/Core/DllGlobals.cpp" - # group 2 - the AIDLL-only AI translation units - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotNavigation.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSquad.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSenses.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPContext.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/Information.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIArmamentReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPICover.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/DrawPrimitives/DPManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AICollisionHandler.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIEventCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMineManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPlayerCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/Material.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIPlanInterpreter/BAPEntries.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadFormation.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/SquadMember.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotMemory.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBot/BotSubObjects.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIConsole.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/AIStrategic/SAI.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotBehaviourManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/CommunicationHub.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/StrategyManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIPathfinding.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/IAIPathfinding.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/UserOrderManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIMain.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIModule.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AIRandom.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AILODManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/IBotManager.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISettings.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/AISingletonServer.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BF2AI.cpp" - "${BF2_ROOT}/AI/AIDLL/AI/Main/BotManager.cpp" - # group 3 - present in BOTH shipped images - "${BF2_ROOT}/AI/AIDLL/AI/Main/CommonSingletonServer.cpp" - # group 4 - engine translation units libaidll.so statically links, added as the strict link - # demands them (census/00_statically_linked_engine_code.tsv confirms each one is really there) - "${BF2_ROOT}/Core/ConsoleObjects.cpp" # 0x4865C0.. - registerConsoleObjects, AIModule::init - "${BF2_ROOT}/Core/ConsoleObjectBase.cpp" # the ConsoleClassN base - the ai.init binding - "${BF2_ROOT}/Math/Frustum.cpp" # a bot sees by frustum - BotSenses - "${BF2_ROOT}/Math/Mat4Inverse.cpp" # AIDLL PE body matches the recovered client PE body - "${BF2_ROOT}/AI/AIInterface/BFKnowledge/PlanePolygon.cpp" # physical-cover fallback dependency - "${BF2_ROOT}/Math/Plane3.cpp" # Frustum pulls Plane3::transform + intersect - "${BF2_ROOT}/Math/Vec3.cpp" # Vec3::getZero - BotMain's constructor - "${BF2_ROOT}/Core/Debug.cpp" # 0x487C30.. - Debug ctor/dtor, reached by checkPointer - "${BF2_ROOT}/Core/StringUtil.cpp" # 0x487AF0 - calcStringHashValueNoCase, for StringHashFunc - # Kept in step with Code/Build/aidll.cmd (2026-09-28): File.cpp joined that manifest on - # 2026-09-11 without this list; PlayerInput.cpp joins both for Input::setInput. - "${BF2_ROOT}/IO/File/File.cpp" # io::File - AerialHeightMap's file paths - "${BF2_ROOT}/IO/Input/PlayerInput.cpp" # 0x18F020 - setInput(float), the plan executor -) +# The AI side-DLL manifest, in link order (= static-initialisation order), shared with aidll.cmd. +set(bf2_aidll_manifest "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/aidll_sources.txt") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${bf2_aidll_manifest}") +file(STRINGS "${bf2_aidll_manifest}" bf2_aidll_manifest_lines) +set(bf2_aidll_sources) +foreach(bf2_aidll_line IN LISTS bf2_aidll_manifest_lines) + string(STRIP "${bf2_aidll_line}" bf2_aidll_line) + if(bf2_aidll_line AND NOT bf2_aidll_line MATCHES "^#") + list(APPEND bf2_aidll_sources "${BF2_ROOT}/${bf2_aidll_line}") + endif() +endforeach() +add_library(bf2_aidll SHARED EXCLUDE_FROM_ALL ${bf2_aidll_sources}) +if(BF2_BUILD_LINUX) + # [CHOSEN, not recovered] Native Linux AI image (a native-port design, not retail); same host toolchain + # and STL ABI as bf2. Never substitute the retail 32-bit libaidll.so. + bf2_configure_cpp_target(bf2_aidll) + bf2_set_image(bf2_aidll 1) + bf2_set_platform_compat(bf2_aidll) + target_compile_definitions(bf2_aidll PRIVATE BF2_IMAGE_AIDLL=1 BF2_PLATFORM_POSIX) + target_include_directories(bf2_aidll PRIVATE ${BF2_PYTHON_INCLUDE_DIRS}) + target_link_libraries(bf2_aidll PRIVATE Threads::Threads ${CMAKE_DL_LIBS}) + set_target_properties(bf2_aidll PROPERTIES + OUTPUT_NAME aidll + LIBRARY_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}" + FOLDER "BF2") + # Keep module globals private, including names also defined by the engine. The only + # cross-image entry points are the existing ClassManager handshake exports. + target_link_options(bf2_aidll PRIVATE + -Wl,--no-undefined + "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") + set_property(TARGET bf2_aidll APPEND PROPERTY LINK_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") + add_dependencies("${BF2_DEDICATED_TARGET}" bf2_aidll) + + # [CHOSEN, not recovered] Engine-free check of the real loader and export lookup. + add_executable(bf2_aidll_loader_check EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/aidll/posix_loader.cpp" + "${BF2_ROOT}/Core/PluginDll.cpp") + bf2_configure_cpp_target(bf2_aidll_loader_check) + bf2_set_image(bf2_aidll_loader_check 1) + bf2_set_platform_compat(bf2_aidll_loader_check) + target_link_libraries(bf2_aidll_loader_check PRIVATE ${CMAKE_DL_LIBS}) + set_target_properties(bf2_aidll_loader_check PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}") + set_target_properties(bf2_aidll_loader_check PROPERTIES BUILD_RPATH "\$ORIGIN") + add_dependencies(bf2_aidll_loader_check bf2_aidll) + +else() set_target_properties(bf2_aidll PROPERTIES LINKER_LANGUAGE CXX OUTPUT_NAME AIDLL_w32ded @@ -1241,6 +1112,11 @@ target_link_options(bf2_aidll PRIVATE /IGNORE:4006,4088,4098 ) +endif() # Linux / Windows AIDLL +endif() # x86 Windows or Linux AIDLL + +if(NOT BF2_BUILD_X64) + # ================================================================================================= # bf2_voipserver - THE VOICE-SERVER SIDE-DLL IMAGE. # diff --git a/Code/AidllAbi/aidll-posix.map b/Code/AidllAbi/aidll-posix.map new file mode 100644 index 000000000..4d06b9dd2 --- /dev/null +++ b/Code/AidllAbi/aidll-posix.map @@ -0,0 +1,5 @@ +/* [CHOSEN, not recovered] Native POSIX AI image boundary; prevent host interposition. */ +{ + global: initDll; deinitDll; + local: *; +}; diff --git a/Code/Build/aidll.cmd b/Code/Build/aidll.cmd index 88c0aeb82..491bce58a 100644 --- a/Code/Build/aidll.cmd +++ b/Code/Build/aidll.cmd @@ -123,101 +123,9 @@ rem at 0x18F020 (with setInputIsMapped and the bool overload). [PLATF rem NOT identical: the shared TU also instantiates Input, which rem the retail DLL does not carry - dead code here, recorded rather than split. rem =========================================================================== -set SOURCES=^ - "%ROOT%\Core\DllModule.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\BotMain.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\BotNavigation.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\BotSquad.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\SensingAgent.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\CommunicationAgent.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\BotSenses.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPlanInterpreter\BAPContext.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\Information.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\WeaponInfo.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIArmament.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIArmamentReal.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPICover.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIMobile.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIMobileReal.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIMobileKnown.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIUnit.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\InformationReal.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\WeaponInfoReal.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIPhysicalReal.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIUtils\VehicleOccupancy.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\BFInformationEnvironment.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\AIInformationGrid.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIUtils\DebugRendering\AIRenderUtil.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\BFInformationCourier.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\InformationFactory.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicMap\BFStrategicEnvironment.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicMap\BotSpawner.cpp" ^ - "%ROOT%\AI\AIDLL\AI\DrawPrimitives\DPManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AICollisionHandler.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIEventCourier.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIMineManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIPlayerCourier.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\BFPathfindingCourier.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\Material\Material.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\Material\MaterialManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\MapProperties.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTree.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeNode.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterGraph.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterNodeManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QTSearchNodeManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicMap\AerialHeightMap.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIPlanInterpreter\BAPEntries.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\SensingAgentPatterns.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\SquadManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\SquadCoordinator.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\SquadFormation.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\SquadMember.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\BotMemory.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBot\BotSubObjects.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBotBehaviour\UrgencyMerger.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIConsole.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIBotBehaviour\UrgeCurve.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CPNodeManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CoverPositionManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObjectManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AILandingZoneManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObject.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AIStrategicArea.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategicEntity\SAWayPoint.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIStrategic\SAI.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\BotBehaviourManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\CommunicationHub.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\StrategyManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIPathfinding.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\IAIPathfinding.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\UserOrderManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\AIKnowledge\WeaponInfoManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIMain.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIModule.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AIRandom.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AILODManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\IBotManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AISettings.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\AISingletonServer.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\BF2AI.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\BotManager.cpp" ^ - "%ROOT%\AI\AIDLL\AI\Main\CommonSingletonServer.cpp" ^ - "%ROOT%\AI\AIInterface\BFKnowledge\PlanePolygon.cpp" ^ - "%ROOT%\Core\DllGlobals.cpp" ^ - "%ROOT%\Core\ConsoleObjects.cpp" ^ - "%ROOT%\Core\ConsoleObjectBase.cpp" ^ - "%ROOT%\Core\Debug.cpp" ^ - "%ROOT%\Math\Frustum.cpp" ^ - "%ROOT%\Math\Mat4Inverse.cpp" ^ - "%ROOT%\Math\Plane3.cpp" ^ - "%ROOT%\Math\Vec3.cpp" ^ - "%ROOT%\IO\File\File.cpp" ^ - "%ROOT%\IO\Input\PlayerInput.cpp" ^ - "%ROOT%\Core\StringUtil.cpp" +rem The source list is Code\Build\aidll_sources.txt (shared with CMake; one path per line, link order). +rem It is read line by line: one 440-file "set SOURCES=" line exceeds cmd.exe's 8191-character limit. +set MANIFEST=%~dp0aidll_sources.txt echo [1/4] compiling set OK=0 @@ -225,16 +133,20 @@ set BAD=0 set /a OBJN=0 set OBJ_RSP=%OUT%\aidll_objects.rsp type nul > "%OBJ_RSP%" -for %%F in (%SOURCES%) do ( - set /a OBJN+=1 - cl %FLAGS% /Fo"%OUT%\!OBJN!_%%~nF.obj" "%%F" >"%OUT%\cl_%%~nF.log" 2>&1 - if errorlevel 1 ( - set /a BAD+=1 - echo COMPILE FAIL %%~nxF - type "%OUT%\cl_%%~nF.log" - ) else ( - set /a OK+=1 - echo "%OUT%\!OBJN!_%%~nF.obj">>"%OBJ_RSP%" +for /f "usebackq eol=# tokens=* delims=" %%L in ("%MANIFEST%") do ( + set "REL=%%L" + set "SRC=%ROOT%\!REL:/=\!" + for %%F in ("!SRC!") do ( + set /a OBJN+=1 + cl %FLAGS% /Fo"%OUT%\!OBJN!_%%~nF.obj" "%%~fF" >"%OUT%\cl_%%~nF.log" 2>&1 + if errorlevel 1 ( + set /a BAD+=1 + echo COMPILE FAIL %%~nxF + type "%OUT%\cl_%%~nF.log" + ) else ( + set /a OK+=1 + echo "%OUT%\!OBJN!_%%~nF.obj">>"%OBJ_RSP%" + ) ) ) echo %OK% compiled, %BAD% failed diff --git a/Code/Build/aidll_sources.txt b/Code/Build/aidll_sources.txt new file mode 100644 index 000000000..05548c92a --- /dev/null +++ b/Code/Build/aidll_sources.txt @@ -0,0 +1,471 @@ +# Source manifest of the AI side-DLL image (Windows AIDLL_w32ded.dll, Linux libaidll.so). +# One path per line, relative to Code/BF2. The order is the retail link order, read from the +# static-initialiser table (.ctors) of libaidll.so 1.5.3153 ia-32 and mapped to source files; units +# without a static initialiser sit alphabetically among their directory. Link order is the static- +# initialisation order of the image, so do not sort. Lines starting with # are comments. +# Read by CMakeLists.txt (bf2_aidll) and Code/Build/aidll.cmd. +AI/AIDLL/AI/AIBot/BotMain.cpp +AI/AIDLL/AI/AIBot/BotMemory.cpp +AI/AIDLL/AI/AIBot/BotNavigation.cpp +AI/AIDLL/AI/AIBot/BotSenses.cpp +AI/AIDLL/AI/AIBot/BotSquad.cpp +AI/AIDLL/AI/AIBot/CoverDetection.cpp +AI/AIDLL/AI/AIBot/BotSubObjects.cpp +AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp +AI/AIDLL/AI/AIBot/SensedObject.cpp +AI/AIDLL/AI/AIBot/SquadCoordinator.cpp +AI/AIDLL/AI/AIBot/SquadFormation.cpp +AI/AIDLL/AI/AIBot/SquadManager.cpp +AI/AIDLL/AI/AIBot/SquadMember.cpp +AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp +AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp +AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp +AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp +AI/AIDLL/AI/AIBot/WPBeachLanding.cpp +AI/AIDLL/AI/AIBot/WPCloseTo.cpp +AI/AIDLL/AI/AIBot/WPEmpty.cpp +AI/AIDLL/AI/AIBot/WPMoveTo.cpp +AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp +AI/AIDLL/AI/AIBot/WPPatrol.cpp +AI/AIDLL/AI/AIBot/SensingAgent.cpp +AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp +AI/AIDLL/AI/AIBot/CommunicationAgent.cpp +AI/AIDLL/AI/AIBot/Aimer.cpp +AI/AIDLL/AI/AIPlanInterpreter/BAPContext.cpp +AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp +# S0 behaviour-system skeleton +AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtObject3d.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAAimAtPoint3d.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluateCondition.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAForgetTarget.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAHonkHorn.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPALook.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPALookAhead.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPALookAtObject.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPALookAtPoint.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPALookInDir.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMergeSoldierInputs.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveAwayFrom3dObject.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3d.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dDirection.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveTo3dObject.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirect.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirection.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionDirect.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToDirectionFinding.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObject.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectDirect.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPANotifyBot.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAOverrideSensingAgent.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAPhysicsEnable.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAResetControls.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPARevive.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPARoll3d.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPASendRadioMessage.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPASetSensingAgentFocus.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPATrigger.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPATriggerContinously.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPATurn.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsDirection.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPATurnTowardsObject.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAUpdateVehicle.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConDistanceToProj.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConEndOfPath.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConInsideBattleZone.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConIsTriggered.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConLineOfFire.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConPointAt.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConPointDistance.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConPointInFront.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConPosition.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConTriggerableActive.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPCConBombPrecision3d.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPCConLookDeviation.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision3d.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectBehind.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistance.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectDistanceToPoint.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectEnemyOccupied.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectExists.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInFront.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInLandingZone.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectMoved.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectOccupied.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectSpeed.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectTouchingLand.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPitchAiming.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidPosition.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidYawAiming.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectVisible.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPInfoWrapper.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPIWDefuseMines.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPIWTakeCover.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPCondition.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPStatement.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPICChangeVehicle.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPICTurnLock.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPWrapperFinished.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPADebug.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAEvaluate.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPAIdle.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPASense.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPASoldierPose.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConFalse.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConIteration.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConObjectManDown.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConTime.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConTrue.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHeat.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponMagAmmo.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTotalAmmo.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPIWRoam.cpp +AI/AIDLL/AI/AIBotActionPlan/BAPWrapperWeapon.cpp +AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp +AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp +AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp +AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp +AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp +AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp +AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp +AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp +AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp +AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp +AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp +AI/AIDLL/AI/AIBotBehaviour/BBFireInfantery.cpp +AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp +AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp +AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp +AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp +AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp +AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp +AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp +AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp +AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp +AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp +AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp +AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp +AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp +AI/AIDLL/AI/AIBotBehaviour/BBTriggerable.cpp +AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp +AI/AIDLL/AI/AIBotBehaviour/UrgeCurve.cpp +AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPPattern.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp +AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp +AI/AIDLL/AI/AIPlanInterpreter/BAPDebugger.cpp +AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp +AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp +AI/AIDLL/AI/AIPlanInterpreter/BotScriptDebugger.cpp +AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp +AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp +AI/AIDLL/AI/AIPlanInterpreter/ControlFunctions.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToDirection.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToDirection.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToDirection.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryResetControls.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryInfoWrapper.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToDirection.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntrySense.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToDirection.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp +AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp +AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp +AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp +AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp +AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp +AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp +AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp +AI/AIDLL/AI/AIKnowledge/DangerObject.cpp +AI/AIDLL/AI/AIKnowledge/FireObject.cpp +AI/AIDLL/AI/AIKnowledge/Information.cpp +AI/AIDLL/AI/AIKnowledge/InformationDummy.cpp +AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp +AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp +AI/AIDLL/AI/AIKnowledge/InformationReal.cpp +AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp +AI/AIDLL/AI/Main/AIMineManager.cpp +AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp +AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp +AI/AIDLL/AI/AIKnowledge/InformationManager.cpp +AI/AIDLL/AI/Main/BFPathfindingCourier.cpp +AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp +AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp +AI/AIDLL/AI/AIUtils/AimerHelper.cpp +AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp +AI/AIDLL/AI/AIKnowledge/IPIArmamentDummy.cpp +AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp +AI/AIDLL/AI/AIKnowledge/IPIArmamentReal.cpp +AI/AIDLL/AI/AIKnowledge/IPIControlInfo.cpp +AI/AIDLL/AI/AIKnowledge/IPICover.cpp +AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp +AI/AIDLL/AI/AIKnowledge/IPIMobileDummy.cpp +AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp +AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp +AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp +AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp +AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp +AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp +AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp +AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp +AI/AIDLL/AI/AIKnowledge/WeaponInfoReal.cpp +Math/DoubleVec3.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/MapProperties.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/MeshImporterExporter.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/QTPath.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNode.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp +AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp +AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp +AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp +AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp +AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp +AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp +AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodePath.cpp +AI/AIDLL/AI/AIPathFinding/Material/Material.cpp +AI/AIDLL/AI/AIPathFinding/Material/MaterialManager.cpp +AI/AIDLL/AI/AIStrategic/SAI.cpp +AI/AIDLL/AI/AIStrategic/SCArea.cpp +AI/AIDLL/AI/AIStrategic/SCConstant.cpp +AI/AIDLL/AI/AIStrategic/SCHeterogeneous.cpp +AI/AIDLL/AI/AIStrategic/SCHomogeneous.cpp +AI/AIDLL/AI/AIStrategic/Strategy.cpp +AI/AIDLL/AI/AIStrategic/StrategyCondition.cpp +AI/AIDLL/AI/AIStrategic/StrategyPrerequisite.cpp +AI/AIDLL/AI/AIStrategicEntity/AILandingZone.cpp +AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp +AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp +AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp +AI/AIDLL/AI/AIStrategicEntity/AreaAssignment.cpp +AI/AIDLL/AI/AIStrategicEntity/SAWayPoint.cpp +AI/AIDLL/AI/AIStrategicEntity/GuardPosition.cpp +AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotDCB.cpp +AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp +AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp +AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp +AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp +AI/AIDLL/AI/Main/UserOrderManager.cpp +AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp +AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp +AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp +AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNodeManager.cpp +AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp +AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp +AI/AIDLL/AI/AIStrategicMap/SAIMapRenderUtil.cpp +AI/AIDLL/AI/AIStrategicMap/SAIMapSquare.cpp +AI/AIDLL/AI/AIStrategicMap/AICamera.cpp +AI/AIDLL/AI/AIStrategicMap/ScalarMap.cpp +AI/AIDLL/AI/AIStrategicMap/StatusMap.cpp +AI/AIDLL/AI/AIStrategicMap/TemperatureTree.cpp +AI/AIDLL/AI/AIStrategicMap/TemperatureTreeModifiers.cpp +# Vec3::getZero - BotMain's constructor +Math/Vec3.cpp +AI/AIDLL/AI/AIUtils/AIVectorMath.cpp +AI/AIDLL/AI/AIUtils/IAimerHelper.cpp +AI/AIDLL/AI/AIUtils/Opening.cpp +# physical-cover fallback dependency +AI/AIInterface/BFKnowledge/PlanePolygon.cpp +AI/AIDLL/AI/AIUtils/TraceUtils.cpp +AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp +AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp +AI/AIDLL/AI/DrawPrimitives/DPManager.cpp +AI/AIDLL/AI/DrawPrimitives/DPStatic2dText.cpp +AI/AIDLL/AI/DrawPrimitives/DPStatic3dText.cpp +AI/AIDLL/AI/DrawPrimitives/DPStaticCirlce.cpp +AI/AIDLL/AI/DrawPrimitives/DPStaticLine.cpp +AI/AIDLL/AI/DrawPrimitives/DPStaticMesh.cpp +AI/AIDLL/AI/DrawPrimitives/DPStaticPolygon.cpp +AI/AIDLL/AI/DrawPrimitives/DPStaticTriangle.cpp +AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp +AI/AIDLL/AI/Main/AICollisionHandler.cpp +AI/AIDLL/AI/Main/AIConsole.cpp +AI/AIDLL/AI/Main/AIEventCourier.cpp +AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp +AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp +AI/AIDLL/AI/Main/AILODManager.cpp +AI/AIDLL/AI/Main/AIMain.cpp +AI/AIDLL/AI/Main/AIPathfinding.cpp +AI/AIDLL/AI/Main/AIPlayerCourier.cpp +AI/AIDLL/AI/Main/AIRadio.cpp +AI/AIDLL/AI/Main/AIRandom.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp +AI/AIDLL/AI/AIUtils/DebugRendering/DPGraph.cpp +AI/AIDLL/AI/Main/AISettings.cpp +AI/AIDLL/AI/Main/AIStreamOperators.cpp +AI/AIDLL/AI/Main/BotBehaviourManager.cpp +AI/AIDLL/AI/Main/BotManager.cpp +AI/AIDLL/AI/Main/BotPlacementManager.cpp +AI/AIDLL/AI/Main/CommunicationHub.cpp +AI/AIDLL/AI/Main/IAIPathfinding.cpp +AI/AIDLL/AI/Main/StrategyManager.cpp +AI/AIDLL/AI/Main/BF2AI.cpp +AI/AIDLL/AI/Main/AIModule.cpp +AI/AIDLL/AI/Main/AISingletonServer.cpp +AI/AIDLL/AI/Main/CommonSingletonServer.cpp +AI/AIDLL/AI/Main/IBotManager.cpp +# the ConsoleClassN base - the ai.init binding +Core/ConsoleObjectBase.cpp +# demands them (census/00_statically_linked_engine_code.tsv confirms each one is really there) +# 0x4865C0.. - registerConsoleObjects, AIModule::init +Core/ConsoleObjects.cpp +# 0x487C30.. - Debug ctor/dtor, reached by checkPointer +Core/Debug.cpp +Core/DllGlobals.cpp +Core/DllModule.cpp +# shared array-storage allocation pair +Core/DllStlAllocator.cpp +# image-local Rand seed and iostream initialization +Core/Random.cpp +# 0x487AF0 - calcStringHashValueNoCase, for StringHashFunc +Core/StringUtil.cpp +# Kept in step with Code/Build/aidll.cmd (2026-09-28): File.cpp joined that manifest on +# 2026-09-11 without this list; PlayerInput.cpp joins both for Input::setInput. +# io::File - AerialHeightMap's file paths +IO/File/File.cpp +# shared memory stream and calcSeek +IO/Stream/MemStream.cpp +# shared eight-corner bounds +IO/Stream/BoundingBox.cpp +# a bot sees by frustum - BotSenses +Math/Frustum.cpp +# shared plane/ray and frustum/box intersections +Math/Intersect.cpp +# shared transformed bounds queries +Math/LocalBoundingBox.cpp +# shared 2D transform products and inverse +Math/Mat3.cpp +# 0x499B40 setRotateYDeg - SensingAgent::withinCamView +Math/Mat4.cpp +# AIDLL PE body matches the recovered client PE body +Math/Mat4Inverse.cpp +# lifecycle and PController, shared with bf2 +Math/Math.cpp +# Frustum pulls Plane3::transform + intersect +Math/Plane3.cpp +# PlayerInputMap token conversion +IO/Input/InputMapStream.cpp +# 0x18F020 - setInput(float), the plan executor +IO/Input/PlayerInput.cpp diff --git a/Code/Build/build.cmd b/Code/Build/build.cmd index c34727a27..f1a75aad6 100644 --- a/Code/Build/build.cmd +++ b/Code/Build/build.cmd @@ -106,8 +106,13 @@ for /r "%ROOT%" %%F in (*.cpp) do ( ) else ( set /a OK+=1 rem The repository contains source for more than one shipped image. Compile every TU - rem for coverage, but never link the seven AIDLL-only units into bf2_w32ded.exe. + rem for coverage, but never link AIDLL-only units into bf2_w32ded.exe. set "ENGINE_OBJECT=1" + rem AIDLL owns every TU under AI\AIDLL except the shared singleton bridge. + echo %%F | find /i "\AI\AIDLL\" >nul + if not errorlevel 1 set "ENGINE_OBJECT=0" + if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\CommonSingletonServer.cpp" set "ENGINE_OBJECT=1" + if /i "%%~fF"=="%ROOT%\Math\DoubleVec3.cpp" set "ENGINE_OBJECT=0" rem Code\BF2\VoipServer is a THIRD server-side image (BF2VoipServer_w32ded.dll - see rem bf2_voipserver in CMakeLists.txt). No unit in it is an engine member, so the whole rem directory is excluded here; CMakeLists.txt mirrors this with bf2_voipserver_only_sources. @@ -178,91 +183,12 @@ for /r "%ROOT%" %%F in (*.cpp) do ( if /i "%%~fF"=="%ROOT%\IO\Input\GameControllerDevice.cpp" set "ENGINE_OBJECT=0" if /i "%%~fF"=="%ROOT%\IO\Input\FalconDevice.cpp" set "ENGINE_OBJECT=0" if /i "%%~fF"=="%ROOT%\IO\Input\DX8InputDeviceManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\BotMain.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\BotNavigation.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\BotSquad.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\SensingAgent.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\CommunicationAgent.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\BotSenses.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPlanInterpreter\BAPContext.cpp" set "ENGINE_OBJECT=0" rem 2026-09-08, chunk 02: both managers are libaidll-only (CLASS_CENSUS_LIBAIDLL.tsv rows rem WeaponInfoManager 0x36CF40 and the fully inlined InformationManager); neither has a rem counterpart in bf2. Core\SpHandlePool.h is a header-only template and needs no row. - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\Information.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\WeaponInfo.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIArmament.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIArmamentReal.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPICover.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIMobile.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIMobileReal.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIMobileKnown.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIUnit.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\InformationReal.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\WeaponInfoReal.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\IPIPhysicalReal.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIUtils\VehicleOccupancy.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\BFInformationEnvironment.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\AIInformationGrid.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIUtils\DebugRendering\AIRenderUtil.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\WeaponInfoManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\BFInformationCourier.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIKnowledge\InformationFactory.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicMap\BFStrategicEnvironment.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicMap\BotSpawner.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\DrawPrimitives\DPManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AICollisionHandler.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIEventCourier.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIMineManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIPlayerCourier.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\BFPathfindingCourier.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\Material\MaterialManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\MapProperties.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTree.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeNode.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterGraph.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterNodeManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPathFinding\NavMesh\QTSearchNodeManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicMap\AerialHeightMap.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIPlanInterpreter\BAPEntries.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\SensingAgentPatterns.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\SquadManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\SquadCoordinator.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\SquadFormation.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\SquadMember.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\BotMemory.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBot\BotSubObjects.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBotBehaviour\UrgencyMerger.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIConsole.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIBotBehaviour\UrgeCurve.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CPNodeManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CoverPositionManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObjectManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AILandingZoneManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObject.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicEntity\AIStrategicArea.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategicEntity\SAWayPoint.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\AIStrategic\SAI.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\BotBehaviourManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\CommunicationHub.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\StrategyManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIPathfinding.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\IAIPathfinding.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\UserOrderManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIMain.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIModule.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AIRandom.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AILODManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\IBotManager.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AISettings.cpp" set "ENGINE_OBJECT=0" rem 2026-09-08: AISingletonServer exists ONLY in libaidll.so (0x2EAC60); the engine has rem BFSingletonServer instead. CommonSingletonServer.cpp keeps the half that is in BOTH rem images and stays in this link. See that file's header for the census rows. - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\AISingletonServer.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\BF2AI.cpp" set "ENGINE_OBJECT=0" - if /i "%%~fF"=="%ROOT%\AI\AIDLL\AI\Main\BotManager.cpp" set "ENGINE_OBJECT=0" if /i "%%~fF"=="%ROOT%\Game\Main\BF2Window.cpp" set "ENGINE_OBJECT=0" if /i "%%~fF"=="%ROOT%\Game\Main\BF2FrameInterpolator.cpp" set "ENGINE_OBJECT=0" if /i "%%~fF"=="%ROOT%\Game\Main\BF2Render.cpp" set "ENGINE_OBJECT=0" diff --git a/Code/Tests/aidll/navmesh_loader_runtime.cpp b/Code/Tests/aidll/navmesh_loader_runtime.cpp index 98a954e17..169afc4a4 100644 --- a/Code/Tests/aidll/navmesh_loader_runtime.cpp +++ b/Code/Tests/aidll/navmesh_loader_runtime.cpp @@ -213,7 +213,7 @@ class CountingDPManager : public IDPManager return false; } void setTextGamma(float) override { unexpected("setTextGamma"); } - float getTextGamma() override { unexpected("getTextGamma"); } + float getTextGamma() const override { unexpected("getTextGamma"); } void drawAll() override { unexpected("drawAll"); } void nodrawUpdate() override { unexpected("nodrawUpdate"); } int deleteAll() override { unexpected("deleteAll"); } diff --git a/Code/Tests/aidll/posix_loader.cpp b/Code/Tests/aidll/posix_loader.cpp new file mode 100644 index 000000000..c7a0216e8 --- /dev/null +++ b/Code/Tests/aidll/posix_loader.cpp @@ -0,0 +1,42 @@ +// [TEMP] [CHOSEN, not recovered] Engine-free POSIX loader fixture. Does not call initDll, +// create host services, bind sockets or establish AI initialization/gameplay coverage. +#include "../../BF2/Core/PluginDll.h" +#include +#include +#include + +// Satisfy references from the unused LoadLibraryBf body. Accidental invocation stops visibly. +namespace dice { namespace hfe { +class ClassManager; +ClassManager* classManager = nullptr; +namespace memory { +void memory_update_modules(const char*) +{ + std::fputs("[TEMP] POSIX loader fixture unexpectedly called memory_update_modules\n", stderr); + std::fflush(stderr); + std::abort(); +} +} +} } + +int main() +{ + void* library = ::LoadLibrary(".\\aidll.so"); + if (!library) + { + std::fprintf(stderr, "AI library load failed: %s\n", ::dlerror()); + return 1; + } + const bool exports = ::GetProcAddress(library, "initDll") != nullptr + && ::GetProcAddress(library, "deinitDll") != nullptr; + const bool privateGlobals = ::GetProcAddress(library, "_ZN4dice3hfe12classManagerE") == nullptr; + const bool closed = ::FreeLibrary(library); + if (!exports || !privateGlobals || !closed) + { + std::fprintf(stderr, "AI loader check failed: exports=%d privateGlobals=%d closed=%d\n", + exports, privateGlobals, closed); + return 1; + } + std::puts("AI library loaded, handshake exports found, globals private, library closed; initDll not called"); + return 0; +} diff --git a/Code/Tests/syntaxcheck.cmd b/Code/Tests/syntaxcheck.cmd index 25269fe83..65efcdf75 100644 --- a/Code/Tests/syntaxcheck.cmd +++ b/Code/Tests/syntaxcheck.cmd @@ -312,8 +312,6 @@ cl %FLAGS% "%~dp0..\BF2\Animation\BoneAnimation\CompressedAnim.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% "%~dp0..\BF2\Animation\BoneAnimation\RagDoll.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFGame.cpp" -if errorlevel 1 set /a RC+=1 cl %FLAGS% "%~dp0..\BF2\Physics\BspBuilder.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% "%~dp0..\BF2\Math\TriangleToAABBIntersection.cpp" @@ -840,110 +838,11 @@ cl %FLAGS% "%~dp0..\BF2\Physics\BasicPhysicsSystem.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% "%~dp0..\BF2\Scene\Object\WorldObjTemplPortal\PortalManager.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\Main\AIConnection.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\Module\BFConsole.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\IAIEventCourier.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\SingletonServer.cpp" -if errorlevel 1 set /a RC+=1 @rem Chunk 01's sixteen engine-side AI adapters plus the event listener (2026-09-08). @rem ENGINE members - unlike the AIDLL block below, these DO enter bf2_w32ded.exe. -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\Main\AIEventListener.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIPlayerFactory.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIPlayer.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplatePlugInManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplate.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplatePlugIn.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplatePhysical.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\InformationType.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateArmament.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateControlInfo.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateCover.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateMobile.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateUnit.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\SoldierPose.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\WeaponTemplate.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFCollisionHandler.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFCommander.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFGame.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFGameEffector.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFGraphCreator.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFObjectEnvironment.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFPhysics.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFRadioComm.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFSquad.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFTerrain.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFTimer.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\DebugRenderer.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\KitTemplateManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\KitTemplate.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\WeaponTemplateManager.cpp" -if errorlevel 1 set /a RC+=1 @rem AI chunk 07 (2026-09-29): the engine's AIObject family, its six plug-ins, the footprint polygon @rem and the AI weapon component (WeaponObject). -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObject.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectShared.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectPrimaryReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectPrimaryShared.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectSecondaryReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectSecondaryShared.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectArmament.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectControlInfo.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectCover.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectMobile.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectPhysical.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectUnit.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\PlanePolygon.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\WeaponObject.cpp" -if errorlevel 1 set /a RC+=1 @rem Side-image coverage. These TUs are AIDLL-only and are deliberately absent from the @rem bf2_w32ded engine-object manifest; CommonSingletonServer is the genuine shared member (its @@ -955,143 +854,6 @@ cl %FLAGS% "%~dp0..\BF2\Core\DllModule.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% "%~dp0..\BF2\Core\DllGlobals.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AISingletonServer.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotMain.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotNavigation.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotSquad.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgent.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\CommunicationAgent.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotSenses.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\BAPContext.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\Information.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfo.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIArmament.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIArmamentReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPICover.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIMobile.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIMobileReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIMobileKnown.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIUnit.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIPhysicalReal.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\VehicleOccupancy.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\BFInformationEnvironment.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\AIInformationGrid.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\AIRenderUtil.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\BFInformationCourier.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationFactory.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\BFStrategicEnvironment.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\BotSpawner.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AICollisionHandler.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIEventCourier.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIMineManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIPlayerCourier.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\BFPathfindingCourier.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Material\Material.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Material\MaterialManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\MapProperties.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterNodeManager.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QTSearchNodeManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTree.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeNode.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterGraph.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\AerialHeightMap.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\BAPEntries.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgentPatterns.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadManager.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadCoordinator.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadFormation.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadMember.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotMemory.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotSubObjects.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\UrgencyMerger.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIConsole.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\UrgeCurve.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CPNodeManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CoverPositionManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObjectManager.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AILandingZoneManager.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObject.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AIStrategicArea.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\SAWayPoint.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\SAI.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\BotBehaviourManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\CommunicationHub.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\StrategyManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIPathfinding.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\IAIPathfinding.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\UserOrderManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIMain.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIModule.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AIRandom.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AILODManager.cpp" -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\IBotManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\AISettings.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\BF2AI.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\BotManager.cpp" -if errorlevel 1 set /a RC+=1 -cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\CommonSingletonServer.cpp" -if errorlevel 1 set /a RC+=1 cl %FLAGS% "%~dp0..\BF2\Core\ClassFactoryInstances.cpp" if errorlevel 1 set /a RC+=1 @@ -1754,5 +1516,953 @@ if errorlevel 1 set /a RC+=1 cl %FLAGS0% "%~dp0..\BF2\Game\Objects\Visual\LightSourceTemplate.cpp" if errorlevel 1 set /a RC+=1 +@rem AI manifests: every engine AI TU and every AIDLL-only TU. +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\Aimer.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotMain.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotMemory.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotNavigation.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotSenses.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotSquad.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotSubObjects.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\CommunicationAgent.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\CoverDetection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\RandomSquareMerger.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensedObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgent.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgentPatterns.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadCoordinator.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadFormation.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadMember.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPAltitudeCloseTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPAltitudeMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPAltitudePatrol.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPBeachLanding.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPCloseTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPEmpty.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPMoveToBeachLanding.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\WPPatrol.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAAimAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAAimAt3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAAimAtObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAAimAtObject3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAAimAtPoint.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAAimAtPoint3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAChangeWeapon.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAComponentSoldierPose.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPADebug.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAEvaluate.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAEvaluateCondition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAForgetTarget.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAHonkHorn.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAIdle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPALook.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPALookAhead.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPALookAtObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPALookAtPoint.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPALookInDir.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMergeSoldierInputs.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveAwayFrom3dObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveTo3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveTo3dDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveTo3dObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToDirect.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToDirectionDirect.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToDirectionFinding.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToFinding.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToObjectDirect.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAMoveToObjectFinding.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPANotifyBot.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAOverrideSensingAgent.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAPhysicsEnable.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAPlaceC4.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAResetControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPARevive.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPARoll3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPARunOverObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPASendRadioMessage.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPASense.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPASetSensingAgentFocus.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPASoldierPose.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPATrigger.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPATriggerContinously.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPATurn.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPATurnTowardsDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPATurnTowardsObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAUpdateVehicle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPAUseFlareOnMissileLock.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPCConBombPrecision3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPCConLookDeviation.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPCConPrecision.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPCConPrecision3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPCombinerParallel.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPCombinerSerial.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConAllowFire.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConAnd.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConDistanceToProj.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConEndOfPath.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConFalse.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConInsideBattleZone.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConIsSprinting.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConIsTriggered.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConIteration.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConLineOfFire.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConNot.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectBehind.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectDistance.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectDistanceToPoint.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectEnemyOccupied.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectExists.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectHealth.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectInFront.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectInLandingZone.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectInsideFrustum.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectLineOfFire.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectManDown.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectMoved.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectOccupied.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectSpeed.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectTouchingLand.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectValidAiming.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectValidPitchAiming.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectValidPosition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectValidYawAiming.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConObjectVisible.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConOkToThrowGrenade.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConOr.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConPointAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConPointDistance.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConPointInFront.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConPosition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConSharedCondition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConSplashDamage.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConStrategicObjectStatus.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConTime.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConTotalAmmo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConTriggerableActive.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConTrue.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponDetonatorIsActive.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponHasLockOnTarget.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponHeat.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponIsActive.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponIsZoomed.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponMagAmmo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponReadyToFire.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponTargetReachable.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPConWeaponTotalAmmo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPCondition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPFlowCEnd.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPFlowCIf.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPFlowCWait.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPFlowCWhile.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPICChangeVehicle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPICTurnLock.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPIWChange.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPIWDefuseMines.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPIWFire.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPIWIdle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPIWMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPIWRoam.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPIWTakeCover.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPInfoWrapper.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPStatement.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPWrapperAiming.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPWrapperFinished.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPWrapperLookAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\BAPWrapperWeapon.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBAvoid.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBBridgeRepair.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBC4.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBCallForMedic.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBChange.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBChangeLandingCraft.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBChangeTeleport.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBDefuseMines.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBFire.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBFire3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBFireArtilleryDriver.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBFireInfantery.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBFireLargeBore.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBFireUnarmed.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBIdle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBMedicAssist.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBMoveToFixed.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBRandom.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBRevive.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBRunOverSoldier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBSuicide.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBTakeCover.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBTakeCover3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBTakeCoverInfantry.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBTriggerable.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BotBehaviour.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\UrgeCurve.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\UrgencyMerger.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\VehicleUrgencyCalculator.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPAvoidCollision.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPAvoidCollision2d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPAvoidCollision3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPAvoidCollisionInfantery.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPBridgeRepair.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPC4.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPCallForMedic.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPChange.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPChangeLandingCraft.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPChangeTeleport.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPDefuseMines.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPFire.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPFire2d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPFire2dDriver.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPFire3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPFireInfantery.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPGotoWaypoints2d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPGotoWaypoints3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPGotoWaypointsBoat.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPGotoWaypointsInfantery.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPHeliFire3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPIdle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPIdle2d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPIdle3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPIdleInfantery.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPMedicAssist.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPPattern.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPRandom.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPRevive.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPRoam.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPRoam2d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPRoam3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPRunOverSoldier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPSuicide.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPTakeCover.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPTakeCover3d.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPTakeCoverInfantry.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\BBPTriggerable.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviourPattern\WeaponChoice.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\AIInformationGrid.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\BFInformationCourier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\BFInformationEnvironment.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\DangerObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\FireObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIArmament.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIArmamentDummy.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIArmamentKnown.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIArmamentReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIControlInfo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPICover.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIMobile.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIMobileDummy.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIMobileKnown.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIMobileReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIPhysicalDummy.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIPhysicalKnown.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIPhysicalReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\IPIUnit.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\Information.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationDummy.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationFactory.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationKnown.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoKnown.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Cluster\Cluster.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterGraph.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterNode.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterNodeManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Cluster\ClusterNodePath.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Material\Material.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\Material\MaterialManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\GTSDataOptimiser.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\MapProperties.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\MeshImporterExporter.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QTPath.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QTSearchNode.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QTSearchNodeManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTree.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\NavMesh\QuadTreeNode.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\BAPContext.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\BAPDebugger.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\BAPInterpreter.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\BoatControl.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\BotScriptDebugger.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\CarControl.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\CommonControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\ControlFunctions.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryBoatMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryBoatMoveToDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryBoatMoveToObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryBoatResetControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryCarMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryCarMoveToDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryCarMoveToObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryCarResetControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryHeliAimAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryHeliMoveAwayFromObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryHeliMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryHeliMoveToDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryHeliMoveToObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryHeliResetControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryInfanteryMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryInfanteryMoveToDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryInfanteryMoveToObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryInfanteryResetControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryInfoWrapper.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryKeyTurretAimAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMouseTurretAimAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMouseTurretLookAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMoveToMedium.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMoveToMediumBoat.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMoveToMediumSoldier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMoveToObjectMedium.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMoveToObjectMediumBoat.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryMoveToObjectMediumSoldier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryPlaneAimAt.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryPlaneMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryPlaneMoveToDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryPlaneMoveToObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryPlaneResetControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryPlaneRoll.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntrySense.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntrySoldierPose.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTankMoveTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTankMoveToDirection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTankMoveToObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTankResetControls.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTankTurnTo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTrigger.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTriggerContinously.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\EntryTurnToMedium.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\HeliControl.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\InfanteryControl.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\MouseControl.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\PlaneControl.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\PrettyPrinter.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPlanInterpreter\TankControl.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\SAI.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\SCArea.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\SCConstant.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\SCHeterogeneous.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\SCHomogeneous.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\Strategy.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\StrategyCondition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\StrategyPrerequisite.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AILandingZone.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AILandingZoneManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AIStrategicArea.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AIStrategicObjectManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AreaAssignment.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AreaDistanceInfo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CPNode.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CPNodeManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CoverPosition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\CoverPosition\CoverPositionManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\GuardPosition.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\GuardPositionBotDCB.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\GuardPositionBotSCB.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\PatrolPath.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\PatrolPathBotDCB.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\PatrolPathBotSCB.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\SAWayPoint.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\AICamera.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\AerialHeightMap.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\BFStrategicEnvironment.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\BotSpawner.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\SAIMap.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\SAIMapRenderUtil.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\SAIMapSquare.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\ScalarMap.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\StatusMap.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\TemperatureTree.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\TemperatureTreeModifiers.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\AIVectorMath.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\AimerHelper.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\AIRenderUtil.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\DPAIObject3dText.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\DPAIObjectCircle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\DPAIObjectLine.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\DPDynamic3dText.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\DPDynamicCircle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\DPDynamicLine.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\DebugRendering\DPGraph.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\IAimerHelper.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\IgnoreListPredicate.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\Opening.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\TraceUtils.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\VehicleOccupancy.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPStatic2dText.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPStatic3dText.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPStaticCirlce.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPStaticLine.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPStaticMesh.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPStaticPolygon.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DPStaticTriangle.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\DrawPrimitives\DrawPrimitive.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AICollisionHandler.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIConsole.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIEventCourier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AILODManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIMain.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIMineManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIModule.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIPathfinding.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIPlayerCourier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIRadio.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIRandom.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AISettings.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AISingletonServer.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIStreamOperators.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\BF2AI.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\BFPathfindingCourier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\BotBehaviourManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\BotManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\BotPlacementManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIDLL\AI\Main\CommonSingletonServer.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\CommunicationHub.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\IAIPathfinding.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\IBotManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\StrategyManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\UserOrderManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectArmament.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectControlInfo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectCover.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectMobile.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectPhysical.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectPrimaryReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectPrimaryShared.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectSecondaryReal.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectSecondaryShared.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectShared.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObjectUnit.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIPlayer.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIPlayerFactory.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplate.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateArmament.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateControlInfo.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateCover.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateMobile.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplatePhysical.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplatePlugIn.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplatePlugInManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AITemplateUnit.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFCollisionHandler.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFCommander.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFGame.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFGameEffector.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFGraphCreator.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFObjectEnvironment.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFPhysics.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFRadioComm.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFSquad.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFTerrain.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\BFTimer.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\DebugRenderer.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\InformationType.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\KitTemplate.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\KitTemplateManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\PlanePolygon.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\SoldierPose.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\WeaponObject.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\WeaponTemplate.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\WeaponTemplateManager.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\IAIEventCourier.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\Main\AIConnection.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\Main\AIEventListener.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\Module\BFConsole.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\SingletonServer.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\Math\Mat3.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\Math\Intersect.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\Math\DoubleVec3.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\IO\Stream\BoundingBox.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\Scene\Object\WorldObjTemplPortal\PortalEvent.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% "%~dp0..\BF2\Core\DllStlAllocator.cpp" +if errorlevel 1 set /a RC+=1 +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\Core\Random.cpp" +if errorlevel 1 set /a RC+=1 + if %RC%==0 (echo ALL OK) else (echo *** %RC% FILE^(S^) FAILED ***) exit /b %RC% From 519ad453a73f32d3386a92d679854b2368c3caeb Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Tue, 3 Nov 2026 19:02:07 +0100 Subject: [PATCH 05/71] Core: one retail random instance name, dice::hfe::Rand, in both images The engine's instance (bf2 ds:0x8ABBCB0) was declared under the [CHOSEN] name g_random and defined in ParticleTemplate.cpp; the AI DLL's (libaidll BSS 0x4DD454) as Rand in Random.cpp. Both retail images name it dice::hfe::Rand and initialise it in Random.cpp's static init (bf2 0x83CB610, libaidll 0x48A850: iostream Init, then the default seed). Random.h now declares one extern Random Rand; Random.cpp defines it for each image; every g_random use is renamed (mechanical, no behaviour change). Co-Authored-By: Claude Opus 5.5 Co-Authored-By: OpenAI Codex --- .../BFKnowledge/BFObjectEnvironment.cpp | 4 +- Code/BF2/Core/Random.cpp | 12 +++--- Code/BF2/Core/Random.h | 5 +-- Code/BF2/Game/Objects/Fx/EffectBundle.cpp | 4 +- .../Game/Objects/Fx/EffectBundleTemplate.h | 2 +- Code/BF2/Game/Objects/Fx/Emitter.cpp | 40 +++++++++---------- Code/BF2/Game/Objects/Fx/Particle.cpp | 8 ++-- Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp | 17 ++++---- .../Game/Objects/Game/AmbientEffectArea.cpp | 4 +- .../Game/Objects/Game/PlayerControlObject.cpp | 2 +- .../Objects/GameLogicComp/ArmorGLComp.cpp | 4 +- .../Objects/Projectiles/GenericProjectile.cpp | 10 ++--- Code/BF2/Physics/HeightmapClusterEditable.cpp | 4 +- Code/BF2/Physics/ResponsePhysics.cpp | 2 +- Code/BF2/Sound/EngineSound.cpp | 4 +- Code/Tests/runtime_pair.cpp | 2 +- Code/Tests/tier2/bodies.cpp | 10 ++--- 17 files changed, 65 insertions(+), 69 deletions(-) diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp index 516321c09..9a3e2bc7f 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp @@ -40,7 +40,7 @@ #include #include "IWeapon.h" // hasIndirectLineOfFire's weapon reads #include "BFPhysics.h" // IAIPhysics::getGravity -#include "../../../Core/Random.h" // g_random (ELF dice::hfe::Rand) +#include "../../../Core/Random.h" // Rand (ELF dice::hfe::Rand) #include "../../../Game/Objects/Game/Soldier.h" // Soldier::getCameras #include "../../../Game/Objects/ICameraObject.h" #include "../../../Game/Objects/ObjectLayoutAccess.h" // the cached collision mesh (+0x40) @@ -353,7 +353,7 @@ class AISeeingPredWrapper : public world::ObjectPredicator // built on it: lo + (hi - lo) * draw + 0.5, truncated. [CHOSEN] helper spellings for inlined code. inline float randomUnit() { - return static_cast(static_cast(((g_random.getRaw() >> 7) | 1u) + 1u)) * 5.9604645e-08f; + return static_cast(static_cast(((Rand.getRaw() >> 7) | 1u) + 1u)) * 5.9604645e-08f; } inline unsigned int randomIndex(float hi) diff --git a/Code/BF2/Core/Random.cpp b/Code/BF2/Core/Random.cpp index 70552a64b..29090f778 100644 --- a/Code/BF2/Core/Random.cpp +++ b/Code/BF2/Core/Random.cpp @@ -1,9 +1,8 @@ // Random state and distribution serialization. [INFERRED] Core placement; AI FILE symbol: Random.cpp. -#if defined(BF2_IMAGE_AIDLL) -// static init: ELF 0x48A850 (__tcf_0 0x48A8D0, _GLOBAL__I 0x48A900): iostream Init, then Rand. +// static init (each image's own Random.cpp): iostream Init, then Rand. +// bf2 ELF 0x83CB610 (seed store 0x83CB642); libaidll ELF 0x48A850 (__tcf_0 0x48A8D0, _GLOBAL__I 0x48A900). #include -#endif #include "Random.h" @@ -15,10 +14,11 @@ namespace dice { namespace hfe { -#if defined(BF2_IMAGE_AIDLL) -// ELF BSS 0x4DD454; the initializer's store at 0x48A8BA is Random's default seed. +// Each image owns one instance under the same symbol, dice::hfe::Rand: bf2 ds:0x8ABBCB0 and +// libaidll BSS 0x4DD454. The initializers store Random's default seed (0x759DC150). Random Rand; -#else + +#if !defined(BF2_IMAGE_AIDLL) // [CHOSEN, not recovered] Image partition: these distribution codecs belong to the engine; // the original AI Random.cpp contributes its independent state and initialization only. diff --git a/Code/BF2/Core/Random.h b/Code/BF2/Core/Random.h index e9181663a..f658c52fb 100644 --- a/Code/BF2/Core/Random.h +++ b/Code/BF2/Core/Random.h @@ -60,9 +60,8 @@ static_assert(sizeof(Random) == 4, "Random must retain its shipped x86 layout"); static_assert(sizeof(RandomDistribution) == 0x14, "RandomDistribution must retain its shipped x86 layout"); -extern Random g_random; // ELF ds:0x8ABBCB0 [CHOSEN symbol name] - -// The AI DLL's independent random instance (ia-32 BSS 0x4DD454, Random.cpp initializer). +// The image's random instance, defined in Random.cpp: dice::hfe::Rand in both retail images +// (bf2 ds:0x8ABBCB0, libaidll BSS 0x4DD454); the engine and the AI DLL each have their own. extern Random Rand; } // namespace hfe diff --git a/Code/BF2/Game/Objects/Fx/EffectBundle.cpp b/Code/BF2/Game/Objects/Fx/EffectBundle.cpp index efca48c67..e3aaf3a1c 100644 --- a/Code/BF2/Game/Objects/Fx/EffectBundle.cpp +++ b/Code/BF2/Game/Objects/Fx/EffectBundle.cpp @@ -71,7 +71,7 @@ void normalize(Vec3& value) float unitRandom() { // sign draw / Random helpers: signed shift after setting bit 7. - return static_cast((static_cast(g_random.getRaw() | 0x80u) >> 7) + 1) + return static_cast((static_cast(Rand.getRaw() | 0x80u) >> 7) + 1) * 0.000000059604645f; } float sample(const RandomDistribution& distribution) @@ -86,7 +86,7 @@ float sample(const RandomDistribution& distribution) result = distribution.value + (distribution.variation - distribution.value) * unitRandom(); break; case CRD_EXPONENTIAL: result = -distribution.value * std::log(unitRandom()); break; - case CRD_NORMAL: result = distribution.value + g_random.getNormal() * distribution.variation; break; + case CRD_NORMAL: result = distribution.value + Rand.getNormal() * distribution.variation; break; default: result = 0.0f; break; } return result * sign; diff --git a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h index e35067f63..c99cf01e3 100644 --- a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h +++ b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h @@ -1,7 +1,7 @@ // Groups effect emitters and supplies EffectProperties as a secondary base. // Client creation constructs an EffectBundle; dedicated creation returns null. Initialization adds a 3D looping Start sound. // preCache explicitly calls ObjectTemplate, and child info uses the EffectInfo subclass. -// RandomDistribution members retain their embedded seed/layout even though sampling uses g_random. +// RandomDistribution members retain their embedded seed/layout even though sampling uses Rand. // Original ELF size is 0x340; unresolved own-field roles remain marked below. Placement is [INFERRED]. #ifndef GAME_OBJECTS_FX_EFFECTBUNDLETEMPLATE_H // [INFERRED] guard style diff --git a/Code/BF2/Game/Objects/Fx/Emitter.cpp b/Code/BF2/Game/Objects/Fx/Emitter.cpp index d027c50b6..450bc8e0d 100644 --- a/Code/BF2/Game/Objects/Fx/Emitter.cpp +++ b/Code/BF2/Game/Objects/Fx/Emitter.cpp @@ -12,7 +12,7 @@ #include "../ObjectTemplate.h" // ObjectTemplate::getIsPreCaching #include "../ObjectLayoutAccess.h" // physicsNode / geometry of other objects #include "../../../Core/Ids.h" // CID_EffectBundle/Particle/SpriteParticleTemplate -#include "../../../Core/Random.h" // RandomDistribution, g_random (ELF dice::hfe::Rand) +#include "../../../Core/Random.h" // RandomDistribution, Rand (ELF dice::hfe::Rand) #include "../../../Core/OverTimeDistribution.h" #include "../../../Core/System.h" // g_system->getExactTime (ELF +0x18 / PE +0x14) #include "../../../Physics/MaterialManager.h" // playParticleCollisionSound @@ -232,7 +232,7 @@ float Emitter::calcInvItensity(const EmitterTemplate* objectTemplate, float spee const float fraction = scaled - static_cast(index); const float curve = (1.0f - fraction) * objectTemplate->m_intensityOverTime.m_samples[index] + fraction * objectTemplate->m_intensityOverTime.m_samples[index + 1]; - const double product = static_cast(sampleDistribution(objectTemplate->m_intensity, g_random)) + const double product = static_cast(sampleDistribution(objectTemplate->m_intensity, Rand)) * curve * speedFactor; float intensity = static_cast(product); if (!std::isfinite(product)) @@ -315,8 +315,8 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) handleMessage(static_cast(1), 0, false); return; } - m_delay = sampleDistribution(t->m_delay, g_random); - m_timeToLive = sampleDistribution(t->m_timeToLive, g_random); + m_delay = sampleDistribution(t->m_delay, Rand); + m_timeToLive = sampleDistribution(t->m_timeToLive, Rand); if (m_timeToLive < 0.01f) // ds:0x892ADC, NaN kept m_timeToLive = 0.01f; m_age = 0.0f; @@ -387,15 +387,15 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) { // Velocity from the emitter's axes - row 2 dof, row 1 up, row 0 right - drawn in that order. // quirk 4: `transform` carries the previous particles' roll (rows 0/1). - const float speedDof = sampleDistribution(t->m_positionalSpeed[0], g_random); // +0x50C + const float speedDof = sampleDistribution(t->m_positionalSpeed[0], Rand); // +0x50C speed.x = transform.m[8] * speedDof; speed.y = transform.m[9] * speedDof; speed.z = transform.m[10] * speedDof; - const float speedUp = sampleDistribution(t->m_positionalSpeed[1], g_random); // +0x520 + const float speedUp = sampleDistribution(t->m_positionalSpeed[1], Rand); // +0x520 speed.x = transform.m[4] * speedUp + speed.x; speed.y = transform.m[5] * speedUp + speed.y; speed.z = transform.m[6] * speedUp + speed.z; - const float speedRight = sampleDistribution(t->m_positionalSpeed[2], g_random); // +0x534 + const float speedRight = sampleDistribution(t->m_positionalSpeed[2], Rand); // +0x534 speed.x = transform.m[0] * speedRight + speed.x; speed.y = transform.m[1] * speedRight + speed.y; speed.z = transform.m[2] * speedRight + speed.z; @@ -406,15 +406,15 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) position.x = travel.x * along + m_lastPosition.x; position.y = travel.y * along + m_lastPosition.y; position.z = travel.z * along + m_lastPosition.z; - const float relativeDof = sampleDistribution(t->m_relativePosition[0], g_random); // +0x4D0 + const float relativeDof = sampleDistribution(t->m_relativePosition[0], Rand); // +0x4D0 position.x = transform.m[8] * relativeDof + position.x; position.y = transform.m[9] * relativeDof + position.y; position.z = transform.m[10] * relativeDof + position.z; - const float relativeUp = sampleDistribution(t->m_relativePosition[1], g_random); // +0x4E4 + const float relativeUp = sampleDistribution(t->m_relativePosition[1], Rand); // +0x4E4 position.x = transform.m[4] * relativeUp + position.x; position.y = transform.m[5] * relativeUp + position.y; position.z = transform.m[6] * relativeUp + position.z; - const float relativeRight = sampleDistribution(t->m_relativePosition[2], g_random); // +0x4F8 + const float relativeRight = sampleDistribution(t->m_relativePosition[2], Rand); // +0x4F8 position.x = transform.m[0] * relativeRight + position.x; position.y = transform.m[1] * relativeRight + position.y; position.z = transform.m[2] * relativeRight + position.z; @@ -424,10 +424,10 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) // Roll: zRotation snapped down (truncated) to zRotationSnap steps, plus startRotation. // Draw order as shipped: zRotation (+0x598) before startRotation (+0x584). - const float zRotation = sampleDistribution(t->m_zRotation, g_random); + const float zRotation = sampleDistribution(t->m_zRotation, Rand); const float snapped = static_cast(static_cast(zRotation / t->m_zRotationSnap)) * t->m_zRotationSnap; - const float angle = sampleDistribution(t->m_startRotation, g_random) + snapped; + const float angle = sampleDistribution(t->m_startRotation, Rand) + snapped; if (!t->m_addChild) // +0x5B2 { if (angle != 0.0f) // `fucompp; test ah, 44h; jnp` - NaN rotates (0x5A2800 then skips it) @@ -454,7 +454,7 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) // (0x402EC0), then truncated; an index at or past the count (signed `jge`) is the main one. if (t->m_numAlternateTemplates) // +0x5B8 { - const float draw = sampleDistribution(selector, g_random) + const float draw = sampleDistribution(selector, Rand) * static_cast(t->m_numAlternateTemplates + 1); const int choice = static_cast(std::floor(draw)); if (choice < t->m_numAlternateTemplates) @@ -526,9 +526,9 @@ void Emitter::handleUpdate(float deltaTime, unsigned int flags) { // Draw order as shipped: right (+0x570), UP (+0x55C), DOF (+0x548) - the source's // Vec3(dof, up, right) arguments evaluated right to left by MSVC. - const float spinRight = sampleDistribution(t->m_rotationalSpeed[2], g_random); - const float spinUp = sampleDistribution(t->m_rotationalSpeed[1], g_random); - const float spinDof = sampleDistribution(t->m_rotationalSpeed[0], g_random); + const float spinRight = sampleDistribution(t->m_rotationalSpeed[2], Rand); + const float spinUp = sampleDistribution(t->m_rotationalSpeed[1], Rand); + const float spinDof = sampleDistribution(t->m_rotationalSpeed[0], Rand); Vec3 spin = { spinDof, spinUp, spinRight }; if (t->m_addEmitterSpeed && rootPhysics) { @@ -577,7 +577,7 @@ void Emitter::handleMessage(TemplateMessage message, IPlayer* /*player*/, bool / roll.distribution = CRD_UNIFORM; roll.value = 0.0f; roll.variation = 1.0f; - if (sampleDistribution(roll, g_random) >= t->m_startProbability) + if (sampleDistribution(roll, Rand) >= t->m_startProbability) return; } // A fresh start (the age is exactly 0 - after a stop, or never started). @@ -605,8 +605,8 @@ void Emitter::handleMessage(TemplateMessage message, IPlayer* /*player*/, bool / if (m_particleTemplate) updateFlags(0x3800, 1); // updates + visual + frame updates on, the disabled bit off } - m_delay = sampleDistribution(t->m_delay, g_random); - m_timeToLive = sampleDistribution(t->m_timeToLive, g_random); + m_delay = sampleDistribution(t->m_delay, Rand); + m_timeToLive = sampleDistribution(t->m_timeToLive, Rand); m_startTime = static_cast(g_system->getExactTime()); m_age = 0.0f; m_nextEmitTime = 0.0f; @@ -643,7 +643,7 @@ void Emitter::handleMessage(TemplateMessage message, IPlayer* /*player*/, bool / static_cast(getParent())->decNumEmittersPlaying(); if (t->m_looping) { - m_timeToLive = sampleDistribution(t->m_timeToLive, g_random); + m_timeToLive = sampleDistribution(t->m_timeToLive, Rand); m_nextEmitTime = 0.0f; return; } diff --git a/Code/BF2/Game/Objects/Fx/Particle.cpp b/Code/BF2/Game/Objects/Fx/Particle.cpp index 6445f75ea..1178c2dac 100644 --- a/Code/BF2/Game/Objects/Fx/Particle.cpp +++ b/Code/BF2/Game/Objects/Fx/Particle.cpp @@ -11,7 +11,7 @@ #include "../../../Core/ClassManager.h" #include "../../../Core/Debug.h" #include "../../../Core/Ids.h" -#include "../../../Core/Random.h" // g_random, RandomDistribution +#include "../../../Core/Random.h" // Rand, RandomDistribution #include "../../../Geom/GeometryInstanceData.h" // the two opacity factors + setOpacity #include "../../../Physics/CollisionManager.h" // ICollisionManager::getCollisionMeshPart #include "../../../Physics/ICollisionMesh.h" // ICollisionMesh::createMaterialMapping @@ -49,7 +49,7 @@ class IScaleable : public IBase // the RandomDistribution sampler, client order // BF2.exe 0x5E74B0 (121 B) on the process-global Random (ds:977F88; the ELF's Rand 0x8ABBCB0, this -// tree's g_random): when `relative` is set it draws the sign first - u <= 0.5 (compared as a double +// tree's Rand): when `relative` is set it draws the sign first - u <= 0.5 (compared as a double // 0.5) gives -1 - and only then 0x5E7450 draws the value; the product is the result. [PLATFORM] The // ELF constructor inlines the same distribution five times with the draws the other way round // (value first, sign second: e.g. 0x82060BC after the arm at 0x8207000). Both use the global @@ -58,7 +58,7 @@ float unitRandom() { // / 0x5E7360 / 0x5E74B0: `(raw | 0x80) sar 7, + 1` - equal to `((raw >> 7) | 1) + 1` // for every raw the Lehmer state can produce (< 2^31) - then * 2^-24. - return static_cast(static_cast(((g_random.getRaw() >> 7) | 1u) + 1u)) + return static_cast(static_cast(((Rand.getRaw() >> 7) | 1u) + 1u)) * 0.000000059604645f; } @@ -79,7 +79,7 @@ float sampleDistribution(const RandomDistribution& distribution) * distribution.value)); break; case CRD_NORMAL: // (getNormal) * variation + value - value = g_random.getNormal() * distribution.variation + distribution.value; + value = Rand.getNormal() * distribution.variation + distribution.value; break; default: value = 0.0f; diff --git a/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp b/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp index 7a8ad9aa8..e44399ef9 100644 --- a/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp +++ b/Code/BF2/Game/Objects/Fx/ParticleTemplate.cpp @@ -30,9 +30,6 @@ namespace dice { namespace hfe { -Random g_random; // ds:0x8ABBCB0 [CHOSEN name] - THE object, seeded 0x759DC150 by - // its ctor (the ELF's static init). See the class note. - // , read in full. Two Lehmer steps x' = a*x mod (2^31 - 1), a = 24112 then 26143, // each in the classic overflow-free 16-bit-halves form, on the persistent state. namespace { @@ -155,14 +152,14 @@ ParticleTemplate::ParticleTemplate() break; // sample = the value case 1: sample = m_gravityModifier.value + (m_gravityModifier.variation - m_gravityModifier.value) - * (float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * (float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 2: sample = -m_gravityModifier.value - * std::log(float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * std::log(float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 3: - sample = m_gravityModifier.value + g_random.getNormal() * m_gravityModifier.variation; + sample = m_gravityModifier.value + Rand.getNormal() * m_gravityModifier.variation; break; default: sample = 0.0f; @@ -177,21 +174,21 @@ ParticleTemplate::ParticleTemplate() break; case 1: sample = m_gravityModifier.value + (m_gravityModifier.variation - m_gravityModifier.value) - * (float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * (float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 2: sample = -m_gravityModifier.value - * std::log(float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); + * std::log(float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f); break; case 3: - sample = m_gravityModifier.value + g_random.getNormal() * m_gravityModifier.variation; + sample = m_gravityModifier.value + Rand.getNormal() * m_gravityModifier.variation; break; default: sample = 0.0f; break; } // The coin flip: u <= 0.5 negates. - if (float(((g_random.getRaw() >> 7) | 1) + 1) * 0.000000059604645f <= 0.5f) + if (float(((Rand.getRaw() >> 7) | 1) + 1) * 0.000000059604645f <= 0.5f) sample = -sample; } m_sampledValue = sample; diff --git a/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp b/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp index 7fdd4675a..75835bec3 100644 --- a/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp +++ b/Code/BF2/Game/Objects/Game/AmbientEffectArea.cpp @@ -168,7 +168,7 @@ unsigned int ambientRandom(int& seed) // ELF 81658B8..5BE9 samples the distribution, materializes float, then draws its sign. double ambientUnitRandom() { - return static_cast((static_cast(g_random.getRaw() | 0x80u) >> 7) + 1) + return static_cast((static_cast(Rand.getRaw() | 0x80u) >> 7) + 1) * (1.0 / 16777216.0); } double ambientLifetimeSample(const RandomDistribution& distribution) @@ -184,7 +184,7 @@ double ambientLifetimeSample(const RandomDistribution& distribution) value = distribution.value + (double(distribution.variation) - distribution.value) * ambientUnitRandom(); break; case CRD_EXPONENTIAL: value = -double(distribution.value) * std::log(ambientUnitRandom()); break; - case CRD_NORMAL: value = distribution.value + double(g_random.getNormal()) * distribution.variation; break; + case CRD_NORMAL: value = distribution.value + double(Rand.getNormal()) * distribution.variation; break; default: value = 0; break; } #if defined(_WIN32) diff --git a/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp b/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp index 2a514bf3f..6de04372b 100644 --- a/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp +++ b/Code/BF2/Game/Objects/Game/PlayerControlObject.cpp @@ -2784,7 +2784,7 @@ void PlayerControlObject::getUnmannedInput(io::PlayerInput& input) + static_cast(30.0f * *pcoUnmannedInputTime); #endif const auto randomInteger = []() -> float { - return static_cast((static_cast(g_random.getRaw()) >> 7 | 1) + 1); + return static_cast((static_cast(Rand.getRaw()) >> 7 | 1) + 1); }; const float inverseRange = 0.000000059604645f; const int majorAxis = static_cast(std::ceil(randomInteger() * (2.0f * inverseRange))); diff --git a/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp b/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp index 0e165a96a..f8aed79bd 100644 --- a/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp +++ b/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp @@ -26,7 +26,7 @@ #include "../../IGame.h" // game->destroyObject #include "../../IGameLogic.h" // gameLogic - isServer / getGameStatus / giveDamage #include "../../Common/GameEvent.h" // revive: ECGameLogic 14 replication -#include "../Fx/ParticleTemplate.h" // g_random - UpdateInWaterStatus' jitter +#include "../Fx/ParticleTemplate.h" // Rand - UpdateInWaterStatus' jitter #include "../IObject.h" #include "../IStrategicObjectComp.h" // ResetStrategicObject's component #include "../StrategicObjectComp.h" // ... and the holder it looks up @@ -571,7 +571,7 @@ void ArmorGLComp::UpdateInWaterStatus() if (worldTime > *g_armorWaterSafetyCheckTime + m_lastWaterCheckTime) { timerFired = true; - const unsigned int x = g_random.getRaw(); // two Lehmer steps, inlined in the ELF + const unsigned int x = Rand.getRaw(); // two Lehmer steps, inlined in the ELF const float roll = static_cast(((static_cast(x) >> 7) | 1) + 1) * 5.9604645e-08f; m_lastWaterCheckTime = worldTime - (roll * 0.30000001f + 0.0f); } diff --git a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp index 89689c6ea..8cded68d5 100644 --- a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp +++ b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp @@ -28,7 +28,7 @@ #include "../../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler #include "../../../Core/Ids.h" #include "../../../Core/Debug.h" // getStickTransformation's retail error arm -#include "../../../Core/Random.h" // g_random - retail distribution sampler +#include "../../../Core/Random.h" // Rand - retail distribution sampler #include "../../../Core/System.h" // launch clocks / ticks #include "../../../Core/WeakPtr.h" // the +0x174 ctrl read - PCO's idiom #include "../../../Geom/IGeometryTemplate.h" @@ -82,20 +82,20 @@ float sampleRandomDistribution(const RandomDistribution& distribution) break; case CRD_UNIFORM: sample = distribution.value - + (distribution.variation - distribution.value) * unitRandom(g_random); + + (distribution.variation - distribution.value) * unitRandom(Rand); break; case CRD_EXPONENTIAL: - sample = -distribution.value * static_cast(std::log(unitRandom(g_random))); + sample = -distribution.value * static_cast(std::log(unitRandom(Rand))); break; case CRD_NORMAL: - sample = distribution.value + g_random.getNormal() * distribution.variation; + sample = distribution.value + Rand.getNormal() * distribution.variation; break; default: sample = 0.0f; break; } - if (distribution.relative && unitRandom(g_random) <= 0.5f) + if (distribution.relative && unitRandom(Rand) <= 0.5f) sample = -sample; return sample; } diff --git a/Code/BF2/Physics/HeightmapClusterEditable.cpp b/Code/BF2/Physics/HeightmapClusterEditable.cpp index 0d6470256..96d3e108c 100644 --- a/Code/BF2/Physics/HeightmapClusterEditable.cpp +++ b/Code/BF2/Physics/HeightmapClusterEditable.cpp @@ -526,7 +526,7 @@ void HeightmapClusterEditable::smooth(int x, int z, float radius, float strength // ; Noise: every inside sample gets a uniform draw in // [-strength, +strength) added (no falloff), from a local generator seeded with -// time(0) & 0x7FFFFFFF - not the engine's g_random. +// time(0) & 0x7FFFFFFF - not the engine's Rand. void HeightmapClusterEditable::random(int x, int z, float radius, float strength, int flags) { const int extent = getHeightmapSize() * getClusterSize() / 2; @@ -717,7 +717,7 @@ void HeightmapClusterEditable::smoothEdges(int width, float amplitude, float fal float offset; if (falloff == 0.0f) { - offset = randomRange(g_random, -amplitude, amplitude); + offset = randomRange(Rand, -amplitude, amplitude); } else { diff --git a/Code/BF2/Physics/ResponsePhysics.cpp b/Code/BF2/Physics/ResponsePhysics.cpp index 6c2273cca..312f07af0 100644 --- a/Code/BF2/Physics/ResponsePhysics.cpp +++ b/Code/BF2/Physics/ResponsePhysics.cpp @@ -513,7 +513,7 @@ void ResponsePhysics::addEffect(int ownMaterial, int otherMaterial, Vec3 speed, m_effect0.sound = 0; record = &m_effect0; } - const unsigned int raw = g_random.getRaw(); + const unsigned int raw = Rand.getRaw(); record->timer = static_cast(static_cast(((raw >> 7) | 1u) + 1u)) * 0.000000059604645f + 0.5f; record->position = point; record->normal = normal; diff --git a/Code/BF2/Sound/EngineSound.cpp b/Code/BF2/Sound/EngineSound.cpp index b1c4dc94c..2c3850965 100644 --- a/Code/BF2/Sound/EngineSound.cpp +++ b/Code/BF2/Sound/EngineSound.cpp @@ -205,9 +205,9 @@ float EngineSound::updateAudioRpm(bool engineOn, float input, int material) + m_velocity.y * m_velocity.y + m_velocity.z * m_velocity.z; const float low = amount * -0.30000001f; - const float noiseDraw = static_cast(((g_random.getRaw() >> 7) | 1u) + 1u); + const float noiseDraw = static_cast(((Rand.getRaw() >> 7) | 1u) + 1u); m_noiseRpm = (amount - low) * noiseDraw * 0.000000059604645f + low; - const float delayDraw = static_cast(((g_random.getRaw() >> 7) | 1u) + 1u); + const float delayDraw = static_cast(((Rand.getRaw() >> 7) | 1u) + 1u); m_noiseCountdown = static_cast((std::sqrt(speedSquared) * 0.033333335f * 23.0f + 2.0f) * delayDraw * 0.000000059604645f); diff --git a/Code/Tests/runtime_pair.cpp b/Code/Tests/runtime_pair.cpp index ddfa7a878..979c29532 100644 --- a/Code/Tests/runtime_pair.cpp +++ b/Code/Tests/runtime_pair.cpp @@ -138,7 +138,7 @@ void resetSimpleCollisionCall(bool result) namespace dice { namespace hfe { -Random g_random; +Random Rand; unsigned int Random::getRaw() { diff --git a/Code/Tests/tier2/bodies.cpp b/Code/Tests/tier2/bodies.cpp index 1f619afde..d69f6c7ea 100644 --- a/Code/Tests/tier2/bodies.cpp +++ b/Code/Tests/tier2/bodies.cpp @@ -113,22 +113,22 @@ bool vehicleBodies() { check(pco!=0,"stock PCO available"); if(pco) { auto& nextInput=pco->*PcoAccess::timer(); - const auto timer=nextInput, seed=g_random.m_seed; + const auto timer=nextInput, seed=Rand.m_seed; io::PlayerInput input; std::memset(&input,0,sizeof(input)); input.inputs[50]=0.75f;input.mappingFlags=1ULL<<50; const auto original=input; - nextInput=0xffffffffu;g_random.m_seed=0x12345678u; + nextInput=0xffffffffu;Rand.m_seed=0x12345678u; pco->getUnmannedInput(input); - check(std::memcmp(&input,&original,sizeof(input))==0 && g_random.m_seed==0x12345678u,"unsigned timer leaves input and RNG untouched"); + check(std::memcmp(&input,&original,sizeof(input))==0 && Rand.m_seed==0x12345678u,"unsigned timer leaves input and RNG untouched"); nextInput=0; const auto tick=static_cast(WorldPref::getTickCount()); pco->getUnmannedInput(input); check(input.mappingFlags==((1ULL<<50)|15) && input.inputs[50]==0.75f,"unmanned mapping preserves unrelated controls"); check(input.inputs[0]==-1 && near(input.inputs[1],-0.6735224f) && near(input.inputs[2],0.0627387f) && input.inputs[3]==1 - && g_random.m_seed==1242154650u,"seeded five-draw retail sequence"); + && Rand.m_seed==1242154650u,"seeded five-draw retail sequence"); check(nextInput==tick+300,"default unsigned next-input tick"); - nextInput=timer;g_random.m_seed=seed; + nextInput=timer;Rand.m_seed=seed; } int parented=0; for(const auto& entry:objectManager->getAllRegisteredObjects()) { From 1b679a0ac82b043c3cc2db620eac06106558bca8 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Tue, 3 Nov 2026 20:02:56 +0100 Subject: [PATCH 06/71] ci: fix Windows x86 runtime-pair and x64 dedicated links bf2_runtime_pair (x86 checks): e44067b3 added the [TEMP] grenade_trace diagnostic (GrenadeTrace.h), whose log() reads WorldPref::mTickCount from PointPhysicsNode.cpp. The counter is defined in Core/System.cpp, which the harness does not link, so link.exe failed with LNK2019. Define the counter in the harness's existing link-completion scaffolding, next to the other retail globals it stands in for. No production TU changes, so the x86 retail images are untouched; runtime_pair.cmd needs no source-list change. bf2_w64ded (x64 strict link): e0fcdaa1 made VoipServerInternal call the CBF2VoipServer facade, which the x86 image imports from the BF2VoipServer_w32ded.dll side image. That DLL target is defined only under NOT BF2_BUILD_X64 (and its .def pins x86 decorations), so the x64 exe had no definitions. Link the voice-server module statically into the native Windows x64 port, as the Linux image already does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BGWewitYSRmJLenBNiW8ar --- CMakeLists.txt | 10 ++++++++++ Code/Tests/runtime_pair.cpp | 5 +++++ 2 files changed, 15 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index dd83553e6..96f68d12e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1005,6 +1005,16 @@ else() "${BF2_DEDICATED_TARGET}: ${BF2_DICE_PY_LIB} is missing. " "${BF2_DICE_PY_BUILD_HINT}.") endif() +if(BF2_BUILD_X64 AND NOT BF2_BUILD_LINUX) + # [CHOSEN, not recovered] The native Windows x64 port links the voice-server module statically, + # like the Linux image (which adds the same sources above). The BF2VoipServer_w32ded.dll side + # image (bf2_voipserver, below) is x86-only: it is defined under NOT BF2_BUILD_X64 and its .def + # pins x86 decorated names. Without these sources the strict x64 link has no CBF2VoipServer + # definitions for VoipServerInternal. + target_sources("${BF2_DEDICATED_TARGET}" PRIVATE + ${bf2_voipserver_only_sources} + ) +endif() # dice_py IS A REAL DLL, so linking dice_py.lib is only half the job - the DLL has to be FOUND at # run time. Windows searches the executable's own directory before the working directory, and the # run target deliberately sets the working directory to the GAME folder, so the only place that diff --git a/Code/Tests/runtime_pair.cpp b/Code/Tests/runtime_pair.cpp index d2b45845b..23353c2a7 100644 --- a/Code/Tests/runtime_pair.cpp +++ b/Code/Tests/runtime_pair.cpp @@ -157,6 +157,11 @@ unsigned int Random::getRaw() return m_seed; } +// Core/System.cpp owns the retail tick counter (ds:0x8AC0D68). The runtime-pair harness does not +// link that platform-heavy TU, while PointPhysicsNode.cpp names the counter from the opt-in +// grenade_trace::log diagnostic (GrenadeTrace.h, [TEMP]), which these checks never arm. +namespace WorldPref { unsigned int mTickCount = 0; } + namespace world { ClassManager* classManager = 0; From 5ddf524b3dd92de84c9272ad85591ac67c699106 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Tue, 3 Nov 2026 20:18:52 +0100 Subject: [PATCH 07/71] Update runtime_pair.cpp --- Code/Tests/runtime_pair.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Code/Tests/runtime_pair.cpp b/Code/Tests/runtime_pair.cpp index 21e90d878..979c29532 100644 --- a/Code/Tests/runtime_pair.cpp +++ b/Code/Tests/runtime_pair.cpp @@ -157,10 +157,12 @@ unsigned int Random::getRaw() return m_seed; } -// Core/System.cpp owns the retail tick counter (ds:0x8AC0D68). The runtime-pair harness does not -// link that platform-heavy TU, while PointPhysicsNode.cpp names the counter from the opt-in -// grenade_trace::log diagnostic (GrenadeTrace.h, [TEMP]), which these checks never arm. -namespace WorldPref { unsigned int mTickCount = 0; } +// [TEMP] The grenade trace in PointPhysicsNode.cpp reads the tick count, and its production +// definition sits in Core/System.cpp, which this harness does not link. Tests here leave the trace +// disarmed, so the counter only has to exist. +namespace WorldPref { +unsigned int mTickCount = 0; +} // namespace WorldPref namespace world { From 3b977e7de8ae2f0beafc44dc1226c175e83ae870 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Thu, 5 Nov 2026 01:06:25 +0100 Subject: [PATCH 08/71] AI: cross-check against the AIDLL_r debug build (names, TU placement) AIDLL_r.dll is a DICE Canada BoosterPack2 debug build of the AI DLL (2006-05-04, asserts and __FILE__ paths, no PDB). It is older than 1.50 but already has the 1.50 AI features. It is used as evidence for names, enum values and source-file placement only; behaviour stays matched to retail 1.50 (libaidll.so / AIDLL.dll). Follows the review notes on B2BF/OpenBF2#68. Names - WTSticky -> WTC4 (assert "wInfo->getWeaponType() == WTC4", BBC4.cpp). - Information::isOfType(InformationType), DICE's name (assert "!targetPrimaryInfo->isOfType(ITSoldier)"). The single-bit object-type flag tests use it with the IT* names (enum-to-string switch 0x100D3010), resolving the [UNRESOLVED] flag notes. BotMain::event_airborn tests ITAir, then ITHelicopter, as retail compiles it (ELF 0x18D740). - Kit types documented: 6 is KTAT, 7..12 KTExtended1..6. - 89 member and parameter renames from AIDLL_r assert expressions, each checked by the field offset the assert reads and by its use in the tree (BotNavigation, BotMain, SquadManager/Formation, SAI, AIStrategicObject*, AISettings, BotManager, QuadTree/ClusterGraph, ...). Evidence addresses are in the comments. Source placement (AIDLL_r __FILE__ paths) - Moved: Aimer, BotScript.h -> AIBotActionPlan/; UrgencyMerger -> AIBot/; AIMineManager -> AIKnowledge/; WeaponInfoManager, CustomCurve -> AIUtils/; AerialHeightMap -> AIPathFinding/AerialHeightMap/; UserOrderManager -> AIStrategicEntity/UserOrders/; AILandingZoneManager, InformationManager -> Main/. - Split, functions moved unchanged: SensingAgentPatterns into the Soldier, Turret, MouseFreeLook and Null pattern TUs; SCurve out of CustomCurve; IAIMain, IAIPathfindingSetup and IBotManagerModifier into their own TUs. - Code/Build/aidll_sources.txt, Code/Tests/syntaxcheck.cmd and the Code/Tests/aidll fixtures follow the moves and renames. No behaviour change intended: where AIDLL_r and the tree were compared, they agree with 1.50 apart from asserts. Built and smoke-tested on macOS (bf2_aidll, vtable audit unchanged, 16-bot round); the Windows fixtures were updated as text only. Co-Authored-By: Claude Opus 5.5 --- Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp | 97 +++--- Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h | 8 +- Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp | 328 +++++++++--------- Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h | 22 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp | 48 +-- Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h | 6 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp | 2 +- .../AI/AIDLL/AI/AIBot/CommunicationAgent.cpp | 26 +- .../AI/AIDLL/AI/AIBot/CommunicationAgent.h | 4 +- .../AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp | 6 +- .../AI/AIDLL/AI/AIBot/RandomSquareMerger.h | 2 +- Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp | 35 +- .../SensingAgentMouseFreeLookPattern.cpp | 86 +++++ .../AI/AIBot/SensingAgentNullPattern.cpp | 55 +++ .../AI/AIBot/SensingAgentPatternPrologue.h | 61 ++++ .../AIDLL/AI/AIBot/SensingAgentPatterns.cpp | 309 ----------------- .../AI/AIDLL/AI/AIBot/SensingAgentPatterns.h | 3 +- .../AI/AIBot/SensingAgentSoldierPattern.cpp | 114 ++++++ .../AI/AIBot/SensingAgentTurretPattern.cpp | 70 ++++ .../AI/AIDLL/AI/AIBot/SquadCoordinator.cpp | 56 +-- Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h | 14 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp | 150 ++++---- Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h | 12 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp | 117 ++++--- Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h | 12 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp | 20 +- .../UrgencyMerger.cpp | 18 +- .../{AIBotBehaviour => AIBot}/UrgencyMerger.h | 4 +- .../AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp | 2 +- Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp | 2 +- Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp | 2 +- Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp | 2 +- .../AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp | 4 +- .../AI/{AIBot => AIBotActionPlan}/Aimer.cpp | 6 +- .../AI/{AIBot => AIBotActionPlan}/Aimer.h | 7 +- .../AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h | 2 +- .../AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h | 2 +- .../AI/AIBotActionPlan/BAPAChangeWeapon.cpp | 4 +- .../BAPAComponentSoldierPose.cpp | 2 +- .../AI/AIBotActionPlan/BAPAMoveToFinding.cpp | 4 +- .../BAPAMoveToObjectFinding.cpp | 12 +- .../AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp | 2 +- .../AI/AIBotActionPlan/BAPARunOverObject.cpp | 4 +- .../BAPAUseFlareOnMissileLock.cpp | 4 +- .../AI/AIBotActionPlan/BAPActionInline.h | 2 +- .../AI/AIBotActionPlan/BAPCConPrecision.cpp | 8 +- .../AIBotActionPlan/BAPCombinerParallel.cpp | 6 +- .../AI/AIBotActionPlan/BAPCombinerSerial.cpp | 4 +- .../AI/AIBotActionPlan/BAPConAllowFire.cpp | 2 +- .../AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp | 4 +- .../AI/AIBotActionPlan/BAPConIsSprinting.cpp | 2 +- .../AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp | 6 +- .../AI/AIBotActionPlan/BAPConObjectHealth.cpp | 2 +- .../BAPConObjectInsideFrustum.cpp | 2 +- .../BAPConObjectLineOfFire.cpp | 6 +- .../BAPConObjectValidAiming.cpp | 2 +- .../AIBotActionPlan/BAPConObjectValidAiming.h | 2 +- .../BAPConOkToThrowGrenade.cpp | 7 +- .../AIBotActionPlan/BAPConOkToThrowGrenade.h | 2 +- .../AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp | 4 +- .../AIBotActionPlan/BAPConSharedCondition.cpp | 2 +- .../AI/AIBotActionPlan/BAPConSplashDamage.cpp | 4 +- .../AI/AIBotActionPlan/BAPConSplashDamage.h | 2 +- .../BAPConStrategicObjectStatus.cpp | 2 +- .../AI/AIBotActionPlan/BAPConTotalAmmo.cpp | 2 +- .../BAPConWeaponDetonatorIsActive.cpp | 2 +- .../BAPConWeaponHasLockOnTarget.cpp | 4 +- .../BAPConWeaponHasLockOnTarget.h | 2 +- .../AIBotActionPlan/BAPConWeaponIsActive.cpp | 2 +- .../AIBotActionPlan/BAPConWeaponIsZoomed.cpp | 2 +- .../BAPConWeaponReadyToFire.cpp | 2 +- .../BAPConWeaponTargetReachable.cpp | 2 +- .../AIDLL/AI/AIBotActionPlan/BAPCondition.h | 8 +- .../AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp | 2 +- .../AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp | 6 +- .../AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp | 2 +- .../AI/AIBotActionPlan/BAPFlowCWhile.cpp | 8 +- .../AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp | 2 +- .../AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp | 2 +- .../AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp | 2 +- .../AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp | 2 +- .../AIDLL/AI/AIBotActionPlan/BAPStatement.h | 8 +- .../AI/AIBotActionPlan/BAPWrapperAiming.cpp | 10 +- .../AI/AIBotActionPlan/BAPWrapperAiming.h | 2 +- .../AI/AIBotActionPlan/BAPWrapperLookAt.cpp | 4 +- .../BotScript.h | 5 +- .../AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp | 18 +- .../AI/AIBotBehaviour/BBBridgeRepair.cpp | 8 +- Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp | 8 +- .../AI/AIBotBehaviour/BBCallForMedic.cpp | 6 +- .../AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp | 62 ++-- .../AIBotBehaviour/BBChangeLandingCraft.cpp | 14 +- .../AI/AIBotBehaviour/BBChangeTeleport.cpp | 11 +- .../AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp | 10 +- .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp | 35 +- .../AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp | 22 +- .../AIBotBehaviour/BBFireArtilleryDriver.cpp | 2 +- .../AI/AIBotBehaviour/BBFireLargeBore.cpp | 16 +- .../AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp | 7 +- .../BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp | 25 +- .../AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp | 8 +- .../AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp | 2 +- .../AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp | 2 +- .../AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp | 2 +- .../AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp | 8 +- .../AI/AIBotBehaviour/BBRunOverSoldier.cpp | 8 +- .../AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp | 2 +- .../AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp | 2 +- .../AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp | 2 +- .../AI/AIBotBehaviour/BBTakeCoverInfantry.cpp | 2 +- .../AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp | 8 +- .../AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h | 2 +- .../VehicleUrgencyCalculator.cpp | 13 +- .../BBPAvoidCollision2d.cpp | 6 +- .../BBPAvoidCollision3d.cpp | 4 +- .../BBPAvoidCollisionInfantery.cpp | 4 +- .../AIBotBehaviourPattern/BBPBridgeRepair.cpp | 8 +- .../AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp | 6 +- .../AIBotBehaviourPattern/BBPCallForMedic.cpp | 2 +- .../AI/AIBotBehaviourPattern/BBPChange.cpp | 33 +- .../AI/AIBotBehaviourPattern/BBPChange.h | 2 +- .../BBPChangeLandingCraft.cpp | 4 +- .../BBPChangeTeleport.cpp | 4 +- .../AIBotBehaviourPattern/BBPDefuseMines.cpp | 8 +- .../AI/AIBotBehaviourPattern/BBPFire2d.cpp | 6 +- .../AIBotBehaviourPattern/BBPFire2dDriver.cpp | 6 +- .../AI/AIBotBehaviourPattern/BBPFire3d.cpp | 8 +- .../BBPFireInfantery.cpp | 20 +- .../BBPGotoWaypoints2d.cpp | 4 +- .../BBPGotoWaypoints3d.cpp | 6 +- .../BBPGotoWaypointsBoat.cpp | 2 +- .../BBPGotoWaypointsInfantery.cpp | 6 +- .../AIBotBehaviourPattern/BBPHeliFire3d.cpp | 8 +- .../AI/AIBotBehaviourPattern/BBPIdle.cpp | 2 +- .../AI/AIBotBehaviourPattern/BBPIdle2d.cpp | 8 +- .../AI/AIBotBehaviourPattern/BBPIdle3d.cpp | 12 +- .../BBPIdleInfantery.cpp | 8 +- .../AIBotBehaviourPattern/BBPMedicAssist.cpp | 8 +- .../AI/AIBotBehaviourPattern/BBPRandom.cpp | 6 +- .../AI/AIBotBehaviourPattern/BBPRevive.cpp | 6 +- .../AI/AIBotBehaviourPattern/BBPRoam2d.cpp | 4 +- .../AI/AIBotBehaviourPattern/BBPRoam3d.cpp | 4 +- .../BBPRunOverSoldier.cpp | 4 +- .../AI/AIBotBehaviourPattern/BBPSuicide.cpp | 2 +- .../AI/AIBotBehaviourPattern/BBPTakeCover.cpp | 4 +- .../AIBotBehaviourPattern/BBPTakeCover3d.cpp | 4 +- .../BBPTakeCoverInfantry.cpp | 4 +- .../AIBotBehaviourPattern/BBPTriggerable.cpp | 4 +- .../AI/AIBotBehaviourPattern/WeaponChoice.cpp | 2 +- .../AI/AIKnowledge/AIInformationGrid.cpp | 24 +- .../AIDLL/AI/AIKnowledge/AIInformationGrid.h | 2 +- .../{Main => AIKnowledge}/AIMineManager.cpp | 27 +- .../AI/{Main => AIKnowledge}/AIMineManager.h | 6 +- .../AI/AIKnowledge/BFInformationCourier.cpp | 20 +- .../AIKnowledge/BFInformationEnvironment.cpp | 17 +- .../AI/AIDLL/AI/AIKnowledge/DangerObject.h | 2 +- .../AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp | 2 +- .../AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp | 2 +- .../BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp | 4 +- Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h | 2 +- .../AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp | 2 +- .../AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp | 2 +- .../AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp | 2 +- .../AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp | 2 +- Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp | 4 +- .../AI/AIDLL/AI/AIKnowledge/Information.cpp | 10 +- .../BF2/AI/AIDLL/AI/AIKnowledge/Information.h | 12 +- .../AI/AIKnowledge/InformationFactory.cpp | 4 +- .../AIDLL/AI/AIKnowledge/InformationKnown.cpp | 4 +- .../AIDLL/AI/AIKnowledge/InformationReal.cpp | 4 +- .../AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp | 24 +- .../AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h | 6 +- .../AerialHeightMap}/AerialHeightMap.cpp | 17 +- .../AerialHeightMap}/AerialHeightMap.h | 6 +- .../AI/AIPathFinding/Cluster/ClusterGraph.cpp | 72 ++-- .../AI/AIPathFinding/Cluster/ClusterGraph.h | 2 +- .../Cluster/ClusterNodeManager.cpp | 20 +- .../Cluster/ClusterNodeManager.h | 4 +- .../NavMesh/GTSDataOptimiser.cpp | 30 +- .../AIPathFinding/NavMesh/GTSDataOptimiser.h | 2 +- .../NavMesh/QTSearchNodeManager.cpp | 4 +- .../AI/AIPathFinding/NavMesh/QuadTree.cpp | 236 ++++++------- .../AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h | 10 +- .../AIPathFinding/NavMesh/QuadTreeManager.cpp | 122 +++---- .../AIPathFinding/NavMesh/QuadTreeManager.h | 6 +- .../AI/AIPathFinding/NavMesh/QuadTreeNode.cpp | 4 +- .../AI/AIPlanInterpreter/BAPInterpreter.cpp | 2 +- .../AI/AIPlanInterpreter/BoatControl.cpp | 2 +- .../AIDLL/AI/AIPlanInterpreter/CarControl.cpp | 8 +- .../AI/AIPlanInterpreter/CommonControls.cpp | 10 +- .../AI/AIPlanInterpreter/EntryBoatMoveTo.cpp | 2 +- .../EntryBoatMoveToObject.cpp | 2 +- .../EntryBoatResetControls.cpp | 2 +- .../AI/AIPlanInterpreter/EntryCarMoveTo.cpp | 2 +- .../EntryCarMoveToObject.cpp | 2 +- .../EntryCarResetControls.cpp | 2 +- .../AI/AIPlanInterpreter/EntryHeliAimAt.cpp | 4 +- .../EntryHeliMoveAwayFromObject.cpp | 2 +- .../AI/AIPlanInterpreter/EntryHeliMoveTo.cpp | 2 +- .../EntryHeliMoveToDirection.cpp | 2 +- .../EntryHeliMoveToObject.cpp | 2 +- .../EntryHeliResetControls.cpp | 2 +- .../EntryInfanteryMoveTo.cpp | 2 +- .../EntryInfanteryMoveToObject.cpp | 2 +- .../AIPlanInterpreter/EntryKeyTurretAimAt.cpp | 4 +- .../EntryMouseTurretAimAt.cpp | 4 +- .../EntryMouseTurretLookAt.cpp | 2 +- .../AIPlanInterpreter/EntryMoveToMedium.cpp | 2 +- .../EntryMoveToMediumBoat.cpp | 2 +- .../EntryMoveToMediumSoldier.cpp | 2 +- .../EntryMoveToObjectMedium.cpp | 2 +- .../EntryMoveToObjectMediumBoat.cpp | 2 +- .../EntryMoveToObjectMediumSoldier.cpp | 2 +- .../AI/AIPlanInterpreter/EntryPlaneAimAt.cpp | 4 +- .../AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp | 2 +- .../EntryPlaneMoveToObject.cpp | 4 +- .../EntryPlaneResetControls.cpp | 2 +- .../AI/AIPlanInterpreter/EntryPlaneRoll.cpp | 2 +- .../AI/AIPlanInterpreter/EntrySoldierPose.cpp | 2 +- .../AI/AIPlanInterpreter/EntryTankMoveTo.cpp | 2 +- .../EntryTankMoveToObject.cpp | 2 +- .../EntryTankResetControls.cpp | 2 +- .../AI/AIPlanInterpreter/EntryTankTurnTo.cpp | 2 +- .../AI/AIPlanInterpreter/EntryTrigger.cpp | 14 +- .../EntryTriggerContinously.cpp | 16 +- .../AIPlanInterpreter/EntryTurnToMedium.cpp | 2 +- .../AI/AIPlanInterpreter/HeliControl.cpp | 4 +- .../AI/AIPlanInterpreter/InfanteryControl.cpp | 14 +- .../AI/AIPlanInterpreter/MouseControl.cpp | 4 +- .../AI/AIPlanInterpreter/PlaneControl.cpp | 4 +- .../AI/AIPlanInterpreter/TankControl.cpp | 8 +- .../AIPlanInterpreter/VehicleControlInline.h | 2 +- Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp | 280 +++++++-------- Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h | 32 +- .../AI/AIStrategicEntity/AIStrategicArea.cpp | 49 ++- .../AI/AIStrategicEntity/AIStrategicArea.h | 4 +- .../AIStrategicEntity/AIStrategicObject.cpp | 68 ++-- .../AI/AIStrategicEntity/AIStrategicObject.h | 10 +- .../AIStrategicObjectManager.cpp | 246 ++++++------- .../AIStrategicObjectManager.h | 16 +- .../UserOrders}/UserOrderManager.cpp | 7 +- .../UserOrders}/UserOrderManager.h | 4 +- .../AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp | 5 +- .../BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp | 6 +- Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp | 2 +- .../CustomCurve.cpp | 154 +------- .../{AIBotBehaviour => AIUtils}/CustomCurve.h | 16 +- .../AIUtils/DebugRendering/AIRenderUtil.cpp | 2 +- .../DebugRendering/DPAIObject3dText.cpp | 2 +- .../DebugRendering/DPAIObjectCircle.cpp | 2 +- .../AIUtils/DebugRendering/DPAIObjectLine.cpp | 2 +- .../DebugRendering/DPDynamic3dText.cpp | 2 +- .../DebugRendering/DPDynamicCircle.cpp | 2 +- .../AIUtils/DebugRendering/DPDynamicLine.cpp | 2 +- Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp | 168 +++++++++ Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h | 27 ++ .../AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp | 2 +- .../WeaponInfoManager.cpp | 4 +- .../WeaponInfoManager.h | 2 +- .../AI/AIDLL/AI/Main/AICollisionHandler.cpp | 4 +- Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp | 6 +- Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h | 4 +- Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp | 2 +- Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp | 2 +- .../AILandingZoneManager.cpp | 4 +- .../AILandingZoneManager.h | 2 +- Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp | 26 +- Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp | 6 +- Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp | 92 ++--- Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h | 2 +- Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp | 2 +- Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp | 190 +++++----- Code/BF2/AI/AIDLL/AI/Main/AISettings.h | 24 +- .../AI/AIDLL/AI/Main/AIStreamOperators.cpp | 3 + Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp | 14 +- .../AI/AIDLL/AI/Main/BFPathfindingCourier.cpp | 2 +- Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp | 222 ++++++------ Code/BF2/AI/AIDLL/AI/Main/BotManager.h | 40 +-- .../BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp | 10 +- Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h | 2 +- Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp | 31 ++ Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp | 28 +- .../AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp | 42 +++ Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp | 14 +- .../AI/AIDLL/AI/Main/IBotManagerModifier.cpp | 26 ++ .../InformationManager.cpp | 2 +- .../InformationManager.h | 2 +- .../BFKnowledge/BFCollisionHandler.cpp | 2 +- .../AIInterface/BFKnowledge/WeaponObject.cpp | 2 +- .../AIInterface/BFKnowledge/WeaponTemplate.h | 12 +- .../AI/AIInterface/Main/AIEventListener.cpp | 2 +- Code/Build/aidll_sources.txt | 27 +- Code/Tests/aidll/action_runtime.h | 2 +- Code/Tests/aidll/action_runtime.py | 2 +- Code/Tests/aidll/area_update_runtime.cmd | 7 +- Code/Tests/aidll/area_update_runtime.h | 4 +- Code/Tests/aidll/area_update_runtime.py | 4 +- Code/Tests/aidll/bot_selector_runtime.cmd | 5 +- Code/Tests/aidll/bot_selector_runtime.cpp | 2 +- Code/Tests/aidll/bot_selector_runtime.h | 2 +- Code/Tests/aidll/closest_slots_runtime.cpp | 30 +- Code/Tests/aidll/coordinator_tail_runtime.cpp | 8 +- Code/Tests/aidll/coordinator_tick_runtime.cpp | 8 +- .../aidll/destroyable_map_part_runtime.cpp | 24 +- .../aidll/formation_membership_runtime.cpp | 34 +- Code/Tests/aidll/formation_tick_runtime.cpp | 96 ++--- .../aidll/free_unit_predicate_runtime.cmd | 2 +- .../Tests/aidll/free_unit_predicate_runtime.h | 2 +- .../aidll/information_factory_runtime.cmd | 6 +- .../aidll/information_factory_runtime.cpp | 8 +- .../aidll/information_factory_runtime.py | 2 +- .../aidll/information_frontiers_runtime.cmd | 9 +- .../aidll/information_frontiers_runtime.cpp | 4 +- .../aidll/information_frontiers_runtime.py | 4 +- .../aidll/information_prefix_runtime.cpp | 4 +- Code/Tests/aidll/information_query_runtime.h | 2 +- Code/Tests/aidll/ipicover_runtime.cpp | 2 +- Code/Tests/aidll/map_polygon_runtime.cpp | 6 +- Code/Tests/aidll/map_polygon_runtime.py | 2 +- Code/Tests/aidll/material_query_runtime.cpp | 16 +- Code/Tests/aidll/material_query_runtime.py | 2 +- Code/Tests/aidll/member_formation_runtime.cpp | 4 +- Code/Tests/aidll/member_update_runtime.cmd | 2 +- Code/Tests/aidll/member_update_runtime.cpp | 2 +- Code/Tests/aidll/member_update_runtime.h | 2 +- Code/Tests/aidll/member_update_runtime.py | 2 +- Code/Tests/aidll/mobile_courier_runtime.cmd | 6 +- Code/Tests/aidll/mobile_courier_runtime.cpp | 12 +- Code/Tests/aidll/mobile_courier_runtime.py | 2 +- Code/Tests/aidll/movement_runtime.cpp | 2 +- Code/Tests/aidll/plan_executor_runtime.cmd | 2 +- Code/Tests/aidll/plan_executor_runtime.cpp | 18 +- Code/Tests/aidll/plan_executor_runtime.h | 2 +- Code/Tests/aidll/plan_executor_runtime.py | 2 +- Code/Tests/aidll/random_kit_runtime.cmd | 2 +- Code/Tests/aidll/random_kit_runtime.h | 2 +- Code/Tests/aidll/random_kit_runtime.py | 4 +- Code/Tests/aidll/rectangle_query_runtime.h | 2 +- Code/Tests/aidll/sai_prepare_runtime.cmd | 2 +- Code/Tests/aidll/sai_prepare_runtime.cpp | 10 +- Code/Tests/aidll/sai_prepare_runtime.h | 2 +- Code/Tests/aidll/sai_strengths_runtime.cmd | 2 +- Code/Tests/aidll/sai_strengths_runtime.h | 2 +- Code/Tests/aidll/sai_update_runtime.cpp | 4 +- Code/Tests/aidll/seeded_polygon_runtime.cpp | 6 +- Code/Tests/aidll/squad_assignment_runtime.cpp | 10 +- Code/Tests/aidll/squad_kit_runtime.cpp | 4 +- Code/Tests/aidll/squad_maneuver_runtime.cmd | 2 +- Code/Tests/aidll/squad_maneuver_runtime.cpp | 6 +- Code/Tests/aidll/squad_maneuver_runtime.h | 2 +- Code/Tests/aidll/squad_maneuver_runtime.py | 2 +- Code/Tests/aidll/squad_queries_runtime.cpp | 16 +- Code/Tests/aidll/squad_runtime.cpp | 22 +- Code/Tests/aidll/squad_strength_runtime.cpp | 22 +- Code/Tests/aidll/squad_update_runtime.cpp | 34 +- Code/Tests/aidll/user_order_runtime.cmd | 2 +- Code/Tests/aidll/user_order_runtime.cpp | 2 +- .../Tests/aidll/vehicle_occupancy_runtime.cmd | 2 +- .../Tests/aidll/vehicle_occupancy_runtime.cpp | 4 +- Code/Tests/aidll/vehicle_occupancy_runtime.py | 4 +- Code/Tests/syntaxcheck.cmd | 27 +- 361 files changed, 3016 insertions(+), 2822 deletions(-) create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatternPrologue.h delete mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp rename Code/BF2/AI/AIDLL/AI/{AIBotBehaviour => AIBot}/UrgencyMerger.cpp (88%) rename Code/BF2/AI/AIDLL/AI/{AIBotBehaviour => AIBot}/UrgencyMerger.h (90%) rename Code/BF2/AI/AIDLL/AI/{AIBot => AIBotActionPlan}/Aimer.cpp (99%) rename Code/BF2/AI/AIDLL/AI/{AIBot => AIBotActionPlan}/Aimer.h (91%) rename Code/BF2/AI/AIDLL/AI/{AIPlanInterpreter => AIBotActionPlan}/BotScript.h (89%) rename Code/BF2/AI/AIDLL/AI/{Main => AIKnowledge}/AIMineManager.cpp (95%) rename Code/BF2/AI/AIDLL/AI/{Main => AIKnowledge}/AIMineManager.h (95%) rename Code/BF2/AI/AIDLL/AI/{AIStrategicMap => AIPathFinding/AerialHeightMap}/AerialHeightMap.cpp (91%) rename Code/BF2/AI/AIDLL/AI/{AIStrategicMap => AIPathFinding/AerialHeightMap}/AerialHeightMap.h (86%) rename Code/BF2/AI/AIDLL/AI/{Main => AIStrategicEntity/UserOrders}/UserOrderManager.cpp (95%) rename Code/BF2/AI/AIDLL/AI/{Main => AIStrategicEntity/UserOrders}/UserOrderManager.h (93%) rename Code/BF2/AI/AIDLL/AI/{AIBotBehaviour => AIUtils}/CustomCurve.cpp (76%) rename Code/BF2/AI/AIDLL/AI/{AIBotBehaviour => AIUtils}/CustomCurve.h (86%) create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h rename Code/BF2/AI/AIDLL/AI/{AIKnowledge => AIUtils}/WeaponInfoManager.cpp (94%) rename Code/BF2/AI/AIDLL/AI/{AIKnowledge => AIUtils}/WeaponInfoManager.h (92%) rename Code/BF2/AI/AIDLL/AI/{AIStrategicEntity => Main}/AILandingZoneManager.cpp (97%) rename Code/BF2/AI/AIDLL/AI/{AIStrategicEntity => Main}/AILandingZoneManager.h (96%) create mode 100644 Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp create mode 100644 Code/BF2/AI/AIDLL/AI/Main/IBotManagerModifier.cpp rename Code/BF2/AI/AIDLL/AI/{AIKnowledge => Main}/InformationManager.cpp (85%) rename Code/BF2/AI/AIDLL/AI/{AIKnowledge => Main}/InformationManager.h (91%) diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp index d29b96c15..d77e151da 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp @@ -18,15 +18,15 @@ #include "BotNavigation.h" #include "BotSquad.h" #include "../AIPlanInterpreter/BAPContext.h" -#include "../AIPlanInterpreter/BotScript.h" +#include "../AIBotActionPlan/BotScript.h" #include "../AIPlanInterpreter/PlanInterpreter.h" #include "SensingAgent.h" #include "CommunicationAgent.h" #include "BotSubObjects.h" #include "../AIBotBehaviour/BotBehaviour.h" -#include "../AIBotBehaviour/UrgencyMerger.h" +#include "UrgencyMerger.h" #include "../AIUtils/checkPointer.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" // updatePlayerAction: the equipment's mobile plug-in #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" @@ -36,7 +36,7 @@ #include "../Main/IBotManager.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../AIKnowledge/IPIArmament.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "BotSenses.h" #include "WaypointList.h" #include "WPEmpty.h" @@ -137,7 +137,7 @@ BotMain::BotMain(IAIPlayer* player, // Use -DBL_MAX for uninitialized timestamps; magnitude sentinels use separate values. m_time276 = -DBL_MAX; - m_poseChangeTime = -DBL_MAX; + m_soldierPoseAlteredTime = -DBL_MAX; m_botStuck = false; m_poseInputActive = false; for (int k = 0; k < 4; ++k) @@ -160,9 +160,9 @@ BotMain::BotMain(IAIPlayer* player, m_currentWaypoint[2] = 0.0f; m_int412 = -1; m_stalledPlanTicks = 0; - m_c4.position.x = 0.0f; // +428..+436 (three zero word stores) - m_c4.position.y = 0.0f; - m_c4.position.z = 0.0f; + m_c4Explosives.position.x = 0.0f; // +428..+436 (three zero word stores) + m_c4Explosives.position.y = 0.0f; + m_c4Explosives.position.z = 0.0f; m_moveToStatus = 0; m_timeOfLastFailedStaticAttack = 0.0; m_timeOfLastFailedStaticSkyAttack = 0.0; @@ -171,7 +171,7 @@ BotMain::BotMain(IAIPlayer* player, (&m_wantsToSimulateArtillery)[k] = false; // +500..+502 m_avoidSideChanged = false; // +512 m_collidedObject = -1; - m_double516 = 0.0; + m_timeOfLastStateChange = 0.0; for (int k = 0; k < 3; ++k) m_collidedObjectPosition[k] = 0; // +528..+536 @@ -234,7 +234,7 @@ BotMain::BotMain(IAIPlayer* player, // sense every player, and the storage for that is committed at construction. m_sensedObjects.reserve(256); - m_c4.placed = false; // the constructor's last field store + m_c4Explosives.isPlaced = false; // the constructor's last field store reset(); } @@ -339,7 +339,7 @@ void BotMain::reset() m_grenadeThrownTime[2] = 0.0; m_timeOfLastFailedStaticAttack = 0.0; m_timeOfLastFailedStaticSkyAttack = 0.0; - m_double516 = 0.0; + m_timeOfLastStateChange = 0.0; m_wantsToSimulateArtillery = false; m_isSimulatingArtillery = false; m_forcePose = false; @@ -362,7 +362,7 @@ void BotMain::reset() m_isGoingForFlag = false; m_useStaticAttack = false; // 9999.0, not the ctor's -DBL_MAX. See the block above. - m_poseChangeTime = -9999.0; + m_soldierPoseAlteredTime = -9999.0; m_timeOfLastFailedSplashDamageAttack = -9999.0; m_takeOffPosition[0] = 0.0f; m_takeOffPosition[1] = 0.0f; @@ -487,7 +487,7 @@ void BotMain::prePlanExecution() void BotMain::postPlanExecution() { Information* const equipment = informationManager->getInformation(getCurrentEquipment()); - if ((equipment->getObjectTypeFlags() & 0x00200000) == 0) + if (!equipment->isOfType(ITSoldier)) return; const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); const double sinceFriendsInLine = now - getFriendsInLineOfFireTime(); @@ -601,7 +601,7 @@ void BotMain::planExecution(const double& slice) m_activePlan = behaviour->generatePlan(this); if (m_activePlan) { - m_activePlan->m_owner = this; + m_activePlan->mpOwner = this; m_hasDefaultPlan = true; m_planInvalid = false; } @@ -635,7 +635,7 @@ void BotMain::planExecution(const double& slice) // No null guard: the ELF reads the flag word of whatever the handle resolves to. Information* const current = informationManager->getInformation(m_currentEquipment); - if ((current->getObjectTypeFlags() & 0x00200000) == 0) + if (!current->isOfType(ITSoldier)) { m_playerInput->setInput(io::PIWeaponSelect9, 0.0f); } @@ -838,7 +838,7 @@ int BotMain::decisionMaking(const double& slice) { if (!m_planInvalid) { - m_activePlan->m_owner = chosen; + m_activePlan->mpOwner = chosen; } else { @@ -854,7 +854,7 @@ int BotMain::decisionMaking(const double& slice) { if (m_activePlan) { - m_activePlan->m_owner = this; + m_activePlan->mpOwner = this; delete m_activePlan; m_activePlan = 0; m_sensingAgent->setOverride(false); @@ -870,7 +870,7 @@ int BotMain::decisionMaking(const double& slice) { m_planInvalid = false; m_hasDefaultPlan = false; - plan->m_owner = this; + plan->mpOwner = this; } for (std::list::iterator it = refreshed.begin(); it != refreshed.end(); ++it) { @@ -1020,7 +1020,7 @@ bool BotMain::updateBot() calculateMods(); getSelector()->updateActiveUrgency(this); // UrgencyGenerator +0x10 getMemory()->reset(); - if ((equipment->getObjectTypeFlags() & 0x10) == 0) + if (!equipment->isOfType(ITAir)) { // The image re-reads +0x8C (m_currentEquipment) inline here; no null guard. Information* const self = informationManager->getInformation(m_currentEquipment); @@ -1394,14 +1394,14 @@ void BotMain::resetAllControls(bool movement, bool look, bool actions) { static float minThrottle = 0.4f; Information* const equipment = informationManager->getInformation(m_currentEquipment); - const bool soldier = equipment && (equipment->getObjectTypeFlags() & 0x00200000) != 0; + const bool soldier = equipment && equipment->isOfType(ITSoldier); if (movement) { m_playerInput->setInput(io::PISprint, 0.0f); m_playerInput->setInput(io::PIYaw, 0.0f); m_playerInput->setInput(io::PIPitch, 0.0f); m_playerInput->setInput(io::PIRoll, 0.0f); - if ((equipment->getObjectTypeFlags() & 0x10) == 0) + if (!equipment->isOfType(ITAir)) { IPIMobile* const mobile = equipment->getMobile(); float throttle = 0.0f; @@ -1524,7 +1524,7 @@ void BotMain::pollRequestedSoldierPose() { input->setInput(io::PICrouch, 0.0f); Lie::toggle(input); - m_poseChangeTime = now; + m_soldierPoseAlteredTime = now; m_poseInputActive = true; } } @@ -1561,7 +1561,7 @@ void BotMain::pollRequestedSoldierPose() { input->setInput(io::PICrouch, 0.0f); Lie::toggle(input); - m_poseChangeTime = now; + m_soldierPoseAlteredTime = now; m_poseInputActive = true; } } @@ -1582,7 +1582,7 @@ void BotMain::pollRequestedSoldierPose() { input->setInput(io::PICrouch, 1.0f); input->setInput(io::PILie, 0.0f); - m_poseChangeTime = now; + m_soldierPoseAlteredTime = now; m_poseInputActive = true; } } @@ -1591,7 +1591,7 @@ void BotMain::pollRequestedSoldierPose() input->setInput(io::PICrouch, 0.0f); Lie::toggle(input); clearTestResults(); - m_poseChangeTime = now; + m_soldierPoseAlteredTime = now; m_poseInputActive = true; } else if (requested == SPLying || requested == SPSwimming) @@ -1621,7 +1621,7 @@ void BotMain::pollRequestedSoldierPose() } m_forcePose = false; - if (m_poseInputActive && (equipment->getObjectTypeFlags() & 0x00200000) != 0) + if (m_poseInputActive && equipment->isOfType(ITSoldier)) input->setInput(io::PIFire, 0.0f); } @@ -1882,46 +1882,46 @@ void BotMain::setBotStuck(bool b) void BotMain::placeC4(int placementType, Vec3 v, AIStrategicObject* o) { const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - m_c4.placed = true; - m_c4.placementType = placementType; - m_c4.object = o; - m_c4.position = v; - m_c4.placedTime = now; - m_c4.lifeTime = 240.0; + m_c4Explosives.isPlaced = true; + m_c4Explosives.placementType = placementType; + m_c4Explosives.object = o; + m_c4Explosives.position = v; + m_c4Explosives.placedTime = now; + m_c4Explosives.lifeTime = 240.0; } // +0x150 // ELF 0x1889C0. bool BotMain::isC4Placed() { - return m_c4.placed; + return m_c4Explosives.isPlaced; } // +0x154 // ELF 0x188980: type and position stay. void BotMain::removeC4() { - m_c4.placed = false; - m_c4.object = 0; - m_c4.placedTime = 0.0; - m_c4.lifeTime = 0.0; + m_c4Explosives.isPlaced = false; + m_c4Explosives.object = 0; + m_c4Explosives.placedTime = 0.0; + m_c4Explosives.lifeTime = 0.0; } // +0x158 // ELF 0x188880: a copy of +0x1A4..+0x1CB. Bot::C4State BotMain::getC4() { - return m_c4; + return m_c4Explosives; } // +0x15C // ELF 0x1889D0: a placed charge past its life time is removed (virtual +0x154). void BotMain::updateC4() { - if (!m_c4.placed) + if (!m_c4Explosives.isPlaced) return; const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - if (now > m_c4.placedTime + m_c4.lifeTime) + if (now > m_c4Explosives.placedTime + m_c4Explosives.lifeTime) removeC4(); } @@ -2038,7 +2038,7 @@ void BotMain::requestSoldierPose(int pose, bool b) const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); if (pose != m_requestedSoldierPose) { - if ((m_poseInputActive || now <= 1.0 + m_poseChangeTime) && !b) + if ((m_poseInputActive || now <= 1.0 + m_soldierPoseAlteredTime) && !b) return; m_requestedSoldierPose = pose; } @@ -2070,11 +2070,12 @@ void BotMain::setPoseStatus(int pose, unsigned int h, bool a, bool b) } // +0x1A0 -// ELF 0x18D740: airborne when the equipment carries type flag 0x10 or 0x20. +// ELF 0x18D740: airborne when the equipment is ITAir or ITHelicopter (two single-bit tests, +// testb $0x10 then testb $0x20). void BotMain::event_airborn() { Information* const equipment = informationManager->getInformation(m_currentEquipment); - m_airBorn = equipment && (equipment->getObjectTypeFlags() & 0x30) != 0; + m_airBorn = equipment && (equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter)); } // +0x1A4 @@ -2375,11 +2376,11 @@ int BotMain::getMoveToStatus() const void BotMain::setMoveToStatus(int status) { const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - if (m_double516 > now) - m_double516 = 0.0; - if (now - m_double516 > 0.0) + if (m_timeOfLastStateChange > now) + m_timeOfLastStateChange = 0.0; + if (now - m_timeOfLastStateChange > 0.0) { - m_double516 = now; + m_timeOfLastStateChange = now; m_moveToStatus = status; } } @@ -2479,7 +2480,7 @@ bool BotMain::botInPoseTransition() const { static double changeTime = 0.8; const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - return now - m_poseChangeTime < changeTime; + return now - m_soldierPoseAlteredTime < changeTime; } // +0x284 diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h index 99be9382a..8c75df2c7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h @@ -63,7 +63,7 @@ class Bot // recovered; Bot::C4PlacementType is attested by the placeC4 mangling). struct C4State { - /* +0x00 */ bool placed; + /* +0x00 */ bool isPlaced; // name: AIDLL_r assert "m_c4Explosives.isPlaced" (0x1014B2E0; PE +0x1D8) /* +0x04 */ int placementType; /* +0x08 */ Vec3 position; /* +0x14 */ AIStrategicObject* object; @@ -569,7 +569,7 @@ class BotMain : public Bot /* 286 */ char m_pad286[2]; // Construction uses -DBL_MAX as the timestamp sentinel; reset uses -9999.0. // When pollRequestedSoldierPose last pressed lie/crouch; botInPoseTransition is 0.8 s after it. - /* 288 */ double m_poseChangeTime; // ctor: -DBL_MAX, reset: -9999.0 + /* 288 */ double m_soldierPoseAlteredTime; // ctor: -DBL_MAX, reset: -9999.0 // name: AIDLL_r assert 0x1014C060 (PE +0x148) /* 296 */ int m_requestedSoldierPose; // = 1 dice spells the getter "Solder" // setPoseStatus / checkPoseOk / clearTestResults: [0],[1] crouch, [2],[3] lie. /* 300 */ bool m_poseTestResults[4]; // +300..+303, all false @@ -609,7 +609,7 @@ class BotMain : public Bot // +420..+459: placed (= false, the ctor's last field store), type, position (+428..+436, the // ctor zeroes it), object, placed time, life time. - /* 420 */ C4State m_c4; + /* 420 */ C4State m_c4Explosives; // name: AIDLL_r asserts 0x1014B2E0, 0x1014D180 (PE +0x1D8) // Three grenade timestamps. getTimeOfGrenadeThrown requires an index in [0, 3); // it performs no bounds check and larger indices read adjacent attack timestamps. /* 460 */ double m_grenadeThrownTime[3]; // +460, +468, +476 @@ -624,7 +624,7 @@ class BotMain : public Bot /* 508 */ int m_avoidSide; // = 0 /* 512 */ bool m_avoidSideChanged; // +512 byte = 0; setAvoidSide: switched between two non-zero sides [INFERRED] /* 513 */ char m_pad513[3]; - /* 516 */ double m_double516; // = 0.0; setMoveToStatus: the game time of the last status change + /* 516 */ double m_timeOfLastStateChange; // = 0.0; setMoveToStatus: the game time of the last status change // name: AIDLL_r assert in setMoveToStatus 0x1014C250 (PE +0x238) /* 524 */ unsigned int m_collidedObject; // = -1 /* 528 */ float m_collidedObjectPosition[3]; // a Vec3 - getCollidedObjectPosition /* 540 */ bool m_ignoreObstacles; // = false diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp index b308e220f..f73385637 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp @@ -10,7 +10,7 @@ #include "BotMain.h" // getBotId / getCurrentEquipment - vtable +0xE8, +0xD8 #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/AIInformationGrid.h" #include "../AIKnowledge/BFInformationEnvironment.h" @@ -45,18 +45,18 @@ BotNavigation::BotNavigation(BotMain* owner) : m_bot(owner) , m_arriveDistance(2.0f) , m_float8(2.0f) - , m_island(-1) + , m_startIsland(-1) , m_startPolygon(-1) , m_goalPolygon(-1) , m_goalMaterial(0) // the two paths, in the order the binary builds them: the fine one first. - , m_polygonPath(checkPointer(new QTPath())) + , m_path(checkPointer(new QTPath())) , m_int76(-1) , m_currentPoint(0) , m_clusterPath(checkPointer(new ClusterNodePath())) , m_int128(-1) - , m_double144(0.0) - , m_double152(0.0) + , m_noProgressTimer(0.0) + , m_noThrottleTimer(0.0) , m_double160(0.0) , m_double168(0.0) // 9,999,999.0f - a distance sentinel, not a time and not a magnitude. See above. @@ -64,15 +64,15 @@ BotNavigation::BotNavigation(BotMain* owner) , m_flag192(false) , m_flag193(false) , m_flag195(false) - , m_vehiclePolygon(-1) + , m_currentPolygon(-1) , m_vehicleIsland(-1) , m_infantryPolygon(-1) , m_infantryIsland(-1) - , m_int240(0) + , m_skipTraceCount(0) , m_grenadeTime(0.0) , m_grenadeFlag(false) // Independent sentinel, initialized to -1.0. - , m_double300(-1.0) + , m_lastAngleDiffTest(-1.0) { for (int i = 0; i < 3; ++i) { @@ -100,7 +100,7 @@ BotNavigation::BotNavigation(BotMain* owner) m_searchGoal.z = 0.0f; // the dead resize - see the block above. Written as what it is rather than dropped. - m_points.resize(0); + m_navigationPoints.resize(0); } // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. @@ -110,8 +110,8 @@ BotNavigation::BotNavigation(BotMain* owner) BotNavigation::~BotNavigation() { reset(); - if (m_polygonPath) - delete m_polygonPath; + if (m_path) + delete m_path; if (m_clusterPath) delete m_clusterPath; } @@ -126,7 +126,7 @@ void BotNavigation::resetAll() // Not the constructor's 0.0 - see the block above. m_grenadeTime = -9999.0; m_largestAngleDiff = 0.0f; - m_double300 = -1.0; + m_lastAngleDiffTest = -1.0; clearProgress(); } @@ -149,18 +149,18 @@ void BotNavigation::reset() } // Reaching through both path objects - see the block above. - m_polygonPath->m_nodes.resize(0); - m_polygonPath->m_i0 = 0; - m_polygonPath->m_i20 = 0; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0; m_clusterPath->m_nodes.resize(0); m_clusterPath->m_i0 = 0; m_int56 = 0; - m_points.resize(0); + m_navigationPoints.resize(0); - m_int240 = 0; + m_skipTraceCount = 0; m_currentPoint = 0; m_double160 = 0.0; m_flag195 = false; @@ -177,9 +177,9 @@ void BotNavigation::reset() { m_mapIndex = mobile->getVehicleNumber(); const IPIMobile::ValidPos& vehicle = mobile->getLastValidPosition(m_mapIndex); - m_vehicleIsland = static_cast(vehicle.quadTree); - m_vehiclePolygon = static_cast(vehicle.polygon); - m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().quadTree); + m_vehicleIsland = static_cast(vehicle.island); + m_currentPolygon = static_cast(vehicle.polygon); + m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().island); m_infantryPolygon = static_cast(mobile->getLastValidInfantryPos().polygon); } } @@ -197,13 +197,13 @@ void BotNavigation::clearProgress() m_zero176[0] = 0; // +176 // the one non-zero store. See the block above. - m_double144 = + m_noProgressTimer = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); m_double168 = 0.0; m_zero176[1] = 0; // +180 m_zero176[2] = 0; // +184 - m_double152 = 0.0; + m_noThrottleTimer = 0.0; m_flag192 = false; m_zero280[0] = 0; // +280 m_zero280[1] = 0; // +284 @@ -223,7 +223,7 @@ class MobileOrObstaclePredicate : public IAIInformationGridPredicate virtual bool includeInformation(Information* information) const { return (information->isPrimary() && information->hasMobile()) - || (information->getObjectTypeFlags() & 0x02000000) != 0; + || information->isOfType(ITObstacle); } }; @@ -287,7 +287,7 @@ bool BotNavigation::update(bool& a, bool* b) *b = false; if (m_flag195) { - m_points.resize(0); + m_navigationPoints.resize(0); m_currentPoint = 0; m_polygonSearchPending = true; m_flag195 = false; @@ -329,7 +329,7 @@ bool BotNavigation::initPathfinding(unsigned int island, unsigned int goalPolygo m_flag193 = false; return false; } - m_updateSpaceLeftAndRight = (info->getObjectTypeFlags() & 0x00200000) != 0; // byte +6 & 0x20 + m_updateSpaceLeftAndRight = info->isOfType(ITSoldier); // byte +6 & 0x20 if (m_pathfinding == 0) m_pathfinding = IAIPathfinding::instance; IPIMobile* const mobile = info->getMobile(); @@ -349,11 +349,11 @@ bool BotNavigation::initPathfinding(unsigned int island, unsigned int goalPolygo { if (static_cast(m_int56) < 2) return true; - if (!m_points.empty() && m_points[m_currentPoint].m_polygon == static_cast(valid.polygon)) + if (!m_navigationPoints.empty() && m_navigationPoints[m_currentPoint].m_polygon == static_cast(valid.polygon)) return true; - if (!m_points.empty() && stillOnPath()) + if (!m_navigationPoints.empty() && stillOnPath()) return true; - if (m_points.size() > 1) + if (m_navigationPoints.size() > 1) { retrace(); return true; @@ -364,7 +364,7 @@ bool BotNavigation::initPathfinding(unsigned int island, unsigned int goalPolygo { m_goalPolygon = static_cast(goalPolygon); m_goal = to; - if (valid.quadTree != 0xFFFFFFFFu && valid.polygon != 0xFFFFFFFFu) + if (valid.island != 0xFFFFFFFFu && valid.polygon != 0xFFFFFFFFu) { const Vec3& position = info->getPosition(); // Information slot +0x30 const float dx = position.x - valid.position.x; @@ -372,13 +372,13 @@ bool BotNavigation::initPathfinding(unsigned int island, unsigned int goalPolygo const float dz = position.z - valid.position.z; if (dx * dx + dy * dy + dz * dz <= 100.0f) { - if (island == valid.quadTree) + if (island == valid.island) { m_polygonSearchPending = true; m_useClusterSearch = true; m_flag192 = false; - m_island = static_cast(valid.quadTree); - m_pathIsland = static_cast(valid.quadTree); + m_startIsland = static_cast(valid.island); + m_island = static_cast(valid.island); m_startPolygon = static_cast(valid.polygon); m_startPosition = valid.position; m_arriveDistance = arriveDistance; @@ -386,27 +386,27 @@ bool BotNavigation::initPathfinding(unsigned int island, unsigned int goalPolygo m_float8Squared = b * b; m_mapIndex = mobile->getVehicleNumber(); const IPIMobile::ValidPos& vehicle = mobile->getLastValidPosition(m_mapIndex); - m_vehicleIsland = static_cast(vehicle.quadTree); - m_vehiclePolygon = static_cast(vehicle.polygon); - m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().quadTree); + m_vehicleIsland = static_cast(vehicle.island); + m_currentPolygon = static_cast(vehicle.polygon); + m_infantryIsland = static_cast(mobile->getLastValidInfantryPos().island); m_infantryPolygon = static_cast(mobile->getLastValidInfantryPos().polygon); m_equipmentType = info->getUnit()->getEquipmentType(); m_flag195 = false; - m_int240 = 0; + m_skipTraceCount = 0; reset(); m_flag193 = true; m_radius = info->getPhysical()->getSmallestRadius(); // IPIPhysical slot +0x34 m_pathfinding->getMaterial(m_mapIndex, island, static_cast(m_goalPolygon), m_goalMaterial); // slot +0x5C testDirectPath(); - void* const quadTree = m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_island)); + void* const quadTree = m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_startIsland)); m_flag316 = true; m_quadTree = static_cast(quadTree); // slot +0x64 return true; } Debug(DebugTypeError, "AI/AIDLL/AI/AIBot/BotNavigation.cpp", 0xC4, "") << "Bot " << m_bot->getName() << " is ordered to go to an island that it is not on (" - << island << " != " << valid.quadTree << ")"; + << island << " != " << valid.island << ")"; m_flag193 = false; return false; } @@ -423,12 +423,12 @@ void BotNavigation::updateLastPoint(Information* info) { const ClusterNodePath* const cluster = m_clusterPath; if (cluster->m_nodes.size() <= static_cast(cluster->m_i0) && !m_useClusterSearch - && !m_polygonSearchPending && static_cast(m_points.size()) > 0) + && !m_polygonSearchPending && static_cast(m_navigationPoints.size()) > 0) { const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(m_mapIndex); - if (static_cast(m_pathIsland) == valid.quadTree) + if (static_cast(m_island) == valid.island) { - NavigationPoint& last = m_points[m_points.size() - 1]; + NavigationPoint& last = m_navigationPoints[m_navigationPoints.size() - 1]; last.m_position = valid.position; last.m_polygon = static_cast(valid.polygon); } @@ -458,7 +458,7 @@ bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float d direct = false; if (static_cast(m_int56) < 2) m_double244 = 0.0; - if (m_useClusterSearch || m_flag195 || (m_polygonSearchPending && m_points.size() <= m_currentPoint)) + if (m_useClusterSearch || m_flag195 || (m_polygonSearchPending && m_navigationPoints.size() <= m_currentPoint)) { direct = true; return true; @@ -466,15 +466,15 @@ bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float d // a soldier firing at an enemy does not walk onto material 4 polygons Information* const target = informationManager->getInformation(m_bot->getFiringTarget()); - if (!m_points.empty() && m_updateSpaceLeftAndRight && m_bot->isFiring() && target) + if (!m_navigationPoints.empty() && m_updateSpaceLeftAndRight && m_bot->isFiring() && target) { if (target->getSide() != m_bot->getSide()) { - const unsigned int polygon = m_points.size() < 2 + const unsigned int polygon = m_navigationPoints.size() < 2 ? static_cast(m_goalPolygon) - : static_cast(m_points[m_currentPoint].m_polygon); + : static_cast(m_navigationPoints[m_currentPoint].m_polygon); unsigned char material; - if (m_pathfinding->getMaterial(m_mapIndex, static_cast(m_pathIsland), polygon, material) + if (m_pathfinding->getMaterial(m_mapIndex, static_cast(m_island), polygon, material) && material == 4) { direct = true; @@ -492,7 +492,7 @@ bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float d if (checkArrivedAtPoint(distance)) { - if (m_currentPoint == m_points.size() - 1) + if (m_currentPoint == m_navigationPoints.size() - 1) { m_double244 = 0.0; m_sentinel188 = 100000000.0f; @@ -502,23 +502,23 @@ bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float d else { ++m_currentPoint; - if (m_int240 > 0) - --m_int240; + if (m_skipTraceCount > 0) + --m_skipTraceCount; } } ClusterNodePath* const cluster = m_clusterPath; bool trim = true; - if (m_pathLength >= 30.0f && m_currentPoint + 10 < m_points.size()) + if (m_pathLength >= 30.0f && m_currentPoint + 10 < m_navigationPoints.size()) { - const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_points[m_currentPoint].m_polygon)); - if (static_cast(polygon->m_cluster) != static_cast(cluster->m_i0)) + const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_navigationPoints[m_currentPoint].m_polygon)); + if (static_cast(polygon->cluster) != static_cast(cluster->m_i0)) { - const Polygon* const again = m_quadTree->getPolygon(static_cast(m_points[m_currentPoint].m_polygon)); + const Polygon* const again = m_quadTree->getPolygon(static_cast(m_navigationPoints[m_currentPoint].m_polygon)); unsigned short current = 0xFFFF; if (cluster->m_i0 < static_cast(cluster->m_nodes.size())) current = cluster->m_nodes[cluster->m_i0].first; - if (again->m_cluster != current) + if (again->cluster != current) trim = false; } } @@ -526,10 +526,10 @@ bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float d { // keep at most ten points ahead and search the rest again m_polygonSearchPending = true; - unsigned int keep = static_cast(m_points.size()); + unsigned int keep = static_cast(m_navigationPoints.size()); if (m_currentPoint + 10 < keep) keep = m_currentPoint + 10; - m_points.resize(keep, NavigationPoint()); + m_navigationPoints.resize(keep, NavigationPoint()); } if (!m_flag195) @@ -547,12 +547,12 @@ bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float d if (static_cast(delay) < now - m_double160) { m_flag194 = false; - m_int240 = (useSkipTrace && m_updateSpaceLeftAndRight) ? 1 : 0; + m_skipTraceCount = (useSkipTrace && m_updateSpaceLeftAndRight) ? 1 : 0; retrace(); } } } - vec3ToVec2XZ(m_points[m_currentPoint].m_position, point); + vec3ToVec2XZ(m_navigationPoints[m_currentPoint].m_position, point); return true; } @@ -560,32 +560,32 @@ bool BotNavigation::updatePath(Vec2& point, bool& arrived, bool& direct, float d // current point's, or one behind; or within the next 20 points (which becomes the current one). bool BotNavigation::stillOnPath() { - if (m_points.size() < 2) + if (m_navigationPoints.size() < 2) return false; Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); const int polygon = static_cast(info->getMobile()->getLastValidPosition().polygon); if (polygon == -1) return false; const unsigned int current = m_currentPoint; - if (current >= m_points.size()) + if (current >= m_navigationPoints.size()) return false; - const int previous = current != 0 ? m_points[current - 1].m_polygon : -1; - if (polygon == previous || polygon == m_points[current].m_polygon) + const int previous = current != 0 ? m_navigationPoints[current - 1].m_polygon : -1; + if (polygon == previous || polygon == m_navigationPoints[current].m_polygon) return true; for (int i = static_cast(current); i >= 0; --i) - if (m_points[i].m_polygon == polygon) + if (m_navigationPoints[i].m_polygon == polygon) return true; - unsigned int ahead = static_cast(m_points.size()) - current; + unsigned int ahead = static_cast(m_navigationPoints.size()) - current; if (ahead > 0x14) ahead = 0x14; const unsigned int end = ahead + current; for (unsigned int i = current; i < end; ++i) { - if (m_points[i].m_polygon == polygon) + if (m_navigationPoints[i].m_polygon == polygon) { m_currentPoint = i; - const int left = m_int240 - static_cast(i - current); - m_int240 = left > 0 ? left : 0; + const int left = m_skipTraceCount - static_cast(i - current); + m_skipTraceCount = left > 0 ? left : 0; return true; } } @@ -605,15 +605,15 @@ void BotNavigation::retrace() return; } cluster->m_i0 = 0; - m_points.resize(0, NavigationPoint()); + m_navigationPoints.resize(0, NavigationPoint()); Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); const IPIMobile::ValidPos& valid = info->getMobile()->getLastValidPosition(); - m_island = static_cast(valid.quadTree); + m_startIsland = static_cast(valid.island); m_startPolygon = static_cast(valid.polygon); m_startPosition = valid.position; m_flag195 = true; const short own = static_cast(m_pathfinding->getClusterOfPolygon( - m_mapIndex, static_cast(m_island), valid.polygon)); // slot +0x7C + m_mapIndex, static_cast(m_startIsland), valid.polygon)); // slot +0x7C for (unsigned int i = 0; i < count - 1; ++i) { short node = -1; @@ -629,7 +629,7 @@ void BotNavigation::retrace() unsigned short node = 0xFFFF; if (m_clusterPath->m_i0 < static_cast(m_clusterPath->m_nodes.size())) node = m_clusterPath->m_nodes[m_clusterPath->m_i0].first; - if (m_pathfinding->areNeighbouringClusters(m_mapIndex, static_cast(m_island), + if (m_pathfinding->areNeighbouringClusters(m_mapIndex, static_cast(m_startIsland), static_cast(own), node)) // slot +0x80 return; ++m_clusterPath->m_i0; @@ -655,16 +655,16 @@ void BotNavigation::testDirectPath() hit.x = 0.0f; hit.y = 0.0f; hit.z = 0.0f; unsigned int polygon; unsigned char material; - if (!m_pathfinding->trace(static_cast(m_startPolygon), static_cast(m_pathIsland), + if (!m_pathfinding->trace(static_cast(m_startPolygon), static_cast(m_island), m_mapIndex, m_startPosition, m_goal, hit, polygon, m_equipmentType, -1, 0.0f, 5, &material)) // slot +0x8C return; - const unsigned int index = static_cast(m_points.size()); - m_points.resize(index + 1, NavigationPoint()); - NavigationPoint& last = m_points[index]; + const unsigned int index = static_cast(m_navigationPoints.size()); + m_navigationPoints.resize(index + 1, NavigationPoint()); + NavigationPoint& last = m_navigationPoints[index]; last.m_position = m_goal; last.m_polygon = static_cast(polygon); - last.m_point0 = m_goal; + last.edgePoint1 = m_goal; last.m_pointC = m_goal; m_goalPolygon = static_cast(polygon); m_goalMaterial = material; @@ -683,9 +683,9 @@ bool BotNavigation::checkArrivedAtPoint(float) // The image reads BotMain +0x8C (m_currentEquipment) inline; getCurrentEquipment returns it. Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); const Vec3& position = info->getPosition(); - if (m_points.empty()) + if (m_navigationPoints.empty()) return false; - const NavigationPoint& p = m_points[m_currentPoint]; + const NavigationPoint& p = m_navigationPoints[m_currentPoint]; if (!(std::fabs(position.y - p.m_position.y) <= 3.0f)) return false; float distance = soldierMinDist; @@ -696,7 +696,7 @@ bool BotNavigation::checkArrivedAtPoint(float) distance = 1.0f; } float limit = distance; - if (!m_updateSpaceLeftAndRight && m_currentPoint == m_points.size() - 1) + if (!m_updateSpaceLeftAndRight && m_currentPoint == m_navigationPoints.size() - 1) { limit = m_radius - 1.0f; if (limit <= distance) @@ -711,9 +711,9 @@ bool BotNavigation::checkArrivedAtPoint(float) bool BotNavigation::getSecondPoint(Vec2& out) { const unsigned int next = m_currentPoint + 1; - const bool exists = next < m_points.size(); + const bool exists = next < m_navigationPoints.size(); if (exists) - vec3ToVec2XZ(m_points[next].m_position, out); + vec3ToVec2XZ(m_navigationPoints[next].m_position, out); return exists; } @@ -723,17 +723,17 @@ bool BotNavigation::getLargestAngleDiff(float& out) { static float timeStep = 2.0f; // ELF 0x4B6C2C (.data) const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - if (!(now - m_double300 >= 0.5)) + if (!(now - m_lastAngleDiffTest >= 0.5)) { out = m_largestAngleDiff; return true; } - m_double300 = now; + m_lastAngleDiffTest = now; // The image reads BotMain +0x8C inline (no null guard). Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); const Vec3& position = info->getPosition(); unsigned int index = m_currentPoint; - const Vec3& first = m_points[index].m_position; + const Vec3& first = m_navigationPoints[index].m_position; float covered = length3(position.x - first.x, position.y - first.y, position.z - first.z); Vec2 facing; facing.x = 0.0f; facing.y = 0.0f; @@ -743,14 +743,14 @@ bool BotNavigation::getLargestAngleDiff(float& out) float range = info->getMobile()->getSpeedMagnitude() * timeStep; // IPIMobile slot +0x24 if (range <= 3.0f) range = 3.0f; - for (; covered < range && index < m_points.size(); ++index) + for (; covered < range && index < m_navigationPoints.size(); ++index) { Vec3 from; if (index == 0) from = info->getPosition(); else - from = m_points[index - 1].m_position; - const Vec3& to = m_points[index].m_position; + from = m_navigationPoints[index - 1].m_position; + const Vec3& to = m_navigationPoints[index].m_position; covered = length3(from.x - to.x, from.y - to.y, from.z - to.z) + covered; Vec3 leg; leg.x = to.x - from.x; leg.y = to.y - from.y; leg.z = to.z - from.z; @@ -782,9 +782,9 @@ bool BotNavigation::getLargestAngleDiff(float& out) // `from` in the plane; `out` keeps the last point looked at. void BotNavigation::getFirstPointBeyondDist(const Vec2& from, float distance, Vec2& out) { - for (unsigned int i = m_currentPoint; i < m_points.size(); ++i) + for (unsigned int i = m_currentPoint; i < m_navigationPoints.size(); ++i) { - const Vec3& p = m_points[i].m_position; + const Vec3& p = m_navigationPoints[i].m_position; out.x = p.x; out.y = p.z; const float dx = from.x - p.x; @@ -831,19 +831,19 @@ bool BotNavigation::doPolygonSearch(bool& finished, bool* blocked) } if (m_mapIndex != m_pathfinding->getTraceMapIndex()) m_pathfinding->setUsePathTopologySmoothing(m_int76, true); - if (m_points.empty()) + if (m_navigationPoints.empty()) { m_searchStart = m_startPosition; m_searchStartPolygon = static_cast(m_startPolygon); } else { - const NavigationPoint& last = m_points.back(); + const NavigationPoint& last = m_navigationPoints.back(); m_searchStart = last.m_position; m_searchStartPolygon = static_cast(last.m_polygon); } m_set132.clear(); - m_set132.insert(m_quadTree->getPolygon(m_searchStartPolygon)->m_cluster); + m_set132.insert(m_quadTree->getPolygon(m_searchStartPolygon)->cluster); m_searchGoalIsFinal = false; if (!m_clusterPath->getPoint(m_searchGoal, m_searchGoalPolygon, static_cast(m_clusterPath->m_i0 + 2))) { @@ -861,12 +861,12 @@ bool BotNavigation::doPolygonSearch(bool& finished, bool* blocked) static_cast(index) < static_cast(nodes) ? m_clusterPath->m_nodes[index].first : 0xFFFF; m_set132.insert(cluster); } - m_set132.insert(m_quadTree->getPolygon(m_searchGoalPolygon)->m_cluster); + m_set132.insert(m_quadTree->getPolygon(m_searchGoalPolygon)->cluster); m_pathfinding->setAllowedClusters(m_int76, &m_set132); } - m_int56 = m_pathfinding->localSearch(static_cast(m_int76), m_mapIndex, static_cast(m_island), + m_int56 = m_pathfinding->localSearch(static_cast(m_int76), m_mapIndex, static_cast(m_startIsland), m_searchStartPolygon, m_searchStart, m_searchGoalPolygon, m_searchGoal, - m_equipmentType, m_polygonPath); + m_equipmentType, m_path); if (m_int56 != 1) { m_pathfinding->releaseResource(m_int76, m_bot->getBotId()); @@ -876,16 +876,16 @@ bool BotNavigation::doPolygonSearch(bool& finished, bool* blocked) calculatePoints(); if (m_searchGoalIsFinal) { - const unsigned int n = static_cast(m_points.size()); - m_points.resize(n + 1, NavigationPoint()); - m_points[n].m_position = m_goal; - m_points[n].m_polygon = m_goalPolygon; + const unsigned int n = static_cast(m_navigationPoints.size()); + m_navigationPoints.resize(n + 1, NavigationPoint()); + m_navigationPoints[n].m_position = m_goal; + m_navigationPoints[n].m_polygon = m_goalPolygon; m_clusterPath->m_nodes.resize(0); m_clusterPath->m_i0 = 0; } m_flag192 = false; m_quadTree = static_cast( - m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_polygonPath->m_island))); + m_pathfinding->getQuadTree(m_mapIndex, static_cast(m_path->m_island))); optimizePoints(); updateNavPoints(); updateNavPoints(); @@ -913,7 +913,7 @@ bool BotNavigation::doClusterSearch(bool& finished, bool* blocked) return false; } } - m_int56 = m_pathfinding->clusterSearch(static_cast(m_int128), m_mapIndex, static_cast(m_island), + m_int56 = m_pathfinding->clusterSearch(static_cast(m_int128), m_mapIndex, static_cast(m_startIsland), static_cast(m_startPolygon), m_startPosition, static_cast(m_goalPolygon), m_goal, m_equipmentType, m_clusterPath); @@ -944,7 +944,7 @@ bool BotNavigation::pointWithinObstacleRadius(const Vec3& point) for (unsigned int i = 0; i < m_obstacles.size(); ++i) { Information* const info = informationManager->getInformation(m_obstacles[i]); - if (!info || (info->getObjectTypeFlags() & 0x00200000u) || !info->getPhysical()) + if (!info || info->isOfType(ITSoldier) || !info->getPhysical()) continue; const Vec3& p = info->getPosition(); const float radius = info->getPhysical()->getSmallestRadius(); @@ -962,11 +962,11 @@ bool BotNavigation::pointWithinObstacleRadius(const Vec3& point) // emptied afterwards. void BotNavigation::calculatePoints() { - m_polygonPath->m_i0 = 0; - QTPath* path = m_polygonPath; + m_path->m_i0 = 0; + QTPath* path = m_path; const unsigned int island = static_cast(path->m_island); const unsigned int steps = static_cast(path->m_nodes.size()); - const unsigned int count = static_cast(m_points.size()); + const unsigned int count = static_cast(m_navigationPoints.size()); unsigned int base = count - 1; if (count <= m_currentPoint) base = 0; @@ -979,27 +979,27 @@ void BotNavigation::calculatePoints() int polygon = -1; if (path->m_i0 < static_cast(path->m_nodes.size())) polygon = static_cast(path->m_nodes[path->m_i0].first); - m_points.resize(size, NavigationPoint()); - path = m_polygonPath; + m_navigationPoints.resize(size, NavigationPoint()); + path = m_path; unsigned int k = base; while (static_cast(path->m_i0) < steps) { int entered = polygon; - NavigationPoint& point = m_points[k]; + NavigationPoint& point = m_navigationPoints[k]; point.m_position = *path->getPosition(static_cast(path->m_i0)); - point.m_polygon = static_cast(m_polygonPath->getPolygon(static_cast(m_polygonPath->m_i0))); + point.m_polygon = static_cast(m_path->getPolygon(static_cast(m_path->m_i0))); if (from == -1) { - point.m_point0 = *m_polygonPath->getPosition(static_cast(m_polygonPath->m_i0)); - point.m_pointC = *m_polygonPath->getPosition(static_cast(m_polygonPath->m_i0)); + point.edgePoint1 = *m_path->getPosition(static_cast(m_path->m_i0)); + point.m_pointC = *m_path->getPosition(static_cast(m_path->m_i0)); } else { - m_pathfinding->getEdge(point.m_point0, point.m_pointC, m_mapIndex, static_cast(from), + m_pathfinding->getEdge(point.edgePoint1, point.m_pointC, m_mapIndex, static_cast(from), static_cast(entered), island); } - ++m_polygonPath->m_i0; - path = m_polygonPath; + ++m_path->m_i0; + path = m_path; int next = -1; if (path->m_i0 < static_cast(path->m_nodes.size())) next = static_cast(path->m_nodes[path->m_i0].second); @@ -1022,7 +1022,7 @@ void BotNavigation::calculatePoints() // point where that line crosses its edge, when it does within the edge. void BotNavigation::optimizePoints() { - if (m_points.empty()) + if (m_navigationPoints.empty()) return; Vec2 from; from.x = 0.0f; @@ -1032,10 +1032,10 @@ void BotNavigation::optimizePoints() vec3ToVec2XZ(info->getPosition(), from); for (int pass = 0; pass < 2; ++pass) { - for (unsigned int i = 0; i < m_points.size() - 1; ++i) + for (unsigned int i = 0; i < m_navigationPoints.size() - 1; ++i) { const Vec3& p = info->getPosition(); - const Vec3& at = m_points[i].m_position; + const Vec3& at = m_navigationPoints[i].m_position; const float dx = p.x - at.x; const float dy = p.y - at.y; const float dz = p.z - at.z; @@ -1045,9 +1045,9 @@ void BotNavigation::optimizePoints() next.x = 0.0f; next.y = 0.0f; a.x = 0.0f; a.y = 0.0f; b.x = 0.0f; b.y = 0.0f; - vec3ToVec2XZ(m_points[i + 1].m_position, next); - vec3ToVec2XZ(m_points[i].m_point0, a); - vec3ToVec2XZ(m_points[i].m_pointC, b); + vec3ToVec2XZ(m_navigationPoints[i + 1].m_position, next); + vec3ToVec2XZ(m_navigationPoints[i].edgePoint1, a); + vec3ToVec2XZ(m_navigationPoints[i].m_pointC, b); float s; float t; if (lineIntersect(from, next, a, b, s, t)) @@ -1071,36 +1071,36 @@ void BotNavigation::optimizePoints() { t = margin / length; } - NavigationPoint& point = m_points[i]; + NavigationPoint& point = m_navigationPoints[i]; const float u = t <= 1.0f ? t : 1.0f; - point.m_position.x = point.m_point0.x + (point.m_pointC.x - point.m_point0.x) * u; - point.m_position.y = (point.m_pointC.y - point.m_point0.y) * u + point.m_point0.y; - point.m_position.z = (point.m_pointC.z - point.m_point0.z) * u + point.m_point0.z; + point.m_position.x = point.edgePoint1.x + (point.m_pointC.x - point.edgePoint1.x) * u; + point.m_position.y = (point.m_pointC.y - point.edgePoint1.y) * u + point.edgePoint1.y; + point.m_position.z = (point.m_pointC.z - point.edgePoint1.z) * u + point.edgePoint1.z; } } - vec3ToVec2XZ(m_points[i].m_position, from); + vec3ToVec2XZ(m_navigationPoints[i].m_position, from); } } vec3ToVec2XZ(info->getPosition(), from); - for (unsigned int i = 0; i < m_points.size() - 1; ++i) + for (unsigned int i = 0; i < m_navigationPoints.size() - 1; ++i) { Vec2 next, a, b; next.x = 0.0f; next.y = 0.0f; a.x = 0.0f; a.y = 0.0f; b.x = 0.0f; b.y = 0.0f; - vec3ToVec2XZ(m_points[i + 1].m_position, next); - vec3ToVec2XZ(m_points[i].m_point0, a); - vec3ToVec2XZ(m_points[i].m_pointC, b); + vec3ToVec2XZ(m_navigationPoints[i + 1].m_position, next); + vec3ToVec2XZ(m_navigationPoints[i].edgePoint1, a); + vec3ToVec2XZ(m_navigationPoints[i].m_pointC, b); float s; float t; if (lineIntersect(from, next, a, b, s, t) && 0.0f <= t && t <= 1.0f) { - NavigationPoint& point = m_points[i]; - point.m_position.x = (point.m_pointC.x - point.m_point0.x) * t + point.m_point0.x; - point.m_position.y = (point.m_pointC.y - point.m_point0.y) * t + point.m_point0.y; - point.m_position.z = (point.m_pointC.z - point.m_point0.z) * t + point.m_point0.z; + NavigationPoint& point = m_navigationPoints[i]; + point.m_position.x = (point.m_pointC.x - point.edgePoint1.x) * t + point.edgePoint1.x; + point.m_position.y = (point.m_pointC.y - point.edgePoint1.y) * t + point.edgePoint1.y; + point.m_position.z = (point.m_pointC.z - point.edgePoint1.z) * t + point.edgePoint1.z; } - vec3ToVec2XZ(m_points[i].m_position, from); + vec3ToVec2XZ(m_navigationPoints[i].m_position, from); } } @@ -1130,9 +1130,9 @@ void BotNavigation::updateNavPoints() bool advanced = false; const float clearance = soldier ? minClearanceSoldier : minClearanceVehicle; unsigned int polygon; - if (m_int240 == 0) + if (m_skipTraceCount == 0) { - const Vec3& current = m_points[m_currentPoint].m_position; + const Vec3& current = m_navigationPoints[m_currentPoint].m_position; const float dx = position.x - current.x; const float dy = position.y - current.y; const float dz = position.z - current.z; @@ -1140,8 +1140,8 @@ void BotNavigation::updateNavPoints() { for (int i = 0; i < (soldier ? 1 : 4); ++i) { - if (m_points.size() - 1 <= m_currentPoint - || !m_pathfinding->trace(this, false, m_points[m_currentPoint + 1].m_position, hit, polygon, + if (m_navigationPoints.size() - 1 <= m_currentPoint + || !m_pathfinding->trace(this, false, m_navigationPoints[m_currentPoint + 1].m_position, hit, polygon, m_equipmentType, steps, clearance, 5, 0)) break; ++m_currentPoint; @@ -1151,7 +1151,7 @@ void BotNavigation::updateNavPoints() return; } } - if (!m_pathfinding->trace(this, false, m_points[m_currentPoint].m_position, hit, polygon, m_equipmentType, -1, + if (!m_pathfinding->trace(this, false, m_navigationPoints[m_currentPoint].m_position, hit, polygon, m_equipmentType, -1, 0.0f, 0, 0)) m_flag194 = true; } @@ -1162,7 +1162,7 @@ void BotNavigation::updateNavPoints() // as in the image. void BotNavigation::updateClosestDistance() { - if (m_points.empty()) + if (m_navigationPoints.empty()) { m_sentinel188 = 0.0f; return; @@ -1170,13 +1170,13 @@ void BotNavigation::updateClosestDistance() // The image reads BotMain +0x8C inline (no null guard). Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); const Vec3& position = info->getPosition(); - const Vec3& current = m_points[m_currentPoint].m_position; + const Vec3& current = m_navigationPoints[m_currentPoint].m_position; float distance = length3(position.x - current.x, position.y - current.y, position.z - current.z); unsigned int i = m_currentPoint + 1; - for (; i < m_points.size(); ++i) + for (; i < m_navigationPoints.size(); ++i) { - const Vec3& a = m_points[i - 1].m_position; - const Vec3& b = m_points[i].m_position; + const Vec3& a = m_navigationPoints[i - 1].m_position; + const Vec3& b = m_navigationPoints[i].m_position; distance = length3(a.x - b.x, a.y - b.y, a.z - b.z) + distance; } ClusterNodePath* const cluster = m_clusterPath; @@ -1185,7 +1185,7 @@ void BotNavigation::updateClosestDistance() if (static_cast(cluster->m_i0) < nodes) { const unsigned int remaining = nodes - static_cast(cluster->m_i0); - Vec3 previous = m_points[i - 1].m_position; + Vec3 previous = m_navigationPoints[i - 1].m_position; for (unsigned int k = 1; k < remaining; ++k) { Vec3 point; @@ -1202,9 +1202,9 @@ void BotNavigation::updateClosestDistance() // ELF 0x1927A0 (130 bytes): a point on a missing or non-walkable (material 0) polygon. bool BotNavigation::hasIllegalPath() { - for (unsigned int i = 0; i < m_points.size(); ++i) + for (unsigned int i = 0; i < m_navigationPoints.size(); ++i) { - const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_points[i].m_polygon)); + const Polygon* const polygon = m_quadTree->getPolygon(static_cast(m_navigationPoints[i].m_polygon)); if (!polygon || polygon->m_material == 0) return true; } @@ -1238,7 +1238,7 @@ bool BotNavigation::checkProgress() const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); if (1.0 < now - m_double168 && ((input->mappingFlags >> io::PIAction) & 1ULL)) input->inputs[io::PIAction] = 0.0f; - if (m_points.empty() || m_int56 != 2) + if (m_navigationPoints.empty() || m_int56 != 2) return true; float move = mappedInput(input, io::PIThrottle); const float sprint = mappedInput(input, io::PISprint); @@ -1250,16 +1250,16 @@ bool BotNavigation::checkProgress() const double still = m_updateSpaceLeftAndRight ? 0.1 : 0.5; if (std::fabs(move) <= 0.1f) { - if (still < now - m_double152) + if (still < now - m_noThrottleTimer) { - m_double144 = now; + m_noProgressTimer = now; m_flag192 = false; return true; } } else { - m_double152 = now; + m_noThrottleTimer = now; } const float radius = m_updateSpaceLeftAndRight ? 2.0f : 4.0f; Information* const info = informationManager->getInformation(m_bot->getCurrentEquipment()); @@ -1267,7 +1267,7 @@ bool BotNavigation::checkProgress() if (distanceSq(m_zero280, position) <= radius * radius) { const float limit = m_updateSpaceLeftAndRight ? 10.0f : 20.0f; - const double since = m_double144; + const double since = m_noProgressTimer; if (m_updateSpaceLeftAndRight && 2.0f < static_cast(now - since) && 3.0 < now - m_double168) { if (distanceSq(m_zero176, info->getPosition()) < 0.001f) @@ -1282,7 +1282,7 @@ bool BotNavigation::checkProgress() m_zero280[0] = position.x; m_zero280[1] = position.y; m_zero280[2] = position.z; - m_double144 = now; + m_noProgressTimer = now; m_flag192 = false; return true; } @@ -1347,16 +1347,16 @@ void BotNavigation::getTraceData(int mapIndex, unsigned int& polygon, unsigned i m_tracePosition = valid.position; position = valid.position; polygon = valid.polygon; - island = valid.quadTree; + island = valid.island; if (m_mapIndex == mapIndex) { - m_vehiclePolygon = static_cast(valid.polygon); - m_vehicleIsland = static_cast(valid.quadTree); + m_currentPolygon = static_cast(valid.polygon); + m_vehicleIsland = static_cast(valid.island); } if (mapIndex == IAIPathfinding::instance->getTraceMapIndex()) { m_infantryPolygon = static_cast(valid.polygon); - m_infantryIsland = static_cast(valid.quadTree); + m_infantryIsland = static_cast(valid.island); } return; } @@ -1368,7 +1368,7 @@ void BotNavigation::getTraceData(int mapIndex, unsigned int& polygon, unsigned i } else if (mapIndex == m_mapIndex) { - polygon = static_cast(m_vehiclePolygon); + polygon = static_cast(m_currentPolygon); island = static_cast(m_vehicleIsland); } else @@ -1380,25 +1380,25 @@ void BotNavigation::getTraceData(int mapIndex, unsigned int& polygon, unsigned i // ELF 0x192EA0: append the old route's remaining interior points after recalculating the prefix. void BotNavigation::mergeNavigationPoints() { - const std::vector previous(m_points); + const std::vector previous(m_navigationPoints); unsigned int index = m_currentPoint; - m_polygonPath->m_i0 = 0; + m_path->m_i0 = 0; calculatePoints(); // Shipped defect: an empty previous route underflows this unsigned bound. for (; index < previous.size() - 1; ++index) - m_points.push_back(previous[index]); + m_navigationPoints.push_back(previous[index]); NavigationPoint last; - last.m_point0 = m_goal; + last.edgePoint1 = m_goal; last.m_pointC = m_goal; last.m_position = m_goal; last.m_polygon = m_goalPolygon; - m_points.push_back(last); + m_navigationPoints.push_back(last); } // ELF 0x195390: appends to the caller's vector without clearing it. void BotNavigation::getNavigationPoints(std::vector& points) const { - for (std::vector::const_iterator it = m_points.begin(); it != m_points.end(); ++it) + for (std::vector::const_iterator it = m_navigationPoints.begin(); it != m_navigationPoints.end(); ++it) points.push_back(it->m_position); } diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h index 4a111c0ef..1e25acba7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h @@ -107,12 +107,12 @@ class BotNavigation NavigationPoint() : m_polygon(-1) { - m_point0.x = 0.0f; m_point0.y = 0.0f; m_point0.z = 0.0f; + edgePoint1.x = 0.0f; edgePoint1.y = 0.0f; edgePoint1.z = 0.0f; m_pointC.x = 0.0f; m_pointC.y = 0.0f; m_pointC.z = 0.0f; m_position.x = 0.0f; m_position.y = 0.0f; m_position.z = 0.0f; } - /* +0x00 */ Vec3 m_point0; + /* +0x00 */ Vec3 edgePoint1; // name: AIDLL_r assert "m_navigationPoints[i].edgePoint1" 0x10149B20 (entry +0) /* +0x0C */ Vec3 m_pointC; /* +0x18 */ Vec3 m_position; /* +0x24 */ int m_polygon; // = -1 @@ -128,7 +128,7 @@ class BotNavigation /* 8 */ float m_float8; // = 2.0f [UNRESOLVED] /* 12 */ float m_float8Squared; // initPathfinding: b * b // initPathfinding / retrace: the bot's last valid position (IPIMobile::ValidPos fields). - /* 16 */ int m_island; // = -1; ValidPos::quadTree + /* 16 */ int m_startIsland; // = -1; ValidPos::island [INFERRED] name: AIDLL_r names +112 m_island (0x10149B20), so this one was renamed /* 20 */ int m_startPolygon; // = -1 /* 24 */ Vec3 m_startPosition; // all 0 /* 36 */ int m_goalPolygon; // = -1 @@ -147,7 +147,7 @@ class BotNavigation // is set. [CHOSEN] name. /* 68 */ bool m_polygonSearchPending; /* 69 */ char m_pad69[3]; - /* 72 */ QTPath* m_polygonPath; // new(0x18) - the fine path + /* 72 */ QTPath* m_path; // new(0x18) - the fine path // name: AIDLL_r assert 0x10149B20 (PE +0x48) // IAIPathfinding::acquireResource's polygon-search slot; -1 = none. /* 76 */ unsigned int m_int76; // = -1 // AIPathfinding::trace (ELF 0x3A81C0) reads +0x50 as the map index passed to getTraceData @@ -159,9 +159,9 @@ class BotNavigation // stores its size at +252. /* 88 */ std::vector m_obstacles; // the walkable result - see the header note. The constructor's dead resize targets this. - /* 100 */ std::vector m_points; + /* 100 */ std::vector m_navigationPoints; // name: AIDLL_r assert 0x10149B20 (PE +0x68, 0x28-byte entries) // the island the path was searched on (initPathfinding: the start island). - /* 112 */ int m_pathIsland; // never written by the constructor + /* 112 */ int m_island; // never written by the constructor // name: AIDLL_r assert "m_island == m_path->getIsland()" 0x10149B20 (PE +0x78) // index of the point being walked to. /* 116 */ unsigned int m_currentPoint; // = 0 // update: nonzero selects the cluster search. [CHOSEN] name. @@ -174,8 +174,8 @@ class BotNavigation // so the value type is four bytes - a set of pointers or handles. Which is [UNRESOLVED]; // `void*` holds the width and claims nothing. /* 132 */ std::set m_set132; // doPolygonSearch: the clusters the local search may use (setAllowedClusters) - /* 144 */ double m_double144; // = 0.0 - /* 152 */ double m_double152; // = 0.0 + /* 144 */ double m_noProgressTimer; // = 0.0 // name: AIDLL_r assert in checkProgress 0x10145DD0 (PE +0x98) + /* 152 */ double m_noThrottleTimer; // = 0.0 // name: AIDLL_r assert in checkProgress 0x10145DD0 (PE +0xA0) /* 160 */ double m_double160; // = 0.0 /* 168 */ double m_double168; // = 0.0 /* 176 */ float m_zero176[3]; // +176..+184; checkProgress: the soldier position at the last action-press check @@ -192,7 +192,7 @@ class BotNavigation /* 196 */ char m_gap196[4]; // [UNRESOLVED] - never written // the last valid positions (reset / initPathfinding): the vehicle's (getLastValidPosition of // the vehicle number) and the infantry one (IPIMobile +8 / +0xC). - /* 200 */ int m_vehiclePolygon; // = -1 + /* 200 */ int m_currentPolygon; // = -1 // name: AIDLL_r asserts 0x10146930, 0x1014AD10 (PE +0xD0) /* 204 */ int m_vehicleIsland; // = -1 /* 208 */ int m_infantryPolygon; // = -1 /* 212 */ int m_infantryIsland; // = -1 @@ -208,7 +208,7 @@ class BotNavigation /* 236 */ bool m_updateSpaceLeftAndRight; /* 237 */ char m_pad237[3]; // updatePath: useSkipTrace && soldier before a retrace; stillOnPath counts it down. - /* 240 */ int m_int240; // = 0 + /* 240 */ int m_skipTraceCount; // = 0 // name: AIDLL_r assert 0x101471C0 (PE +0xF8) // updatePath's game time (isActive: three seconds). /* 244 */ double m_double244; // not a gap - `reset` zeroes it // resetAll clears this field. @@ -224,7 +224,7 @@ class BotNavigation // and towards side 2 while +296 > 0.5; updateSpaceLeftAndRight writes them. [INFERRED] names. /* 292 */ float m_spaceLeft; /* 296 */ float m_spaceRight; - /* 300 */ double m_double300; // Initially -1.0; independent of the distance sentinel. + /* 300 */ double m_lastAngleDiffTest; // Initially -1.0; independent of the distance sentinel. // name: AIDLL_r assert 0x10147490 (PE +0x138) // getLargestAngleDiff's cached answer (recomputed every 0.5 s, +300 the time). /* 308 */ float m_largestAngleDiff; // = 0 // updateClosestDistance: the walked-points length from the bot (updatePath re-checks the diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp index e5b2e6646..b0bd80861 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp @@ -7,7 +7,7 @@ #include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" #include "BotMain.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIPhysical.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" @@ -87,10 +87,10 @@ void BotSenses::reset() m_frustumStep = 0; m_collectTime = -1000000.0; - m_set64.clear(); - m_list76.clear(); + m_hearingMemHelperSet.clear(); + m_hearingMemCheckQueue.clear(); // The constructor never did this; the cursor at +80 becomes valid here for the first time. - m_cursor80 = m_list76.end(); + m_cursor80 = m_hearingMemCheckQueue.end(); // The fire list owns its objects; the attacker map below only borrows them. for (std::list::iterator it = m_list84.begin(); it != m_list84.end(); ++it) @@ -256,7 +256,7 @@ void BotSenses::see(const double& slice) Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); m_bot->getName(); const Mat4& camera = *static_cast(m_bot->getPlayer()->getCameraTransformation()); - m_viewMode = (equipment->getObjectTypeFlags() & 0x400000u) != 0; + m_viewMode = equipment->isOfType(ITObstructedView); if (m_seeState == 3) { m_bot->setQuadSeen(); @@ -287,7 +287,7 @@ void BotSenses::see(const double& slice) m_candidates.resize(0); const int side = m_bot->getSide(); bool vehicleSight = false; - if ((equipment->getObjectTypeFlags() & 0x10u) || (equipment->getObjectTypeFlags() & 0x20u)) + if (equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter)) vehicleSight = true; SideFilter filter(side, equipment->getPosition(), viewDistance * viewDistance, vehicleSight); const float ownRadius = equipment->getPhysical()->getRadius(); @@ -303,8 +303,8 @@ void BotSenses::see(const double& slice) bool take = m_frustum->inside(object->getPosition(), radius); if (!take) { - if (!(equipment->getObjectTypeFlags() & 0x200000u) - && (!information || (information->getObjectTypeFlags() & 0x200000u))) + if (!equipment->isOfType(ITSoldier) + && (!information || information->isOfType(ITSoldier))) { take = vehicleSight && isCloseAndInFront(equipment, object); } @@ -413,7 +413,7 @@ void BotSenses::see(const double& slice) bool keepRider = false; if (IPIUnit* const unit = target->getUnit()) { - if (!(target->getObjectTypeFlags() & 0x200000u)) + if (!target->isOfType(ITSoldier)) { if (unit->hasExposedSoldier()) { @@ -464,7 +464,7 @@ void BotSenses::see(const double& slice) else if (10 < samples) samples = 10; unsigned int part = static_cast(-1); - const bool soldier = (target->getObjectTypeFlags() & 0x200000u) != 0; + const bool soldier = target->isOfType(ITSoldier); for (int k = 0; k < samples; ++k) { Vec3 point; @@ -533,17 +533,17 @@ void BotSenses::updateHearing(const double& slice) const double budget = slice; if (!informationManager->getInformation(m_bot->getCurrentEquipment())) return; - const unsigned int count = static_cast(m_list76.size()); + const unsigned int count = static_cast(m_hearingMemCheckQueue.size()); const int side = m_bot->getSide(); for (unsigned int i = 0; i < count && timer->getUpdateTime() < static_cast(start + budget); ++i) { - SensedObject* const object = m_list76.front().second; - m_list76.erase(m_list76.begin()); + SensedObject* const object = m_hearingMemCheckQueue.front().second; + m_hearingMemCheckQueue.erase(m_hearingMemCheckQueue.begin()); const unsigned int handle = object->m_handle; Information* information = informationManager->getInformation(handle); if (!information || (!information->getMobile() && !information->getArmament())) { - m_set64.erase(handle); + m_hearingMemHelperSet.erase(handle); const unsigned int flags = object->m_flags; object->m_flags = flags & ~SensedObject::SENSE_HEARD; if (!(flags & SensedObject::SENSE_SEEN)) @@ -581,7 +581,7 @@ void BotSenses::updateHearing(const double& slice) { if (30.0 < now - object->m_lastSensedTime) { - m_set64.erase(handle); + m_hearingMemHelperSet.erase(handle); const unsigned int flags = object->m_flags; object->m_flags = flags & ~SensedObject::SENSE_HEARD; if (!(flags & SensedObject::SENSE_SEEN)) @@ -597,7 +597,7 @@ void BotSenses::updateHearing(const double& slice) object->m_flags &= ~SensedObject::SENSE_HEARD_NOW; object->m_lastSensedTime = now; } - m_list76.push_back(TimedObject(now, object)); + m_hearingMemCheckQueue.push_back(TimedObject(now, object)); } } @@ -838,13 +838,13 @@ void BotSenses::event_heardObject(unsigned int handle) return; if (information->getSide() == m_bot->getSide()) return; - if (!(equipment->getObjectTypeFlags() & 0x200000u) && (information->getObjectTypeFlags() & 0x200000u)) + if (!equipment->isOfType(ITSoldier) && information->isOfType(ITSoldier)) return; const float strength = hear(handle, information); if (!(0.0f < strength)) return; const int side = m_bot->getSide(); - const std::pair::iterator, bool> inserted = m_set64.insert(handle); + const std::pair::iterator, bool> inserted = m_hearingMemHelperSet.insert(handle); if (!inserted.second) { // The image does not check the find result. @@ -889,7 +889,7 @@ void BotSenses::event_heardObject(unsigned int handle) weight = strength; if (primary->setTime(now, weight)) primary->getAIObject()->addInformationToGrid(side); - m_list76.push_back(TimedObject(now, object)); + m_hearingMemCheckQueue.push_back(TimedObject(now, object)); } // ELF 0x19D8F0 (1152 bytes). Zero unless the bot has equipment, 1.5 s have passed since its own @@ -938,7 +938,7 @@ float BotSenses::hear(unsigned int, Information* information) weaponRadius = weapon->getSoundSphereRadius(); } } - if (information->getObjectTypeFlags() & 0x200000u) + if (information->isOfType(ITSoldier)) { const int pose = information->getSoldierPose(); if (pose != 1 && !(pose < 1)) @@ -1126,7 +1126,7 @@ void BotSenses::updateSeeing(const double& slice) // As in the image, the equipment information is used without a null check. Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); - const bool ownSoldier = (equipment->getObjectTypeFlags() & 0x200000u) != 0; + const bool ownSoldier = equipment->isOfType(ITSoldier); const float ownRadius3 = equipment->getPhysical()->getRadius() * 3.0f; std::vector ignore; ignore.push_back(equipment->getAIObject()->getPrimaryObject()); @@ -1164,7 +1164,7 @@ void BotSenses::updateSeeing(const double& slice) { IAIObject* const target = information->getAIObject(); const bool primary = information->isPrimary(); - const bool soldier = (information->getObjectTypeFlags() & 0x200000u) != 0; + const bool soldier = information->isOfType(ITSoldier); const float radius = target->getBoundingRadius(); const Vec3& position = target->getPosition(); const float dx = position.x - eye.x; @@ -1186,7 +1186,7 @@ void BotSenses::updateSeeing(const double& slice) } } } - const bool vehicleSight = (equipment->getObjectTypeFlags() & 0x10u) || (equipment->getObjectTypeFlags() & 0x20u); + const bool vehicleSight = equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter); const bool consider = inView || (vehicleSight && isCloseAndInFront(equipment, target)); bool visible = consider; Vec3 point; @@ -1371,7 +1371,7 @@ void BotSenses::updateSeeing(const double& slice) // As in the image, the equipment information is used without a null check. Information* const own = informationManager->getInformation(m_bot->getCurrentEquipment()); IPIArmament* const armament = own->getArmament(); - const bool canEngage = armament && (lost->getObjectTypeFlags() & 0x10u) && 0 < armament->isAntiAircraft(); + const bool canEngage = armament && lost->isOfType(ITAir) && 0 < armament->isAntiAircraft(); if (60.0 < unseen || !primary || (!own->getMobile() && 5.0 < unseen) || (canEngage && 5.0 < unseen) || (m_bot->getIsGoingForFlag() && 5.0 < unseen)) forget = true; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h index f945c6617..40e94b0c4 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h @@ -75,7 +75,7 @@ class BotSenses /* 0 */ BotMain* m_bot; // the ctor argument, and the first store /* 4 */ Frustum* m_frustum; // new(0x1E8) - . See the header block. - // see (ELF 0x198420): 1 when the equipment has type flag 0x400000 (meaning [UNRESOLVED]); the + // see (ELF 0x198420): 1 when the equipment is ITObstructedView (bit 22, AIDLL_r enum switch 0x100D3010); the // row of tweak_frustumUpdateAngle used for the frustum. /* 8 */ int m_viewMode; /* 12 */ double m_collectTime; // = -1000000.0; see: the game time of the last candidate scan @@ -90,8 +90,8 @@ class BotSenses /* 56 */ TimedList m_list56; // A cursor into the list above, seeded to end by the constructor's last statement. /* 60 */ TimedList::iterator m_cursor60; - /* 64 */ std::set m_set64; - /* 76 */ TimedList m_list76; + /* 64 */ std::set m_hearingMemHelperSet; // name: AIDLL_r assert 0x101D6BF0 (PE +0x50) + /* 76 */ TimedList m_hearingMemCheckQueue; // name: AIDLL_r assert 0x101D6BF0 (PE +0x5C) // A cursor into the list above - and unlike +60 the constructor leaves it default-constructed. // Only `reset` makes it valid. See the header block. /* 80 */ TimedList::iterator m_cursor80; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp index fdbdeac0d..aa00402ed 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSubObjects.cpp @@ -6,7 +6,7 @@ // 0x1A2210, __tcf_0 0x1A2270, _GLOBAL__I 0x1A22A0). #include -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp index 98c54f965..2541bfb29 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.cpp @@ -9,13 +9,13 @@ #include #include "BotMain.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../../../../IO/Input/PlayerInput.h" #include "../Main/IBotManager.h" @@ -88,7 +88,7 @@ void CommunicationAgent::reset() m_lastPollTime = 0.0; m_int92 = -1; // This order is the binary's. - m_hornTime = 0.0; + m_lastHornHonkTime = 0.0; m_double96 = 0.0; } @@ -156,7 +156,7 @@ void CommunicationAgent::sendCallForMedic(Information* equipment) IPIMobile* const mobile = primary->getMobile(); bool skip = false; if (m_bot->isAirBorn() - || (primary && (primary->getObjectTypeFlags() & 0x10) != 0 && mobile + || (primary && primary->isOfType(ITAir) && mobile && mobile->getSpeedMagnitude() > 3.0f)) skip = true; if (!equipment->isPrimary() || skip) @@ -242,10 +242,10 @@ void CommunicationAgent::receiveRadioMessage(const AIRadioMessageSettings& setti // ELF 0x1C53F0: horn-capable equipment (type flag 0x04000000) releases fire after 2 s. void CommunicationAgent::shutOffHorn(Information* equipment) { - if ((equipment->getObjectTypeFlags() & 0x04000000) == 0) + if (!equipment->isOfType(ITHasCarHorn)) return; const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - if (now - m_hornTime > 2.0) + if (now - m_lastHornHonkTime > 2.0) m_bot->m_playerInput->setInput(io::PIFire, 0.0f); } @@ -267,16 +267,16 @@ void CommunicationAgent::honkHorn(Information* target) if (!player) return; const float interval = player->getIsAIPlayer() ? 20.0f : 5.0f; - if (interval > now - m_hornTime) + if (interval > now - m_lastHornHonkTime) return; Information* const equipment = informationManager->getInformation(m_bot->getCurrentEquipment()); - if ((equipment->getObjectTypeFlags() & 0x04000000) != 0) + if (equipment->isOfType(ITHasCarHorn)) m_bot->m_playerInput->setInput(io::PIFire, 1.0f); else sendImmediately(static_cast(11), static_cast(6), 3, targetPlayerId); - m_hornTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - if ((target->getObjectTypeFlags() & 0x00200000) == 0) + m_lastHornHonkTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + if (!target->isOfType(ITSoldier)) return; Bot* const horned = IBotManager::instance->getBot(target->getAIObject()); if (!horned) @@ -350,7 +350,7 @@ void CommunicationAgent::enqueueRadioMessage(AIRadioMessageType type, AIRadioCha message.m_type = type; message.m_channel = channel; message.m_priority = static_cast(priority); - message.m_int12 = c; + message.m_receiverPlayerId = c; message.m_sendTime = now + static_cast(delay); message.m_delay = delay; if (m_map20.insert(std::make_pair(type, message.m_sendTime)).second) @@ -366,7 +366,7 @@ void CommunicationAgent::postEvent(const CAPrioMessage& message) const const unsigned char sender = static_cast(m_bot->getPlayerId()); const unsigned char player = static_cast(m_bot->getPlayerId()); const unsigned char side = static_cast(m_bot->getSide()); - const unsigned char argument = static_cast(message.m_int12); + const unsigned char argument = static_cast(message.m_receiverPlayerId); int voice; if (!static_cast(CommonSingletonServer::m_iBFModuleCourier) ->getVoiceFromAiMessageType(message.m_type, voice)) @@ -456,7 +456,7 @@ void CommunicationAgent::sendImmediately(AIRadioMessageType type, AIRadioChannel message.m_channel = channel; message.m_priority = static_cast(priority); message.m_sendTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - message.m_int12 = c; + message.m_receiverPlayerId = c; message.m_delay = 0.0f; postEvent(message); } diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h index 916e2c459..6003aaa56 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/CommunicationAgent.h @@ -66,7 +66,7 @@ class CommunicationAgent // enqueueRadioMessage (ELF 0x1C4290) fills all seven words from its arguments. /* 4 */ AIRadioChannelType m_channel; // postEvent's fifth hub argument /* 8 */ int m_priority; // the unsigned argument - /* 12 */ int m_int12; // the last argument; postEvent passes its low byte + /* 12 */ int m_receiverPlayerId; // the last argument; postEvent passes its low byte // name: AIDLL_r assert "message.m_receiverPlayerId" 0x101640F0 (+0xC; channel AIRCPlayer = 8) /* 16 */ double m_sendTime; // now + delay; not sent before this time /* 24 */ float m_delay; }; @@ -148,7 +148,7 @@ class CommunicationAgent // the game time another bot last horned at this one (honkHorn); BBAvoid reads it. /* 96 */ double m_double96; // reset: 0.0 // shutOffHorn (ELF 0x1C53F0) releases the horn (PIFire) two seconds after this time. - /* 104 */ double m_hornTime; // reset: 0.0 + /* 104 */ double m_lastHornHonkTime; // reset: 0.0 // name: AIDLL_r assert in honkHorn (0x10165630) }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp index a556b1edc..96d1316ba 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.cpp @@ -42,7 +42,7 @@ float RandomSquareMerger::updateActiveUrgency(Bot* bot) } } float pick = static_cast(AIRandom::m_instance->next()) * 2.3283064e-10f * total; - m_chosen = 0; + mpMaxGenerator = 0; int index = 0; for (; index < m_count; ++index) { @@ -51,9 +51,9 @@ float RandomSquareMerger::updateActiveUrgency(Bot* bot) const float active = m_generators[index]->getActiveUrgency(bot); // +0x0C pick = pick - active; if (active / total > 0.01f) - m_chosen = m_generators[index]->getChosenGenerator(); // +0x20 + mpMaxGenerator = m_generators[index]->getChosenGenerator(); // +0x20 } - if (pick <= 0.0f && m_chosen != 0) + if (pick <= 0.0f && mpMaxGenerator != 0) break; } return m_generators[index]->getActiveUrgency(bot); diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h index 37d4d8d93..7a7429d31 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/RandomSquareMerger.h @@ -8,7 +8,7 @@ #ifndef AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AIBOT_RANDOMSQUAREMERGER_H -#include "../AIBotBehaviour/UrgencyMerger.h" +#include "UrgencyMerger.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp index cb0a89b2c..8eda2bc3f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.cpp @@ -26,14 +26,14 @@ #include "../Main/AIDllFrontier.h" #include "../AIKnowledge/FireObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../Core/Debug.h" -#include "../AIPlanInterpreter/BotScript.h" +#include "../AIBotActionPlan/BotScript.h" #include "SensedObject.h" #include "../DrawPrimitives/DPManager.h" #include @@ -422,7 +422,7 @@ void SensingAgent::update() Information* const current = informationManager->getInformation(m_bot->getCurrentEquipment()); bool turnedAway = false; - if ((current->getObjectTypeFlags() & 0x00200000) != 0 && m_flag133 + if (current->isOfType(ITSoldier) && m_flag133 && !isForward(m_int24, m_moveDirection)) turnedAway = true; if (!(elapsed >= m_currentPeriod || m_flag120 || m_flag140 == true) && !turnedAway) @@ -477,7 +477,7 @@ void SensingAgent::update() void SensingAgent::updateQuadTimeUrgencies(Vec2& direction, bool turnedAway) { Information* const current = informationManager->getInformation(m_bot->getCurrentEquipment()); - if ((current->getObjectTypeFlags() & 0x00200000) == 0) + if (!current->isOfType(ITSoldier)) { Information* const primary = informationManager->getInformation(current->getPrimaryObject(m_bot->getSide())); @@ -494,7 +494,7 @@ void SensingAgent::updateQuadTimeUrgencies(Vec2& direction, bool turnedAway) direction.y = -move.y; } bool clearBehind = false; - if ((current->getObjectTypeFlags() & 0x00200000) == 0 && current->hasMobile() && current->isPrimary()) + if (!current->isOfType(ITSoldier) && current->hasMobile() && current->isPrimary()) clearBehind = true; for (int q = 0; q < 8; ++q) { @@ -709,7 +709,7 @@ void SensingAgent::checkForPlanInvalidation(const QuadrantInformation& info, boo { Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); bool vehicle = false; - if ((equipment->getObjectTypeFlags() & 0x20) || (equipment->getObjectTypeFlags() & 0x10)) + if (equipment->isOfType(ITHelicopter) || equipment->isOfType(ITAir)) vehicle = true; if (equipment->getUnit()->mustBorrowArmament() || vehicle) { @@ -822,8 +822,7 @@ void SensingAgent::calculateCurrentPeriod(const QuadrantInformation& info, Infor const io::PlayerInput* const input = m_bot->getInput(); if (!equipment->getUnit()) return; - const unsigned int flags = equipment->getObjectTypeFlags(); - if (equipment->getUnit()->mustBorrowArmament() || (flags & 0x20) || (flags & 0x10)) + if (equipment->getUnit()->mustBorrowArmament() || equipment->isOfType(ITHelicopter) || equipment->isOfType(ITAir)) { m_currentPeriod = randomBetween(1.0f, 1.5f); return; @@ -834,7 +833,7 @@ void SensingAgent::calculateCurrentPeriod(const QuadrantInformation& info, Infor m_currentPeriod = randomBetween(1.5f, 2.0f); return; } - const bool soldier = (flags & 0x00200000) != 0; + const bool soldier = equipment->isOfType(ITSoldier); if (boundInput(input, io::PIThrottle) < 0.01f && boundInput(input, io::PIYaw) < 0.01f) { m_currentPeriod = soldier ? randomBetween(3.0f, 4.0f) : randomBetween(7.0f, 10.0f); @@ -859,10 +858,10 @@ void SensingAgent::calculateCurrentPeriod(const QuadrantInformation& info, Infor void SensingAgent::createPlan(ISensingAgentPattern* pattern, const QuadrantInformation& info) { if (m_plan) - m_plan->m_owner = pattern; + m_plan->mpOwner = pattern; Information* const equipment = informationManager->getInformation(m_bot->m_currentEquipment); bool vehicle = false; - if ((equipment->getObjectTypeFlags() & 0x20) || (equipment->getObjectTypeFlags() & 0x10)) + if (equipment->isOfType(ITHelicopter) || equipment->isOfType(ITAir)) vehicle = true; if (equipment->getUnit()->mustBorrowArmament() || vehicle) { @@ -871,7 +870,7 @@ void SensingAgent::createPlan(ISensingAgentPattern* pattern, const QuadrantInfor { Vec3 down; down.x = forward.x; - down.y = (equipment->getObjectTypeFlags() & 0x10) ? -0.4f : -0.7f; + down.y = equipment->isOfType(ITAir) ? -0.4f : -0.7f; down.z = forward.z; createDirPlan(down, pattern); } @@ -940,17 +939,17 @@ void SensingAgent::createPlan(ISensingAgentPattern* pattern, const QuadrantInfor m_flag133 = false; } if (m_plan) - m_plan->m_owner = this; + m_plan->mpOwner = this; } // ELF 0x1BF120: the previous plan's owner becomes the pattern, the new plan's this agent. void SensingAgent::createDirPlan(const Vec3& direction, ISensingAgentPattern* pattern) { if (m_plan) - m_plan->m_owner = pattern; + m_plan->mpOwner = pattern; m_plan = pattern->createPlan(this, m_bot, direction); if (m_plan) - m_plan->m_owner = this; + m_plan->mpOwner = this; } // ELF 0x1BF180: IAISettings +0x8C getSensingAgentNullPattern, target handle 0. @@ -959,10 +958,10 @@ void SensingAgent::createNullPlan() ISensingAgentPattern* const pattern = static_cast(CommonSingletonServer::m_iaiSettings)->getSensingAgentNullPattern(); if (m_plan) - m_plan->m_owner = pattern; + m_plan->mpOwner = pattern; m_plan = pattern->createPlan(this, m_bot, 0u); if (m_plan) - m_plan->m_owner = this; + m_plan->mpOwner = this; } void SensingAgent::insertPlanDirectionInformation(float weight, const Vec3& direction, bool flag) @@ -1016,7 +1015,7 @@ void SensingAgent::drawSensingAgentDebugStuff() static_cast(CommonSingletonServer::m_iDPStaticCreator) ->createStaticLine(0.1f, 0xFFFF00, start, end, 0.1f); } - if (equipment->getObjectTypeFlags() & 0x200000) + if (equipment->isOfType(ITSoldier)) { const Vec3 direction = { m_moveDirection.x * 10.0f, 0.0f * 10.0f, m_moveDirection.y * 10.0f }; const Vec3 end = { position.x + direction.x, position.y + direction.y, position.z + direction.z }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp new file mode 100644 index 000000000..a631c0bd9 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp @@ -0,0 +1,86 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\SensingAgentMouseFreeLookPattern.cpp" +// (asserts in 0x10136CD0 and 0x10137020, e.g. "lookDir vector empty!"). Split out of the former +// SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C1780, 0x1C17E0, 0x1C1810 (MouseFreeLook) + +#include "SensingAgentPatternPrologue.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" + +namespace dice { +namespace hfe { +namespace ai { + +// The base owns the shared id field used by every pattern's getId/reset pair. +// Constructors and destructors perform no additional member initialization or cleanup. +// [INFERRED] placement: weak in the ELF, emitted right after this TU's static init (0x1C1830). +ISensingAgentPattern::~ISensingAgentPattern() +{ +} + +SensingAgentMouseFreeLookPattern::SensingAgentMouseFreeLookPattern() +{ +} + +SensingAgentMouseFreeLookPattern::~SensingAgentMouseFreeLookPattern() +{ +} + +int SensingAgentMouseFreeLookPattern::getId() const +{ + return m_id; +} + +void SensingAgentMouseFreeLookPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C0560: hold the mouse-look button and look in the direction, in parallel. +BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + BAPATriggerContinously* const trigger = holdMouseLook(getId()); + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + parallel->addStatement(trigger); + parallel->addStatement(look); + parallel->mpOwner = this; + plan = parallel; + } + return plan; +} + +// ELF 0x1C0E60: as above, looking at the object. +BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + BAPATriggerContinously* const trigger = holdMouseLook(getId()); + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + parallel->addStatement(trigger); + parallel->addStatement(look); + parallel->mpOwner = this; + plan = parallel; + } + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp new file mode 100644 index 000000000..06f0a4c48 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp @@ -0,0 +1,55 @@ +// [INFERRED] Source placement and file name: the ELF gives the null pattern its own TU (own static +// init below, between the MouseFreeLook and Soldier TUs); AIDLL_r.dll has no assert in it, so no +// __FILE__ names it. Its three siblings are SensingAgentMouseFreeLookPattern.cpp, +// SensingAgentSoldierPattern.cpp and SensingAgentTurretPattern.cpp (AIDLL_r __FILE__). Split out of +// the former SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C1DD0, 0x1C1E30, 0x1C1E60 (Null) + +#include "SensingAgentPatternPrologue.h" +#include "../AIBotActionPlan/BAPAResetControls.h" + +namespace dice { +namespace hfe { +namespace ai { + +SensingAgentNullPattern::SensingAgentNullPattern() +{ +} + +SensingAgentNullPattern::~SensingAgentNullPattern() +{ +} + +int SensingAgentNullPattern::getId() const +{ + return m_id; +} + +void SensingAgentNullPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C1A70: BAPAResetControls(false, true, false, id) (0x1C bytes), owned by the pattern. +BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, const Vec3& /*direction*/) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); + reset->mpOwner = this; + return reset; +} + +// ELF 0x1C1C20: identical to the direction overload. +BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, unsigned int /*target*/) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); + reset->mpOwner = this; + return reset; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatternPrologue.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatternPrologue.h new file mode 100644 index 000000000..9608d8cfb --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatternPrologue.h @@ -0,0 +1,61 @@ +// [CHOSEN, not recovered] Private helpers shared by the sensing-agent pattern TUs +// (SensingAgentMouseFreeLookPattern.cpp, SensingAgentNullPattern.cpp, SensingAgentTurretPattern.cpp). +// The retail images expand them inline in each createPlan; this header only keeps one copy of the +// source after the split of the former SensingAgentPatterns.cpp. Include it from those .cpp files only. + +#ifndef AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNPROLOGUE_H +#define AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNPROLOGUE_H + +#include "SensingAgent.h" +#include "BotMain.h" +#include "../AIBotActionPlan/BAPATriggerContinously.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPConTrue.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIUtils/checkPointer.h" + +// The patterns' shared prologue (inline in every createPlan but the soldier's, e.g. 0x1C2B10): the +// agent's plan is kept when this pattern built it (BAPStatement +0x10 == getId()); otherwise it is +// deleted and the agent's BAP context cleared. The function returns the kept plan or null. +#define SENSING_PATTERN_KEEP_OR_DROP(agent) \ + if (BotScript* const previous = (agent)->m_plan) \ + { \ + if (static_cast(previous)->getPatternId() == getId()) \ + return previous; \ + delete previous; \ + (agent)->m_plan = 0; \ + } \ + (agent)->m_bapContext->clear() + +namespace dice { +namespace hfe { +namespace ai { +namespace { + +// The bot's current equipment's control info, or null (Bot +0xD8, Information +0x30). +inline IPIControlInfo* currentControlInfo(Bot* bot) +{ + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + return equipment ? equipment->getControlInfo() : 0; +} + +// BAPATriggerContinously(PIMouseLook, true, false, false, mask 0x800, id, 0.0): the mouse-look +// button held for the plan's life (0x1C06F9..0x1C0727; 0x30 bytes). +inline BAPATriggerContinously* holdMouseLook(int id) +{ + BAPCondition* const third = checkPointer(new BAPConFalse()); + BAPCondition* const second = checkPointer(new BAPConFalse()); + BAPCondition* const first = checkPointer(new BAPConTrue()); + return checkPointer(new BAPATriggerContinously(io::PIMouseLook, first, second, third, 0x800ULL, id, 0.0)); +} + +} // namespace +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNPROLOGUE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp deleted file mode 100644 index d5374c38c..000000000 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp +++ /dev/null @@ -1,309 +0,0 @@ - -#include "SensingAgentPatterns.h" -#include -// Four original pattern TUs are combined here; each only initialized iostreams. -// static init: ELF 0x1C1780, 0x1C17E0, 0x1C1810 (MouseFreeLook) -// static init: ELF 0x1C1DD0, 0x1C1E30, 0x1C1E60 (Null) -// static init: ELF 0x1C2980, 0x1C29E0, 0x1C2A10 (Soldier) -// static init: ELF 0x1C31A0, 0x1C3200, 0x1C3230 (Turret) - -#include "SensingAgent.h" -#include "BotMain.h" -#include "../AIBotActionPlan/BAPALookAtObject.h" -#include "../AIBotActionPlan/BAPALookInDir.h" -#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" -#include "../AIBotActionPlan/BAPAResetControls.h" -#include "../AIBotActionPlan/BAPATriggerContinously.h" -#include "../AIBotActionPlan/BAPCombinerParallel.h" -#include "../AIBotActionPlan/BAPConFalse.h" -#include "../AIBotActionPlan/BAPConTrue.h" -#include "../AIBotActionPlan/BAPStatement.h" -#include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" -#include "../AIKnowledge/IPIControlInfo.h" -#include "../AIPlanInterpreter/BAPContext.h" -#include "../AIUtils/checkPointer.h" - -namespace dice { -namespace hfe { -namespace ai { - -// The base owns the shared id field used by every pattern's getId/reset pair. -// Constructors and destructors perform no additional member initialization or cleanup. -ISensingAgentPattern::~ISensingAgentPattern() -{ -} - -SensingAgentTurretPattern::SensingAgentTurretPattern() -{ -} - -SensingAgentTurretPattern::~SensingAgentTurretPattern() -{ -} - -int SensingAgentTurretPattern::getId() const -{ - return m_id; -} - -void SensingAgentTurretPattern::reset(int id) -{ - m_id = id; -} - -SensingAgentMouseFreeLookPattern::SensingAgentMouseFreeLookPattern() -{ -} - -SensingAgentMouseFreeLookPattern::~SensingAgentMouseFreeLookPattern() -{ -} - -int SensingAgentMouseFreeLookPattern::getId() const -{ - return m_id; -} - -void SensingAgentMouseFreeLookPattern::reset(int id) -{ - m_id = id; -} - -SensingAgentSoldierPattern::SensingAgentSoldierPattern() -{ -} - -SensingAgentSoldierPattern::~SensingAgentSoldierPattern() -{ -} - -int SensingAgentSoldierPattern::getId() const -{ - return m_id; -} - -void SensingAgentSoldierPattern::reset(int id) -{ - m_id = id; -} - -SensingAgentNullPattern::SensingAgentNullPattern() -{ -} - -SensingAgentNullPattern::~SensingAgentNullPattern() -{ -} - -int SensingAgentNullPattern::getId() const -{ - return m_id; -} - -void SensingAgentNullPattern::reset(int id) -{ - m_id = id; -} - -// The patterns' shared prologue (inline in every createPlan but the soldier's, e.g. 0x1C2B10): the -// agent's plan is kept when this pattern built it (BAPStatement +0x10 == getId()); otherwise it is -// deleted and the agent's BAP context cleared. The function returns the kept plan or null. -#define SENSING_PATTERN_KEEP_OR_DROP(agent) \ - if (BotScript* const previous = (agent)->m_plan) \ - { \ - if (static_cast(previous)->getPatternId() == getId()) \ - return previous; \ - delete previous; \ - (agent)->m_plan = 0; \ - } \ - (agent)->m_bapContext->clear() - -namespace { - -// The bot's current equipment's control info, or null (Bot +0xD8, Information +0x30). -IPIControlInfo* currentControlInfo(Bot* bot) -{ - Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); - return equipment ? equipment->getControlInfo() : 0; -} - -// BAPATriggerContinously(PIMouseLook, true, false, false, mask 0x800, id, 0.0): the mouse-look -// button held for the plan's life (0x1C06F9..0x1C0727; 0x30 bytes). -BAPATriggerContinously* holdMouseLook(int id) -{ - BAPCondition* const third = checkPointer(new BAPConFalse()); - BAPCondition* const second = checkPointer(new BAPConFalse()); - BAPCondition* const first = checkPointer(new BAPConTrue()); - return checkPointer(new BAPATriggerContinously(io::PIMouseLook, first, second, third, 0x800ULL, id, 0.0)); -} - -} // namespace - -// ELF 0x1C2B10: look in the direction, 5 degrees (0.08726646 rad) tolerance, never ending. -BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) -{ - SENSING_PATTERN_KEEP_OR_DROP(agent); - BotScript* plan = 0; - if (IPIControlInfo* const control = currentControlInfo(bot)) - { - const int id = getId(); - const unsigned long long controls = control->getLookControls(); - BAPALookInDir* const look = checkPointer( - new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); - look->m_owner = this; - plan = look; - } - return plan; -} - -// ELF 0x1C2E50: look at the object, as above. -BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) -{ - SENSING_PATTERN_KEEP_OR_DROP(agent); - BotScript* plan = 0; - if (IPIControlInfo* const control = currentControlInfo(bot)) - { - const int id = getId(); - const unsigned long long controls = control->getLookControls(); - BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( - bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); - look->m_owner = this; - plan = look; - } - return plan; -} - -// ELF 0x1C0560: hold the mouse-look button and look in the direction, in parallel. -BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) -{ - SENSING_PATTERN_KEEP_OR_DROP(agent); - BotScript* plan = 0; - if (IPIControlInfo* const control = currentControlInfo(bot)) - { - BAPATriggerContinously* const trigger = holdMouseLook(getId()); - const int id = getId(); - const unsigned long long controls = control->getLookControls(); - BAPALookInDir* const look = checkPointer( - new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); - BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); - parallel->addStatement(trigger); - parallel->addStatement(look); - parallel->m_owner = this; - plan = parallel; - } - return plan; -} - -// ELF 0x1C0E60: as above, looking at the object. -BotScript* SensingAgentMouseFreeLookPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) -{ - SENSING_PATTERN_KEEP_OR_DROP(agent); - BotScript* plan = 0; - if (IPIControlInfo* const control = currentControlInfo(bot)) - { - BAPATriggerContinously* const trigger = holdMouseLook(getId()); - const int id = getId(); - const unsigned long long controls = control->getLookControls(); - BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( - bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); - BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); - parallel->addStatement(trigger); - parallel->addStatement(look); - parallel->m_owner = this; - plan = parallel; - } - return plan; -} - -// ELF 0x1C1F60. Both createPlan overloads pass a null `plan`, so the reuse arm (the agent's plan -// kept when it is this pattern's: false; otherwise `plan` deleted and the agent's cleared) never -// runs from them. True with the current equipment's control info; otherwise `plan` = 0. -bool SensingAgentSoldierPattern::initPlan(SensingAgent* agent, Bot* bot, IPIControlInfo*& control, - BotScript*& plan) -{ - if (plan) - { - if (static_cast(agent->m_plan)->getPatternId() == getId()) - return false; - delete plan; - agent->m_plan = 0; - } - agent->m_bapContext->clear(); - Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); - if (equipment) - { - control = equipment->getControlInfo(); - if (control) - return true; - } - plan = 0; - return false; -} - -// ELF 0x1C2050: parallel(look, BAPAMergeSoldierInputs), owned by the pattern. -BotScript* SensingAgentSoldierPattern::endPlan(BAPALook* look, Bot* /*bot*/) -{ - BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); - BAPAMergeSoldierInputs* const merge = checkPointer(new BAPAMergeSoldierInputs(getId())); - parallel->addStatement(look); - parallel->addStatement(merge); - parallel->m_owner = this; - return parallel; -} - -// ELF 0x1C2310: look in the direction exactly (tolerance 0), never ending. -BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) -{ - IPIControlInfo* control = 0; - BotScript* plan = 0; - if (initPlan(agent, bot, control, plan)) - { - const int id = getId(); - const unsigned long long controls = control->getLookControls(); - BAPALookInDir* const look = checkPointer( - new BAPALookInDir(direction, 0.0f, checkPointer(new BAPConFalse()), controls, id)); - plan = endPlan(look, bot); - } - return plan; -} - -// ELF 0x1C2640: look at the object (tolerance 0). -BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) -{ - IPIControlInfo* control = 0; - BotScript* plan = 0; - if (initPlan(agent, bot, control, plan)) - { - const int id = getId(); - const unsigned long long controls = control->getLookControls(); - BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( - bot, target, 0.0f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); - plan = endPlan(look, bot); - } - return plan; -} - -// ELF 0x1C1A70: BAPAResetControls(false, true, false, id) (0x1C bytes), owned by the pattern. -BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, const Vec3& /*direction*/) -{ - SENSING_PATTERN_KEEP_OR_DROP(agent); - BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); - reset->m_owner = this; - return reset; -} - -// ELF 0x1C1C20: identical to the direction overload. -BotScript* SensingAgentNullPattern::createPlan(SensingAgent* agent, Bot* /*bot*/, unsigned int /*target*/) -{ - SENSING_PATTERN_KEEP_OR_DROP(agent); - BAPAResetControls* const reset = checkPointer(new BAPAResetControls(false, true, false, getId())); - reset->m_owner = this; - return reset; -} - -#undef SENSING_PATTERN_KEEP_OR_DROP - -} // namespace ai -} // namespace hfe -} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h index 3c6aa6d33..c859d9e47 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentPatterns.h @@ -1,5 +1,6 @@ // The sensing agent's plan patterns (libaidll.so 0x1C0490..0x1C3250). [CHOSEN, not recovered]: the -// four classes stay grouped in one header and one source file. +// four classes stay grouped in one header. Each has its own source file, as in the retail images +// (AIDLL_r __FILE__: SensingAgentSoldier/Turret/MouseFreeLookPattern.cpp; SensingAgentNullPattern.cpp). #ifndef AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNS_H #define AI_AIDLL_AI_AIBOT_SENSINGAGENTPATTERNS_H diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp new file mode 100644 index 000000000..6f94764d6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp @@ -0,0 +1,114 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\SensingAgentSoldierPattern.cpp" +// (asserts "No info" / "No control info" in 0x101368F0). Split out of the former +// SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C2980, 0x1C29E0, 0x1C2A10 (Soldier) + +#include "SensingAgent.h" +#include "BotMain.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" +#include "../AIBotActionPlan/BAPAMergeSoldierInputs.h" +#include "../AIBotActionPlan/BAPCombinerParallel.h" +#include "../AIBotActionPlan/BAPConFalse.h" +#include "../AIBotActionPlan/BAPStatement.h" +#include "../AIKnowledge/Information.h" +#include "../Main/InformationManager.h" +#include "../AIKnowledge/IPIControlInfo.h" +#include "../AIPlanInterpreter/BAPContext.h" +#include "../AIUtils/checkPointer.h" + +namespace dice { +namespace hfe { +namespace ai { + +SensingAgentSoldierPattern::SensingAgentSoldierPattern() +{ +} + +SensingAgentSoldierPattern::~SensingAgentSoldierPattern() +{ +} + +int SensingAgentSoldierPattern::getId() const +{ + return m_id; +} + +void SensingAgentSoldierPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C1F60. Both createPlan overloads pass a null `plan`, so the reuse arm (the agent's plan +// kept when it is this pattern's: false; otherwise `plan` deleted and the agent's cleared) never +// runs from them. True with the current equipment's control info; otherwise `plan` = 0. +bool SensingAgentSoldierPattern::initPlan(SensingAgent* agent, Bot* bot, IPIControlInfo*& control, + BotScript*& plan) +{ + if (plan) + { + if (static_cast(agent->m_plan)->getPatternId() == getId()) + return false; + delete plan; + agent->m_plan = 0; + } + agent->m_bapContext->clear(); + Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); + if (equipment) + { + control = equipment->getControlInfo(); + if (control) + return true; + } + plan = 0; + return false; +} + +// ELF 0x1C2050: parallel(look, BAPAMergeSoldierInputs), owned by the pattern. +BotScript* SensingAgentSoldierPattern::endPlan(BAPALook* look, Bot* /*bot*/) +{ + BAPCombinerParallel* const parallel = checkPointer(new BAPCombinerParallel(getId(), -1, false)); + BAPAMergeSoldierInputs* const merge = checkPointer(new BAPAMergeSoldierInputs(getId())); + parallel->addStatement(look); + parallel->addStatement(merge); + parallel->mpOwner = this; + return parallel; +} + +// ELF 0x1C2310: look in the direction exactly (tolerance 0), never ending. +BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) +{ + IPIControlInfo* control = 0; + BotScript* plan = 0; + if (initPlan(agent, bot, control, plan)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.0f, checkPointer(new BAPConFalse()), controls, id)); + plan = endPlan(look, bot); + } + return plan; +} + +// ELF 0x1C2640: look at the object (tolerance 0). +BotScript* SensingAgentSoldierPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) +{ + IPIControlInfo* control = 0; + BotScript* plan = 0; + if (initPlan(agent, bot, control, plan)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.0f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + plan = endPlan(look, bot); + } + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp new file mode 100644 index 000000000..19e9714f6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp @@ -0,0 +1,70 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\SensingAgentTurretPattern.cpp" +// (asserts "No info" / "No control info" in 0x10137390 and 0x10137570). Split out of the former +// SensingAgentPatterns.cpp; the functions are unchanged. +#include "SensingAgentPatterns.h" +#include +// static init: ELF 0x1C31A0, 0x1C3200, 0x1C3230 (Turret) + +#include "SensingAgentPatternPrologue.h" +#include "../AIBotActionPlan/BAPALookAtObject.h" +#include "../AIBotActionPlan/BAPALookInDir.h" + +namespace dice { +namespace hfe { +namespace ai { + +SensingAgentTurretPattern::SensingAgentTurretPattern() +{ +} + +SensingAgentTurretPattern::~SensingAgentTurretPattern() +{ +} + +int SensingAgentTurretPattern::getId() const +{ + return m_id; +} + +void SensingAgentTurretPattern::reset(int id) +{ + m_id = id; +} + +// ELF 0x1C2B10: look in the direction, 5 degrees (0.08726646 rad) tolerance, never ending. +BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, const Vec3& direction) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookInDir* const look = checkPointer( + new BAPALookInDir(direction, 0.08726646f, checkPointer(new BAPConFalse()), controls, id)); + look->mpOwner = this; + plan = look; + } + return plan; +} + +// ELF 0x1C2E50: look at the object, as above. +BotScript* SensingAgentTurretPattern::createPlan(SensingAgent* agent, Bot* bot, unsigned int target) +{ + SENSING_PATTERN_KEEP_OR_DROP(agent); + BotScript* plan = 0; + if (IPIControlInfo* const control = currentControlInfo(bot)) + { + const int id = getId(); + const unsigned long long controls = control->getLookControls(); + BAPALookAtObject* const look = checkPointer(new BAPALookAtObject( + bot, target, 0.08726646f, checkPointer(new BAPConFalse()), controls, id, 0, 0.0f)); + look->mpOwner = this; + plan = look; + } + return plan; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp index 197cd95a3..ba9f0a893 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp @@ -18,7 +18,7 @@ #include "SensingAgent.h" #include "CommunicationAgent.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/AIDllFrontier.h" #include "../Main/AIMain.h" #include "SquadManager.h" @@ -260,7 +260,7 @@ static bool insideControlPointRadius(const Vec3& controlPoint, const Vec3& posit void SquadCoordinator::update(double time) { m_d124 = time; - if (m_i120 == 2 && !IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) + if (m_missionStatus == 2 && !IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) { if (m_i40 == 0) { @@ -538,8 +538,8 @@ int SquadCoordinator::chooseSquadManeuver() if (bot->isFiring()) { // No information-null guard exists in either image. - const unsigned int flags = information->getObjectTypeFlags(); - if (!(flags & 0x10u) && !(flags & 0x20u) && !(flags & 0x80u) && + if (!information->isOfType(ITAir) && !information->isOfType(ITHelicopter) && + !information->isOfType(ITNaval) && member->getPosition(position) && maneuverMemberWithinRange(position, m_v108)) ++firingMembers; @@ -548,7 +548,7 @@ int SquadCoordinator::chooseSquadManeuver() } if (firingMembers > 1) return 1; - if (m_i120 != 2) + if (m_missionStatus != 2) return 0; // ELF 0x1A5741: the mission target (+28) at terrain height (IAITerrain +0x14), 50..173 m from the @@ -602,8 +602,8 @@ void SquadCoordinator::squadManeuverAlternateFire() Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); if (!bot->isFiring() || !equipment->isPrimary() || !equipment->hasMobile()) continue; - const unsigned int flags = equipment->getObjectTypeFlags(); - if ((flags & 0x10u) || (flags & 0x20u) || (flags & 0x80u) || !member->getPosition(position)) + if (equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter) || equipment->isOfType(ITNaval) || + !member->getPosition(position)) continue; const float dx = m_v108.x - position.x; const float dy = m_v108.y - position.y; @@ -692,7 +692,7 @@ void SquadCoordinator::squadManeuverStaticFlank() if (m_squadMembers[i]->isBot()) m_squadMembers[i]->getBot()->setAllowFire(true); } - if (m_b157 || m_i120 != 2) + if (m_b157 || m_missionStatus != 2) return; if (!m_formation->hasSquadMembers() || !m_strategicAreaAssignment) return; @@ -737,7 +737,7 @@ const Vec3& SquadCoordinator::getSquadGotoPos() // return enum spelling is unresolved, so int records the observed payload without new labels. int SquadCoordinator::getMissionStatus() { - return m_i120; + return m_missionStatus; } // The assignment is borrowed and nullable. @@ -838,10 +838,10 @@ bool SquadCoordinator::isValidPosition(SquadMember* member, const Vec3& position const int equipment = soldier->getUnit()->getEquipmentType(); if (!IAIPathfinding::instance->getPolygon(position, mobile->getVehicleNumber(), polygon, island, equipment)) return false; - if (last.quadTree == static_cast(-1) || island != last.quadTree) + if (last.island == static_cast(-1) || island != last.island) return false; return IAIPathfinding::instance->isValidPosition( - mobile->getVehicleNumber(), soldier->getUnit()->getEquipmentType(), position, last.quadTree, true); + mobile->getVehicleNumber(), soldier->getUnit()->getEquipmentType(), position, last.island, true); } // ELF 0x1A3A40: the requested-mission record (+60..+95) by value. @@ -892,12 +892,12 @@ void SquadCoordinator::requestMission(BotSquad::OrderType type, const Vec3& posi return; } if ((!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander() && isSquadCloseToNonOwnedTarget()) - || m_i120 != 0) + || m_missionStatus != 0) { if (!IAIMain::m_instance->getSAI(m_side + 1)->isPlayerCommander()) return; } - m_i120 = 1; + m_missionStatus = 1; m_d132 = m_d124 + 10.0f; m_v64 = position; m_i76 = type; @@ -991,7 +991,7 @@ bool SquadCoordinator::acceptMission(SquadMember* member) { m_v64 = centre; m_v28 = centre; - m_i120 = 2; + m_missionStatus = 2; m_i40 = m_i76; m_strategicAreaAssignment = closest; m_i44 = m_requestedObject; @@ -1007,7 +1007,7 @@ bool SquadCoordinator::acceptMission(SquadMember* member) if (getRandomValidPosition(member, position, 30.0f)) { m_v64 = position; - m_i120 = 2; + m_missionStatus = 2; m_v28 = m_v64; m_i40 = m_i76; m_i44 = m_requestedObject; @@ -1114,9 +1114,9 @@ SquadCoordinator::SquadCoordinator(int side, int squadIndex) , m_requestedArea(0) , m_i76(4) , m_requestedObject(0) - , m_i96(-1) + , m_squadLeaderIndex(-1) , m_list104() - , m_i120(0) + , m_missionStatus(0) , m_d124(0.0) , m_d132(0.0) , m_d140(0.0) @@ -1186,7 +1186,7 @@ void SquadCoordinator::getSquadPosition(Vec3& position) // used directly, including the absence of an empty-vector or negative-index guard. SquadMember* SquadCoordinator::getSquadLeader() { - return m_squadMembers[m_i96]; + return m_squadMembers[m_squadLeaderIndex]; } // Signed count consumed by the manager's comparisons. @@ -1217,7 +1217,7 @@ void SquadCoordinator::unAssignSquad() m_strategicAreaAssignment = 0; m_i40 = 4; m_i44 = 0; - m_i120 = 0; + m_missionStatus = 0; } // Allocation is not checkPointer-wrapped. The human arm @@ -1245,7 +1245,7 @@ void SquadCoordinator::addSquadMember(IAIPlayer* player) // change arm, but the single-member trailing-position reset still runs. void SquadCoordinator::updateSquadLeader() { - const int oldLeader = m_i96; + const int oldLeader = m_squadLeaderIndex; bool found = false; for (unsigned int i = 0; i < m_squadMembers.size(); ++i) { @@ -1254,7 +1254,7 @@ void SquadCoordinator::updateSquadLeader() m_squadIndex + 1, m_squadMembers[i]->getPlayer())); if (m_squadMembers[i]->isSquadLeader()) { - m_i96 = static_cast(i); + m_squadLeaderIndex = static_cast(i); found = true; break; } @@ -1262,12 +1262,12 @@ void SquadCoordinator::updateSquadLeader() if (!found) return; - if (oldLeader != m_i96 && oldLeader != -1 && !m_squadMembers.empty()) + if (oldLeader != m_squadLeaderIndex && oldLeader != -1 && !m_squadMembers.empty()) { // ELF 0x1A5C66: a new leader - the formation rejoins it and the squad position and paths // are refreshed; a human leader of a squad with more members leaves the AI commander's // assignment (unless the side has a player commander). - m_squadMembers[m_i96]->updateMemberPos(); + m_squadMembers[m_squadLeaderIndex]->updateMemberPos(); m_formation->joinSquadLeader(); updateSquadPosition(); updateSquadPaths(); @@ -1347,7 +1347,7 @@ void SquadCoordinator::reset() m_i76 = 4; m_requestedArea = 0; m_requestedObject = 0; - m_i120 = 0; + m_missionStatus = 0; m_formation->joinSquadLeader(); for (std::list::iterator it = m_list12.begin(); it != m_list12.end();) { @@ -1428,16 +1428,16 @@ bool SquadCoordinator::isSquadCloseToNonOwnedTarget() return false; } -// ELF 0x1A6B00: the mission state at +0x78 (m_i120) equals 2. +// ELF 0x1A6B00: the mission state at +0x78 (m_missionStatus) equals 2. bool SquadCoordinator::squadHasMission() { - return m_i120 == 2; + return m_missionStatus == 2; } // ELF 0x1A7FA0. bool SquadCoordinator::isSquadAvailable() { - return m_i120 == 0; + return m_missionStatus == 0; } // ELF 0x1A7F60: the requested area's index (+0xF0). @@ -1737,7 +1737,7 @@ void SquadCoordinator::squadManeuverDynamicFlank() if (member->isBot()) member->getBot()->setAllowFire(true); // +0x134 } - if (m_b157 || m_i120 != 2 || !m_formation->hasSquadMembers()) + if (m_b157 || m_missionStatus != 2 || !m_formation->hasSquadMembers()) return; m_b157 = true; SquadMember* const leader = m_squadMembers[m_formation->getSquadMemberIndexAtSlot(0)]; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h index b8ef1cc05..7ce3e6bc4 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h @@ -119,7 +119,7 @@ class SquadCoordinator // ELF 0x1A69C0: the accepted order (+40 type, +44 object, +28 position within FLT_EPSILON per axis). bool isSameMission(BotSquad::OrderType type, const Vec3& position, IAIObject* object); const Vec3& getSquadLeaderGotoPos() { return m_v200; } // ELF 0x1A7FE0: this + 0xC8 - int getSquadLeaderIndex() { return m_i96; } // ELF 0x1A5D70: +0x60 + int getSquadLeaderIndex() { return m_squadLeaderIndex; } // ELF 0x1A5D70: +0x60 bool isRepairRequested() { return m_b172; } // ELF 0x1A49F0: movzbl +0xAC Vec3& getRepairRequestPos() { return m_v176; } // ELF 0x1A4A00: this + 0xB0 void setRogerThatPositionMessage(bool roger) { m_b220 = roger; } // ELF 0x1A39F0: +0xDC @@ -161,7 +161,8 @@ class SquadCoordinator /* +24 */ AIStrategicArea* m_strategicAreaAssignment; // [INFERRED] name; ELF +0x18 / PE +0x28, borrowed; initially null /* +28 */ Vec3 m_v28; // zeroed [UNRESOLVED] /* +40 */ int m_i40; // = 4 [UNRESOLVED] - /* +44 */ IAIObject* m_i44; // = 0; acceptMission: the request's object + /* +44 */ IAIObject* m_i44; // = 0; acceptMission: the request's object. DICE: m_mission.target + // (AIDLL_r assert "m_mission.target == 0", 0x101BA880) /* +48 */ double m_d48; // = -20.0 a "never happened" sentinel; acceptMission: the game time /* +56 */ bool m_b56; // never written by the constructor; acceptMission: the request's commander flag // isSquadRequestedToArea (ELF 0x1A7F60) compares the area index at +0xF0 of this pointer. @@ -170,13 +171,16 @@ class SquadCoordinator /* +76 */ int m_i76; // = 4 [UNRESOLVED] - the twin of m_i40 /* +80 */ IAIObject* m_requestedObject; // = 0; requestMission's object [INFERRED] name /* +84 */ double m_d84; // never written by the constructor; getMissionRequest copies it - /* +92 */ bool m_b92; // requestMission: the order came from the commander - /* +96 */ int m_i96; // leader member index, initially -1 + /* +92 */ bool m_b92; // requestMission: the order came from the commander. DICE: + // m_missionRequest.isCommanderOrder (AIDLL_r assert, 0x101BA880) + /* +96 */ int m_squadLeaderIndex; // leader member index, initially -1. Name: AIDLL_r assert + // "m_squadLeaderIndex >= 0" in getSquadLeaderIndex (0x101B8910, PE +0x78) /* +100 */ SquadFormation* m_formation; // new SquadFormation(this) /* +104 */ std::list m_list104; // the area nav points; getListOfAreaNavPoints copies it /* +108 */ Vec3 m_v108; // zeroed twice - once before the formation, once after // 0 = available (isSquadAvailable, ELF 0x1A7FA0), 2 = has a mission (squadHasMission). - /* +120 */ int m_i120; // = 0 + /* +120 */ int m_missionStatus; // = 0. Name: AIDLL_r assert "m_missionStatus == MSOnMission" + // (getSquadMissionTargetPos 0x101B8B00 compares PE +0x98 with 2) /* +124 */ double m_d124; // = 0.0 [UNRESOLVED] /* +132 */ double m_d132; // = 0.0 [UNRESOLVED] /* +140 */ double m_d140; // = 0.0 [UNRESOLVED] diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp index a75eb158d..fc8cd0484 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp @@ -14,7 +14,7 @@ #include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" #include "../Main/AIRandom.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" @@ -262,7 +262,7 @@ void SquadFormation::selectFormation() void SquadFormation::updateFormationForwardVector() { Slot* const anchor = m_slots[0]; - if (!anchor->m_occupied) + if (!anchor->hasSquadMemberAssigned) return; IAIPlayer* const player = m_coordinator->getSquadMember(anchor->m_memberIndex)->getPlayer(); @@ -298,7 +298,7 @@ void SquadFormation::updateTrailingPositions() m_trailingPosition = m_v72; return; } - if (!anchor->m_occupied) + if (!anchor->hasSquadMemberAssigned) return; const float distanceSq = trailCrumbDistanceSq(m_v72, m_trailingPosition); @@ -307,14 +307,14 @@ void SquadFormation::updateTrailingPositions() if (!(distanceSq > 36.0f)) return; - for (unsigned int index = m_maxSquadMembers - 1; index != 0; --index) + for (unsigned int index = m_numberOfSlots - 1; index != 0; --index) { // Two statements: both images reload the vector's storage after the byte store. - m_slotTargets[index].first = m_slotTargets[index - 1].first; - m_slotTargets[index].second = m_slotTargets[index - 1].second; + m_trailingPositions[index].first = m_trailingPositions[index - 1].first; + m_trailingPositions[index].second = m_trailingPositions[index - 1].second; } - m_slotTargets[0].first = true; - m_slotTargets[0].second = m_trailingPosition; + m_trailingPositions[0].first = true; + m_trailingPositions[0].second = m_trailingPosition; m_trailingPosition = m_v72; } @@ -324,10 +324,10 @@ void SquadFormation::updateTrailingSlots() std::list members; Vec3 position = {}; - for (unsigned int index = 0; index < m_maxSquadMembers; ++index) + for (unsigned int index = 0; index < m_numberOfSlots; ++index) { Slot* const slot = m_slots[index]; - if (slot->m_i20 != -1 && slot->m_occupied) + if (slot->m_i20 != -1 && slot->hasSquadMemberAssigned) { SquadMember* const member = m_coordinator->getSquadMember(slot->m_memberIndex); member->getPosition(position); @@ -342,7 +342,7 @@ void SquadFormation::updateTrailingSlots() members.sort(); Slot* slot = 0; - for (unsigned int index = 0; index < m_maxSquadMembers; ++index) + for (unsigned int index = 0; index < m_numberOfSlots; ++index) { slot = m_slots[index]; slot->m_i20 = -1; @@ -352,7 +352,7 @@ void SquadFormation::updateTrailingSlots() for (std::list::iterator it = members.begin(); it != members.end(); ++it) { SquadMember* const member = it->m_member; - for (unsigned int index = 1; index < m_maxSquadMembers; ++index) + for (unsigned int index = 1; index < m_numberOfSlots; ++index) { slot = m_slots[index]; if (slot->m_memberIndex == member->getMemberIndex()) @@ -405,7 +405,7 @@ bool SquadFormation::getSlotWorldPos(int memberIndex, Vec3& position) } float fx = m_forward.x; float fy = m_forward.y; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; if (slot->m_memberIndex != memberIndex) @@ -463,7 +463,7 @@ bool SquadFormation::getSlotWorldPos(int memberIndex, Vec3& position) } slot->m_i20 = trail; } - position = m_slotTargets[trail].second; + position = m_trailingPositions[trail].second; return true; } return found; @@ -473,11 +473,11 @@ bool SquadFormation::getSlotWorldPos(int memberIndex, Vec3& position) // valid for `member`; -1 when none. (The image also computes, and drops, the distance to it.) int SquadFormation::getFirstFreeTrailingSlot(SquadMember* member) { - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { const bool assigned = isTrailPosAssigned(static_cast(i)); - const bool valid = m_coordinator->isValidPosition(member, m_slotTargets[i].second); - if (m_slotTargets[i].first && !assigned && valid) + const bool valid = m_coordinator->isValidPosition(member, m_trailingPositions[i].second); + if (m_trailingPositions[i].first && !assigned && valid) return static_cast(i); } return -1; @@ -486,7 +486,7 @@ int SquadFormation::getFirstFreeTrailingSlot(SquadMember* member) // ELF 0x1ACB70: whether any slot falls back to trailing position `trailIndex`. bool SquadFormation::isTrailPosAssigned(int trailIndex) { - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { if (m_slots[i]->m_i20 == trailIndex) return true; @@ -514,10 +514,10 @@ void SquadFormation::updateFormation() m_coordinator->getSquadPosition(squadPosition); unsigned int leaderSlotIndex = 0; - for (; leaderSlotIndex < m_maxSquadMembers; ++leaderSlotIndex) + for (; leaderSlotIndex < m_numberOfSlots; ++leaderSlotIndex) { slot = m_slots[leaderSlotIndex]; - if (slot->m_occupied && slot->m_memberIndex == leaderIndex) + if (slot->hasSquadMemberAssigned && slot->m_memberIndex == leaderIndex) { leaderPresent = true; break; @@ -530,10 +530,10 @@ void SquadFormation::updateFormation() { if (leaderSlotIndex != 0) return; - for (unsigned int index = m_maxSquadMembers - 1; index > 0; --index) + for (unsigned int index = m_numberOfSlots - 1; index > 0; --index) { Slot* const other = m_slots[index]; - if (!other->m_occupied) + if (!other->hasSquadMemberAssigned) continue; const int otherIndex = other->m_memberIndex; const int oldIndex = slot->m_memberIndex; @@ -562,9 +562,9 @@ void SquadFormation::updateFormation() m_b85 = false; Slot* const zero = m_slots[0]; - const bool oldOccupied = zero->m_occupied; + const bool oldOccupied = zero->hasSquadMemberAssigned; const int oldIndex = zero->m_memberIndex; - zero->m_occupied = true; + zero->hasSquadMemberAssigned = true; zero->m_memberIndex = leaderIndex; zero->m_b24 = false; zero->m_i28 = 0.0f; @@ -572,7 +572,7 @@ void SquadFormation::updateFormation() // The old leader-slot pointer is reloaded after that callback. slot = m_slots[leaderSlotIndex]; - slot->m_occupied = oldOccupied; + slot->hasSquadMemberAssigned = oldOccupied; slot->m_memberIndex = oldIndex; slot->m_b24 = false; slot->m_i28 = 0.0f; @@ -583,17 +583,17 @@ void SquadFormation::updateFormation() } Slot* const zero = m_slots[0]; - if (!zero->m_occupied) + if (!zero->hasSquadMemberAssigned) return; if (m_coordinator->getSquadMember(zero->m_memberIndex)->isBot() == leaderIsBot) return; // Find the first occupied slot whose bot/human kind matches the captured leader. // The bound, vector and coordinator are fresh after each member callback. - for (unsigned int index = 1; index < m_maxSquadMembers; ++index) + for (unsigned int index = 1; index < m_numberOfSlots; ++index) { Slot* const other = m_slots[index]; - if (!other->m_occupied || + if (!other->hasSquadMemberAssigned || m_coordinator->getSquadMember(other->m_memberIndex)->isBot() != leaderIsBot) continue; const int oldIndex = zero->m_memberIndex; @@ -623,10 +623,10 @@ void SquadFormation::updateWaitForSquadMembers(double time) m_b36 = true; Vec3 memberPosition = {}; Vec3 squadPosition = {}; - for (unsigned int index = 1; index < m_maxSquadMembers; ++index) + for (unsigned int index = 1; index < m_numberOfSlots; ++index) { Slot* const slot = m_slots[index]; - if (!slot->m_occupied) + if (!slot->hasSquadMemberAssigned) continue; SquadMember* const member = m_coordinator->getSquadMember(slot->m_memberIndex); @@ -739,7 +739,7 @@ static bool nearerFormationMember(const Vec3& position, const Vec3& destination, // comparison, no occupied/null/vector-size test. Even an empty slot's -1 can match. bool SquadFormation::isInFormation(int memberIndex) { - const unsigned int count = m_maxSquadMembers; + const unsigned int count = m_numberOfSlots; for (unsigned int i = 0; i < count; ++i) if (m_slots[i]->m_memberIndex == memberIndex) return true; @@ -751,7 +751,7 @@ bool SquadFormation::isInFormation(int memberIndex) void SquadFormation::resetSlot(int slotIndex) { Slot* const slot = m_slots[slotIndex]; - slot->m_occupied = false; + slot->hasSquadMemberAssigned = false; slot->m_memberIndex = -1; slot->m_i20 = -1; slot->m_b24 = false; @@ -765,7 +765,7 @@ void SquadFormation::resetSlot(int slotIndex) void SquadFormation::leaveFormation(int memberIndex) { unsigned int removed = 0; - for (; removed < m_maxSquadMembers; ++removed) + for (; removed < m_numberOfSlots; ++removed) { if (m_slots[removed]->m_memberIndex == memberIndex) { @@ -774,13 +774,13 @@ void SquadFormation::leaveFormation(int memberIndex) } } - if (removed < m_maxSquadMembers - 1 && m_slots[removed + 1]->m_occupied) + if (removed < m_numberOfSlots - 1 && m_slots[removed + 1]->hasSquadMemberAssigned) { - unsigned int last = m_maxSquadMembers - 1; + unsigned int last = m_numberOfSlots - 1; while (last > 0) { Slot* const lastSlot = m_slots[last]; - if (lastSlot->m_occupied) + if (lastSlot->hasSquadMemberAssigned) { if (removed == 0 && last > 1) { @@ -792,7 +792,7 @@ void SquadFormation::leaveFormation(int memberIndex) Slot* const slot = m_slots[candidate]; // Retail obtains the member even for an unoccupied candidate. SquadMember* const member = m_coordinator->getSquadMember(slot->m_memberIndex); - if (slot->m_occupied && !member->isSquadLeader() && member->isBot() && + if (slot->hasSquadMemberAssigned && !member->isSquadLeader() && member->isBot() && member->getPosition(position)) { const Vec3& destination = m_coordinator->getSquadGotoPos(); @@ -803,7 +803,7 @@ void SquadFormation::leaveFormation(int memberIndex) Slot* destination = m_slots[0]; Slot* source = m_slots[selected]; - destination->m_occupied = source->m_occupied; + destination->hasSquadMemberAssigned = source->hasSquadMemberAssigned; destination->m_b24 = source->m_b24; destination->m_offset = source->m_offset; destination->m_memberIndex = source->m_memberIndex; @@ -812,16 +812,16 @@ void SquadFormation::leaveFormation(int memberIndex) m_coordinator->getSquadMember(destination->m_memberIndex)->setHavePath(false); resetSlot(static_cast(selected)); - if (selected < m_maxSquadMembers - 1 && m_slots[selected + 1]->m_occupied) + if (selected < m_numberOfSlots - 1 && m_slots[selected + 1]->hasSquadMemberAssigned) { - unsigned int replacement = m_maxSquadMembers - 1; + unsigned int replacement = m_numberOfSlots - 1; while (replacement > 0) { source = m_slots[replacement]; - if (source->m_occupied) + if (source->hasSquadMemberAssigned) { destination = m_slots[selected]; - destination->m_occupied = source->m_occupied; + destination->hasSquadMemberAssigned = source->hasSquadMemberAssigned; destination->m_b24 = source->m_b24; destination->m_offset = source->m_offset; destination->m_memberIndex = source->m_memberIndex; @@ -843,7 +843,7 @@ void SquadFormation::leaveFormation(int memberIndex) const float oldValue = lastSlot->m_i28; resetSlot(static_cast(last)); Slot* const slot = m_slots[removed]; - slot->m_occupied = true; + slot->hasSquadMemberAssigned = true; slot->m_memberIndex = movedMember; slot->m_i20 = oldIndex; slot->m_b24 = oldFlag; @@ -864,9 +864,9 @@ void SquadFormation::leaveFormation(int memberIndex) // callbacks; occupied candidates only, with -1 and identical-slot results skipped. void SquadFormation::updateClosestSlots() { - for (unsigned int slot = 1; slot < m_maxSquadMembers; ++slot) + for (unsigned int slot = 1; slot < m_numberOfSlots; ++slot) { - if (m_slots[slot]->m_occupied) + if (m_slots[slot]->hasSquadMemberAssigned) { const int closest = getClosestSlotIndex(static_cast(slot)); if (closest != -1 && closest != static_cast(slot)) @@ -885,9 +885,9 @@ int SquadFormation::getClosestSlotIndex(int slotIndex) Vec3 position = {}; if (!getSlotWorldPos(m_slots[slotIndex]->m_memberIndex, target)) return best; - for (unsigned int i = 1; i < m_maxSquadMembers; ++i) + for (unsigned int i = 1; i < m_numberOfSlots; ++i) { - if (!m_slots[i]->m_occupied) + if (!m_slots[i]->hasSquadMemberAssigned) continue; if (!m_coordinator->getSquadMember(m_slots[i]->m_memberIndex)->getPosition(position)) continue; @@ -932,7 +932,7 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) , m_forward() , m_i88(0) , m_d92(0.0) - , m_slotTargets() + , m_trailingPositions() , m_trailingPosition() { m_direction.x = 0.0f; @@ -948,10 +948,10 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) m_side = coordinator->getSide(); - m_maxSquadMembers = static_cast( + m_numberOfSlots = static_cast( static_cast(CommonSingletonServer::m_iaiGame)->getMaxNumberOfSquadMembers()); - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { m_slots.push_back(new Slot()); @@ -959,7 +959,7 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) zero.x = 0.0f; zero.y = 0.0f; zero.z = 0.0f; - m_slotTargets.push_back(std::pair(false, zero)); + m_trailingPositions.push_back(std::pair(false, zero)); } // FLT_MAX, written as the bit pattern the binary stores. @@ -995,12 +995,12 @@ float SquadFormation::getFormationMaxSpeed() // even when the scan finds no free slot. PE inlines updateMovementFlag(true). void SquadFormation::joinFormation(int memberIndex) { - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; - if (!slot->m_occupied) + if (!slot->hasSquadMemberAssigned) { - slot->m_occupied = true; + slot->hasSquadMemberAssigned = true; slot->m_memberIndex = memberIndex; slot->m_i20 = -1; slot->m_b24 = false; @@ -1018,7 +1018,7 @@ void SquadFormation::joinFormation(int memberIndex) // when forced or when both strict thresholds pass. No empty-slot-vector guard. void SquadFormation::updateMovementFlag(bool force) { - if (!m_slots[0]->m_occupied) + if (!m_slots[0]->hasSquadMemberAssigned) return; m_b56 = false; @@ -1046,7 +1046,7 @@ void SquadFormation::updateMovementFlag(bool force) // Preserve both guards (inlined in the image): the positioned squad's slot-zero world position. void SquadFormation::updateSlotZeroPos() { - if (m_slots[0]->m_occupied && m_coordinator->squadHasPosition()) + if (m_slots[0]->hasSquadMemberAssigned && m_coordinator->squadHasPosition()) getSlotWorldPos(getSquadMemberIndexAtSlot(0), m_v72); } @@ -1057,9 +1057,9 @@ void SquadFormation::resetTrailingPositions() updateSlotZeroPos(); m_trailingPosition = m_v72; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { - m_slotTargets[i].first = false; + m_trailingPositions[i].first = false; m_slots[i]->m_i20 = -1; } } @@ -1076,11 +1076,11 @@ void SquadFormation::updateFormationMaxSpeed() m_formationMaxSpeed = 3.402823466e+38F; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; - if (slot->m_occupied) + if (slot->hasSquadMemberAssigned) { ++occupied; IAIObject* const vehicle = @@ -1156,7 +1156,7 @@ void SquadFormation::setLineFormation() float offset = 0.0f; int referenceSlot = 0; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; @@ -1187,7 +1187,7 @@ void SquadFormation::setLineFormation() // reference slot: offset = reference offset + offset * (3 * own radius + 3 * reference // radius) (0x49CC90 = 3.0f; the image rounds the first product to float, keeps the x // product's sum in x87 precision). - if (slot->m_occupied) + if (slot->hasSquadMemberAssigned) { const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); Slot* const reference = m_slots[slot->m_referenceSlot]; @@ -1210,7 +1210,7 @@ void SquadFormation::setWedgeFormation() Vec3 offset = {}; int referenceSlot = 0; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; @@ -1237,7 +1237,7 @@ void SquadFormation::setWedgeFormation() slot->m_offset = offset; - if (slot->m_occupied) + if (slot->hasSquadMemberAssigned) { const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); Slot* const reference = m_slots[slot->m_referenceSlot]; @@ -1258,7 +1258,7 @@ void SquadFormation::setEchelonFormation() Vec3 offset = {}; int referenceSlot = 0; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) { Slot* const slot = m_slots[i]; @@ -1285,7 +1285,7 @@ void SquadFormation::setEchelonFormation() slot->m_offset = offset; - if (slot->m_occupied) + if (slot->hasSquadMemberAssigned) { const float own = 3.0f * m_coordinator->getSquadMember(slot->m_memberIndex)->getVehicleRadius(); Slot* const reference = m_slots[slot->m_referenceSlot]; @@ -1302,11 +1302,11 @@ void SquadFormation::setEchelonFormation() // least as many members as slots, the last slot is left free. void SquadFormation::reassignSlots() { - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) resetSlot(static_cast(i)); unsigned int count = static_cast(m_coordinator->getNumberOfSquadMembers()); - if (count >= m_maxSquadMembers) - count = m_maxSquadMembers - 1; + if (count >= m_numberOfSlots) + count = m_numberOfSlots - 1; unsigned int next = 0; for (unsigned int i = 0; i < count; ++i) { @@ -1314,28 +1314,28 @@ void SquadFormation::reassignSlots() if (!member->isAllowedInFormation()) continue; Slot* const slot = m_slots[next++]; - slot->m_occupied = true; + slot->hasSquadMemberAssigned = true; slot->m_memberIndex = member->getMemberIndex(); } } // ELF 0x1A9E10 (D1, 240 B; recovered on the client track, docs/macos-c-singleplayer.md). Clears -// the coordinator back-pointer, deletes the first m_maxSquadMembers slots (the bound is the +// the coordinator back-pointer, deletes the first m_numberOfSlots slots (the bound is the // member count fixed at construction, not the vector's size), then empties both vectors. SquadFormation::~SquadFormation() { m_coordinator = 0; - for (unsigned int i = 0; i < m_maxSquadMembers; ++i) + for (unsigned int i = 0; i < m_numberOfSlots; ++i) delete m_slots[i]; m_slots.erase(m_slots.begin(), m_slots.end()); - m_slotTargets.erase(m_slotTargets.begin(), m_slotTargets.end()); + m_trailingPositions.erase(m_trailingPositions.begin(), m_trailingPositions.end()); } // ELF 0x1A9FB0. Shipped defect: the gap-checking loop has no checks left in this image. void SquadFormation::debugCheckNoFormationSlotGaps() { - unsigned int last = m_maxSquadMembers - 1; - while (last && !m_slots[last]->m_occupied) + unsigned int last = m_numberOfSlots - 1; + while (last && !m_slots[last]->hasSquadMemberAssigned) --last; if (last) for (unsigned int index = 0; index <= last; ++index) {} diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h index a44309c19..6cdac329c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.h @@ -32,7 +32,7 @@ class SquadFormation explicit Slot(SwapTemporary) : m_offset() {} Slot() - : m_occupied(false) + : hasSquadMemberAssigned(false) , m_memberIndex(-1) , m_i20(-1) , m_b24(false) @@ -44,10 +44,10 @@ class SquadFormation m_offset.z = 0.0f; } - /* +0 */ bool m_occupied; // the flag every deep branch in this class is guarded by + /* +0 */ bool hasSquadMemberAssigned; // the flag every deep branch in this class is guarded by; name: AIDLL_r assert (0x101B4F00; +0) /* +4 */ int m_memberIndex; // = -1; indexes the coordinator's squad-member vector /* +8 */ Vec3 m_offset; // the position the formation setters compute - /* +20 */ int m_i20; // = -1; the trailing position (m_slotTargets) this slot falls back to + /* +20 */ int m_i20; // = -1; the trailing position (m_trailingPositions) this slot falls back to /* +24 */ bool m_b24; // = false [UNRESOLVED] /* +28 */ float m_i28; // legacy inferred name; float proved by leaveFormation's x87 loads/stores /* +32 */ int m_referenceSlot; // the slot this one is measured from [INFERRED] @@ -75,7 +75,7 @@ class SquadFormation void selectFormation(); // / PE inlined at int getSquadMemberIndexAtSlot(int slotIndex); // no occupied test // ELF 0x1AB6C0: the first slot is occupied (no empty-vector guard). - bool hasSquadMembers() { return m_slots[0]->m_occupied; } + bool hasSquadMembers() { return m_slots[0]->hasSquadMemberAssigned; } bool getSlotWorldPos(int memberIndex, Vec3& position); // ELF 0x1AC550 int getFirstFreeTrailingSlot(SquadMember* member); // ELF 0x1ACA30 bool isTrailPosAssigned(int trailIndex); // ELF 0x1ACB70 @@ -111,7 +111,7 @@ class SquadFormation /* +12 */ SquadCoordinator* m_coordinator; // the constructor's argument /* +16 */ int m_formation; // = 0 (line); `setFormation` switches on it /* +20 */ Vec3 m_direction; // set by `setFormation` per formation - /* +32 */ unsigned int m_maxSquadMembers; // = IAIGame::getMaxNumberOfSquadMembers + /* +32 */ unsigned int m_numberOfSlots; // = IAIGame::getMaxNumberOfSquadMembers // name: AIDLL_r assert 0x101B5980 (PE +0x24) /* +36 */ bool m_b36; // = false; shouldSquadMoveOut returns it /* +40 */ float m_formationMaxSpeed; // FLT_MAX, then 5.0f - see the header note /* +44 */ int m_side; // = the coordinator's side @@ -128,7 +128,7 @@ class SquadFormation /* +92 */ double m_d92; // = 0.0; next movement-stamp time (now + 0.2) // [INFERRED] Per-slot breadcrumb targets. Anchor movement beyond six metres shifts the // trail and inserts its previous position; construction sizes it to the slot count. - /* +100 */ std::vector > m_slotTargets; // (valid, crumb) per index + /* +100 */ std::vector > m_trailingPositions; // (valid, crumb) per index // name: AIDLL_r assert 0x101B7E20 (PE +0x68) /* +112 */ Vec3 m_trailingPosition; // [INFERRED name]; the newest crumb, seeded from m_v72 }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp index 63233d26e..b3e48c773 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.cpp @@ -4,7 +4,7 @@ #include "SquadManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF // 0x1B0FE0, __tcf_0 0x1B1040, _GLOBAL__I 0x1B1070). @@ -17,7 +17,7 @@ #include "SquadMember.h" #include "../Main/AIDllFrontier.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../Main/IBotManager.h" #include "../Main/AIMain.h" @@ -31,7 +31,7 @@ #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../../Core/SettingsRepostitory.h" #include "../../../../Core/StringUtil.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../Main/AIRandom.h" #include "../Main/IAIPathfinding.h" @@ -51,12 +51,12 @@ namespace ai { int SquadManager::getSquadStrengths(int side, int areaIndex, StrategicStrengthType type) { int total = 0; - for (std::size_t index = 0; index < m_coordinators[side - 1].size(); ++index) + for (std::size_t index = 0; index < m_Squads[side - 1].size(); ++index) { - if (m_coordinators[side - 1][index]->getMissionStatus() == 2 && - m_coordinators[side - 1][index]->isSquadAssignedToArea(areaIndex)) + if (m_Squads[side - 1][index]->getMissionStatus() == 2 && + m_Squads[side - 1][index]->isSquadAssignedToArea(areaIndex)) { - total += m_coordinators[side - 1][index]->getStrategicStrength(type); + total += m_Squads[side - 1][index]->getStrategicStrength(type); } } return total; @@ -72,10 +72,10 @@ void SquadManager::update(double time) updateArtilleryStatus(time); updateCommanderMessages(); m_sideCursor = m_sideCursor == 0; - m_coordinators[m_sideCursor][m_squadCursor]->update(time); + m_Squads[m_sideCursor][m_squadCursor]->update(time); if (m_sideCursor == 1) { - if (static_cast(m_squadCursor) < m_coordinators[0].size() - 1) + if (static_cast(m_squadCursor) < m_Squads[0].size() - 1) m_squadCursor = static_cast(static_cast(m_squadCursor) + 1); else { @@ -91,15 +91,15 @@ void SquadManager::update(double time) // therefore runs two complete traversals. void SquadManager::updateArtilleryStatus(double time) { - SideBlock* blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + SideBlock* blocks[2] = { &m_artillery[0], &m_artillery[1] }; for (unsigned int block = 0; block < 2; ++block) { - if (blocks[block]->m_b0 && time > m_double156 + blocks[block]->m_artilleryStartTime) + if (blocks[block]->incomingArtillery && time > m_double156 + blocks[block]->m_artilleryStartTime) { - blocks[block]->m_b0 = false; + blocks[block]->incomingArtillery = false; for (unsigned int side = 0; side < 2; ++side) - for (unsigned int index = 0; index < m_coordinators[side].size(); ++index) - m_coordinators[side][index]->updateSquadPaths(); + for (unsigned int index = 0; index < m_Squads[side].size(); ++index) + m_Squads[side][index]->updateSquadPaths(); } } } @@ -231,7 +231,7 @@ void SquadManager::updateHumanPlayers(double time) // Creates a coordinator for each squad on each side, excluding squad zero. SquadManager::SquadManager() - : m_coordinators() + : m_Squads() // Default-initialize SideBlock: its three Vec3 values alone are zeroed. Value-initializing // the blocks would also zero timestamps/flags retail leaves untouched (full //PE reads). , m_commanderMessages() @@ -246,8 +246,8 @@ SquadManager::SquadManager() for (unsigned int i = 0; i < last; ++i) { - m_coordinators[0].push_back(new SquadCoordinator(0, static_cast(i))); - m_coordinators[1].push_back(new SquadCoordinator(1, static_cast(i))); + m_Squads[0].push_back(new SquadCoordinator(0, static_cast(i))); + m_Squads[1].push_back(new SquadCoordinator(1, static_cast(i))); } } @@ -258,8 +258,8 @@ SquadManager::SquadManager() m_float152 = 40.0f; m_sideCursor = 1; - m_sideBlock0.m_b0 = false; - m_sideBlock1.m_b0 = false; + m_artillery[0].incomingArtillery = false; + m_artillery[1].incomingArtillery = false; m_double156 = 25.0; @@ -301,7 +301,7 @@ void SquadManager::addSquadMember(int playerId, int side) const int maximum = static_cast(CommonSingletonServer::m_iaiGame) ->getMaxNumberOfSquadMembers(); int best = maximum; - std::vector& coordinators = m_coordinators[side]; + std::vector& coordinators = m_Squads[side]; for (unsigned int i = 0; i < coordinators.size(); ++i) { if (coordinators[i]->getNumberOfSquadMembers() <= best && @@ -366,14 +366,14 @@ void SquadManager::addSquadMember(int playerId, int side) // singleton or coordinator-null check here; the courier owns only the singleton guard. void SquadManager::newSquadLeader(int side, int squadId) { - m_coordinators[side - 1][squadId - 1]->updateSquadLeader(); + m_Squads[side - 1][squadId - 1]->updateSquadLeader(); } // Search this side in coordinator order and return the first // matching member. The coordinator's output index is intentionally not used by this caller. SquadMember* SquadManager::getSquadMember(int playerId, int side) { - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { int memberIndex; @@ -389,7 +389,7 @@ SquadMember* SquadManager::getSquadMember(int playerId, int side) // The member index output is not consumed, and null coordinator entries are not guarded. SquadCoordinator* SquadManager::getSquadFromPlayer(int playerId, int side) { - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { int memberIndex; @@ -412,7 +412,7 @@ int SquadManager::getSquadFromPlayer(int playerId, SquadCoordinator*& squad) // ELF 0x1AF720: one-based squad id and side, no range checks. SquadCoordinator* SquadManager::getSquadFromId(int squadId, int side) { - return m_coordinators[side - 1][squadId - 1]; + return m_Squads[side - 1][squadId - 1]; } // ELF 0x1AF860 (256 bytes). An order received by the player's squad: the order position comes @@ -493,7 +493,7 @@ void SquadManager::playerJoinsSquad(int playerId, int squadId, int side) if (getSquadMember(playerId, side)) return; - SquadCoordinator* coordinator = m_coordinators[side - 1][squadId - 1]; + SquadCoordinator* coordinator = m_Squads[side - 1][squadId - 1]; IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) ->getPlayerFromId(playerId); coordinator->addSquadMember(player); @@ -503,7 +503,7 @@ void SquadManager::playerJoinsSquad(int playerId, int squadId, int side) // ELF 0x1AF800: every coordinator of the one-based side drops its strategic-area assignment. void SquadManager::unAssignSquads(int side) { - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) coordinators[i]->unAssignSquad(); } @@ -519,9 +519,9 @@ SquadManager::~SquadManager() { for (int side = 0; side < 2; ++side) { - for (unsigned int i = 0; i < m_coordinators[side].size(); ++i) - delete m_coordinators[side][i]; - m_coordinators[side].erase(m_coordinators[side].begin(), m_coordinators[side].end()); + for (unsigned int i = 0; i < m_Squads[side].size(); ++i) + delete m_Squads[side][i]; + m_Squads[side].erase(m_Squads[side].begin(), m_Squads[side].end()); } clearCommanderMessages(); clearPlayerValidPositions(); @@ -534,13 +534,13 @@ void SquadManager::reset() unAssignSquads(2); clearCommanderMessages(); clearPlayerValidPositions(); - m_sideBlock0.m_b0 = false; - m_sideBlock1.m_b0 = false; + m_artillery[0].incomingArtillery = false; + m_artillery[1].incomingArtillery = false; m_squadCursor = 0; m_sideCursor = 1; for (int side = 0; side < 2; ++side) - for (unsigned int i = 0; i < m_coordinators[side].size(); ++i) - m_coordinators[side][i]->reset(); + for (unsigned int i = 0; i < m_Squads[side].size(); ++i) + m_Squads[side][i]->reset(); } // ELF 0x1B0180: squad 0 (no squad) is ignored. Otherwise the player's member record is unlinked @@ -553,7 +553,7 @@ void SquadManager::playerRemovedFromSquad(int playerId, int squadId, int side) SquadMember* const member = getSquadMember(playerId, side); if (!member) return; - SquadCoordinator* const coordinator = m_coordinators[side - 1][squadId - 1]; + SquadCoordinator* const coordinator = m_Squads[side - 1][squadId - 1]; coordinator->removeSquadMember(member); coordinator->updateSquadLeader(); } @@ -563,7 +563,7 @@ void SquadManager::playerRemovedFromSquad(int playerId, int squadId, int side) int SquadManager::unAssignSquads(int areaIndex, int side) { int released = 0; - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { if (coordinators[i]->isSquadCloseToNonOwnedTarget()) @@ -615,7 +615,7 @@ SquadCoordinator* SquadManager::getClosestAvailableSquad(AIStrategicArea* area, SquadCoordinator* closest = 0; float best = 3.4028235e+38f; Vec3 squadPosition = { 0.0f, 0.0f, 0.0f }; - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; strength = 0; for (unsigned int i = 0; i < coordinators.size(); ++i) { @@ -648,7 +648,7 @@ float SquadManager::getDistanceToClosestSquad(const Vec3& position, int side) { float best = 3.4028235e+38f; Vec3 leader = { 0.0f, 0.0f, 0.0f }; - const std::vector& coordinators = m_coordinators[side - 1]; + const std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { SquadCoordinator* const squad = coordinators[i]; @@ -692,8 +692,7 @@ bool SquadManager::friendliesCloseTo(Vec3 position, float radius, int side) Information* const info = informationManager->getInformation(vehicle->getInformation(side)); if (!info) continue; - const unsigned int flags = info->getObjectTypeFlags(); - if ((flags & 0x20) == 0 && (flags & 0x10) != 0) + if (!info->isOfType(ITHelicopter) && info->isOfType(ITAir)) continue; const Vec3& p = info->getPosition(); const float dx = p.x - position.x; @@ -713,10 +712,10 @@ bool SquadManager::friendliesCloseTo(Vec3 position, float radius, int side) // The sum is x87 extended in the ELF (fildll, fmuls, fmul, faddp); bf2x87::Real keeps that. void SquadManager::incomingArtillery(Vec3 position, int side) { - SideBlock& block = side - 1 == 0 ? m_sideBlock0 : m_sideBlock1; - SideBlock& other = side - 1 == 0 ? m_sideBlock1 : m_sideBlock0; + SideBlock& block = side - 1 == 0 ? m_artillery[0] : m_artillery[1]; + SideBlock& other = side - 1 == 0 ? m_artillery[1] : m_artillery[0]; const double half = 0.5 * m_double156; - block.m_b0 = true; + block.incomingArtillery = true; block.m_artilleryStartTime = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); block.m_artilleryPosition = position; const unsigned int r = AIRandom::m_instance->next(); @@ -734,8 +733,8 @@ void SquadManager::incomingArtillery(Vec3 position, int side) // artillerySide = the striking side. Otherwise -1.0 and 0. bool SquadManager::isInArtilleryDangerZone(Vec3 position, int side, double& sinceStart, int& artillerySide) { - SideBlock& own = side - 1 == 0 ? m_sideBlock0 : m_sideBlock1; - SideBlock& other = side - 1 == 0 ? m_sideBlock1 : m_sideBlock0; + SideBlock& own = side - 1 == 0 ? m_artillery[0] : m_artillery[1]; + SideBlock& other = side - 1 == 0 ? m_artillery[1] : m_artillery[0]; const int otherSide = side - 1 == 0 ? 2 : 1; bool danger = false; sinceStart = -1.0; @@ -748,13 +747,13 @@ bool SquadManager::isInArtilleryDangerZone(Vec3 position, int side, double& sinc const float dz = block.m_artilleryPosition.z - position.z; return dx * dx + dy * dy + dz * dz; }; - if (own.m_b0 && distanceSq(own) < safe) + if (own.incomingArtillery && distanceSq(own) < safe) { danger = true; sinceStart = static_cast(now - bf2x87::Real(own.m_artilleryStartTime)); artillerySide = side; } - else if (other.m_b0 && distanceSq(other) < safe + else if (other.incomingArtillery && distanceSq(other) < safe && bf2x87::Real(other.m_artilleryStartTime) + bf2x87::Real(other.m_artilleryDelay) < now) { danger = true; @@ -768,7 +767,7 @@ bool SquadManager::isInArtilleryDangerZone(Vec3 position, int side, double& sinc // engine squad (IBFSquad::exitSquad, squad id + 1) and re-elects its leader. void SquadManager::removeSquadMember(int playerId, int side) { - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { SquadCoordinator* const squad = coordinators[i]; @@ -787,10 +786,10 @@ void SquadManager::removeSquadMember(int playerId, int side) // ELF 0x1AE000: both sides' squads are emptied, then every active bot is added again. void SquadManager::removeAllSquads() { - for (unsigned int i = 0; i < m_coordinators[0].size(); ++i) - m_coordinators[0][i]->removeAll(); - for (unsigned int i = 0; i < m_coordinators[1].size(); ++i) - m_coordinators[1][i]->removeAll(); + for (unsigned int i = 0; i < m_Squads[0].size(); ++i) + m_Squads[0][i]->removeAll(); + for (unsigned int i = 0; i < m_Squads[1].size(); ++i) + m_Squads[1][i]->removeAll(); IBotManager* const manager = IBotManager::instance; if (!manager) return; @@ -809,7 +808,7 @@ void SquadManager::removeAllSquads() // ELF 0x1B0010: removeSquadMember's search, but the coordinator destroys the member record. void SquadManager::destroySquadMember(int playerId, int side) { - std::vector& coordinators = m_coordinators[side - 1]; + std::vector& coordinators = m_Squads[side - 1]; for (unsigned int i = 0; i < coordinators.size(); ++i) { SquadCoordinator* const squad = coordinators[i]; @@ -902,7 +901,7 @@ SquadMember* SquadManager::getSquadLeaderClosestTo(const Vec3& position) Vec3 leaderPosition = {}; for (unsigned int side = 0; side < 2; ++side) { - std::vector& squads = m_coordinators[side]; + std::vector& squads = m_Squads[side]; for (unsigned int i = 0; i < squads.size(); ++i) { if (squads[i]->getNumberOfSquadMembers() <= 0) @@ -940,7 +939,7 @@ SquadMember* SquadManager::getSquadMember(unsigned int handle, int side) // ELF 0x1B0440. bool SquadManager::isAnySquadMemberRespondingToRequest(unsigned int handle, int action, int side) { - const std::vector& squads = m_coordinators[side - 1]; + const std::vector& squads = m_Squads[side - 1]; for (unsigned int i = 0; i < squads.size(); ++i) { if (squads[i]->isAnySquadMemberRespondingToRequest(handle, action)) @@ -967,7 +966,7 @@ float SquadManager::requestResponseModifier(SquadMember* member, unsigned int ha // ELF 0x1B0D40. Vec3 SquadManager::getArtilleryTargetPos(int side) { - SideBlock* const blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + SideBlock* const blocks[2] = { &m_artillery[0], &m_artillery[1] }; return blocks[side - 1]->m_artilleryPosition; } @@ -991,12 +990,12 @@ Information* fleeInformation(SquadMember* member, int side) bool SquadManager::haveValidArtilleryFleePos(SquadMember* member, Vec3& position) { const int side = member->getSide(); - SideBlock* const blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + SideBlock* const blocks[2] = { &m_artillery[0], &m_artillery[1] }; SideBlock* const block = blocks[side - 1]; Information* const info = fleeInformation(member, side); if (!info) return false; - if ((info->getObjectTypeFlags() & 0x00200000u) == 0) + if (!info->isOfType(ITSoldier)) { if (!block->m_validFlee1) return false; @@ -1015,12 +1014,12 @@ bool SquadManager::haveValidArtilleryFleePos(SquadMember* member, Vec3& position void SquadManager::setValidArtilleryFleePos(SquadMember* member, Vec3 position) { const int side = member->getSide(); - SideBlock* const blocks[2] = { &m_sideBlock0, &m_sideBlock1 }; + SideBlock* const blocks[2] = { &m_artillery[0], &m_artillery[1] }; SideBlock* const block = blocks[side - 1]; Information* const info = fleeInformation(member, side); if (!info) return; - if ((info->getObjectTypeFlags() & 0x00200000u) == 0) + if (!info->isOfType(ITSoldier)) { block->m_validFlee1 = true; block->m_fleePos1 = position; diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h index 41993e001..37692a421 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h @@ -113,12 +113,12 @@ class SquadManager // Three Vec3 values, not containers: incomingArtillery // and setValidArtilleryFleePos store their scalar components. // [INFERRED] field names. ELF offsets below; PE offsets are 0,8,16,32,40,41,44,56. - // Only the three positions are zeroed here. The manager tail clears m_b0; both doubles + // Only the three positions are zeroed here. The manager tail clears incomingArtillery; both doubles // and the two validity flags remain unwritten by retail construction. class SideBlock { public: - /* +0 */ bool m_b0; + /* +0 */ bool incomingArtillery; // name: AIDLL_r assert (0x1012FC60) /* +4 */ double m_artilleryStartTime; /* +12 */ Vec3 m_artilleryPosition{}; /* +24 */ double m_artilleryDelay; @@ -131,13 +131,15 @@ class SquadManager private: // no vtable. The constructor stores no vptr on any path, so this class has no virtuals at // all - checked before writing, because a missing vptr shifts every offset below by four. - /* 0 */ std::vector m_coordinators[2]; // ELF stride 12 / PE stride 16 + /* 0 */ std::vector m_Squads[2]; // ELF stride 12 / PE stride 16 // name: AIDLL_r assert "m_Squads[side - 1]" 0x101320A0 (PE +0) /* 24 */ int m_squadCursor; // = 0; [INFERRED] name, update uses unsigned comparison /* 28 */ int m_sideCursor; // = 1; [INFERRED] name, update alternates zero/nonzero // Per-side state blocks, each 60 bytes in the original layout. Construction clears // the leading flag and the same nine words in each block. - /* 32 */ SideBlock m_sideBlock0; // +32..+91 - /* 92 */ SideBlock m_sideBlock1; // +92..+151 + // Two blocks, one per side: AIDLL_r asserts "m_artillery[side - 1].incomingArtillery" (0x1012FC60) + // and "m_artillery[theSide].incomingArtillery || m_artillery[otherSide].incomingArtillery" + // (0x1012FD90; PE stride 0x48, flag at +0x28 + index * 0x48). + /* 32 */ SideBlock m_artillery[2]; // +32..+91, +92..+151 /* 152 */ float m_float152; // = 40.0f (bit pattern ) /* 156 */ double m_double156; // = 25.0 // with a bare `operator delete` one at a time. diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp index 975e072f0..4a2959749 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp @@ -13,11 +13,11 @@ #include "SquadCoordinator.h" #include "SquadFormation.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "SquadManager.h" #include "WaypointList.h" #include "../../../AIInterface/BFKnowledge/BFSquad.h" @@ -270,7 +270,7 @@ void SquadMember::update(double time) Information* const information = manager->getInformation(handle); #endif IPIArmament* const armament = information ? information->getArmament() : 0; - if (information && (information->getObjectTypeFlags() & 0x200000u) && armament + if (information && information->isOfType(ITSoldier) && armament && armament->getActiveWeapon() != -1) { // ELF 0x1B1ED0: a soldier who is not firing switches to weapon slot 2 (activation @@ -395,7 +395,7 @@ bool SquadMember::isAllowedInFormation() if (!vehicle) return false; Information* const info = informationManager->getInformation(vehicle->getInformation(m_side + 1)); - if (info && info->getUnit() && (info->getObjectTypeFlags() & 0x00200000) != 0 && info->getMobile()) + if (info && info->getUnit() && info->isOfType(ITSoldier) && info->getMobile()) { allowed = true; Vec3 goal = m_squad->getSquadGotoPos(); @@ -532,7 +532,7 @@ void SquadMember::moveToSlotPos(const Vec3& position, Information* information) { m_havePath = true; m_vector60 = position; - if (!(information->getObjectTypeFlags() & 0x10u)) + if (!information->isOfType(ITAir)) { WPMoveTo::GoalList goals; goals.push_back(std::make_pair(position, -1)); @@ -541,7 +541,7 @@ void SquadMember::moveToSlotPos(const Vec3& position, Information* information) } float altitude = 70.0f; float radius = 30.0f; - if (information->getObjectTypeFlags() & 0x20u) + if (information->isOfType(ITHelicopter)) { radius = 5.0f; altitude = 20.0f; @@ -634,7 +634,7 @@ void SquadMember::moveToGoalPos(Information* information) AIStrategicArea* area = m_squad->getSquadStrategicAreaAssignment(); const int side = m_side + 1; - if (!(information->getObjectTypeFlags() & 0x10u) + if (!information->isOfType(ITAir) && m_squad->getSquadFormation()->shouldLeaveSquadLeader() && !m_squad->isSquadCloseToNonOwnedTarget()) { @@ -671,11 +671,11 @@ void SquadMember::moveToGoalPos(Information* information) goal = m_squad->getSquadGotoPos(); if (m_squad->isSquadAssignedToAnyArea()) m_squad->getValidSaPos(this, goal); - if (information->getObjectTypeFlags() & 0x10u) + if (information->isOfType(ITAir)) { float altitude = 70.0f; float radius = 30.0f; - if (information->getObjectTypeFlags() & 0x20u) + if (information->isOfType(ITHelicopter)) { radius = 5.0f; altitude = 20.0f; @@ -1078,7 +1078,7 @@ bool SquadMember::canDamageTarget(unsigned int target) const float dz = m_position.z - targetPosition.z; (void)std::sqrt(dx * dx + dy * dy + dz * dz); float strength = 0.0f; - if (armament->isAntiAircraft() || !(targetInformation->getObjectTypeFlags() & 0x10u)) + if (armament->isAntiAircraft() || !targetInformation->isOfType(ITAir)) { for (unsigned int i = 0; i < weapons.size(); ++i) { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.cpp similarity index 88% rename from Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp rename to Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.cpp index a25e41e3f..22a60fe25 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.cpp @@ -1,4 +1,4 @@ -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIBot\UrgencyMerger.cpp" (assert "mpMaxGenerator != 0", 0x101F9180). // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining UrgencyMerger operations. // static init: ELF 0x1B5CD0 (__tcf_0 0x1B5D30, _GLOBAL__I 0x1B5D60): 's Init object only. @@ -24,7 +24,7 @@ UrgencyMerger::UrgencyMerger(int count, float* weights, UrgencyGenerator** gener : m_count(count) , m_weights(weights) , m_generators(generators) - , m_chosen(0) + , mpMaxGenerator(0) { } @@ -36,17 +36,17 @@ UrgencyMerger::~UrgencyMerger() // ELF 0x1B59B0. The chosen generator's urgency, 0 when none is chosen. float UrgencyMerger::getUrgency(Bot* bot) { - if (m_chosen == 0) + if (mpMaxGenerator == 0) return 0.0f; - return m_chosen->getUrgency(bot); + return mpMaxGenerator->getUrgency(bot); } // ELF 0x1B5A00. float UrgencyMerger::getActiveUrgency(Bot* bot) { - if (m_chosen == 0) + if (mpMaxGenerator == 0) return 0.0f; - return m_chosen->getActiveUrgency(bot); + return mpMaxGenerator->getActiveUrgency(bot); } // ELF 0x1B5A40. Updates every generator; the strictly most urgent one's own chosen generator @@ -54,7 +54,7 @@ float UrgencyMerger::getActiveUrgency(Bot* bot) float UrgencyMerger::updateActiveUrgency(Bot* bot) { float best = 0.0f; - m_chosen = 0; + mpMaxGenerator = 0; for (int i = 0; i < m_count; ++i) { const float urgency = @@ -62,7 +62,7 @@ float UrgencyMerger::updateActiveUrgency(Bot* bot) if (urgency > best) { best = urgency; - m_chosen = m_generators[i]->getChosenGenerator(); + mpMaxGenerator = m_generators[i]->getChosenGenerator(); } } return best; @@ -109,7 +109,7 @@ bool UrgencyMerger::hasChanged(Bot* bot, float lower, float upper) // ELF 0x1A2850. UrgencyGenerator* UrgencyMerger::getChosenGenerator() { - return m_chosen; + return mpMaxGenerator; } // ELF 0x1B5C80. Resets every present generator. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.h similarity index 90% rename from Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h rename to Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.h index 128d4367d..b682364e4 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/UrgencyMerger.h @@ -1,5 +1,5 @@ // Combines per-behavior urgency generators for a bot. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIBot/UrgencyMerger.cpp). #ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_URGENCYMERGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AIBOTBEHAVIOUR_URGENCYMERGER_H @@ -54,7 +54,7 @@ class UrgencyMerger : public UrgencyGenerator /* 4 */ int m_count; // the generator count; getSize returns it /* 8 */ float* m_weights; // null from BotManager's pool /* 12 */ UrgencyGenerator** m_generators; - /* 16 */ UrgencyGenerator* m_chosen; // = 0; the winner of the last updateActiveUrgency + /* 16 */ UrgencyGenerator* mpMaxGenerator; // = 0; the winner of the last updateActiveUrgency // name: AIDLL_r assert "mpMaxGenerator != 0" (0x101F9180) }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp index 4082668bc..07ee8b149 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp @@ -4,7 +4,7 @@ #include "WPAltitudeCloseTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF // 0x1B60D0, __tcf_0 0x1B6130, _GLOBAL__I 0x1B6160). diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp index 9a282e437..ec62d6415 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPBeachLanding.cpp @@ -5,7 +5,7 @@ #include "BotMain.h" #include "../AIStrategicEntity/AILandingZone.h" -#include "../AIStrategicEntity/AILandingZoneManager.h" +#include "../Main/AILandingZoneManager.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF // 0x1B86C0, __tcf_0 0x1B8720, _GLOBAL__I 0x1B8750). diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp index 1526a9a7a..5a528e104 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPCloseTo.cpp @@ -8,7 +8,7 @@ #include #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../../../../Math/Mat4.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp index 66d2aafbb..46d1b0255 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveTo.cpp @@ -9,7 +9,7 @@ #include "../Main/AIDllFrontier.h" #include "BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp index c01eacbfb..ab76ea47d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp @@ -8,10 +8,10 @@ #include "BotMain.h" #include "WPBeachLanding.h" // storeLandingZone #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIStrategicEntity/AILandingZone.h" -#include "../AIStrategicEntity/AILandingZoneManager.h" +#include "../Main/AILandingZoneManager.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.cpp similarity index 99% rename from Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp rename to Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.cpp index ca4cff437..328ba8c53 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.cpp @@ -1,4 +1,4 @@ -// Ballistic aiming. Evidence: libaidll.so 1.5.3153 (ia-32), AIBot/Aimer.cpp, 0x1C7120..0x1C8EA0 +// Ballistic aiming. Evidence: libaidll.so 1.5.3153 (ia-32), Aimer.cpp, 0x1C7120..0x1C8EA0 // (see Aimer.h). Read from the Ghidra decompile and checked against objdump where Ghidra hides x87 // precision (getFiringDirection's impact time is `double time + float t`, 0x1C8134..0x1C8143). @@ -48,7 +48,7 @@ Aimer::Aimer() m_drag = 0.0f; m_gravity = 0.0f; m_speed = 1.0f; - m_hasTargetData = 0; + m_nSamples = 0; m_time = 0.0; m_relativePos.x = 1.0f; m_relativePos.y = 0.0f; m_relativePos.z = 0.0f; m_targetVelocity.x = 0.0f; m_targetVelocity.y = 0.0f; m_targetVelocity.z = 0.0f; @@ -71,7 +71,7 @@ Aimer::~Aimer() bool Aimer::setTargetData(const Vec3& relativePos, const Vec3& targetVelocity, const Vec3& shooterVelocity, const Mat4* transform, double time) { - m_hasTargetData = 1; + m_nSamples = 1; m_relativePos = relativePos; m_relativeDir = relativePos; const float lengthSq = m_relativeDir.x * m_relativeDir.x + m_relativeDir.y * m_relativeDir.y diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.h similarity index 91% rename from Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h rename to Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.h index d66eac7e9..f4884e078 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/Aimer.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/Aimer.h @@ -1,7 +1,8 @@ // Ballistic aiming for one weapon at one target: given the shooter-relative target state and the // projectile's speed, drag and gravity, finds the firing direction by iterating the elevation. -// Evidence: libaidll.so 1.5.3153 (ia-32). Attested file AIBot/Aimer.cpp (FILE symbol beside -// 0x1C8EA0, after CommunicationAgent.cpp); constructors 0x1C7120 / 0x1C71E0, destructors +// Evidence: libaidll.so 1.5.3153 (ia-32). FILE symbol Aimer.cpp beside +// 0x1C8EA0, after CommunicationAgent.cpp; the directory is AIDLL_r.dll's __FILE__ +// "Code\BF2\AI\AIDLL\AI\AIBotActionPlan\Aimer.cpp" (the tree had inferred AIBot/); constructors 0x1C7120 / 0x1C71E0, destructors // 0x1C72A0 / 0x1C72B0 (empty, not virtual). sizeof 0x6C: BAPAAimAt embeds it at +0xA4 and its next // member is at +0x110 (BAPAAimAt::BAPAAimAt 0x1CD5E0). // @@ -60,7 +61,7 @@ class Aimer /* +0x30 */ Vec3 m_targetVelocity; /* +0x3C */ Vec3 m_shooterVelocity; /* +0x48 */ Vec3 m_forward; // transform * (0, 0, 1); ctor (0, 0, 1) - /* +0x54 */ int m_hasTargetData; // ctor 0, setTargetData 1 + /* +0x54 */ int m_nSamples; // ctor 0, setTargetData 1 // name: AIDLL_r asserts 0x101FE960, 0x101FFC20 (+0x54) /* +0x58 */ double m_verticalExtreme; // half the last impact time (getFiringDirection) /* +0x60 */ float m_angle; // last elevation; ctor 666.0f = none yet /* +0x64 */ float m_angleStep; // ctor 0.0174533f (one degree) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h index 470637754..bcd7efe45 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt.h @@ -11,7 +11,7 @@ #include "BAPAction.h" #include "BAPTypes.h" #include "BAPVariable.h" -#include "../AIBot/Aimer.h" +#include "Aimer.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h index 299764dcc..73bbbb5fc 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAAimAt3d.h @@ -9,7 +9,7 @@ #include "../../../../Math/Mat4.h" #include "../../../../Math/Vec3.h" -#include "../AIBot/Aimer.h" +#include "Aimer.h" #include "BAPAction.h" #include "BAPTypes.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp index 979809760..ecd6be91a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAChangeWeapon.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { @@ -46,7 +46,7 @@ bool BAPAChangeWeapon::execute(Bot* bot, bool& ok, bool& failed) return true; } io::PlayerInput* input = bot->getInput(); - if (info->getObjectTypeFlags() & 0x200000u) { + if (info->isOfType(ITSoldier)) { if (info->getArmament()->getActiveWeapon() != m_weaponIndex) { input->setInput(io::PIFire, 0.0f); input->setInput(io::PIAltFire, 0.0f); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp index a59cd3abc..16268a6b1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAComponentSoldierPose.cpp @@ -97,7 +97,7 @@ bool BAPAComponentSoldierPose::objectForcesCrouch() const if (m_object == 0xFFFFFFFFu) return false; Information* info = bapinline::info(m_object); - if (!info || !(info->getObjectTypeFlags() & 0x200000u)) + if (!info || !info->isOfType(ITSoldier)) return false; IAIPlayer* player = static_cast(CommonSingletonServer::m_iaiPlayerFactory) ->getPlayerFromId(info->getPlayerId()); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp index dc5b89571..6338095e3 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToFinding.cpp @@ -156,7 +156,7 @@ int BAPAMoveToFinding::update(Vec2& point, bool& reached, bool& done, float) const Vec3 target = bapinline::vec3(point.x, self->getPosition().y, point.y); double sinceStart; int artillerySide; - if (!(self->getObjectTypeFlags() & 0x10u)) { + if (!self->isOfType(ITAir)) { const int side = m_bot->getSide(); if (SquadManager::m_instance->isInArtilleryDangerZone(target, side, sinceStart, artillerySide) && !SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), m_bot->getSide(), @@ -165,7 +165,7 @@ int BAPAMoveToFinding::update(Vec2& point, bool& reached, bool& done, float) goto finish; } } - if (self->getObjectTypeFlags() & 0x200000u) { + if (self->isOfType(ITSoldier)) { SquadMember* member; if (SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), m_bot->getSide(), sinceStart, artillerySide) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp index d82dc2a2a..50859d443 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAMoveToObjectFinding.cpp @@ -16,7 +16,7 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/AIDllFrontier.h" #include "../Main/IAIPathfinding.h" #include "../Main/IBotManager.h" @@ -208,10 +208,10 @@ int BAPAMoveToObjectFinding::update(Vec2& point, bool& reached, bool& done, floa } } if (replan == 1) { - initObjectFinding(dist, dir, own.position, goal.quadTree, goal.polygon, goal.position, false); + initObjectFinding(dist, dir, own.position, goal.island, goal.polygon, goal.position, false); } else if (replan == 2) { const Vec3 zero = bapinline::vec3(0.0f, 0.0f, 0.0f); - initObjectFinding(0.0f, zero, zero, goal.quadTree, goal.polygon, goal.position, true); + initObjectFinding(0.0f, zero, zero, goal.island, goal.polygon, goal.position, true); } m_pathStarted = true; @@ -227,7 +227,7 @@ int BAPAMoveToObjectFinding::update(Vec2& point, bool& reached, bool& done, floa if (got) { point = m_currentPoint; reached = m_pathDone; - if (!(self->getObjectTypeFlags() & 0x10u) + if (!self->isOfType(ITAir) && SquadManager::m_instance->isInArtilleryDangerZone(target3, bot->getSide(), sinceStart, artillerySide) && !SquadManager::m_instance->isInArtilleryDangerZone(self->getPosition(), bot->getSide(), sinceStart, artillerySide)) { @@ -236,7 +236,7 @@ int BAPAMoveToObjectFinding::update(Vec2& point, bool& reached, bool& done, floa } } if (!done) { - const bool soldier = (self->getObjectTypeFlags() & 0x200000u) != 0; + const bool soldier = self->isOfType(ITSoldier); bool artilleryCheck = true; if (!stopped && !m_movingAway && soldier && std::fabs(target->getPosition().y - self->getPosition().y) < 2.0f) { @@ -408,7 +408,7 @@ void BAPAMoveToObjectFinding::initObjectFinding(float distance, const Vec3&, con const Vec3& speed = mobile->getSpeed(); Vec3 flat = bapinline::vec3(speed.x, 0.0f, speed.z); const float flatSpeed = std::sqrt(flat.x * flat.x + 0.0f * 0.0f + flat.z * flat.z); - const bool soldier = (self->getObjectTypeFlags() & 0x200000u) != 0; + const bool soldier = self->isOfType(ITSoldier); if (!soldier || !(flatSpeed > 1.5f)) { // 0x1DB53E ja float d = (m_distance - m_minDistance) * 0.2f; if (10.0f < d) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp index 2160de40c..e08e0303a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAPlaceC4.cpp @@ -8,7 +8,7 @@ #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../../Math/Vec3.h" #include diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp index dbeb57b33..fbc6acc71 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPARunOverObject.cpp @@ -6,7 +6,7 @@ #include "BAPActionInline.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" @@ -67,7 +67,7 @@ bool BAPARunOverObject::execute(Bot* bot, bool& ok, bool& done) hit.z = 0.0f; unsigned int polygon; const int equipmentType = equipment->getUnit()->getEquipmentType(); - if (!IAIPathfinding::instance->trace(ownValid.polygon, ownValid.quadTree, mobile->getVehicleNumber(), + if (!IAIPathfinding::instance->trace(ownValid.polygon, ownValid.island, mobile->getVehicleNumber(), ownValid.position, targetValid.position, hit, polygon, equipmentType, -1, 0.0f, 5, 0)) { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp index f314c99b6..5cbd42016 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPAUseFlareOnMissileLock.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { @@ -48,7 +48,7 @@ bool BAPAUseFlareOnMissileLock::execute(Bot* bot, bool& ok, bool& failed) m_lockTime = now; } double wait = time; - if (!(info->getObjectTypeFlags() & 0x10u)) + if (!info->isOfType(ITAir)) wait = 0.0; if (locked && wait <= now - m_lockTime) { io::PlayerInput* input = bot->getInput(); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h index 59ebceb9d..8301b5bf9 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h @@ -7,7 +7,7 @@ #include "../../../../Math/Vec3.h" #include "../../../../IO/Input/PlayerInput.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/AIDllFrontier.h" #include "BAPCondition.h" #include "BAPTypes.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp index bacee5d32..9add832cf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCConPrecision.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include #include @@ -148,12 +148,12 @@ bool BAPCConPrecision::evaluate(Bot* bot) float distance = std::sqrt(toPoint.x * toPoint.x + toPoint.y * toPoint.y + toPoint.z * toPoint.z); bool closeVehicle = false; if (5.0f <= std::fabs(point.y - from.y)) { - } else if (!(target->getObjectTypeFlags() & 0x200000u)) { - if (!(own->getObjectTypeFlags() & 0x200000u) && distance < 15.0f) + } else if (!target->isOfType(ITSoldier)) { + if (!own->isOfType(ITSoldier) && distance < 15.0f) closeVehicle = true; } bool staticAttack = false; - if (!(own->getObjectTypeFlags() & 0x200000u)) + if (!own->isOfType(ITSoldier)) staticAttack = static_cast(bot)->getUseStaticAttack(); const Vec3 aim = m_aimDirection->m_value; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp index 862a2199b..945ee7f5a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerParallel.cpp @@ -47,7 +47,7 @@ BAPCombinerParallel::BAPCombinerParallel(std::list& statements, i m_statements = statements; for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) { - (*it)->m_owner = this; + (*it)->mpOwner = this; m_controls |= (*it)->getControls(); m_isFinished.insert(m_isFinished.end(), false); } @@ -64,7 +64,7 @@ BAPCombinerParallel::BAPCombinerParallel(std::list& statements, i m_statements = statements; for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) { - (*it)->m_owner = this; + (*it)->mpOwner = this; m_controls |= (*it)->getControls(); m_isFinished.insert(m_isFinished.end(), false); } @@ -151,7 +151,7 @@ void BAPCombinerParallel::addStatement(BAPStatement* statement) { if (statement == 0) return; - statement->m_owner = this; + statement->mpOwner = this; m_statements.insert(m_statements.end(), statement); m_controls |= statement->getControls(); m_isFinished.insert(m_isFinished.end(), false); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp index 4c79fb716..a2da06ffa 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCombinerSerial.cpp @@ -42,7 +42,7 @@ BAPCombinerSerial::BAPCombinerSerial(std::list& statements, int p m_statements = statements; m_current = m_statements.begin(); for (std::list::iterator it = m_statements.begin(); it != m_statements.end(); ++it) - (*it)->m_owner = this; + (*it)->mpOwner = this; } // ELF 0x1E65F0 (D2; D1 0x1E66B0, D0 0x1E6770). Deletes the children (slot +8). @@ -142,7 +142,7 @@ void BAPCombinerSerial::addStatement(BAPStatement* statement) { if (statement == 0) return; - statement->m_owner = this; + statement->mpOwner = this; m_statements.insert(m_statements.end(), statement); m_current = m_statements.begin(); } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp index 8d2051998..0322214de 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAllowFire.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp index 198924d81..63598a9e2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConAnd.cpp @@ -14,7 +14,7 @@ BAPConAnd::BAPConAnd(std::list& conditions) { m_conditions = conditions; for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) - (*it)->m_owner = this; + (*it)->mpOwner = this; } // ELF 0x1F3D30 (C2; C1 0x1F3DA0). @@ -48,7 +48,7 @@ bool BAPConAnd::evaluate(Bot* bot) // ELF 0x1F40A0: no null check. void BAPConAnd::addCondition(BAPCondition* condition) { - condition->m_owner = this; + condition->mpOwner = this; m_conditions.insert(m_conditions.end(), condition); } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp index ac378dc2a..318031708 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConIsSprinting.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp index cfe6a09a5..40dd66e8d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConNot.cpp @@ -12,7 +12,7 @@ namespace ai { // ELF 0x1F4580 (C2; C1 0x1F46E0). No null check. BAPConNot::BAPConNot(BAPCondition* condition) { - condition->m_owner = this; + condition->mpOwner = this; m_conditions.insert(m_conditions.end(), condition); } @@ -20,7 +20,7 @@ BAPConNot::BAPConNot(BAPCondition* condition) BAPConNot::BAPConNot(std::list& conditions) { m_conditions.clear(); - conditions.front()->m_owner = this; + conditions.front()->mpOwner = this; m_conditions.insert(m_conditions.end(), conditions.front()); } @@ -51,7 +51,7 @@ void BAPConNot::addCondition(BAPCondition* condition) { if (!m_conditions.empty()) return; - condition->m_owner = this; + condition->mpOwner = this; m_conditions.insert(m_conditions.end(), condition); } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp index 3321b1b8d..9a972a6db 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectHealth.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include namespace dice { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp index 5fcf46b1c..f1176528b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectInsideFrustum.cpp @@ -38,7 +38,7 @@ bool BAPConObjectInsideFrustum::evaluate(Bot* bot) if (m_initialize) { m_initialize = false; const float farDistance = bot->getPlayer()->getViewDistance(); - if (self->getObjectTypeFlags() & 0x400000u) { + if (self->isOfType(ITObstructedView)) { const Mat4& camera = *static_cast(bot->getPlayer()->getCameraTransformation()); m_frustum.setPerspective(1.570796371f, 1.0f, 0.01f, farDistance, camera); } else { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp index 473abd432..c93b0a4cf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectLineOfFire.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" @@ -75,7 +75,7 @@ bool BAPConObjectLineOfFire::evaluate(Bot* bot) result = result && !clear; } } - if (result && (self->getObjectTypeFlags() & 0x200000u)) + if (result && self->isOfType(ITSoldier)) result = !hasFriendlySoldiersInLineOfFire(bot, self, target); return result; } @@ -114,7 +114,7 @@ bool BAPConObjectLineOfFire::hasFriendlySoldiersInLineOfFire(Bot* bot, Informati if (!vehicle) continue; Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); - if (info == self || info == target || !info || !(info->getObjectTypeFlags() & 0x200000u)) + if (info == self || info == target || !info || !info->isOfType(ITSoldier)) continue; const Vec3& p = info->getPosition(); const Vec3 rel = bapinline::vec3(p.x - origin.m[12], p.y - origin.m[13], p.z - origin.m[14]); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp index 062704993..66237bc3b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.cpp @@ -13,7 +13,7 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFPhysics.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h index 560749524..2b9891a05 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConObjectValidAiming.h @@ -11,7 +11,7 @@ #include "BAPConObject.h" #include "BAPTypes.h" #include "BAPVariable.h" -#include "../AIBot/Aimer.h" +#include "Aimer.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp index 097ac6ea6..89e3e44ab 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.cpp @@ -10,7 +10,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" @@ -54,9 +54,8 @@ bool BAPConOkToThrowGrenade::evaluate(Bot* bot) Information* target = bapinline::info(m_object); if (!target) return false; - const unsigned int selfFlags = self->getObjectTypeFlags(); const double now = bapinline::gameTime(); - if (now - main->getTimeOfLastFailedStaticAttack() < 10.0 && (selfFlags & 0x200000u)) + if (now - main->getTimeOfLastFailedStaticAttack() < 10.0 && self->isOfType(ITSoldier)) return false; const std::vector& players = @@ -69,7 +68,7 @@ bool BAPConOkToThrowGrenade::evaluate(Bot* bot) if (!vehicle) continue; Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); - if (info && (info->getObjectTypeFlags() & 0x200000u) + if (info && info->isOfType(ITSoldier) && std::fabs(info->getPosition().y - m_targetPoint->m_value.y) < 2.5f) { const Vec3 d = bapinline::sub(m_targetPoint->m_value, info->getPosition()); if (d.x * d.x + d.y * d.y + d.z * d.z < 49.0f) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h index d63cf01b1..e2e14e725 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOkToThrowGrenade.h @@ -11,7 +11,7 @@ #include "BAPConObject.h" #include "BAPTypes.h" #include "BAPVariable.h" -#include "../AIBot/Aimer.h" +#include "Aimer.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp index 04029a0fe..dce54867a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConOr.cpp @@ -14,7 +14,7 @@ BAPConOr::BAPConOr(std::list& conditions) { m_conditions = conditions; for (std::list::iterator it = m_conditions.begin(); it != m_conditions.end(); ++it) - (*it)->m_owner = this; + (*it)->mpOwner = this; } // ELF 0x1F4F50 (C2; C1 0x1F4FC0). @@ -48,7 +48,7 @@ bool BAPConOr::evaluate(Bot* bot) // ELF 0x1F52C0: no null check. void BAPConOr::addCondition(BAPCondition* condition) { - condition->m_owner = this; + condition->mpOwner = this; m_conditions.insert(m_conditions.end(), condition); } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp index 657ece67e..a87f2fff7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSharedCondition.cpp @@ -19,7 +19,7 @@ BAPConSharedCondition::BAPConSharedCondition(BAPCondition* condition) m_shared->value = false; m_shared->references = 1; m_condition = condition; - condition->m_owner = this; + condition->mpOwner = this; } // ELF 0x1E9E60 (C2; C1 0x1E9EA0): shares the cell, owns no condition. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp index 28b65b986..e46febe86 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" @@ -84,7 +84,7 @@ bool BAPConSplashDamage::evaluate(Bot* bot) if (!vehicle) continue; Information* info = bapinline::info(vehicle->getInformation(bot->getSide())); - if (info && (info->getObjectTypeFlags() & 0x200000u) && std::fabs(info->getPosition().y - hit.y) < 2.5f) { + if (info && info->isOfType(ITSoldier) && std::fabs(info->getPosition().y - hit.y) < 2.5f) { const Vec3& p = info->getPosition(); if ((hit.z - p.z) * (hit.z - p.z) + (hit.x - p.x) * (hit.x - p.x) + (hit.y - p.y) * (hit.y - p.y) < m_radiusSqr) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h index 2db68ce74..57c9d216b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConSplashDamage.h @@ -11,7 +11,7 @@ #include "BAPConObject.h" #include "BAPTypes.h" #include "BAPVariable.h" -#include "../AIBot/Aimer.h" +#include "Aimer.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp index 6a1ce8ea7..ff8a2a6b1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConStrategicObjectStatus.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIStrategicEntity/AIStrategicObject.h" namespace dice { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp index 8589befd3..e1fd78607 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConTotalAmmo.cpp @@ -8,7 +8,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp index e61ebe1b2..e1da9d18e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponDetonatorIsActive.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp index 0773fa002..00a0573a6 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" namespace dice { @@ -22,7 +22,7 @@ namespace ai { BAPConWeaponHasLockOnTarget::BAPConWeaponHasLockOnTarget(BAPVariable* weapon, unsigned int unused) { m_weapon = weapon; - m_unusedC = unused; + m_target = unused; } // ELF 0x1F23B0 (D0 0x1F23D0): base only. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h index 251ce7f32..cc4276493 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponHasLockOnTarget.h @@ -31,7 +31,7 @@ class BAPConWeaponHasLockOnTarget : public BAPConWeapon virtual BAPConditionType getConditionType() const; // 0x1F24A0, slot +0x04; from the base declaration private: - /* +0x0C */ unsigned int m_unusedC; // the ctor's second argument; evaluate does not read it + /* +0x0C */ unsigned int m_target; // the ctor's second argument; evaluate does not read it // name: AIDLL_r assert in the constructor 0x101CE300 (+0xC) }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp index cdd34ec62..5f9ee8e4c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsActive.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp index ce2264f2d..0aa557f1f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponIsZoomed.cpp @@ -10,7 +10,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp index 795c0ab33..9813518d0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponReadyToFire.cpp @@ -11,7 +11,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp index f484120e7..5de808512 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPConWeaponTargetReachable.cpp @@ -3,7 +3,7 @@ #include #include "BAPConWeaponTargetReachable.h" #include "BAPActionInline.h" -#include "../AIBot/Aimer.h" +#include "Aimer.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIMobile.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h index 6bdd70e81..bd797a00e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPCondition.h @@ -22,7 +22,7 @@ class Bot; class BAPCondition { public: - BAPCondition() : m_owner(0) {} // inline in the image (BAPConAnd() 0x1F3D30 stores +4 = 0) + BAPCondition() : mpOwner(0) {} // inline in the image (BAPConAnd() 0x1F3D30 stores +4 = 0) virtual bool evaluate(Bot*) = 0; // no body, slot +0x00; from the base declaration virtual BAPConditionType getConditionType() const = 0; // no body, slot +0x04; from the base declaration @@ -31,15 +31,15 @@ class BAPCondition // [INFERRED] inline (no symbol): statement constructors store themselves at +0x04 of their // conditions (BAPALookAtObject 0x1D318B, BAPALookInDir 0x1D3AEB). - void setOwner(void* owner) { m_owner = owner; } + void setOwner(void* owner) { mpOwner = owner; } protected: // The owner: BAPFlowCEnd's constructor (0x1E3293) stores the owning statement here, // BAPBoleanOp::addCondition (BAPConAnd 0x1F40CC) and the list constructors the owning condition. - // Mixed pointee types, so untyped. [INFERRED] name; public like BotScript::m_owner, because + // Mixed pointee types, so untyped. [INFERRED] name; public like BotScript::mpOwner, because // statements of other packages store it inline. [CHOSEN] visibility. public: - /* +0x04 */ void* m_owner; + /* +0x04 */ void* mpOwner; // name: AIDLL_r asserts 0x101B21C0, 0x101B1340 (+4) }; // ELF 0x1F80D0: condition.streamSelf(os) (slot +8); returns os. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp index a9c811cfe..e8d8a8699 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCEnd.cpp @@ -16,7 +16,7 @@ BAPFlowCEnd::BAPFlowCEnd(int patternId, BAPFlowCEnd::EndType type, BAPCondition* , m_type(type) { if (condition) - condition->m_owner = this; + condition->mpOwner = this; } // ELF 0x1E3310 (D2; D1 0x1E3380, D0 0x1E33F0). The condition's deleting destructor is slot +0x10. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp index d5aac4a7f..e8d15adb9 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCIf.cpp @@ -32,11 +32,11 @@ BAPFlowCIf::BAPFlowCIf(BAPCondition* condition, BAPStatement* trueStatement, BAP , m_reevaluate(reevaluate) , m_keepElse(keepElse) { - condition->m_owner = this; + condition->mpOwner = this; if (m_trueStatement) - m_trueStatement->m_owner = this; + m_trueStatement->mpOwner = this; if (m_falseStatement) - m_falseStatement->m_owner = this; + m_falseStatement->mpOwner = this; } // ELF 0x1E3690 (D2; D1 0x1E3720, D0 0x1E37B0). diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp index 1d0994646..f4b082422 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWait.cpp @@ -14,7 +14,7 @@ BAPFlowCWait::BAPFlowCWait(BAPCondition* condition, int patternId) : BAPFlowControl(patternId) , m_condition(condition) { - condition->m_owner = this; + condition->mpOwner = this; } // ELF 0x1E4060 (D2; D1 0x1E40C0, D0 0x1E4120). diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp index fc44fb86e..4f5c88449 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPFlowCWhile.cpp @@ -27,9 +27,9 @@ BAPFlowCWhile::BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatemen , m_testCondition(true) , m_testOnFinish(true) { - condition->m_owner = this; + condition->mpOwner = this; if (m_loopStatement) - m_loopStatement->m_owner = this; + m_loopStatement->mpOwner = this; } // ELF 0x1E4300 (C2; C1 0x1E4390). @@ -42,9 +42,9 @@ BAPFlowCWhile::BAPFlowCWhile(BAPCondition* condition, BAPStatement* loopStatemen , m_testCondition(true) , m_testOnFinish(testOnFinish) { - condition->m_owner = this; + condition->mpOwner = this; if (m_loopStatement) - m_loopStatement->m_owner = this; + m_loopStatement->mpOwner = this; } // ELF 0x1E4420 (D2; D1 0x1E4490, D0 0x1E4500). diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp index f96092e96..d9846d1b7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWChange.cpp @@ -24,7 +24,7 @@ BAPIWChange::BAPIWChange(unsigned int target, BAPStatement* statement, int patte m_target = target; m_playerId = playerId; bapinline::info(target)->bookVehicle(playerId); - m_statement->m_owner = this; + m_statement->mpOwner = this; } // ELF 0x1F5FC0 (D1; D2 0x1F5B20, D0 0x1F6470). Cancels the booking; then, when the plan's bot diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp index f73c25b61..8d0726cf0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWFire.cpp @@ -27,7 +27,7 @@ BAPIWFire::BAPIWFire(Bot* bot, unsigned int target, bool flag24, bool flag25, in m_int28 = -1; m_flag25 = flag25; m_bot = bot; - m_statement->m_owner = this; + m_statement->mpOwner = this; bot->setIsFiring(true); bot->setFiringTarget(target); m_useStaticAttack = static_cast(bot)->getUseStaticAttack(); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp index 67e5f6b5c..c4c4ce640 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWIdle.cpp @@ -20,7 +20,7 @@ BAPIWIdle::BAPIWIdle(const Vec3& position, BAPStatement* statement, int tag, Bot m_bot = bot; if (bot && bot->getSquadMember()) m_bot->getSquadMember()->setIsIdle(true); - m_statement->m_owner = this; + m_statement->mpOwner = this; } // ELF 0x1F75D0 (D1; D2 0x1F7510 region, D0 0x1F7650): clears the idle flag, deletes the child diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp index 37c522fee..13ab3abdb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPIWMoveTo.cpp @@ -14,7 +14,7 @@ BAPIWMoveTo::BAPIWMoveTo(const Vec3& position, BAPStatement* statement, int tag) : BAPInfoWrapper(statement, tag) { m_position = position; - m_statement->m_owner = this; + m_statement->mpOwner = this; } // ELF 0x1F78F0 (D0 0x1F7940): deletes the child. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h index 446b87e6e..c9a467dc5 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPStatement.h @@ -9,7 +9,7 @@ #include #include -#include "../AIPlanInterpreter/BotScript.h" +#include "BotScript.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "BAPTypes.h" @@ -37,8 +37,8 @@ class BAPStatement : public BotScript virtual void streamSelf(std::ostream&) const; // 0x1F8260, slot +0x1C; from the base declaration // [INFERRED] inline (no symbol): wrappers and combiners store themselves at +0x04 of their - // child statements (BAPIWIdle 0x1F7480, BAPIWMoveTo 0x1F7820). Same as writing m_owner. - void setParent(void* parent) { m_owner = parent; } + // child statements (BAPIWIdle 0x1F7480, BAPIWMoveTo 0x1F7820). Same as writing mpOwner. + void setParent(void* parent) { mpOwner = parent; } // [INFERRED] inline (no symbol): patterns compare the current plan's +0x10 with their own id to // keep it (BBPIdleInfantery::createPlan 0x28F718, BBPGotoWaypointSoldier::createPlan 0x2847DF). @@ -61,7 +61,7 @@ class BAPStatement : public BotScript explicit BAPStatement(int patternId, unsigned long long controls = 0) : m_controls(controls), m_patternId(patternId) { ++news; } - // +0x04 is BotScript::m_owner (the parent node or the behaviour). + // +0x04 is BotScript::mpOwner (the parent node or the behaviour). /* +0x08 */ unsigned long long m_controls; // = 0; getControls 0x1CDB10 returns it; actions store their // `unsigned long long` constructor argument (BAPAIdle 0x1D28B2) /* +0x10 */ int m_patternId; // trailing constructor `int`: the creating pattern's id [INFERRED] name diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp index 15f74fcbd..9ce7c7b33 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.cpp @@ -13,7 +13,7 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/AIDllFrontier.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFPhysics.h" @@ -131,7 +131,7 @@ bool BAPWrapperAiming::execute(Bot* bot, bool& ok, bool& done) // Soldier against soldier: short-range weapons aim 0.2 lower, others 0.3 lower at a standing // target. float yOffset = 0.0f; - if ((self->getObjectTypeFlags() & 0x200000u) && (target->getObjectTypeFlags() & 0x200000u)) { + if (self->isOfType(ITSoldier) && target->isOfType(ITSoldier)) { if (weapon->getMaxRange() < 10.0f) yOffset = -0.2f; else if (target->getSoldierPose() == SPStanding) @@ -157,8 +157,8 @@ bool BAPWrapperAiming::execute(Bot* bot, bool& ok, bool& done) const bool explosive = weapon->getExplosionRadius() != 0.0f && weapon->getWeaponGuidanceType() == 0; const bool explosiveShot = explosive && !weapon->getIsThrown(); - const bool vehicleAtSoldier = !(self->getObjectTypeFlags() & 0x200000u) - && (target->getObjectTypeFlags() & 0x200000u) && explosiveShot; + const bool vehicleAtSoldier = !self->isOfType(ITSoldier) + && target->isOfType(ITSoldier) && explosiveShot; const bool highAbove = bot->getSpawnKit() != 1 && !weapon->getIsThrown() && 30.0f < dy; const bool indirect = (sensed->m_flags & 2u) && ((sensed->m_flags & 8u) || vehicleAtSoldier || highAbove) && explosive; @@ -202,7 +202,7 @@ bool BAPWrapperAiming::execute(Bot* bot, bool& ok, bool& done) point.y = point.y + yOffset; } - if (explosive && !weapon->getIsThrown() && !indirect && (target->getObjectTypeFlags() & 0x200000u)) + if (explosive && !weapon->getIsThrown() && !indirect && target->isOfType(ITSoldier)) point.y = static_cast(CommonSingletonServer::m_iaiTerrain)->getHeight(point.x, point.z); if (m_aimPoint) m_aimPoint->m_value = point; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h index 65950466b..573d7fb66 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperAiming.h @@ -11,7 +11,7 @@ #include "BAPStatement.h" #include "BAPTypes.h" #include "BAPVariable.h" -#include "../AIBot/Aimer.h" +#include "Aimer.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp index 9274d784b..194102138 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPWrapperLookAt.cpp @@ -13,7 +13,7 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/AIDllFrontier.h" #include @@ -127,7 +127,7 @@ bool BAPWrapperLookAt::execute(Bot* bot, bool& ok, bool& done) rel.y = rel.y + 0.0f; } camera = &self->getControlInfo()->getCameraTransformation(); - if (self->getObjectTypeFlags() & 0x200000u) + if (self->isOfType(ITSoldier)) rel.y = distance * 0.05f + rel.y; m_lookPoint->m_value = bapinline::vec3(rel.x + camera->m[12], rel.y + camera->m[13], rel.z + camera->m[14]); if (!m_lookDirection) diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScript.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BotScript.h similarity index 89% rename from Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScript.h rename to Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BotScript.h index 78cc54cc9..2e6513bc6 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BotScript.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BotScript.h @@ -1,4 +1,5 @@ // [CHOSEN, not recovered] S0 skeleton, generated by tools/macos/ai_behaviour_skeleton.py from libaidll.so. +// Header placement: AIDLL_r.dll __FILE__ "Code/BF2//AI/AIDLL/AI/AIBotActionPlan/BotScript.h" (assert "0 == mpOwner"). // Virtual functions are in ELF vtable slot order; the vtable check (tools/macos/ai_behaviour_vtables.py) // compares them with the image. Return types marked [INFERRED] come from the ELF bodies and call sites; // the owning package verifies them. Owner: see docs/macos-ai-behaviour-plan.md (package column). @@ -27,7 +28,7 @@ class Bot; class BotScript { public: - BotScript() : m_owner(0) {} // inline in the image: every BAPStatement constructor stores +4 = 0 + BotScript() : mpOwner(0) {} // inline in the image: every BAPStatement constructor stores +4 = 0 virtual bool execute(Bot*, bool& ok, bool& finished) = 0; // no body, slot +0x00; from the base declaration virtual ~BotScript() {} // weak in the image (inline) slots +0x04/+0x08 @@ -37,7 +38,7 @@ class BotScript // BAPStatement by the combiners (child +4 = parent combiner, 0x1E64D6) and BAPFlowCIf (branches // +4 = the If, 0x1E35CD). Mixed pointee types, so untyped. [INFERRED] name; public because the // image writes it inline from several classes. [CHOSEN] visibility. - /* +0x04 */ void* m_owner; + /* +0x04 */ void* mpOwner; // name: AIDLL_r asserts 0x100EEA60, 0x1014B0C0 (+4) }; } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp index 5070e5272..984882d0e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBAvoid.cpp @@ -19,9 +19,9 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/AIDllFrontier.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" @@ -98,8 +98,8 @@ BBAvoid::~BBAvoid() // ELF 0x1FBC40 (1,201 insns). // Not updating: clears the changed flag and keeps the urgency while the pattern runs, else unInits. -// Updating: only a soldier (Information type flag 0x200000, byte +6 bit 5; [INFERRED] meaning: -// BBRevive picks its man-down targets with the same bit) with a mobile plug-in gets past the first +// Updating: only a soldier (Information::isOfType(ITSoldier), byte +6 bit 5; AIDLL_r names bit 21 +// ITSoldier in its enum switch 0x100D3010 and asserts "!targetPrimaryInfo->isOfType(ITSoldier)") with a mobile plug-in gets past the first // tests. Retail quirks kept: two `!isSoldier` blocks can never run (the flag was tested earlier; the // image reloads the same stack byte); the bot's own Information is used without a null check; so is // the chosen target's Information before insertBehaviourInformation. @@ -146,7 +146,7 @@ float BBAvoid::calculateUrgency(Bot* bot, bool update, float modifier) m_urgency[bot->getBotId()] = total; return total; } - const bool isSoldier = (self->getObjectTypeFlags() & 0x200000u) != 0; // testb $0x20, 0x6(info) + const bool isSoldier = self->isOfType(ITSoldier); // testb $0x20, 0x6(info) if (!isSoldier) { m_urgency[bot->getBotId()] = total; @@ -174,7 +174,7 @@ float BBAvoid::calculateUrgency(Bot* bot, bool update, float modifier) lookAhead *= 1.5f; // rodata 0x49CDC0 } // 0x1FC013: (flags & 0x10) != 0, plus 2; collisionPredicted never reads it. - const int predictMode = ((self->getObjectTypeFlags() & 0x10u) != 0) + 2; + const int predictMode = (self->isOfType(ITAir)) + 2; unsigned int changeTarget = bot->getChangeTarget(); Information* const changeInformation = informationManager->getInformation(changeTarget); @@ -206,7 +206,7 @@ float BBAvoid::calculateUrgency(Bot* bot, bool update, float modifier) obstaclePrimary = obstacle->getPrimaryObject(bot->getSide()); IPIPhysical* const obstaclePhysical = obstacle->getPhysical(); if (!obstaclePhysical || selfPrimary == obstaclePrimary || handle == repairTarget || handle == changeTarget - || handle == bot->getWantedRepairTarget() || (obstacle->getObjectTypeFlags() & 0x200000u) != 0) + || handle == bot->getWantedRepairTarget() || obstacle->isOfType(ITSoldier)) continue; // 0x1FC5DB: obstacle sphere centre minus own centre. @@ -241,7 +241,7 @@ float BBAvoid::calculateUrgency(Bot* bot, bool update, float modifier) bool flee = false; if (isSoldier) { - if (bailValue > obstacleHealth || (obstacle->getObjectTypeFlags() & 0x02000000u) != 0) + if (bailValue > obstacleHealth || obstacle->isOfType(ITObstacle)) { if (!activeWeapon || activeWeapon->getWeaponType() != 4) flee = true; @@ -340,7 +340,7 @@ float BBAvoid::calculateUrgency(Bot* bot, bool update, float modifier) if (bot->isOrderedBehaviour(m_index) && bot->isTakingOrders()) total *= bot->getMemory()->m_float8; - if ((self->getObjectTypeFlags() & 0x200000u) != 0) + if (self->isOfType(ITSoldier)) { // 0x1FC456: IBFTimer +0x08 minus the double at CommunicationAgent +0x60 (fsubl 0x60(%eax)), // compared with 5.0f (rodata 0x49CDAC); a recent time doubles the total. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp index a4f53024b..179bf870a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBBridgeRepair.cpp @@ -17,9 +17,9 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" @@ -148,9 +148,9 @@ float BBBridgeRepair::calculateUrgency(Bot* bot, bool update, float urgencyScale // 0x1FE508: virtual isApplicable (slot +0x34); then the soldier (0x200000) or 0x40 type flag. if (isApplicable(info, bot) && - ((info->getObjectTypeFlags() & 0x200000) || (info->getObjectTypeFlags() & 0x40))) + (info->isOfType(ITSoldier) || info->isOfType(ITGround))) { - if ((info->getObjectTypeFlags() & 0x200000) && info->getSoldierPose() == SPSwimming) + if (info->isOfType(ITSoldier) && info->getSoldierPose() == SPSwimming) { // 0x1FEBF0 m_targetChanged[botId] = true; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp index 2f16d5f12..62057be0d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBC4.cpp @@ -13,9 +13,9 @@ #include "../AIBotBehaviourPattern/BBPC4.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIStrategic/SAI.h" #include "../AIStrategicEntity/AIStrategicObject.h" #include "../AIUtils/checkPointer.h" @@ -71,7 +71,7 @@ float BBC4::calculateUrgency(Bot* bot, bool active, float) // 0x1FF36E: `testb $0x20,0x6(%esi)` - type flag 0x200000 of the equipment, then the // behaviour's own isApplicable (slot +0x34). - if (info && (info->getObjectTypeFlags() & 0x200000) && isApplicable(info, bot)) + if (info && info->isOfType(ITSoldier) && isApplicable(info, bot)) { // 0x1FF41E: the first weapon of type 4 (C4); w keeps the last lookup when none matches. std::vector& weapons = info->getArmament()->getWeapons(); @@ -87,7 +87,7 @@ float BBC4::calculateUrgency(Bot* bot, bool active, float) const Bot::C4State c4 = bot->getC4(); const Vec3 position = info->getPosition(); // slot +0x30, copied - if (c4.placed) + if (c4.isPlaced) { object = c4.object; if (c4.placementType == 0) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp index a2859121d..1ae4c2557 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBCallForMedic.cpp @@ -5,18 +5,18 @@ #include "BBCallForMedic.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBotBehaviourPattern/BBPCallForMedic.h" #include "../AIKnowledge/AIInformationGrid.h" #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" #include "../../../../Math/Vec3.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp index ba92289c8..890b095fe 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChange.cpp @@ -2,8 +2,9 @@ // nearby vehicle and seat (calculateVehicleUrgency), then initialises the BBPChange pattern with the best // one. Radio requests (message types 0 and 1) and the human player calling for a pick-up weigh in. // Recovered from libaidll.so (Linux 1.5.3153, ia-32); F-urgency package, see -// docs/macos-ai-behaviour-plan.md. Information flag bits are named by their test only: 0x10 (the -// air-vehicle tests: altitude, runway), 0x20, 0x80, 0x8000 and 0x200000 [UNRESOLVED] meanings. +// docs/macos-ai-behaviour-plan.md. Information flag bits (InformationType, AIDLL_r enum switch +// 0x100D3010): 0x10 ITAir (the air-vehicle tests: altitude, runway), 0x20 ITHelicopter, 0x40 ITGround, +// 0x80 ITNaval, 0x8000 ITMobile, 0x200000 ITSoldier. // static init: ELF 0x2038C0 (__tcf_0 0x203920, _GLOBAL__I 0x203950): 's Init object only. #include @@ -12,7 +13,7 @@ #include "VehicleUrgencyCalculator.h" #include "UrgeCurve.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBot/CommunicationAgent.h" @@ -27,9 +28,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIStrategicEntity/AIStrategicArea.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../AIStrategicMap/BFStrategicEnvironment.h" #include "../AIUtils/VehicleOccupancy.h" #include "../AIUtils/checkPointer.h" @@ -69,12 +70,11 @@ class RunwayObstructedPredicate : public IAIInformationGridPredicate { if (information == m_vehicle || information == m_other) return false; - const unsigned int flags = information->getObjectTypeFlags(); - if (!(flags & 0x8000)) + if (!information->isOfType(ITMobile)) return false; - if (flags & 0x200000) + if (information->isOfType(ITSoldier)) return false; - if (flags & 0x80) + if (information->isOfType(ITNaval)) return false; return true; } @@ -232,7 +232,7 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) m_urgency[botId] = checkBookings(bot); // ELF 0x200D88: no null test of the equipment information (retail). Information* equipmentInfo = informationManager->getInformation(equipment); - if (equipmentInfo->getObjectTypeFlags() & 0x200000) + if (equipmentInfo->isOfType(ITSoldier)) { const std::list& calls = comm->getReceivedMessages(static_cast(1)); @@ -270,11 +270,11 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) Information* equipmentInfo = informationManager->getInformation(equipment); // -0x208, no null test Vec3& pos = equipmentInfo->getPosition(); // -0x20C IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); // -0x210 - const bool isAir = (equipmentInfo->getObjectTypeFlags() & 0x200000) != 0; // -0x1FB + const bool isAir = equipmentInfo->isOfType(ITSoldier); // -0x1FB bool inArtillery = false; // -0x211 double artillerySinceStart = 0.0; // -0x198 int artillerySide = -1; // -0x190 - if (!(equipmentInfo->getObjectTypeFlags() & 0x10)) + if (!equipmentInfo->isOfType(ITAir)) { // ELF 0x202D27 if (squadManager->isInArtilleryDangerZone(pos, bot->getSide(), artillerySinceStart, artillerySide) @@ -328,7 +328,7 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) candidate = 0.0f; upsideDown = true; radioStrength = 1.0f; - if ((primaryInfo->getObjectTypeFlags() & 0x10) && !primaryInfo->getPhysical()->isInAir()) + if (primaryInfo->isOfType(ITAir) && !primaryInfo->getPhysical()->isInAir()) { // ELF 0x202BB9: a grounded air vehicle counts as upright again. radioStrength = getRadioStrength(primaryInfo, bot); @@ -396,9 +396,9 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) Information* soldierInfo = informationManager->getInformation(soldier); // -0x22C candidate = calculateVehicleUrgency(bot, soldierInfo, enemyStrengths, enemyTypes, false, equipmentInfo, fireShare, moveShare, side) * 0.2f; - if (!requests.empty() && requestValid && !(equipmentInfo->getObjectTypeFlags() & 0x200000)) + if (!requests.empty() && requestValid && !equipmentInfo->isOfType(ITSoldier)) candidate = 100.0f * requests.front().m_modifier * candidate; - if (!requests.empty() && requestValid && (equipmentInfo->getObjectTypeFlags() & 0x10)) + if (!requests.empty() && requestValid && equipmentInfo->isOfType(ITAir)) candidate = 10000.0f; // rodata 0x49F4C0 if (inArtillery) candidate = 10000.0f; @@ -446,7 +446,7 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) { requestedPrimary = currentTarget->getPrimaryObject(side); const std::list& calls = comm->getReceivedMessages(static_cast(1)); - if (!calls.empty() && (equipmentInfo->getObjectTypeFlags() & 0x200000)) + if (!calls.empty() && equipmentInfo->isOfType(ITSoldier)) { IAIPlayer* caller = liveHumanSender(calls); if (caller && caller->getCurrentVehicle()->getPrimaryObject()->getInformation(side) == requestedPrimary) @@ -455,7 +455,7 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) } unsigned int callingHandle = 0xFFFFFFFFu; // -0x238: the last scanned vehicle's caller state (retail) - if (!chooseSoldier && (requests.empty() || !requestValid) && !(equipmentInfo->getObjectTypeFlags() & 0x10) + if (!chooseSoldier && (requests.empty() || !requestValid) && !equipmentInfo->isOfType(ITAir) && !inArtillery && !bot->getSquadMember()->isCloseToNonOwnedTarget()) { // ---- ELF 0x201AF9: every vehicle around. @@ -473,16 +473,16 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) { callingHandle = 0xFFFFFFFFu; unsigned int handle = *it; // -0x1A8 (passed by reference to isMannedByEnemy) - if (!calls.empty() && (equipmentInfo->getObjectTypeFlags() & 0x200000) + if (!calls.empty() && equipmentInfo->isOfType(ITSoldier) && isCallingVehicle(*it, calls, side)) callingHandle = *it; Information* vehicle = informationManager->getInformation(handle); // -0x254 - if (!vehicle || vehicle == primaryInfoAgain || (vehicle->getObjectTypeFlags() & 0x200000)) + if (!vehicle || vehicle == primaryInfoAgain || vehicle->isOfType(ITSoldier)) continue; if (requestedByHuman && handle != requestedPrimary) continue; - if (vehicle->getObjectTypeFlags() & 0x80) + if (vehicle->isOfType(ITNaval)) { // ELF 0x201CF2: only the vehicle the calling human sits in, airborne and in water. if (calls.empty()) @@ -506,11 +506,11 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) Vec3& vehiclePos = vehicle->getPosition(); // -0x258 IPIMobile* mobile = vehicle->getMobile(); // -0x248 - if (mobile && !(vehicle->getObjectTypeFlags() & 0x10)) + if (mobile && !vehicle->isOfType(ITAir)) { // ELF 0x202570: no valid navmesh position - only the calling human's vehicle. const IPIMobile::ValidPos lastValid = mobile->getLastValidPosition(); - if (lastValid.quadTree == 0xFFFFFFFFu) + if (lastValid.island == 0xFFFFFFFFu) { if (calls.empty()) continue; @@ -524,7 +524,7 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) continue; } } - if (mobile && !(vehicle->getObjectTypeFlags() & 0x10) && !(vehicle->getObjectTypeFlags() & 0x200000) + if (mobile && !vehicle->isOfType(ITAir) && !vehicle->isOfType(ITSoldier) && isUpsideDown(vehicle, terrain, 0.7071f)) continue; @@ -574,7 +574,7 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) } } bool usable; - if (!vehicle->getMobile() || (vehicle->getObjectTypeFlags() & 0x10)) + if (!vehicle->getMobile() || vehicle->isOfType(ITAir)) usable = true; else usable = reachable; @@ -596,8 +596,7 @@ float BBChange::calculateUrgency(Bot* bot, bool evaluate, float scale) candidate *= calls.front().m_modifier; if (candidate > best) { - const unsigned int flags = vehicle->getObjectTypeFlags(); - if (!(flags & 0x10) || (flags & 0x20) || runwayClear(vehicle, equipmentInfo, side)) + if (!vehicle->isOfType(ITAir) || vehicle->isOfType(ITHelicopter) || runwayClear(vehicle, equipmentInfo, side)) { bestHandle = handle; wasCalled = callingHandle != 0xFFFFFFFFu; @@ -736,12 +735,11 @@ float BBChange::modifyForDriver(Information* vehicle, bool current) return 1.0f; if (15.0f > sincePossessed) return 1.0f; - const unsigned int flags = vehicle->getObjectTypeFlags(); - if (flags & 0x80) + if (vehicle->isOfType(ITNaval)) return 1.0f; - if (flags & 0x40) + if (vehicle->isOfType(ITGround)) return 0.77f; - if (flags & 0x10) + if (vehicle->isOfType(ITAir)) return 0.5f; return 1.0f; } @@ -783,7 +781,7 @@ bool BBChange::runwayClear(Information* aircraft, Information* other, int side) float BBChange::getRadioStrength(Information* vehicle, Bot*) const { const float strength = 1.0f; - if (vehicle->getObjectTypeFlags() & 0x200000) + if (vehicle->isOfType(ITSoldier)) return strength; return strength * strength; } @@ -819,7 +817,7 @@ bool BBChange::isBailAllowed(Bot* bot) const const Vec3& position = equipment->getPosition(); equipment->getUnit()->useNoPathfindingToGetToObject(); equipment->isPrimary(); - if (equipment->getObjectTypeFlags() & 0x10) + if (equipment->isOfType(ITAir)) { const float altitude = AerialHeightMap::m_instance->getAltitude(position); if (altitude > 2.0f && 12.0f > altitude) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp index 88d1e4408..bb740e5db 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeLandingCraft.cpp @@ -5,7 +5,7 @@ #include "BBChangeLandingCraft.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "VehicleUrgencyCalculator.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" @@ -14,7 +14,7 @@ #include "../AIBotBehaviourPattern/BBPChange.h" #include "../AIBotBehaviourPattern/BBPChangeLandingCraft.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" @@ -109,9 +109,9 @@ float BBChangeLandingCraft::calculateUrgency(Bot* bot, bool evaluate, float) const float secondaryFactor = 0.25f; if (current->isPrimary()) primary = current; - else if (!primary->getUnit()->isOccupied() && !(current->getObjectTypeFlags() & 0x80)) + else if (!primary->getUnit()->isOccupied() && !current->isOfType(ITNaval)) { - primaryFactor = (current->getObjectTypeFlags() & 0x10) ? 1.5f : 1.0f; + primaryFactor = current->isOfType(ITAir) ? 1.5f : 1.0f; currentFactor = 0.25f; } const bool currentIsPrimary = current == primary; @@ -134,7 +134,7 @@ float BBChangeLandingCraft::calculateUrgency(Bot* bot, bool evaluate, float) if (candidate == primary && !primaryUnit->isOccupied() && primaryMobile) { const IPIMobile::ValidPos valid = primaryMobile->getLastValidPosition(); - if (valid.quadTree == 0xFFFFFFFFu) + if (valid.island == 0xFFFFFFFFu) { urgency = 0.0f; invalidPosition = true; } else urgency += 100.0f; } @@ -148,7 +148,7 @@ float BBChangeLandingCraft::calculateUrgency(Bot* bot, bool evaluate, float) } bool disembark = false; - const bool air = (primary->getObjectTypeFlags() & 0x10) != 0; + const bool air = primary->isOfType(ITAir); const Vec3& position = current->getPosition(); bool canDisembark = false; if (air) @@ -194,7 +194,7 @@ float BBChangeLandingCraft::calculateUrgency(Bot* bot, bool evaluate, float) } } } - if (!air && !(primary->getObjectTypeFlags() & 0x200000)) + if (!air && !primary->isOfType(ITSoldier)) { Vec3 normal = {0.0f, 0.0f, 0.0f}; IAITerrain* terrain = static_cast(CommonSingletonServer::m_iaiTerrain); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp index 843a50d85..56780e70c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBChangeTeleport.cpp @@ -6,12 +6,12 @@ #include "BBChangeTeleport.h" #include "VehicleUrgencyCalculator.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBotBehaviourPattern/BBPChangeTeleport.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIStrategicMap/BFStrategicEnvironment.h" #include "../Main/CommonSingletonServer.h" @@ -117,20 +117,19 @@ float BBChangeTeleport::calculateUrgency(Bot* bot, bool evaluate, float) } else { - const unsigned int flags = equipment->getObjectTypeFlags(); - if (flags & 0x80) + if (equipment->isOfType(ITNaval)) { currentModifier = 0.5f; secondaryModifier = 0.65f; primaryModifier = 1.0f; } - else if (flags & 0x40) + else if (equipment->isOfType(ITGround)) { currentModifier = 0.5f; secondaryModifier = 0.7f; primaryModifier = 1.0f; } - else if (flags & 0x10) + else if (equipment->isOfType(ITAir)) { currentModifier = secondaryModifier = 0.5f; primaryModifier = 1.5f; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp index 962cb476f..e5516cc0b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBDefuseMines.cpp @@ -16,11 +16,11 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIUtils/checkPointer.h" -#include "../Main/AIMineManager.h" +#include "../AIKnowledge/AIMineManager.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" @@ -117,9 +117,9 @@ float BBDefuseMines::calculateUrgency(Bot* bot, bool update, float urgencyScale) // 0x206AC4: virtual isApplicable (slot +0x34); then the soldier (0x200000) or 0x40 type flag. if (isApplicable(info, bot) && - ((info->getObjectTypeFlags() & 0x200000) || (info->getObjectTypeFlags() & 0x40))) + (info->isOfType(ITSoldier) || info->isOfType(ITGround))) { - if ((info->getObjectTypeFlags() & 0x200000) && info->getSoldierPose() == SPSwimming) + if (info->isOfType(ITSoldier) && info->getSoldierPose() == SPSwimming) { // 0x207255 m_targetChanged[botId] = true; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp index b257b0b14..bfece1b02 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire.cpp @@ -6,20 +6,20 @@ #include "BBFire.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBotBehaviourPattern/BBPFire.h" #include "../AIBot/BotMemory.h" #include "../AIBot/SensedObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIStrategic/SAI.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" @@ -161,8 +161,7 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) const int side = bot->getSide(); Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); const Vec3& position = equipment->getPosition(); - const unsigned int flags = equipment->getObjectTypeFlags(); - if (!(flags & 0x80) && !(flags & 0x10) && (flags & 0x200000)) + if (!equipment->isOfType(ITNaval) && !equipment->isOfType(ITAir) && equipment->isOfType(ITSoldier)) { // 0x209FE0: a passenger seat whose soldier pose is 4 does not fire. if (equipment->isPrimary() && equipment->getSoldierPose() == 4) @@ -236,8 +235,7 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) IPIPhysical* const targetPhysical = info->getPhysical(); if (!targetPhysical) continue; - const unsigned int targetFlags = info->getObjectTypeFlags(); - if ((targetFlags & 0x20000) || (targetFlags & 0x100000) || (targetFlags & 0x800000)) + if (info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) || info->isOfType(ITNoTemperature)) continue; if (0.0f >= targetPhysical->getHealth()) // 0x208B46 jae: a NaN health is kept continue; @@ -272,7 +270,7 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) ramp = 1.0f; attackFactor = 1.5f - ramp * 0.5f; if (!IBotManager::instance->getBotFromPlayerId(info->getPlayerId()) - && (info->getObjectTypeFlags() & 0x200000)) + && info->isOfType(ITSoldier)) attackFactor = attackFactor * 3.0f; } else @@ -320,7 +318,7 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) if (targetUnit->getEquipmentType() != equipmentType) { unsigned char material; - pathfinding->getMaterial(mobile->getVehicleNumber(), valid.quadTree, valid.polygon, material); + pathfinding->getMaterial(mobile->getVehicleNumber(), valid.island, valid.polygon, material); if (!settings()->isValidMaterial(equipmentType, material)) continue; } @@ -348,8 +346,7 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) + transformation.m[9] * local.z + transformation.m[13]; seen.z = local.x * transformation.m[2] + local.y * transformation.m[6] + local.z * transformation.m[10] + transformation.m[14]; - const unsigned int ownFlags = equipment->getObjectTypeFlags(); - if (!(ownFlags & 0x10) || (ownFlags & 0x20)) + if (!equipment->isOfType(ITAir) || equipment->isOfType(ITHelicopter)) { if (!controlInfo->validateCameraDirectionByPos(seen)) continue; @@ -419,13 +416,13 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) + targetSpeed.z * targetSpeed.z); float targetAreaFactor = areaFactor; // -0x1A0 - if (mobile && !(equipment->getObjectTypeFlags() & 0x10) && area && !area->isInside(targetPosition)) + if (mobile && !equipment->isOfType(ITAir) && area && !area->isInside(targetPosition)) targetAreaFactor = targetAreaFactor * 0.85f; // 0x209247: the approach factor (-0x258). float approachFactor; bool closing = true; // falls through to the closing-speed estimate below - if (info->getObjectTypeFlags() & 0x10) + if (info->isOfType(ITAir)) { // 0x209C55: an aircraft target. const int antiAircraft = armament->isAntiAircraft(); @@ -518,7 +515,7 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) if (targetUnit->getEquipmentType() != equipmentType) { unsigned char material; - pathfinding->getMaterial(mobile->getVehicleNumber(), valid.quadTree, valid.polygon, material); + pathfinding->getMaterial(mobile->getVehicleNumber(), valid.island, valid.polygon, material); if (!settings()->isValidMaterial(equipmentType, material)) continue; } @@ -571,7 +568,7 @@ float BBFire::calculateUrgency(Bot* bot, bool recalculate, float modifier) else strength = std::max(partUnit->getBattleStrengths()[strengthType], partUnit->getBattleStrengths()[soldierStrengthType]); - if (!(info->getObjectTypeFlags() & 0x200000)) + if (!info->isOfType(ITSoldier)) strength = strength * enemyStrengthTweak; score = (strength + part->getStrength() + unit->getBattleStrengths()[targetStrengthType]) * armourClassValues[targetStrengthType] * orderFactor * targetAreaFactor @@ -709,7 +706,7 @@ int BBFire::chooseWeapon(Bot* bot, unsigned int target, float distance) static bool allowMultipleC4 = false; // .bss; nothing in the image writes it Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); - const bool ownIsSoldier = (equipment->getObjectTypeFlags() & 0x200000) != 0; + const bool ownIsSoldier = equipment->isOfType(ITSoldier); IPIArmament* const armament = equipment->getArmament(); static_cast(bot)->setUseStaticAttack(false); const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); @@ -719,7 +716,7 @@ int BBFire::chooseWeapon(Bot* bot, unsigned int target, float distance) Information* const targetInfo = informationManager->getInformation(target); if (!targetInfo) return -1; - const bool targetIsSoldier = (targetInfo->getObjectTypeFlags() & 0x200000) != 0; + const bool targetIsSoldier = targetInfo->isOfType(ITSoldier); IPIPhysical* const targetPhysical = targetInfo->getPhysical(); IPIMobile* const targetMobile = targetInfo->getMobile(); if (!targetPhysical) @@ -795,7 +792,7 @@ int BBFire::chooseWeapon(Bot* bot, unsigned int target, float distance) bool closeQuarters = false; // -0x1B1 bool meleeAttack = false; // -0x1B2 bool splash = false; // -0x1C8: a vehicle's explosive weapon against a soldier - if (!ownIsSoldier && (targetInfo->getObjectTypeFlags() & 0x200000)) + if (!ownIsSoldier && targetInfo->isOfType(ITSoldier)) { if (weapon->getWeaponGuidanceType() == 0 && weapon->getExplosionRadius() != 0.0f) splash = true; @@ -885,7 +882,7 @@ int BBFire::chooseWeapon(Bot* bot, unsigned int target, float distance) return static_cast(i); } - if ((ownIsSoldier || splash) && (targetInfo->getObjectTypeFlags() & 0x200000) + if ((ownIsSoldier || splash) && targetInfo->isOfType(ITSoldier) && weapon->getWeaponGuidanceType() == 0 && weapon->getExplosionRadius() != 0.0f) { // 0x20ABCC: splash damage, unless the bot or the target is at the flag the bot goes for. diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp index 50d7ecce1..a692ef3a3 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFire3d.cpp @@ -5,21 +5,21 @@ #include "BBFire3d.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBot/SensedObject.h" #include "../AIBotBehaviourPattern/BBPFire.h" #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIStrategic/SAI.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObject.h" @@ -164,7 +164,7 @@ float BBFire3d::calculateUrgency(Bot* bot, bool recalculate, float modifier) if (!info) continue; Bot* const other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); - if (other && (info->getObjectTypeFlags() & 0x10)) + if (other && info->isOfType(ITAir)) { Information* const otherTarget = informationManager->getInformation(other->getFiringTarget()); if (otherTarget && otherTarget->getPlayerId() == bot->getPlayerId()) @@ -203,7 +203,7 @@ float BBFire3d::calculateUrgency(Bot* bot, bool recalculate, float modifier) if (!info) continue; Bot* const other = IBotManager::instance->getBotFromPlayerId(info->getPlayerId()); - if (other && (info->getObjectTypeFlags() & 0x10)) + if (other && info->isOfType(ITAir)) { Information* const otherTarget = informationManager->getInformation(other->getFiringTarget()); if (otherTarget && otherTarget->getPlayerId() == bot->getPlayerId()) @@ -319,8 +319,8 @@ float BBFire3d::updateUrgencyWithTarget(unsigned int target, Information* info, return 0.0f; Information* const primary = informationManager->getInformation(info->getPrimaryObject(bot->getSide())); IPIPhysical* const physical = info->getPhysical(); - if (!physical || (info->getObjectTypeFlags() & 0x20000) || (info->getObjectTypeFlags() & 0x100000) - || (info->getObjectTypeFlags() & 0x800000) || 0.0f >= physical->getHealth()) + if (!physical || info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) + || info->isOfType(ITNoTemperature) || 0.0f >= physical->getHealth()) return 0.0f; float attackFactor = 1.0f; @@ -403,7 +403,7 @@ float BBFire3d::updateUrgencyWithTarget(unsigned int target, Information* info, bool calculateApproach = true; float approachFactor = 1.0f; - if (primary->getObjectTypeFlags() & 0x10) + if (primary->isOfType(ITAir)) { if (armament->isAntiAircraft() == 0) { @@ -415,7 +415,7 @@ float BBFire3d::updateUrgencyWithTarget(unsigned int target, Information* info, calculateApproach = false; } } - else if (!(equipment->getObjectTypeFlags() & 0x10) && maxRange * 0.9f > distance) + else if (!equipment->isOfType(ITAir) && maxRange * 0.9f > distance) { calculateApproach = false; } @@ -464,7 +464,7 @@ float BBFire3d::updateUrgencyWithTarget(unsigned int target, Information* info, } float targetAreaFactor = areaFactor; - if (mobile && !(equipment->getObjectTypeFlags() & 0x10) && area + if (mobile && !equipment->isOfType(ITAir) && area && !static_cast(area)->isInside(targetPosition)) targetAreaFactor = targetAreaFactor * 0.75f; if (!info->getUnit() || !vehicleOccupied(target, bot->getSide())) @@ -504,7 +504,7 @@ float BBFire3d::updateUrgencyWithTarget(unsigned int target, Information* info, while (part); float rangeFactor; - if (primary->getObjectTypeFlags() & 0x10) + if (primary->isOfType(ITAir)) { rangeFactor = 1.0f - distance / (maxRange * 1.5f); if (!(rangeFactor > 0.0f)) diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp index 527a6912a..6ba2d65b3 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireArtilleryDriver.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotBehaviourPattern/BBPFire.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIUtils/checkPointer.h" #include "../Main/AISettingsInterfaces.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp index 09e810097..65ce5fd4e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireLargeBore.cpp @@ -5,7 +5,7 @@ #include "BBFireLargeBore.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBot/SensedObject.h" @@ -13,14 +13,14 @@ #include "../AIBotBehaviourPattern/BBPFire2d.h" #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIStrategic/SAI.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" @@ -203,7 +203,7 @@ float BBFireLargeBore::calculateUrgency(Bot* bot, bool recalculate, float modifi targetSpeed = targetMobile->getSpeed(); const float speed = std::sqrt(targetSpeed.x * targetSpeed.x + targetSpeed.y * targetSpeed.y + targetSpeed.z * targetSpeed.z); - if (!(equipment->getObjectTypeFlags() & 0x10) && (info->getObjectTypeFlags() & 0x10)) + if (!equipment->isOfType(ITAir) && info->isOfType(ITAir)) { if (armament->isAntiAircraft() == 0) { @@ -297,8 +297,8 @@ float BBFireLargeBore::calculateUrgency(Bot* bot, bool recalculate, float modifi if (!info || info->getSide() == side) continue; IPIPhysical* const targetPhysical = info->getPhysical(); - if (!targetPhysical || (info->getObjectTypeFlags() & 0x20000) || (info->getObjectTypeFlags() & 0x100000) - || (info->getObjectTypeFlags() & 0x800000) || 0.0f >= targetPhysical->getHealth()) + if (!targetPhysical || info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) + || info->isOfType(ITNoTemperature) || 0.0f >= targetPhysical->getHealth()) continue; if ((object->m_flags & 0x20) && object->m_fireRating < 0) continue; @@ -468,8 +468,8 @@ float BBFireLargeBore::calculateUrgency(Bot* bot, bool recalculate, float modifi if (!info || info->getSide() == side) continue; IPIPhysical* const targetPhysical = info->getPhysical(); - if (!targetPhysical || (info->getObjectTypeFlags() & 0x20000) || (info->getObjectTypeFlags() & 0x100000) - || (info->getObjectTypeFlags() & 0x800000) || 0.0f >= targetPhysical->getHealth()) + if (!targetPhysical || info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) + || info->isOfType(ITNoTemperature) || 0.0f >= targetPhysical->getHealth()) continue; if (20.0 > now - getBBPFeedback(*it)->m_time) continue; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp index d828338eb..3b585531c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBFireUnarmed.cpp @@ -14,13 +14,13 @@ #include "../Main/AISettingsInterfaces.h" #include "../AIUtils/checkPointer.h" #include "../../../../Math/Vec3.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBot/SensedObject.h" #include "../AIKnowledge/FireObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" @@ -141,8 +141,7 @@ float BBFireUnarmed::calculateUrgency(Bot* bot, bool evaluate, float modifier) Information* const info = informationManager->getInformation(object->m_handle); if (!info || info->getSide() == side || !info->getPhysical()) continue; - const unsigned int typeFlags = info->getObjectTypeFlags(); - if ((typeFlags & 0x20000) || (typeFlags & 0x100000) || (typeFlags & 0x800000)) + if (info->isOfType(ITLowPriority) || info->isOfType(ITVegetation) || info->isOfType(ITNoTemperature)) continue; if (!(info->getPhysical()->getHealth() > 0.0f)) continue; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp index 34c11f044..5c20c30e5 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBIdle.cpp @@ -16,7 +16,7 @@ #include "../AIBotBehaviourPattern/BBPIdle3d.h" #include "../AIBotBehaviourPattern/BBPIdleInfantery.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../Main/AIDllFrontier.h" @@ -42,11 +42,9 @@ IAISettings* settings() return static_cast(CommonSingletonServer::m_iaiSettings); } -// Information::m_objectTypeFlags bits read here ([UNRESOLVED] names): 0x10 and 0x20 select the -// larger pickup radius, 0x200000 marks an object that can carry passengers (the pickup vehicle). -const unsigned int kTypeFlag10 = 0x10; -const unsigned int kTypeFlag20 = 0x20; -const unsigned int kTypeFlagCarrier = 0x200000; +// Object-type tests use Information::isOfType (InformationType bits; AIDLL_r enum switch 0x100D3010): +// ITAir and ITHelicopter select the larger pickup radius; ITSoldier marks a soldier (a requester on +// foot, whose "vehicle" is the soldier itself); the bot's own equipment must not be one to give a lift. // The sender id that means "anyone" in a pickup request; a real one makes the request personal. const int kAnySender = 0xFF; @@ -116,12 +114,12 @@ float BBIdle::calculateUrgency(Bot* bot, bool, float modifier) float urgency = modifier; int pickupPlayerId = -1; - if (info->isPrimary() && !(info->getObjectTypeFlags() & kTypeFlagCarrier) && mobile) + if (info->isPrimary() && !info->isOfType(ITSoldier) && mobile) { bool moving = false; if (bot->isAirBorn()) moving = true; - else if ((info->getObjectTypeFlags() & kTypeFlag10) && mobile->getSpeedMagnitude() > 3.0f) + else if (info->isOfType(ITAir) && mobile->getSpeedMagnitude() > 3.0f) moving = true; IPIPhysical* const physical = info->getPhysical(); @@ -262,7 +260,7 @@ void BBIdle::waitForPickup(Bot* bot, unsigned int equipment, Information* equipm if (pickupPlayerId >= 0 && !fromAnyone) continue; - if (equipmentInfo->getObjectTypeFlags() & kTypeFlagCarrier) + if (equipmentInfo->isOfType(ITSoldier)) continue; // 0x21584E: `cmpl 0x5C(agent), primaryPlayerId` (CommunicationAgent +0x5C). if (senderAgent && bbpending::communicationAgentInt92(senderAgent) != primaryPlayerId) @@ -278,12 +276,11 @@ void BBIdle::waitForPickup(Bot* bot, unsigned int equipment, Information* equipm Information* const vehicleInfo = informationManager->getInformation(vehicle->getHandle(bot->getSide())); if (!vehicleInfo) continue; - if (!(vehicleInfo->getObjectTypeFlags() & kTypeFlagCarrier)) + if (!vehicleInfo->isOfType(ITSoldier)) continue; - const unsigned int flags = equipmentInfo->getObjectTypeFlags(); float maxDistanceSqr; - if ((flags & kTypeFlag20) || (flags & kTypeFlag10) || fromAnyone) + if (equipmentInfo->isOfType(ITHelicopter) || equipmentInfo->isOfType(ITAir) || fromAnyone) maxDistanceSqr = 2500.0f; else maxDistanceSqr = 625.0f; @@ -316,9 +313,9 @@ void BBIdle::waitForPickup(Bot* bot, unsigned int equipment, Information* equipm if (!m_waitingForPickup[bot->getBotId()] || m_waitStartTime[bot->getBotId()] == 0.0) m_waitStartTime[bot->getBotId()] = now; const double waited = now - m_waitStartTime[bot->getBotId()]; - if (!(vehicleInfo->getObjectTypeFlags() & kTypeFlagCarrier) || primary != equipmentInfo) + if (!vehicleInfo->isOfType(ITSoldier) || primary != equipmentInfo) continue; - if (!equipmentInfo->getMobile() || (equipmentInfo->getObjectTypeFlags() & kTypeFlagCarrier) || moving) + if (!equipmentInfo->getMobile() || equipmentInfo->isOfType(ITSoldier) || moving) continue; if (!(waited < 10.0)) continue; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp index 471bbb2f3..92fd6c3c0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMedicAssist.cpp @@ -16,7 +16,7 @@ #include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) #include "BBMedicAssist.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBot/CommunicationAgent.h" @@ -30,9 +30,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" #include "../Main/AISettingsInterfaces.h" @@ -305,7 +305,7 @@ float BBMedicAssist::calculateUrgency(Bot* bot, bool recalculate, float urgencyS if (info == self && bot->getPlayer()->getSpawnKit() == 5 && bot->isFiring()) continue; // Object-type flag 0x80 (testb $-0x80, +0x04): only when a human is in it. - if ((info->getObjectTypeFlags() & 0x80) && !isHumanInTarget(info, bot->getSide())) + if (info->isOfType(ITNaval) && !isHumanInTarget(info, bot->getSide())) continue; if (info == self && bot->getPlayer()->getSpawnKit() == 5 && armament->getActiveWeapon() != -1) { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp index d6c09d9e7..cf6b0726b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveTo.cpp @@ -16,7 +16,7 @@ #include "../AIBot/WaypointList.h" #include "../AIBotBehaviourPattern/BBPGotoWaypoint.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/AIDllFrontier.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp index cff3c7f82..3bbfb682d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBMoveToFixed.cpp @@ -15,7 +15,7 @@ #include "../AIBot/BotMemory.h" #include "../AIBot/WaypointList.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/AIMain.h" #include diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp index 83e86c53c..0fb7a74ee 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRandom.cpp @@ -12,7 +12,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotBehaviourPattern/BBPRandom.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIUtils/checkPointer.h" #include "../AIBot/BotNavigation.h" #include "../Main/AISettingsInterfaces.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp index 42f584a82..183e879ba 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRevive.cpp @@ -10,7 +10,7 @@ #include "../AIBot/SquadManager.h" // requestResponseModifier (ai-bot) #include "BBRevive.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBotBehaviourPattern/BBPRevive.h" @@ -20,9 +20,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" #include "../Main/AISettingsInterfaces.h" @@ -163,7 +163,7 @@ float BBRevive::calculateUrgency(Bot* bot, bool update, float modifier) if (!unit) continue; IPIPhysical* const physical = unit->getPhysical(); - if (!physical || unit == self || !unit->hasMobile() || (unit->getObjectTypeFlags() & 0x200000u) == 0) + if (!physical || unit == self || !unit->hasMobile() || !unit->isOfType(ITSoldier)) continue; if (!physical->getManDown()) // IPIPhysical +0x5C continue; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp index ca59b9496..9e210bca5 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBRunOverSoldier.cpp @@ -16,7 +16,7 @@ #include "../AIBot/SensedObject.h" #include "../AIBotBehaviourPattern/BBPRunOverSoldier.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" @@ -91,7 +91,7 @@ float BBRunOverSoldier::calculateUrgency(Bot* bot, bool recalculate, float) || (flags & SensedObject::SENSE_INDIRECT)) continue; Information* const info = informationManager->getInformation(it->second->m_handle); - if (!info || !(info->getObjectTypeFlags() & 0x200000)) + if (!info || !info->isOfType(ITSoldier)) continue; if (info->getSide() == bot->getSide() || info->getSide() == 0) continue; @@ -122,7 +122,7 @@ float BBRunOverSoldier::calculateUrgency(Bot* bot, bool recalculate, float) if (distance > maxDistance) continue; const IPIMobile::ValidPos& targetValid = targetMobile->getLastValidPosition(mobile->getVehicleNumber()); - if (targetValid.quadTree == static_cast(-1) || targetValid.polygon == static_cast(-1)) + if (targetValid.island == static_cast(-1) || targetValid.polygon == static_cast(-1)) continue; const IPIMobile::ValidPos& valid = mobile->getLastValidPosition(); IAIPathfinding* const pathfinding = IAIPathfinding::instance; @@ -131,7 +131,7 @@ float BBRunOverSoldier::calculateUrgency(Bot* bot, bool recalculate, float) end.y = 0.0f; end.z = 0.0f; unsigned int endPolygon; - if (pathfinding->trace(valid.polygon, valid.quadTree, mobile->getVehicleNumber(), valid.position, + if (pathfinding->trace(valid.polygon, valid.island, mobile->getVehicleNumber(), valid.position, targetValid.position, end, endPolygon, equipmentType, -1, 0.0f, 5, 0)) { m_targets[bot->getBotId()] = it->first; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp index a545422b4..3bf75b45a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBSuicide.cpp @@ -8,7 +8,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotBehaviourPattern/BBPSuicide.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp index 1503f53e3..9c8a232aa 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover.cpp @@ -5,7 +5,7 @@ #include "BBTakeCover.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBotBehaviourPattern/BBPTakeCover.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp index 313a1d087..f46c8062b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCover3d.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMemory.h" #include "../AIBotBehaviourPattern/BBPTakeCover3d.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp index 5cc2a0fc9..8ef138536 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BBTakeCoverInfantry.cpp @@ -1,7 +1,7 @@ // Infantry cover selection and per-quadrant threat bookkeeping. #include "BBTakeCoverInfantry.h" -#include "CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIBot/BotMain.h" #include "../AIBot/BotMemory.h" #include "../AIBot/SensedObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp index 73f501c36..655d2cc40 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBot/SensingAgent.h" #include "../AIBotBehaviourPattern/PlanGenerator.h" -#include "../AIPlanInterpreter/BotScript.h" +#include "../AIBotActionPlan/BotScript.h" #include "../AIUtils/checkPointer.h" #include "../Main/AIDllFrontier.h" @@ -151,15 +151,15 @@ BotScript* BotBehaviour::generatePlan(Bot* bot) } if (bot->getPlan() != 0) - bot->getPlan()->m_owner = m_pattern; + bot->getPlan()->mpOwner = m_pattern; BotScript* plan = m_pattern->createPlan(bot); if (plan != 0) { - plan->m_owner = this; + plan->mpOwner = this; if (bot->getPlan() != 0 && bot->getPlan() != plan) { - bot->getPlan()->m_owner = this; + bot->getPlan()->mpOwner = this; bot->getSensingAgent()->setSensedNewObject(); } } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h index b293943e7..07f9a8adc 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h @@ -5,7 +5,7 @@ #ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H #define AI_AIDLL_AI_AIBOTBEHAVIOUR_BOTBEHAVIOUR_H -#include "UrgencyMerger.h" +#include "../AIBot/UrgencyMerger.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp index f2f911011..dad79df7b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/VehicleUrgencyCalculator.cpp @@ -21,14 +21,14 @@ #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/FireObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIStrategic/SAI.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" @@ -572,8 +572,7 @@ bool closeAndShouldAvoidVehiclesImpl(Information* vehicle, int side, Bot* bot) { bool avoid = false; Information* const primary = infoOf(vehicle->getPrimaryObject(side)); - const unsigned int flags = primary->getObjectTypeFlags(); - if ((flags & 0x200000u) || (flags & 0x10u) || (flags & 0x20u)) + if (primary->isOfType(ITSoldier) || primary->isOfType(ITAir) || primary->isOfType(ITHelicopter)) return false; IPIMobile* const mobile = primary->getMobile(); AIStrategicArea* const area = bot->getSquadMember()->getSquad()->getSquadStrategicAreaAssignment(); @@ -644,7 +643,7 @@ float calculateVehicleUrgency(Bot* bot, Information* vehicle, const float* stren IPIUnit* const unit = vehicle->getUnit(); if (vehicle->isBooked() && !vehicle->isBookedBy(bot->getPlayerId())) return 0.0f; - if (vehicle != current && (vehicle->getObjectTypeFlags() & 0x10u) == 0) + if (vehicle != current && !vehicle->isOfType(ITAir)) { if (8.0f < static_cast(CommonSingletonServer::m_iaiTerrain) ->getAltitude(vehicle->getPosition())) @@ -659,10 +658,10 @@ float calculateVehicleUrgency(Bot* bot, Information* vehicle, const float* stren urgency = vehicle->getStrength() * 4.0f + urgency; const float health = physical->getHealth(); float bail = IBotManager::instance->getVehicleBailValue(); - if ((vehicle->getObjectTypeFlags() & 0x200000u) == 0 && vehicle->isPrimary() + if (!vehicle->isOfType(ITSoldier) && vehicle->isPrimary() && vehicle->getHandle() == current->getHandle()) bail = bail * 0.3f; - if (!(bail <= health) && (vehicle->getObjectTypeFlags() & 0x200000u) == 0) + if (!(bail <= health) && !vehicle->isOfType(ITSoldier)) return 0.0f; urgency = urgency * health; const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp index a1e69e556..ba6079a9d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision2d.cpp @@ -16,7 +16,7 @@ #include "../AIBotActionPlan/BAPConPosition.h" #include "../AIBotActionPlan/BAPConTime.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" @@ -162,7 +162,7 @@ BotScript* BBPAvoidCollision2d::createPlan(Bot* bot) const float speed = mobile->getMaxSpeed(); BAPAMoveToDirect* move = checkPointer(new BAPAMoveToDirect(bot, target, speed, arriveSpeed, stop, driveControls, m_id)); BAPAHonkHorn* horn = 0; - if (self->getObjectTypeFlags() & 0x04000000u) + if (self->isOfType(ITHasCarHorn)) { const int obstacleSide = obstacle->getSide(); const int ownSide = self->getSide(); @@ -173,7 +173,7 @@ BotScript* BBPAvoidCollision2d::createPlan(Bot* bot) if (horn) serial->addStatement(horn); serial->addStatement(move); - serial->m_owner = this; + serial->mpOwner = this; return serial; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp index 7e41344e1..3b39fbe59 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollision3d.cpp @@ -19,7 +19,7 @@ #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -174,7 +174,7 @@ BotScript* BBPAvoidCollision3d::createPlan(Bot* bot) maxSpeed *= 0.3f; BAPAMoveTo3d* const move = checkPointer(new BAPAMoveTo3d(bot, destination, maxSpeed, maxSpeed, stop, controls, 30.0f, m_id)); - move->setParent(this); // +0x04 (BotScript::m_owner) + move->setParent(this); // +0x04 (BotScript::mpOwner) return move; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp index 1ac213a12..7a2eb5938 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPAvoidCollisionInfantery.cpp @@ -22,7 +22,7 @@ #include "../AIBotActionPlan/BAPConTime.h" #include "../AIBotActionPlan/BAPICTurnLock.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIUnit.h" @@ -243,7 +243,7 @@ BotScript* BBPAvoidCollisionInfantery::createPlan(Bot* bot) parallel->addStatement(checkPointer(new BAPAMergeSoldierInputs(m_id))); serial->addStatement(parallel); serial->addStatement(checkPointer(new BAPICTurnLock(false))); - serial->setParent(this); // +0x04 (BotScript::m_owner) + serial->setParent(this); // +0x04 (BotScript::mpOwner) return serial; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp index d6fdd3798..d9fcaf7e7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPBridgeRepair.cpp @@ -32,9 +32,9 @@ #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -142,7 +142,7 @@ BotScript* BBPBridgeRepair::createPlan(Bot* bot) BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); sequence->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_unknown8))); BAPStatement* last; - if (!(self->getObjectTypeFlags() & 0x200000)) { + if (!self->isOfType(ITSoldier)) { BAPCombinerSerial* const leave = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); BAPConFalse* const stop = checkPointer(new BAPConFalse()); BAPConTrue* const start = checkPointer(new BAPConTrue()); @@ -201,7 +201,7 @@ BotScript* BBPBridgeRepair::createPlan(Bot* bot) bot->getSquadMember()->setCurrentRequestAction(2, requestHandle); BAPIWFire* const wrapper = checkPointer(new BAPIWFire(bot, m_segment[bot->getBotId()], true, false, weaponIndex, -1, root, m_unknown8)); - wrapper->m_owner = this; + wrapper->mpOwner = this; static_cast(bot)->resetAllControls(true, true, true); return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp index 315982aba..05fe87e5c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPC4.cpp @@ -21,10 +21,10 @@ #include "../AIBotActionPlan/BAPIWFire.h" #include "../AIBotActionPlan/BAPVariable.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -153,7 +153,7 @@ BotScript* BBPC4::createPlan(Bot* bot) // 0x232FE2 BAPIWFire* const root = checkPointer(new BAPIWFire(bot, 0xFFFFFFFFu, true, false, 4, -1, serial, m_id)); - root->setParent(this); // +0x04 (BotScript::m_owner) + root->setParent(this); // +0x04 (BotScript::mpOwner) static_cast(bot)->resetAllControls(true, true, true); return root; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp index 6f2538b28..2b6f2994c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPCallForMedic.cpp @@ -59,7 +59,7 @@ BotScript* BBPCallForMedic::createPlan(Bot* bot) bot->getScriptContext()->clear(); BAPASendRadioMessage* const plan = checkPointer(new BAPASendRadioMessage(static_cast(3), static_cast(0), 5, 0.0f, m_patternId, -1)); - plan->m_owner = this; + plan->mpOwner = this; return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp index 58c8466c6..6e09d73fa 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.cpp @@ -45,7 +45,7 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../Main/IBotManager.h" @@ -67,7 +67,7 @@ namespace ai { // uninitialised), then +0x08 = the argument and +0x0C unsigned int (uninitialised). BBPChange::BBPChange(int value) { - m_entryPositions = checkPointer( + m_noPathfindingPos = checkPointer( new Vec3[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]()); m_sameVehicle = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); m_getInConfirm = checkPointer(new bool[static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots()]); @@ -83,8 +83,8 @@ BBPChange::~BBPChange() delete[] m_targets; if (m_sameVehicle) delete[] m_sameVehicle; - if (m_entryPositions) - delete[] m_entryPositions; + if (m_noPathfindingPos) + delete[] m_noPathfindingPos; if (m_getInConfirm) delete[] m_getInConfirm; } @@ -177,7 +177,7 @@ BotScript* BBPChange::createPlan(Bot* bot) bot->getSquadMember()->clearRequestAction(); BAPStatement* plan; // the node the tail wraps - if (!(current->getObjectTypeFlags() & 0x200000)) { + if (!current->isOfType(ITSoldier)) { // 0x236D12 `testb $0x20, 0x6(%esi)`: the bot sits in a vehicle or stationary weapon. BAPCombinerSerial* const sequence = checkPointer(new BAPCombinerSerial(m_patternId, -1)); // -0x1B0 // Getting out to the bot's own soldier: confirm a pending type-0 message with 6 on channel 7. @@ -226,7 +226,7 @@ BotScript* BBPChange::createPlan(Bot* bot) BAPAction* move; if (toEntryPosition) { - if (!(current->getObjectTypeFlags() & 0x10)) { + if (!current->isOfType(ITAir)) { // 0x239CF0 BAPConAnd* const arrivedBehind = checkPointer(new BAPConAnd()); arrivedBehind->addCondition(arrived); @@ -235,7 +235,7 @@ BotScript* BBPChange::createPlan(Bot* bot) const int patternId = m_patternId; const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; const float speed = mobile->getMaxSpeed(); - move = checkPointer(new BAPAMoveToFinding(bot, m_entryPositions[bot->getBotId()], speed, arriveSpeed, + move = checkPointer(new BAPAMoveToFinding(bot, m_noPathfindingPos[bot->getBotId()], speed, arriveSpeed, arrivedBehind, driveControls, patternId, 0.0f, 0.0f)); } else { // 0x239B40: flag 0x10 (air): 3d move to the target's position. @@ -245,11 +245,10 @@ BotScript* BBPChange::createPlan(Bot* bot) move = checkPointer(new BAPAMoveTo3d(bot, target->getPosition(), speed, arriveSpeed, arrived, driveControls, 25.0f, patternId)); } - } else if (!(current->getObjectTypeFlags() & 0x10)) { + } else if (!current->isOfType(ITAir)) { bool aroundAircraft = false; Vec3 position; - const unsigned int targetFlags = target->getObjectTypeFlags(); - if ((targetFlags & 0x10) && !(targetFlags & 0x20)) { + if (target->isOfType(ITAir) && !target->isOfType(ITHelicopter)) { // 0x239064: the target is an aircraft (0x10 without 0x20): a navigable point behind // or beside it. position = target->getPosition(); @@ -303,8 +302,8 @@ BotScript* BBPChange::createPlan(Bot* bot) // 0x237C66: getting out to the soldier from the primary seat of a ground vehicle whose health // (IPIPhysical vfn +0x14) is below IBotManager::getVehicleBailValue: also press input 0x2F // (controls bit 47). - if ((target->getObjectTypeFlags() & 0x200000) && current->isPrimary() - && !(current->getObjectTypeFlags() & 0x10) && !(current->getObjectTypeFlags() & 0x20)) { + if (target->isOfType(ITSoldier) && current->isPrimary() + && !current->isOfType(ITAir) && !current->isOfType(ITHelicopter)) { if (current->getPhysical()->getHealth() < IBotManager::instance->getVehicleBailValue()) { const int bailPatternId = m_patternId; BAPConFalse* const bailStop = checkPointer(new BAPConFalse()); @@ -349,7 +348,7 @@ BotScript* BBPChange::createPlan(Bot* bot) const int patternId = m_patternId; const float arriveSpeed = mobile->getMaxSpeed() * 0.75f; const float speed = mobile->getMaxSpeed(); - move = checkPointer(new BAPAMoveToFinding(bot, m_entryPositions[bot->getBotId()], speed, arriveSpeed, taken, + move = checkPointer(new BAPAMoveToFinding(bot, m_noPathfindingPos[bot->getBotId()], speed, arriveSpeed, taken, driveControls, patternId, 0.5f, 0.0f)); } else { // 0x23AFEB @@ -406,7 +405,7 @@ BotScript* BBPChange::createPlan(Bot* bot) primaryDistanceSqr = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; } // 0x23B558: ask the driver for a ride when the bot walks into a manned vehicle's seat. - if (!m_sameVehicle[bot->getBotId()] && (current->getObjectTypeFlags() & 0x200000) + if (!m_sameVehicle[bot->getBotId()] && current->isOfType(ITSoldier) && primaryObject->getPlayerId() >= 0 && primary && primary->hasMobile() && primaryDistanceSqr < 400.0f && !type1Waiting && !type0Waiting) { BAPConObjectOccupied* const driverIn = checkPointer(new BAPConObjectOccupied(primary->getHandle())); // -0x464 @@ -447,7 +446,7 @@ BotScript* BBPChange::createPlan(Bot* bot) // BAPAUseFlareOnMissileLock (controls bit 47); wrap it in BAPIWChange (books the target), owner = this // (0x2370E0). BAPStatement* wrapped = plan; - if (!(current->getObjectTypeFlags() & 0x200000)) { + if (!current->isOfType(ITSoldier)) { BAPCombinerParallel* const flares = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); flares->addStatement(checkPointer(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, m_patternId))); flares->addStatement(plan); @@ -456,7 +455,7 @@ BotScript* BBPChange::createPlan(Bot* bot) const int playerId = bot->getPlayerId(); BAPIWChange* const wrapper = checkPointer(new BAPIWChange(m_targets[bot->getBotId()], wrapped, m_patternId, playerId)); - wrapper->m_owner = this; + wrapper->mpOwner = this; return wrapper; } @@ -467,7 +466,7 @@ void BBPChange::init(unsigned int handle, const Vec3& position, bool sameVehicle m_initiated[bot->getBotId()] = true; m_sameVehicle[bot->getBotId()] = sameVehicle; m_targets[bot->getBotId()] = handle; - m_entryPositions[bot->getBotId()] = position; + m_noPathfindingPos[bot->getBotId()] = position; m_getInConfirm[bot->getBotId()] = getInConfirm; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h index a4f557fa0..c155b88f1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChange.h @@ -37,7 +37,7 @@ class BBPChange : public BBPPattern // Every array is new[]'d with IAISettings::getMaxNBots (slot 0) entries and indexed by Bot::getBotId. /* +0x08 */ int m_patternId; // the constructor argument: the pattern id the plan nodes carry /* +0x0C */ unsigned int* m_targets; // init: the vehicle/seat handle - /* +0x10 */ Vec3* m_entryPositions; // value-initialised (0,0,0); init(handle, pos, ...) only + /* +0x10 */ Vec3* m_noPathfindingPos; // value-initialised (0,0,0); init(handle, pos, ...) only // name: AIDLL_r assert 0x100FB800 (+0x10) /* +0x14 */ bool* m_sameVehicle; // [INFERRED] name: init's first bool, BBChange passes "same primary object" /* +0x18 */ bool* m_getInConfirm; // init's second bool and setGetInConfirm (named after the setter) }; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp index 0560c349e..5a814eddd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeLandingCraft.cpp @@ -18,7 +18,7 @@ #include "../AIBotActionPlan/BAPStatement.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -116,7 +116,7 @@ BotScript* BBPChangeLandingCraft::createPlan(Bot* bot) const int playerId = bot->getPlayerId(); BAPIWChange* const wrapper = checkPointer(new BAPIWChange(m_target[bot->getBotId()], sequence, m_patternId, playerId)); - wrapper->setParent(this); // +0x04 (BotScript::m_owner) + wrapper->setParent(this); // +0x04 (BotScript::mpOwner) return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp index 4a7c877dc..f095ed8b1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPChangeTeleport.cpp @@ -17,7 +17,7 @@ #include "../AIBotActionPlan/BAPIWChange.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIStrategic/SAI.h" @@ -108,7 +108,7 @@ BotScript* BBPChangeTeleport::createPlan(Bot* bot) } const int playerId = bot->getPlayerId(); BAPIWChange* const wrapper = checkPointer(new BAPIWChange(m_target[bot->getBotId()], plan, m_patternId, playerId)); - wrapper->m_owner = this; + wrapper->mpOwner = this; return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp index 049f51edd..39e65dafc 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPDefuseMines.cpp @@ -25,12 +25,12 @@ #include "../AIBotActionPlan/BAPICChangeVehicle.h" #include "../AIBotActionPlan/BAPIWDefuseMines.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -136,7 +136,7 @@ BotScript* BBPDefuseMines::createPlan(Bot* bot) BAPCombinerSerial* root = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); BAPCombinerSerial* sequence = checkPointer(new BAPCombinerSerial(m_unknown8, -1)); sequence->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_unknown8))); - if (!(self->getObjectTypeFlags() & 0x200000)) + if (!self->isOfType(ITSoldier)) { BAPCombinerParallel* leave = checkPointer(new BAPCombinerParallel(m_unknown8, -1, false)); leave->addStatement(checkPointer(new BAPICChangeVehicle(soldierHandle))); @@ -184,7 +184,7 @@ BotScript* BBPDefuseMines::createPlan(Bot* bot) root->addStatement(sequence); const unsigned int target = m_mine[bot->getBotId()]; BAPIWDefuseMines* wrapper = checkPointer(new BAPIWDefuseMines(bot, target, root, m_unknown8)); - wrapper->m_owner = this; + wrapper->mpOwner = this; static_cast(bot)->resetAllControls(true, true, true); return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp index 867d4eb31..e0a3d3c7d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2d.cpp @@ -48,9 +48,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" @@ -348,7 +348,7 @@ BotScript* BBPFire2d::createPlan(Bot* bot) const float precisionScale = (1.0f - fraction) * 0.1f + fraction * 5.0f; float precisionFactor; float minimumPrecision; - if (targetInfo->getObjectTypeFlags() & 0x10) + if (targetInfo->isOfType(ITAir)) { precisionFactor = 0.8f; minimumPrecision = 0.5f; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp index b98e236c3..419fc42c0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire2dDriver.cpp @@ -53,9 +53,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/TraceUtils.h" @@ -417,7 +417,7 @@ BotScript* BBPFire2dDriver::createPlan(Bot* bot) BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, m_targets[bot->getBotId()], m_flag20, tooClose, weapon, -1, statement, m_patternId)); plan->setInt28(lineOfFire); - plan->setParent(this); // +0x04 (BotScript::m_owner) + plan->setParent(this); // +0x04 (BotScript::mpOwner) SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp index ca7c28ec7..16f8b4a05 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFire3d.cpp @@ -57,9 +57,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIBotActionPlan/BAPVariable.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" @@ -197,7 +197,7 @@ BotScript* BBPFire3d::createPlan(Bot* bot) const float radius = targetMobile ? targetPhysical->getRadius() + selfRadius : selfRadius + 0.0f; data.m_approachRadius = radius + radius; const bool indirect = weapon->getIndirect(); - const bool flag40 = (targetInfo->getObjectTypeFlags() & 0x40) != 0; + const bool flag40 = targetInfo->isOfType(ITGround); if (!self->getMobile()) { data.m_mode = 3; @@ -231,7 +231,7 @@ BotScript* BBPFire3d::createPlan(Bot* bot) serial->addStatement(parallel); BAPIWFire* const plan = checkPointer( new BAPIWFire(bot, target, m_flag20, false, m_weapons[bot->getBotId()], -1, serial, m_patternId)); - plan->setParent(this); // +0x04 (BotScript::m_owner) + plan->setParent(this); // +0x04 (BotScript::mpOwner) SquadManager::m_instance->shotsFired(bot->getPlayerId(), bot->getSide(), m_targets[bot->getBotId()]); return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp index 0d7e22b2a..721bbf0ba 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPFireInfantery.cpp @@ -88,9 +88,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" @@ -1138,7 +1138,7 @@ BotScript* BBPFireInfantery::createPlanInternal(Bot* bot, bool targetIsLodBot) } const int guidance = weaponInfo->getWeaponGuidanceType(); - if (guidance != 0 && (selfInfo->getObjectTypeFlags() & 0x200000)) + if (guidance != 0 && selfInfo->isOfType(ITSoldier)) return createGuidedPlanInternalInfantry(bot, targetIsLodBot, movePosition); // 0x2779B1 // The plan variables (0x26543B..0x265819), shared by the wrappers and the fire plans. @@ -1160,7 +1160,7 @@ BotScript* BBPFireInfantery::createPlanInternal(Bot* bot, bool targetIsLodBot) const bool placedExplosive = weaponInfo->getWeaponType() == 4; const int antiAircraft = armament->isAntiAircraft(); - const bool targetFlag10 = (targetInfo->getObjectTypeFlags() & 0x10) != 0; + const bool targetFlag10 = targetInfo->isOfType(ITAir); const bool noMove = targetFlag10 && antiAircraft == 1; // -0x246 bool fireFromHere = (targetFlag10 && antiAircraft == 2) || !pathFound; // -0x247 if (weaponInfo->getMaxRange() < 10.0f) @@ -1174,8 +1174,8 @@ BotScript* BBPFireInfantery::createPlanInternal(Bot* bot, bool targetIsLodBot) && squadMember->getSquad()->getValidSaPos(squadMember, squadPosition)) squadPositionValid = true; - const bool selfFlag = (selfInfo->getObjectTypeFlags() & 0x200000) != 0; // -0x249 - const bool targetFlag = (targetInfo->getObjectTypeFlags() & 0x200000) != 0; // -0x24A + const bool selfFlag = selfInfo->isOfType(ITSoldier); // -0x249 + const bool targetFlag = targetInfo->isOfType(ITSoldier); // -0x24A const bool targetIsBot = IBotManager::instance->getBotFromPlayerId(targetInfo->getPlayerId()) != 0; BAPStatement* branch = 0; // added to the parallel block at 0x2671C0 @@ -1211,7 +1211,7 @@ BotScript* BBPFireInfantery::createPlanInternal(Bot* bot, bool targetIsLodBot) if (IPIMobile* const targetMover = targetInfo->getMobile()) { const IPIMobile::ValidPos& valid = targetMover->getLastValidPosition(selfMobile->getVehicleNumber()); - if (valid.quadTree == static_cast(-1) || valid.polygon == static_cast(-1)) + if (valid.island == static_cast(-1) || valid.polygon == static_cast(-1)) fireFromHere = true; } if (!fireFromHere && targetIsBot && targetFlag) @@ -1814,7 +1814,7 @@ BotScript* BBPFireInfantery::createGuidedPlanInternalInfantry(Bot* bot, bool tar root->addStatement(checkPointer(new BAPAChangeWeapon(bot, weapon, m_patternId))); BAPCombinerParallel* const block = checkPointer(new BAPCombinerParallel(m_patternId, true, -1, false)); root->addStatement(block); - const bool selfFlag = (selfInfo->getObjectTypeFlags() & 0x200000) != 0; + const bool selfFlag = selfInfo->isOfType(ITSoldier); block->addStatement(newOverrideSensingAgent(selfFlag, m_patternId)); // before the reset here block->addStatement(checkPointer(new BAPAResetControls(true, true, true, m_patternId))); if (!selfFlag) @@ -1974,8 +1974,8 @@ BAPStatement* BBPFireInfantery::createFirePlan(Bot* bot, BBPFireInfantery::Firin if (weaponInfo->getExplosionRadius() != 0.0f && guidance == 0) splash = true; SensedObject* const sensed = bot->getSensedObjectFromHandle(target); - const bool selfFlag = (selfInfo->getObjectTypeFlags() & 0x200000) != 0; - const bool targetFlag = (targetInfo->getObjectTypeFlags() & 0x200000) != 0; + const bool selfFlag = selfInfo->isOfType(ITSoldier); + const bool targetFlag = targetInfo->isOfType(ITSoldier); bool splashAtTarget = false; // -0x198 if (!selfFlag && targetFlag && guidance == 0 && weaponInfo->getExplosionRadius() != 0.0f) splashAtTarget = true; diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp index 5489e147e..4e877749d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints2d.cpp @@ -20,7 +20,7 @@ #include "../AIBotActionPlan/BAPInfoWrapper.h" #include "../AIBotActionPlan/BAPIWMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIPlanInterpreter/BAPContext.h" @@ -88,7 +88,7 @@ BotScript* finishRoute(Bot* bot, BAPCombinerSerial* serial, const Vec3& goal, in parallel->addStatement(new BAPAUseFlareOnMissileLock(bot, 0x800000000000ULL, patternId)); parallel->addStatement(serial); BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, parallel, patternId)); - root->setParent(owner); // +0x04 (BotScript::m_owner) + root->setParent(owner); // +0x04 (BotScript::mpOwner) return root; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp index afe56bf5f..6574bf826 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypoints3d.cpp @@ -27,7 +27,7 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -123,7 +123,7 @@ BotScript* BBPGotoWaypoint3d::createPlan(Bot* bot) plan->addStatement(checkPointer(new BAPAMoveTo3dObject(closeTo->m_target, radius, speed, speed, closeTo->m_third, checkPointer(new BAPConFalse()), controls, m_patternId))); - plan->setParent(this); // +0x04 (BotScript::m_owner) + plan->setParent(this); // +0x04 (BotScript::mpOwner) return plan; } case 6: @@ -133,7 +133,7 @@ BotScript* BBPGotoWaypoint3d::createPlan(Bot* bot) if (!waypoints->getGoalPoint(goal)) return 0; BAPCombinerParallel* const plan = newFlightPlan(bot, m_patternId); - BAPConPosition* const reached = (self->getObjectTypeFlags() & 0x20) + BAPConPosition* const reached = self->isOfType(ITHelicopter) ? checkPointer(new BAPConPosition(goal, 2.0f)) : checkPointer(new BAPConPosition(goal, radius)); plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, goal, speed, speed, reached, controls, diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp index 9a6edd6a8..f45faafe4 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsBoat.cpp @@ -31,7 +31,7 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIStrategicEntity/AILandingZone.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp index d0654bd33..f6588f2ec 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPGotoWaypointsInfantery.cpp @@ -19,7 +19,7 @@ #include "../AIBotActionPlan/BAPIWMoveTo.h" #include "../AIBotBehaviour/BBPendingCalls.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIPlanInterpreter/BAPContext.h" @@ -220,7 +220,7 @@ BotScript* BBPGotoWaypointSoldier::buildMoveTo(Bot* bot, Information* equipment, serial->addStatement(focus); serial->addStatement(move); BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, serial, m_patternId)); - root->setParent(this); // +0x04 (BotScript::m_owner) + root->setParent(this); // +0x04 (BotScript::mpOwner) return root; } @@ -246,7 +246,7 @@ BotScript* BBPGotoWaypointSoldier::buildMoveToObject(Bot* bot, Information* equi serial->addStatement(focus); serial->addStatement(move); BAPIWMoveTo* const root = checkPointer(new BAPIWMoveTo(goal, serial, m_patternId)); - root->setParent(this); // +0x04 (BotScript::m_owner) + root->setParent(this); // +0x04 (BotScript::mpOwner) return root; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp index 95264a0c5..0e3113d06 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPHeliFire3d.cpp @@ -55,9 +55,9 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -190,7 +190,7 @@ BotScript* BBPHeliFire3d::createPlan(Bot* bot) data.m_position = row(self->getTransformation(), 3); data.m_direction = row(self->getTransformation(), 2); const bool indirect = weapon->getIndirect(); - const bool flag40 = (targetInfo->getObjectTypeFlags() & 0x40) != 0; + const bool flag40 = targetInfo->isOfType(ITGround); bot->getSquadMember()->clearRequestAction(); if (!self->getMobile()) { @@ -223,7 +223,7 @@ BotScript* BBPHeliFire3d::createPlan(Bot* bot) BAPIWFire* const plan = checkPointer(new BAPIWFire(bot, target, m_flag20, false, data.m_weapon, -1, createPlanInternal(bot, data), m_patternId)); - plan->setParent(this); // +0x04 (BotScript::m_owner) + plan->setParent(this); // +0x04 (BotScript::mpOwner) return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp index 88cf59b91..019ff1b2e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle.cpp @@ -7,7 +7,7 @@ #include "BBPIdle.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" namespace dice { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp index d1395997a..c5dbb096d 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle2d.cpp @@ -20,7 +20,7 @@ #include "../AIBotActionPlan/BAPIWIdle.h" #include "../AIBotActionPlan/BAPStatement.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" @@ -92,7 +92,7 @@ BotScript* BBPIdle2d::createPlan(Bot* bot) if (static_cast(bot->getPlan())->getPatternId() == m_patternId) { const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; - if (pickupPlayerId >= 0 && !(equipment->getObjectTypeFlags() & 0x200000) + if (pickupPlayerId >= 0 && !equipment->isOfType(ITSoldier) && bot->getCommunicationAgent()->confirmReceivedMessage(static_cast(2), pickupPlayerId)) { @@ -117,7 +117,7 @@ BotScript* BBPIdle2d::createPlan(Bot* bot) Information* const primary = informationManager->getInformation(equipment->getPrimaryObject(bot->getSide())); const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; const bool anyPosition = pickupPlayerId == 0xFF; - if (pickupPlayerId >= 0 && !(primary->getObjectTypeFlags() & 0x200000)) + if (pickupPlayerId >= 0 && !primary->isOfType(ITSoldier)) { IAIPlayer* const passenger = static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(pickupPlayerId); @@ -160,7 +160,7 @@ BotScript* BBPIdle2d::createPlan(Bot* bot) parallel->addStatement(flares); parallel->addStatement(serial); BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), parallel, m_patternId, bot)); - idle->setParent(this); // +0x04 (BotScript::m_owner) + idle->setParent(this); // +0x04 (BotScript::mpOwner) bot->getBotNavigation()->clearProgress(); return idle; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp index a986e8af0..9d880b7da 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdle3d.cpp @@ -30,10 +30,10 @@ #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../AIUtils/checkPointer.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" @@ -104,7 +104,7 @@ BotScript* BBPIdle3d::createPlan(Bot* bot) IPIMobile* const mobile = equipment->getMobile(); Information* const primary = informationManager->getInformation(equipment->getPrimaryObject(bot->getSide())); bool airborne = false; - if (bot->isAirBorn() || ((primary->getObjectTypeFlags() & 0x10) && mobile->getSpeedMagnitude() > 3.0f)) + if (bot->isAirBorn() || (primary->isOfType(ITAir) && mobile->getSpeedMagnitude() > 3.0f)) airborne = true; if (bot->hasPlan() && static_cast(bot->getPlan())->getPatternId() == m_patternId @@ -139,7 +139,7 @@ BotScript* BBPIdle3d::createPlan(Bot* bot) const int pickupPlayerId = m_pickupPlayerId[bot->getBotId()]; const bool anyPosition = pickupPlayerId == 0xFF; - if (pickupPlayerId >= 0 && !(primary->getObjectTypeFlags() & 0x200000)) + if (pickupPlayerId >= 0 && !primary->isOfType(ITSoldier)) { IAIPlayer* const passenger = static_cast(CommonSingletonServer::m_iaiPlayerFactory)->getPlayerFromId(pickupPlayerId); @@ -180,7 +180,7 @@ BotScript* BBPIdle3d::createPlan(Bot* bot) if (airborne) { Vec3 destination = equipment->getPosition(); // +0x30 - if (!(primary->getObjectTypeFlags() & 0x20) || primary->getArmament()) + if (!primary->isOfType(ITHelicopter) || primary->getArmament()) { const Mat4& heading = equipment->getTransformation(); // +0x3C Vec3 direction; @@ -213,7 +213,7 @@ BotScript* BBPIdle3d::createPlan(Bot* bot) serial->addStatement(parallel); BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), serial, m_patternId, bot)); - idle->setParent(this); // +0x04 (BotScript::m_owner) + idle->setParent(this); // +0x04 (BotScript::mpOwner) bot->getBotNavigation()->clearProgress(); return idle; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp index 0f3fab84c..7ad877fbc 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPIdleInfantery.cpp @@ -21,10 +21,10 @@ #include "../AIBotActionPlan/BAPFlowCWhile.h" #include "../AIBotActionPlan/BAPIWIdle.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIStrategicEntity/AIStrategicObject.h" @@ -126,7 +126,7 @@ BotScript* BBPIdleInfantery::createPlan(Bot* bot) parallel->addStatement(ifNotZoomed); } } - if (equipment->getObjectTypeFlags() & 0x200000) + if (equipment->isOfType(ITSoldier)) { BAPASoldierPose* const pose = checkPointer( new BAPASoldierPose(static_cast(2), checkPointer(new BAPConTrue()), m_patternId, true)); @@ -137,7 +137,7 @@ BotScript* BBPIdleInfantery::createPlan(Bot* bot) BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), parallel, m_patternId)); BAPIWIdle* const idle = checkPointer(new BAPIWIdle(equipment->getPosition(), loop, m_patternId, bot)); - idle->setParent(this); // +0x04 (BotScript::m_owner) + idle->setParent(this); // +0x04 (BotScript::mpOwner) return idle; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp index 1446cfa3e..69227cc49 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPMedicAssist.cpp @@ -43,13 +43,13 @@ #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../Main/IBotManager.h" #include "WeaponChoice.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIUtils/checkPointer.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" @@ -331,7 +331,7 @@ BotScript* BBPMedicAssist::createPlan(Bot* bot) equipment->getControlInfo()->getLookControls(), m_id, 0, yOffset))); BAPASoldierPose* pose; - if ((target->getObjectTypeFlags() & 0x200000u) && (kit == 5 || kit == 3)) + if (target->isOfType(ITSoldier) && (kit == 5 || kit == 3)) pose = checkPointer(new BAPASoldierPose(SPStanding, checkPointer(new BAPConTrue()), m_id, m_target[bot->getBotId()], true)); // 0x294D90 else @@ -438,7 +438,7 @@ BotScript* BBPMedicAssist::createPlan(Bot* bot) // 0x29278F BAPIWFire* const root = checkPointer( new BAPIWFire(bot, m_target[bot->getBotId()], targetVacant, false, weaponIndex, -1, serial, m_id)); - root->setParent(this); // +0x04 (BotScript::m_owner) + root->setParent(this); // +0x04 (BotScript::mpOwner) static_cast(bot)->resetAllControls(true, true, true); return root; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp index 88c64059a..d2c1d08dd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRandom.cpp @@ -16,10 +16,10 @@ #include "../AIBotActionPlan/BAPFlowCWhile.h" #include "../AIBotActionPlan/BAPIWIdle.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -127,7 +127,7 @@ BotScript* BBPRandom::createPlan(Bot* bot) } BAPFlowCWhile* loop = checkPointer(new BAPFlowCWhile(checkPointer(new BAPConTrue()), parallel, true, m_id)); BAPIWIdle* wrapper = checkPointer(new BAPIWIdle(self->getPosition(), loop, m_id, bot)); - wrapper->m_owner = this; + wrapper->mpOwner = this; return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp index 88a41b541..e5f2684b7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRevive.cpp @@ -33,9 +33,9 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" @@ -197,7 +197,7 @@ BotScript* BBPRevive::createPlan(Bot* bot) BAPIWFire* const root = checkPointer( new BAPIWFire(bot, m_target[bot->getBotId()], true, false, weaponIndex, -1, serial, m_id)); - root->setParent(this); // +0x04 (BotScript::m_owner) + root->setParent(this); // +0x04 (BotScript::mpOwner) static_cast(bot)->resetAllControls(true, true, true); return root; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp index f2d226380..ee420a012 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam2d.cpp @@ -13,7 +13,7 @@ #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../../../../Math/Vec3.h" @@ -58,7 +58,7 @@ BotScript* BBPRoam2d::createPlan(Bot* bot) BAPConPosition* const arrived = new BAPConPosition(m_positions[bot->getBotId()], radius); BAPAMoveToFinding* const plan = new BAPAMoveToFinding(bot, m_positions[bot->getBotId()], speed, speed, arrived, controls, m_patternId, 0.0f, 0.0f); - plan->m_owner = this; + plan->mpOwner = this; return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp index 2efdae9a8..04a250b5e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRoam3d.cpp @@ -11,7 +11,7 @@ #include "../AIBotActionPlan/BAPConObjectVisible.h" #include "../AIBotActionPlan/BAPIWRoam.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" @@ -88,7 +88,7 @@ BotScript* BBPRoam3d::createPlan(Bot* bot) BAPAMoveTo3dObject* move = new BAPAMoveTo3dObject(object, radius, speed, arriveSpeed, 50.0f, visible, driveControls, m_patternId); BAPIWRoam* wrapper = new BAPIWRoam(m_objects[bot->getBotId()], move, m_patternId); - wrapper->m_owner = this; + wrapper->mpOwner = this; return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp index 01d157335..df478d229 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPRunOverSoldier.cpp @@ -7,7 +7,7 @@ #include "../AIBotActionPlan/BAPARunOverObject.h" #include "../AIBotActionPlan/BAPIWFire.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" @@ -89,7 +89,7 @@ BotScript* BBPRunOverSoldier::createPlan(Bot* bot) new BAPARunOverObject(m_target[bot->getBotId()], controlInfo->getDriveControls(), m_patternId)); BAPIWFire* const root = checkPointer( new BAPIWFire(bot, m_target[bot->getBotId()], true, false, 4, -1, runOver, m_patternId)); - root->setParent(this); // +0x04 (BotScript::m_owner) + root->setParent(this); // +0x04 (BotScript::mpOwner) static_cast(bot)->resetAllControls(true, true, true); return root; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp index e773b9ad2..ddd66df76 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPSuicide.cpp @@ -67,7 +67,7 @@ BotScript* BBPSuicide::createPlan(Bot* bot) // shipped defect: the signed input-31 mask is widened with every upper bit set. BAPATrigger* const plan = checkPointer(new BAPATrigger(static_cast(31), start, stop, 0xFFFFFFFF80000000ULL, m_patternId, 0.0, false)); - plan->m_owner = this; + plan->mpOwner = this; return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp index 87d5605b1..c4aa8958e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover.cpp @@ -19,7 +19,7 @@ #include "../AIBotActionPlan/BAPConPosition.h" #include "../AIBotActionPlan/BAPIWTakeCover.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIUnit.h" @@ -215,7 +215,7 @@ BotScript* BBPTakeCover::createPlan(Bot* bot) } else wrapper = checkPointer(new BAPIWTakeCover(threatPosition, root, m_patternId)); - wrapper->m_owner = this; + wrapper->mpOwner = this; return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp index 934ddeb71..3c3ebbf1e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCover3d.cpp @@ -22,7 +22,7 @@ #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" #include "../AIUtils/checkPointer.h" @@ -107,7 +107,7 @@ BotScript* BBPTakeCover3d::createPlan(Bot* bot) plan->addStatement(checkPointer(new BAPAMoveTo3d(bot, destination, mobile->getMaxSpeed(), mobile->getMaxSpeed(), checkPointer(new BAPConFalse()), controlInfo->getDriveControls(), 30.0f, m_patternId))); - plan->setParent(this); // +0x04 (BotScript::m_owner) + plan->setParent(this); // +0x04 (BotScript::mpOwner) return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp index 2e1a46378..d66089a96 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTakeCoverInfantry.cpp @@ -25,7 +25,7 @@ #include "../AIBotActionPlan/BAPFlowCIf.h" #include "../AIBotActionPlan/BAPIWTakeCover.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPICover.h" #include "../AIKnowledge/IPIMobile.h" @@ -355,7 +355,7 @@ BotScript* BBPTakeCoverInfantry::createPlan(Bot* bot) } else wrapper = checkPointer(new BAPIWTakeCover(threatPosition, root, m_patternId)); - wrapper->m_owner = this; + wrapper->mpOwner = this; return wrapper; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp index df0f6750f..010148cce 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/BBPTriggerable.cpp @@ -19,7 +19,7 @@ #include "../AIBotActionPlan/BAPFlowCWhile.h" #include "../AIBotActionPlan/BAPIWIdle.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIPlanInterpreter/BAPContext.h" #include "../AIPlanInterpreter/BotScriptDebugger.h" @@ -110,7 +110,7 @@ BotScript* BBPTriggerable::createPlan(Bot* bot) BAPConTrue* const repeat = checkPointer(new BAPConTrue()); BAPFlowCWhile* const loop = checkPointer(new BAPFlowCWhile(repeat, parallel, true, m_id)); BAPIWIdle* const plan = checkPointer(new BAPIWIdle(equipment->getPosition(), loop, m_id, bot)); - plan->m_owner = this; + plan->mpOwner = this; return plan; } diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp index 33a97bbd8..ee2c68e68 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviourPattern/WeaponChoice.cpp @@ -5,7 +5,7 @@ #include "WeaponChoice.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp index d7148ae1f..3eaffd26f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.cpp @@ -7,7 +7,7 @@ #include "Information.h" #include "IPIPhysical.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIUtils/checkPointer.h" // and, through it, Core/Debug.h #include "../../../../Math/Frustum.h" @@ -28,15 +28,15 @@ AIInformationGrid::AIInformationGrid(int side, int dimX, int dimZ, Vec2 min, Vec , m_dimZ(dimZ) , m_min(min) , m_max(max) - , m_cells(0) + , m_grid(0) { - m_cells = checkPointer(new Cell[m_dimX * m_dimZ + 1]); + m_grid = checkPointer(new Cell[m_dimX * m_dimZ + 1]); } // The records the map still points at are not deleted - defect 2. AIInformationGrid::~AIInformationGrid() { - delete[] m_cells; + delete[] m_grid; } // On an id it already holds this updates rather than declining, which makes it @@ -226,7 +226,7 @@ void AIInformationGrid::getInformationWithinCircle(std::vector& ou { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; for (Cell::iterator it = cell.begin(); it != cell.end(); ++it) { InfoInfo* const info = it->m_info; @@ -291,7 +291,7 @@ void AIInformationGrid::getInformationWithinFrustum(std::vector& o { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; for (Cell::iterator it = cell.begin(); it != cell.end(); ++it) { InfoInfo* const info = it->m_info; @@ -346,7 +346,7 @@ void AIInformationGrid::getInformationWithinRectangle(std::vector& { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; for (Cell::iterator it = cell.begin(); it != cell.end(); ++it) { InfoInfo* const info = it->m_info; @@ -471,7 +471,7 @@ void AIInformationGrid::updateElementInCells(unsigned int id, const InfoInfo& ol for (int x = oldMinX; x <= oldMaxX; ++x) { const int cell = x + m_dimX * y; - m_cells[cell].erase(findCellElement(cell, id)); + m_grid[cell].erase(findCellElement(cell, id)); } } @@ -483,7 +483,7 @@ void AIInformationGrid::updateElementInCells(unsigned int id, const InfoInfo& ol { for (int x = newMinX; x <= newMaxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; cell.insert(cell.begin(), element); } } @@ -511,7 +511,7 @@ void AIInformationGrid::addElementToCells(unsigned int id, InfoInfo* info) { for (int x = minX; x <= maxX; ++x) { - Cell& cell = m_cells[x + m_dimX * y]; + Cell& cell = m_grid[x + m_dimX * y]; cell.insert(cell.begin(), element); } } @@ -537,7 +537,7 @@ void AIInformationGrid::removeElementFromCells(unsigned int id, InfoInfo* info) for (int x = minX; x <= maxX; ++x) { const int cell = x + m_dimX * y; - m_cells[cell].erase(findCellElement(cell, id)); + m_grid[cell].erase(findCellElement(cell, id)); } } } @@ -546,7 +546,7 @@ void AIInformationGrid::removeElementFromCells(unsigned int id, InfoInfo* info) AIInformationGrid::Cell::iterator AIInformationGrid::findCellElement(int cell, unsigned int id) const { - Cell& list = m_cells[cell]; + Cell& list = m_grid[cell]; Cell::iterator it = list.begin(); while (it != list.end()) diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h index 8a1bb625b..22aa7b578 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h @@ -131,7 +131,7 @@ class AIInformationGrid : public IAIInformationGrid // [UNRESOLVED] Four-byte member left uninitialized and unread by the implemented methods. /* +0x20 */ int m_unwritten20; - /* +0x24 */ Cell* m_cells; // `new Cell[m_dimX * m_dimZ + 1]` - see the header block + /* +0x24 */ Cell* m_grid; // `new Cell[m_dimX * m_dimZ + 1]` - see the header block // name: AIDLL_r assert 0x101FAC00 (+0x24) /* +0x28 */ InfoMap m_infos; // id -> record; in this libstdc++ /* +0x34 */ mutable std::vector m_visited; // the scratchpad; `mutable` is required // because three `const` queries fill it diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.cpp similarity index 95% rename from Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp rename to Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.cpp index 2bc77c34e..52b330c22 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.cpp @@ -1,3 +1,4 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIKnowledge\AIMineManager.cpp" (asserts in 0x100B3B60 / 0x100B3C60). // static init: ELF 0x2E17C0 (__tcf_0 0x2E1820, _GLOBAL__I 0x2E1850): 's Init object only. #include @@ -9,9 +10,9 @@ #include "../../../../Core/ClassManager.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment::isAsleep #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime -#include "AIRandom.h" -#include "CommonSingletonServer.h" -#include "IAIPathfinding.h" +#include "../Main/AIRandom.h" +#include "../Main/CommonSingletonServer.h" +#include "../Main/IAIPathfinding.h" namespace dice { namespace hfe { @@ -153,7 +154,7 @@ AIMineManager::AIMineManager() // Leaves m_gap64 uninitialized. Creates entries for anti-personnel and anti-tank mines; // init later sizes each type's map dimension. m_minedPolygons.resize(2); - m_polygonData.resize(2); + m_minesInPolygon.resize(2); } // The binary tears down exactly the four containers, in reverse declaration order - the settling @@ -170,7 +171,7 @@ AIMineManager::~AIMineManager() void AIMineManager::init(MineType type, unsigned int islandCount) { m_minedPolygons[type].resize(islandCount); - m_polygonData[type].resize(islandCount); + m_minesInPolygon[type].resize(islandCount); } // Resets scheduling and scalar state while retaining both mine maps and polygon indices. @@ -390,7 +391,7 @@ unsigned int AIMineManager::findSeedPolygonForATMine(MineInfo& info) void AIMineManager::addNewMineToPolygon(MineType type, unsigned int quadTree, unsigned int polygon) { const std::pair::iterator, bool> result = - m_polygonData[type][quadTree].insert(std::make_pair(polygon, PolygonData())); + m_minesInPolygon[type][quadTree].insert(std::make_pair(polygon, PolygonData())); if (result.second) { @@ -409,7 +410,7 @@ void AIMineManager::addNewOtherMineToPolygon(MineType type, unsigned int quadTre unsigned int polygon) { const std::pair::iterator, bool> result = - m_polygonData[type][quadTree].insert(std::make_pair(polygon, PolygonData())); + m_minesInPolygon[type][quadTree].insert(std::make_pair(polygon, PolygonData())); if (result.second) { @@ -425,10 +426,10 @@ void AIMineManager::addNewOtherMineToPolygon(MineType type, unsigned int quadTre // Removes a mine from an existing polygon entry. The caller must ensure the entry exists. // ELF 0x2E14B0 -void AIMineManager::removeMineFromPolygon(MineType type, unsigned int quadTree, +void AIMineManager::removeMineFromPolygon(MineType type, unsigned int island, unsigned int polygon) { - std::map& polygons = m_polygonData[type][quadTree]; + std::map& polygons = m_minesInPolygon[type][island]; // No end check - see above. const std::map::iterator i = polygons.find(polygon); @@ -437,15 +438,15 @@ void AIMineManager::removeMineFromPolygon(MineType type, unsigned int quadTree, if (i->second.m_mines == 0 && i->second.m_otherMines == 0) { polygons.erase(i); - m_minedPolygons[type][quadTree].erase(polygon); + m_minedPolygons[type][island].erase(polygon); } } // ELF 0x2E15D0 -void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int quadTree, +void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int island, unsigned int polygon) { - std::map& polygons = m_polygonData[type][quadTree]; + std::map& polygons = m_minesInPolygon[type][island]; const std::map::iterator i = polygons.find(polygon); --i->second.m_otherMines; @@ -453,7 +454,7 @@ void AIMineManager::removeOtherMineFromPolygon(MineType type, unsigned int quadT if (i->second.m_otherMines == 0 && i->second.m_mines == 0) { polygons.erase(i); - m_minedPolygons[type][quadTree].erase(polygon); + m_minedPolygons[type][island].erase(polygon); } } diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.h similarity index 95% rename from Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h rename to Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.h index 905628e33..4b09023f5 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMineManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.h @@ -1,5 +1,5 @@ // Tracks mines by side and updates navigation hazards when mines settle or disappear. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIKnowledge/AIMineManager.cpp: asserts in 0x100B3B60 / 0x100B3C60). #ifndef AI_AIDLL_AI_MAIN_AIMINEMANAGER_H #define AI_AIDLL_AI_MAIN_AIMINEMANAGER_H @@ -10,7 +10,7 @@ #include #include -#include "AIDllTypes.h" +#include "../Main/AIDllTypes.h" namespace dice { namespace hfe { @@ -118,7 +118,7 @@ class AIMineManager : public IAIMineManager // Indexed by mine type, then quad-tree island. init() sizes the island dimension. /* 12 */ std::vector > > m_minedPolygons; - /* 24 */ std::vector > > m_polygonData; + /* 24 */ std::vector > > m_minesInPolygon; // name: AIDLL_r assert 0x100B3B60 (PE +0x20) /* 36 */ std::map > m_mines; // at rest; node = /* 48 */ std::map m_settlingMines; // still moving; node = 132 diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp index d345861a6..523a87a62 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp @@ -11,11 +11,11 @@ #include #include "Information.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "IPIMobile.h" #include "WeaponInfo.h" -#include "WeaponInfoManager.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../../../../Core/ClassManager.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" @@ -61,7 +61,7 @@ BFInformationCourier::BFInformationCourier() for (int i = 0; i < 3; ++i) { m_saved[i].polygon = 0xFFFFFFFFu; - m_saved[i].quadTree = 0xFFFFFFFFu; + m_saved[i].island = 0xFFFFFFFFu; m_saved[i].position.x = 0.0f; m_saved[i].position.y = 0.0f; m_saved[i].position.z = 0.0f; @@ -255,13 +255,13 @@ void BFInformationCourier::updateCurrentPolygon(IAIObject* object) IPIMobile::ValidPos infantryPosition; infantryPosition.polygon = static_cast(-1); - infantryPosition.quadTree = static_cast(-1); + infantryPosition.island = static_cast(-1); infantryPosition.position.x = 0.0f; infantryPosition.position.y = 0.0f; infantryPosition.position.z = 0.0f; if (pathfinding->getPolygon( - position, traceMapIndex, infantryPosition.polygon, infantryPosition.quadTree, - mobile->m_lastValidInfantryPos.polygon, mobile->m_lastValidInfantryPos.quadTree, + position, traceMapIndex, infantryPosition.polygon, infantryPosition.island, + mobile->m_lastValidInfantryPos.polygon, mobile->m_lastValidInfantryPos.island, equipmentType)) { infantryPosition.position = position; @@ -274,13 +274,13 @@ void BFInformationCourier::updateCurrentPolygon(IAIObject* object) : mobile->m_lastValidVehiclePosB; IPIMobile::ValidPos vehiclePosition; vehiclePosition.polygon = static_cast(-1); - vehiclePosition.quadTree = static_cast(-1); + vehiclePosition.island = static_cast(-1); vehiclePosition.position.x = 0.0f; vehiclePosition.position.y = 0.0f; vehiclePosition.position.z = 0.0f; if (pathfinding->getPolygon( - position, traceMapIndex == 0, vehiclePosition.polygon, vehiclePosition.quadTree, - previousVehiclePosition.polygon, previousVehiclePosition.quadTree, equipmentType)) + position, traceMapIndex == 0, vehiclePosition.polygon, vehiclePosition.island, + previousVehiclePosition.polygon, previousVehiclePosition.island, equipmentType)) { vehiclePosition.position = position; mobile->setLastValidVehiclePos(vehiclePosition); diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp index 208f978e6..2ede0afff 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp @@ -11,7 +11,7 @@ #include "AIInformationGrid.h" // the grids the constructor builds #include "Information.h" // removeAllContacts -#include "InformationManager.h" // the information pool +#include "../Main/InformationManager.h" // the information pool #include "IPIMobile.h" // getCover's search radius #include "../AIBot/BotMain.h" // Bot +0xD8 / +0xE0 #include "../AIUtils/VehicleOccupancy.h" // InfoEnemyPredicate @@ -196,8 +196,9 @@ class CompositeInfoPredicate : public IAIInformationGridPredicate IAIInformationGridPredicate* m_second; // +8 }; -// Cover objects of one side or of side 0. Flag 0x40000 accepts any side; 0x10 and 0x80 reject. -// The flag names are [UNRESOLVED]; the bits are the record's object-type flags (+4). +// Cover objects of one side or of side 0. ITStructure accepts any side; ITAir and ITNaval reject. +// Bit names: InformationType (AIDLL_r 0x100D3010); AIDLL_r's version of this predicate (0x101A83C0) +// asserts "Object has no cover plugin but is of type ITCover" on the ITCover bit. class InfoCoverPredicate : public IAIInformationGridPredicate { public: @@ -205,14 +206,14 @@ class InfoCoverPredicate : public IAIInformationGridPredicate // ELF 0x2E7E80. virtual bool includeInformation(Information* information) const { - if ((information->getObjectTypeFlags() & 0x4000) == 0 || information->getCover() == 0) + if (!information->isOfType(ITCover) || information->getCover() == 0) return false; - if ((information->getObjectTypeFlags() & 0x40000) != 0) + if (information->isOfType(ITStructure)) return true; const int side = information->getSide(); const bool sideOk = m_side == side || side == 0; - return sideOk && (information->getObjectTypeFlags() & 0x10) == 0 - && (information->getObjectTypeFlags() & 0x80) == 0; + return sideOk && !information->isOfType(ITAir) + && !information->isOfType(ITNaval); } int m_side; }; @@ -312,7 +313,7 @@ void BFInformationEnvironment::getEnemyObjects(std::vector& out, B { Information* const self = informationOf(bot); if (radius < 0.0f) - radius = (self->getObjectTypeFlags() & 0x10) != 0 ? 600.0f : 75.0f; + radius = self->isOfType(ITAir) ? 600.0f : 75.0f; InfoEnemyPredicate keep(bot->getSide()); getObjectsWithinRadius(out, radius, *bot, true, &keep); } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h index f0754de20..cb72a5d31 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/DangerObject.h @@ -5,7 +5,7 @@ #include "FireObject.h" #include "Information.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" namespace dice { namespace hfe { namespace ai { diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp index ca0ca7460..916bc4640 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.cpp @@ -8,7 +8,7 @@ #include "Information.h" #include "InformationFactory.h" #include "WeaponInfo.h" -#include "WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp index 2e5daaf89..5095ebbfe 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentKnown.cpp @@ -4,7 +4,7 @@ #include "IPIArmamentKnown.h" #include "WeaponInfo.h" -#include "WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp index 7d099a7ce..5a081a3f7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.cpp @@ -23,7 +23,7 @@ namespace { void clearValidPos(IPIMobile::ValidPos& position) { position.polygon = static_cast(-1); - position.quadTree = static_cast(-1); + position.island = static_cast(-1); position.position.x = 0.0f; position.position.y = 0.0f; position.position.z = 0.0f; @@ -137,7 +137,7 @@ void IPIMobile::setLastValidVehiclePosInternal(const ValidPos& position) { unsigned char material; // Retail ignores getMaterial's result and may inspect this uninitialized. IAIPathfinding::instance->getMaterial(IAIPathfinding::instance->getTraceMapIndex() == 0, - position.quadTree, position.polygon, material); + position.island, position.polygon, material); switch (material) { case 3: diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h index cfc2498d2..5ce679acf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h @@ -21,7 +21,7 @@ class IPIMobile : public InformationPlugIn struct ValidPos { unsigned int polygon; - unsigned int quadTree; + unsigned int island; // name: AIDLL_r assert "oldVehicleVP.island != invalidIslandId" (0x100CDD00; +4) Vec3 position; }; diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp index 35d73c7bf..8a19fac43 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp @@ -9,7 +9,7 @@ #include #include "Information.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp index d5043eef0..fc1542c69 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalDummy.cpp @@ -9,7 +9,7 @@ #include #include "Information.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp index db8e2647e..4d2c99405 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp @@ -9,7 +9,7 @@ #include #include "Information.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp index 29d76a6bd..78ca16b34 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp @@ -6,7 +6,7 @@ #include #include "Information.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectPhysical diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp index 190086947..a78a0443f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp @@ -11,8 +11,8 @@ #include "IPIArmament.h" #include "IPIPhysical.h" #include "WeaponInfo.h" -#include "WeaponInfoManager.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../AIUtils/WeaponInfoManager.h" +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../AIUtils/checkPointer.h" #include "../Main/AISettingsInterfaces.h" #include "../Main/CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp index ccecdcaad..0039931e2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.cpp @@ -11,7 +11,7 @@ #include "IPIMobile.h" #include "IPIPhysical.h" #include "IPIUnit.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObject, IAIObjectMobile namespace dice { namespace hfe { namespace ai { @@ -19,7 +19,7 @@ namespace dice { namespace hfe { namespace ai { // the time, the owner, not booked, no plug-in. The // +0x04..+0x14 prefix is not touched here (the subclass constructors write it). Information::Information(IAIObject* object, double time) - : m_time(time), m_object(object), m_booked(false), m_bookingPlayerId(-1), + : m_time(time), m_object(object), m_isBooked(false), m_bookingPlayerId(-1), m_armament(0), m_controlInfo(0), m_cover(0), m_mobile(0), m_physical(0), m_unit(0) { } @@ -263,7 +263,7 @@ int Information::getBookingPlayerId() bool Information::isBooked() { - return m_booked; + return m_isBooked; } // Compares the id alone - a cancelled booking (-1) is "booked by" player -1. @@ -274,13 +274,13 @@ bool Information::isBookedBy(int playerId) void Information::bookVehicle(int playerId) { - m_booked = true; + m_isBooked = true; m_bookingPlayerId = playerId; } void Information::cancelBookVehicle() { - m_booked = false; + m_isBooked = false; m_bookingPlayerId = -1; } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h index d81e63a8e..a7f10d1af 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/Information.h @@ -11,6 +11,7 @@ #include "../../../../Math/Vec3.h" #include "../../../AIInterface/BFKnowledge/SoldierPose.h" +#include "../../../AIInterface/BFKnowledge/InformationType.h" namespace dice { namespace hfe { @@ -107,6 +108,13 @@ class Information IPIPhysical* getPhysical() const { return m_physical; } IPIUnit* getUnit() const { return m_unit; } unsigned int getObjectTypeFlags() const { return m_objectTypeFlags; } + // DICE's name and form: AIDLL_r.dll (BoosterPack2 debug build) asserts + // "!targetPrimaryInfo->isOfType(ITSoldier)" (BBPChange.cpp, 0x100FD302) and inlines it as + // `(types >> n) & 1` (shr 0x15 / test 1); "Object has no cover plugin but is of type ITCover" + // (BFInformationEnvironment.cpp, 0x101A8419) tests bit 14. Bit n is InformationType n + // (AIDLL_r's enum-to-string switch 0x100D3010, jump table 0x100D32EC: 0 ITProduction .. 26 + // ITHasCarHorn). Both retail images expand it inline as a single-bit test. + bool isOfType(InformationType type) const { return ((m_objectTypeFlags >> type) & 1) != 0; } float getStrength() const { return m_strength; } // BotMain::updateBotVehicle (ELF 0x18BCC0) scales +0x10 inline (x0.75 / x1.3333334). void setStrength(float strength) { m_strength = strength; } @@ -127,14 +135,14 @@ class Information /* +0x00 */ // vptr // Offsets describe ELF. PE members are four bytes higher through +0x18 and eight higher // from the first double onward because of alignment. Original sizes: ELF 68, PE 80 bytes. - /* +0x04 */ unsigned int m_objectTypeFlags; // [INFERRED] name; InformationReal: the template's types + /* +0x04 */ unsigned int m_objectTypeFlags; // [INFERRED] name; InformationReal: the template's types (InformationType bits, see isOfType) /* +0x08 */ float m_allowedTimeDiff; // [INFERRED] name; InformationReal's constructor /* +0x0C */ unsigned char m_unwritten0C[4]; // not written by InformationReal /* +0x10 */ float m_strength; // [INFERRED] name; InformationReal: the template's basicTemp /* +0x14 */ float m_basicTemp; // [INFERRED] name; InformationReal: basicTemp again /* +0x18 */ double m_time; // the constructor's time /* +0x20 */ IAIObject* m_object; // the constructor's owner - /* +0x24 */ bool m_booked; // constructed false; bookVehicle / cancelBookVehicle + /* +0x24 */ bool m_isBooked; // constructed false; bookVehicle / cancelBookVehicle // name: AIDLL_r asserts "m_isBooked != false" / "== false" (0x10161E70) /* +0x28 */ int m_bookingPlayerId; // constructed -1 /* +0x2C */ IPIArmament* m_armament; // type 4 /* +0x30 */ IPIControlInfo* m_controlInfo; // type 5 diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp index 1f2ba1f65..5f401abe3 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp @@ -9,7 +9,7 @@ #include #include "Information.h" -#include "InformationManager.h" +#include "../Main/InformationManager.h" #include "InformationKnown.h" #include "InformationReal.h" #include "IPIArmamentKnown.h" @@ -23,7 +23,7 @@ #include "IPIUnit.h" #include "WeaponInfoKnown.h" #include "WeaponInfoReal.h" -#include "WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIUtils/checkPointer.h" #include "../../../../Core/ClassManager.h" #include "../../../../Core/Ids.h" // IID_IBase diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp index 4cd4a5ae3..66d19c6f4 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp @@ -13,8 +13,8 @@ #include "IPIMobile.h" #include "IPIPhysical.h" #include "IPIUnit.h" -#include "InformationManager.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../Main/InformationManager.h" +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTerrain.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp index bc7cc124d..c393f139c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.cpp @@ -9,8 +9,8 @@ #include "IPIPhysical.h" #include "IPIUnit.h" -#include "InformationManager.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../Main/InformationManager.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../Main/CommonSingletonServer.h" #include "../../../../Math/Mat4.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" // IBFTimer::getGameTime diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp index e23bf6b58..88534c376 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp @@ -3,7 +3,7 @@ #include "WeaponInfoKnown.h" -#include "../AIBotBehaviour/CustomCurve.h" // SCurve::calculate (static) +#include "../AIUtils/CustomCurve.h" // SCurve::calculate (static) #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" @@ -31,12 +31,12 @@ void WeaponInfoKnown::sample() // 0x2DD420: samples the weapon now, then the shots of each magazine (the magazine count is // re-read every iteration). WeaponInfoKnown::WeaponInfoKnown(IWeapon* weapon) - : WeaponInfo(weapon), m_shotsInMag() + : WeaponInfo(weapon), m_mags() { sample(); - m_sampleTime = gameTime(); + m_timeStamp = gameTime(); for (int i = 0; i < m_weapon->getNumberOfMags(); ++i) // +0xCC - m_shotsInMag.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 + m_mags.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 } WeaponInfoKnown::~WeaponInfoKnown() @@ -47,21 +47,21 @@ WeaponInfoKnown::~WeaponInfoKnown() bool WeaponInfoKnown::update() { const double now = gameTime(); - if (now > m_sampleTime + 1.0f) + if (now > m_timeStamp + 1.0f) { sample(); - m_sampleTime = now; - m_shotsInMag.resize(0); + m_timeStamp = now; + m_mags.resize(0); for (int i = 0; i < m_weapon->getNumberOfMags(); ++i) // +0xCC - m_shotsInMag.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 + m_mags.push_back(m_weapon->getAmmoInMag(i)); // +0xC0 } return true; } // 0x2DD990 (unchecked index). -int WeaponInfoKnown::getShotsInMag(int magazine) +int WeaponInfoKnown::getShotsInMag(int mag) { - return m_shotsInMag[magazine]; + return m_mags[mag]; } int WeaponInfoKnown::getAmmo() const @@ -77,7 +77,7 @@ int WeaponInfoKnown::getCurrentAmmo() const // 0x2DD9D0: the number of sampled magazines. int WeaponInfoKnown::getNumberOfMags() const { - return static_cast(m_shotsInMag.size()); + return static_cast(m_mags.size()); } bool WeaponInfoKnown::isReadyToFire() const @@ -110,7 +110,7 @@ float WeaponInfoKnown::getSecurity() const // 0x2DDA80: one minus the SCurve of a fifth of the sample's age. float WeaponInfoKnown::getSecurity(double time) const { - return 1.0f - SCurve::calculate(static_cast((time - m_sampleTime) * 0.2)); + return 1.0f - SCurve::calculate(static_cast((time - m_timeStamp) * 0.2)); } } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h index 03a8ed03a..72aa555b2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.h @@ -18,7 +18,7 @@ class WeaponInfoKnown : public WeaponInfo virtual ~WeaponInfoKnown(); virtual bool update(); - virtual int getShotsInMag(int magazine); + virtual int getShotsInMag(int mag); virtual int getAmmo() const; virtual int getCurrentAmmo() const; virtual int getNumberOfMags() const; @@ -32,13 +32,13 @@ class WeaponInfoKnown : public WeaponInfo private: void sample(); - /* +0x0C */ std::vector m_shotsInMag; + /* +0x0C */ std::vector m_mags; // name: AIDLL_r assert 0x1016CB30 (PE +0xC) /* +0x18 */ int m_ammo; /* +0x1C */ int m_currentAmmo; /* +0x20 */ bool m_readyToFire; /* +0x24 */ float m_heat; /* +0x28 */ double m_timeOfFiring; - /* +0x30 */ double m_sampleTime; // [INFERRED] name + /* +0x30 */ double m_timeStamp; // name: AIDLL_r assert 0x1016CD60 (PE +0x38) }; } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.cpp similarity index 91% rename from Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp rename to Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.cpp index 1a42768ea..6d4d05292 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.cpp @@ -7,13 +7,13 @@ // 0x313C40, __tcf_0 0x313CA0, _GLOBAL__I 0x313CD0). #include -#include "../Main/CommonSingletonServer.h" -#include "../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate -#include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment::getMaxHeight -#include "../../../AIInterface/BFKnowledge/IAIObject.h" -#include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getLevelPath -#include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain, the world bounds -#include "../../../../IO/File/File.h" +#include "../../Main/CommonSingletonServer.h" +#include "../../../../AIInterface/BFKnowledge/AIAdapterTypes.h" // AIObjectPredicate +#include "../../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // IAIObjectEnvironment::getMaxHeight +#include "../../../../AIInterface/BFKnowledge/IAIObject.h" +#include "../../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getLevelPath +#include "../../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain, the world bounds +#include "../../../../../IO/File/File.h" namespace dice { namespace hfe { @@ -23,7 +23,8 @@ AerialHeightMap* AerialHeightMap::m_instance = 0; // Filters vehicles out of the height probe: accepts every object that is not mobile. Inline in // the image (weak ELF 0x313CF0, emitted with this TU), so declared here; its vtable has the one -// predicate slot and no destructor. Placement is [INFERRED]. +// predicate slot and no destructor. Placement: AIDLL_r.dll __FILE__ +// "Code\BF2\AI\AIDLL\AI\AIPathFinding\AerialHeightMap\AerialHeightMap.cpp" (0x1007D0E0). class AIObjectPredicateNoVehicles : public AIObjectPredicate { public: diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h similarity index 86% rename from Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h rename to Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h index 41b2429ed..add12cf70 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h @@ -1,12 +1,12 @@ // Cached ground heights for aerial navigation. Sampling requires in-range coordinates. // An empty map reports the missing-height sentinel 9999. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIPathFinding/AerialHeightMap/AerialHeightMap.cpp: singleton assert in 0x1007D0E0). #ifndef AI_AIDLL_AI_AISTRATEGICMAP_AERIALHEIGHTMAP_H #define AI_AIDLL_AI_AISTRATEGICMAP_AERIALHEIGHTMAP_H -#include "../Main/AIDllTypes.h" // Vec3 -#include "../../../../Math/Vec3.h" // Vec2 lives here too, and both are typedefs - never +#include "../../Main/AIDllTypes.h" // Vec3 +#include "../../../../../Math/Vec3.h" // Vec2 lives here too, and both are typedefs - never // forward-declare either one; see AILandingZoneManager.h. namespace dice { diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp index 1a55ba214..bd1ac8cfb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp @@ -34,8 +34,8 @@ void ClusterGraph::readGTSDataFromFile(QuadTree* tree, io::File& file) { Cluster& cluster = m_clusters[i]; unsigned int count; - cluster.readGTSDataFromFile(m_clusterPolygons + m_numberOfClusterPolygons, - count, m_numberOfClusterPolygons, file); + cluster.readGTSDataFromFile(m_clusterPolygons + m_polygonCount, + count, m_polygonCount, file); const unsigned int first = cluster.m_firstPolygon; const unsigned int size = cluster.m_numberOfPolygons; for (unsigned int j = 0; j < size; ++j) @@ -43,10 +43,10 @@ void ClusterGraph::readGTSDataFromFile(QuadTree* tree, io::File& file) const unsigned int id = m_clusterPolygons[first + j]; Polygon* polygon = tree->getPolygon(id); DoublePolygon* doublePolygon = tree->getPolygonDouble(id); - polygon->m_cluster = i; + polygon->cluster = i; doublePolygon->m_cluster = i; } - m_numberOfClusterPolygons += count; + m_polygonCount += count; } } @@ -175,14 +175,14 @@ void ClusterGraph::buildClusterEdges(const Cluster& cluster, unsigned short clus { const unsigned int id = m_clusterPolygons[first + j]; const Polygon* polygon = tree->getPolygon(id); - for (unsigned char edge = 0; edge < polygon->m_numberOfVertices; ++edge) + for (unsigned char edge = 0; edge < polygon->vertexCount; ++edge) { const unsigned int neighbourId = tree->getNeighbourOfPolygon(id, edge); const Polygon* neighbour = tree->getPolygon(neighbourId); - if (!neighbour || neighbour->m_cluster == polygon->m_cluster) continue; + if (!neighbour || neighbour->cluster == polygon->cluster) continue; const unsigned int a = tree->getVertexIndexForPolygon(id, edge); const unsigned int b = tree->getVertexIndexForPolygon(id, - static_cast((edge + 1) % polygon->m_numberOfVertices)); + static_cast((edge + 1) % polygon->vertexCount)); for (int endpoint = 0; endpoint < 2; ++endpoint) { const unsigned int vertex = endpoint == 0 ? a : b; @@ -190,14 +190,14 @@ void ClusterGraph::buildClusterEdges(const Cluster& cluster, unsigned short clus if (found == vertices.end()) { std::map clusters; - clusters.insert(std::make_pair(neighbour->m_cluster, 1U)); + clusters.insert(std::make_pair(neighbour->cluster, 1U)); vertices.insert(std::make_pair(vertex, clusters)); } else { - std::map::iterator entry = found->second.find(neighbour->m_cluster); + std::map::iterator entry = found->second.find(neighbour->cluster); if (entry == found->second.end()) - found->second.insert(std::make_pair(neighbour->m_cluster, 1U)); + found->second.insert(std::make_pair(neighbour->cluster, 1U)); else if (++entry->second > 2) { printClusterInfo(clusterId, tree, false); @@ -206,13 +206,13 @@ void ClusterGraph::buildClusterEdges(const Cluster& cluster, unsigned short clus } } } - ClusterEdges::iterator found = edges.find(neighbour->m_cluster); + ClusterEdges::iterator found = edges.find(neighbour->cluster); const std::pair edgePair(a, b); if (found == edges.end()) { std::list > list; list.push_back(edgePair); - edges.insert(std::make_pair(neighbour->m_cluster, list)); + edges.insert(std::make_pair(neighbour->cluster, list)); } else found->second.push_back(edgePair); @@ -341,7 +341,7 @@ bool ClusterGraph::calculateMiddleVertex(unsigned short cluster, const ClusterPo if (found) { const bool valid = materials->isValidMaterial(result->m_material); - const bool rightCluster = result->m_cluster == cluster || result->m_cluster == info.neighbour; + const bool rightCluster = result->cluster == cluster || result->cluster == info.neighbour; if (valid && rightCluster) return true; } Vec3 direction; @@ -371,7 +371,7 @@ bool ClusterGraph::calculateMiddleVertex(unsigned short cluster, const ClusterPo { result = tree->getPolygon(polygon); const bool valid = materials->isValidMaterial(result->m_material); - const bool rightCluster = result->m_cluster == cluster || result->m_cluster == info.neighbour; + const bool rightCluster = result->cluster == cluster || result->cluster == info.neighbour; if (valid && rightCluster) return true; } distance += 0.1f; @@ -407,14 +407,14 @@ void ClusterGraph::movePolygonBetweenClusters(unsigned short source, unsigned sh unsigned int polygon) { Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters]); - unsigned int* polygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); + unsigned int* polygons = checkPointer(new unsigned int[m_polygonCount]); for (unsigned int i = 0; i < m_numberOfClusters; ++i) { if (i == source) adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons - 1; else if (i == destination) adjusted[i].m_numberOfPolygons = m_clusters[destination].m_numberOfPolygons + 1; else adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; } - for (unsigned int i = 0; i < m_numberOfClusterPolygons; ++i) + for (unsigned int i = 0; i < m_polygonCount; ++i) { // shipped defect: skipped entries leave holes; insertion also skips the old destination entry. if (m_clusterPolygons[i] == polygon) continue; @@ -439,7 +439,7 @@ void ClusterGraph::addPolygonsToNewCluster(const std::set& selecte std::list& mesh) { Cluster* adjusted = checkPointer(new Cluster[m_numberOfClusters + 1]); - unsigned int* polygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); + unsigned int* polygons = checkPointer(new unsigned int[m_polygonCount]); for (unsigned int i = 0; i < m_numberOfClusters; ++i) adjusted[i].m_numberOfPolygons = m_clusters[i].m_numberOfPolygons; unsigned int write = 0; @@ -725,10 +725,10 @@ void ClusterGraph::getAllDeepWaterAndInvalidPolygonsInCluster(unsigned short clu // ELF 0x31B5B0. void ClusterGraph::setPolygonIndices(const ClusterPolygonMap& clusters) { - m_numberOfClusterPolygons = 0; + m_polygonCount = 0; for (ClusterPolygonMap::const_iterator i = clusters.begin(); i != clusters.end(); ++i) - m_numberOfClusterPolygons += static_cast(i->second.size()); - unsigned int* polygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); + m_polygonCount += static_cast(i->second.size()); + unsigned int* polygons = checkPointer(new unsigned int[m_polygonCount]); unsigned int write = 0; for (ClusterPolygonMap::const_iterator i = clusters.begin(); i != clusters.end(); ++i) for (std::list::const_iterator p = i->second.begin(); p != i->second.end(); ++p) @@ -774,7 +774,7 @@ bool ClusterGraph::validateClusterConnectivityFromPolygon(unsigned short, OptPol // SGI node allocator is inlined into it - same source, two inlining decisions. ClusterGraph::ClusterGraph() : m_clusterPolygons(0) - , m_numberOfClusterPolygons(0) + , m_polygonCount(0) , m_clusters(0) , m_numberOfClusters(0) , m_numberOfPortals(0) @@ -797,7 +797,7 @@ ClusterGraph::~ClusterGraph() void ClusterGraph::clean() { delete[] m_clusterPolygons; - m_numberOfClusterPolygons = 0; + m_polygonCount = 0; delete[] m_clusters; m_numberOfClusters = 0; @@ -826,9 +826,9 @@ void ClusterGraph::readFromFile(io::File& file) m_clusters = checkPointer(new Cluster[m_numberOfClusters]); file.read(m_clusters, sizeof(Cluster) * m_numberOfClusters); - file.read(m_numberOfClusterPolygons); - m_clusterPolygons = checkPointer(new unsigned int[m_numberOfClusterPolygons]); - file.read(m_clusterPolygons, sizeof(unsigned int) * m_numberOfClusterPolygons); + file.read(m_polygonCount); + m_clusterPolygons = checkPointer(new unsigned int[m_polygonCount]); + file.read(m_clusterPolygons, sizeof(unsigned int) * m_polygonCount); file.read(m_numberOfPortals); if (m_numberOfPortals) @@ -857,7 +857,7 @@ void ClusterGraph::readFromFile(io::File& file) // ELF 0x314E10. An out-of-range polygon dereferences null, as in retail. unsigned short ClusterGraph::getClusterId(QuadTree* quadTree, unsigned int polygon) const { - return quadTree->getPolygon(polygon)->m_cluster; + return quadTree->getPolygon(polygon)->cluster; } // ELF 0x31DA70. True when one of the cluster's portals leads to `neighbour`. @@ -1056,8 +1056,8 @@ void ClusterGraph::saveToFile(io::File& file) const file.write(5); file.write(m_numberOfClusters); file.write(m_clusters, sizeof(Cluster) * m_numberOfClusters); - file.write(m_numberOfClusterPolygons); - file.write(m_clusterPolygons, sizeof(unsigned int) * m_numberOfClusterPolygons); + file.write(m_polygonCount); + file.write(m_clusterPolygons, sizeof(unsigned int) * m_polygonCount); file.write(m_numberOfPortals); if (m_numberOfPortals) file.write(m_portals, sizeof(ClusterPortal) * m_numberOfPortals); @@ -1169,13 +1169,13 @@ bool ClusterGraph::allNeighboursOfClusterInSameCluster(QuadTree* quadTree, { const unsigned int polygon = m_clusterPolygons[first + i]; const Polygon* const candidate = quadTree->getPolygon(polygon); - for (unsigned char edge = 0; edge < candidate->m_numberOfVertices; ++edge) + for (unsigned char edge = 0; edge < candidate->vertexCount; ++edge) { const Polygon* const neighbour = quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); - if (neighbour && neighbour->m_cluster != cluster && neighbour->m_cluster != 0xFFFF) + if (neighbour && neighbour->cluster != cluster && neighbour->cluster != 0xFFFF) { - neighbours.insert(neighbour->m_cluster); + neighbours.insert(neighbour->cluster); if (neighbours.size() > 1) return false; } @@ -1199,14 +1199,14 @@ bool ClusterGraph::checkClusterCondition(QuadTree* quadTree, unsigned short clus const unsigned int polygon = m_clusterPolygons[first + i]; const Polygon* const candidate = quadTree->getPolygon(polygon); unsigned char edge = 0; - for (; edge < candidate->m_numberOfVertices; ++edge) + for (; edge < candidate->vertexCount; ++edge) { const Polygon* const neighbour = quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); - if (neighbour && neighbour->m_cluster == cluster) + if (neighbour && neighbour->cluster == cluster) break; } - if (edge >= candidate->m_numberOfVertices) + if (edge >= candidate->vertexCount) return false; } return true; @@ -1224,7 +1224,7 @@ bool ClusterGraph::validateClusterGraphConnectivity(QuadTree* quadTree, bool ver unsigned int members = 0; for (unsigned int i = 0; i < count; ++i) { - if (quadTree->getPolygon(m_clusterPolygons[first + i])->m_cluster == cluster) + if (quadTree->getPolygon(m_clusterPolygons[first + i])->cluster == cluster) ++members; } if (members != count) @@ -1255,7 +1255,7 @@ void ClusterGraph::printClusterInfo(unsigned short cluster, QuadTree* quadTree, { const unsigned int polygon = m_clusterPolygons[first + i]; const Polygon* const candidate = quadTree->getPolygon(polygon); - for (unsigned char edge = 0; edge < candidate->m_numberOfVertices; ++edge) + for (unsigned char edge = 0; edge < candidate->vertexCount; ++edge) { quadTree->getVertexIndexForPolygon(polygon, edge); quadTree->getPolygon(quadTree->getNeighbourOfPolygon(polygon, edge)); diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h index 368f71036..06d8d667e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.h @@ -123,7 +123,7 @@ class ClusterGraph friend class QuadTree; friend class QuadTreeManager; /* +0x00 */ unsigned int* m_clusterPolygons; // [INFERRED] polygon indices grouped by cluster - /* +0x04 */ unsigned int m_numberOfClusterPolygons; // (Dalian Infantry: 18,512, every polygon once) + /* +0x04 */ unsigned int m_polygonCount; // (Dalian Infantry: 18,512, every polygon once) // name: AIDLL_r assert 0x10179F30 (+4) /* +0x08 */ Cluster* m_clusters; // getClusterPortal /* +0x0C */ unsigned int m_numberOfClusters; // loadQuadTrees' empty walk bound /* +0x10 */ unsigned int m_numberOfPortals; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp index 120d58b50..d664f9116 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.cpp @@ -50,9 +50,9 @@ ClusterNodeManager::ClusterNodeManager() , m_clusterGraph(0) , m_goal(0) , m_freeNodes(0) - , m_numberOfNodes(0) + , m_nodeCacheSize(0) , m_freeOCData(0) - , m_numberOfOCData(0) + , m_ocCacheSize(0) , m_ocDataHash(checkPointer(new Hash(kOCDataBuckets))) , m_costType(0) { @@ -75,7 +75,7 @@ ClusterNodeManager::~ClusterNodeManager() ClusterNode* const node = m_freeNodes; m_freeNodes = node->m_next; delete node; - --m_numberOfNodes; + --m_nodeCacheSize; } while (m_freeOCData != 0) @@ -83,7 +83,7 @@ ClusterNodeManager::~ClusterNodeManager() OCData* const data = m_freeOCData; m_freeOCData = data->m_next; delete data; - --m_numberOfOCData; + --m_ocCacheSize; } Hash* const hash = m_ocDataHash; @@ -95,8 +95,8 @@ ClusterNodeManager::~ClusterNodeManager() if (data->m_node != 0) delete data->m_node; delete data; - --m_numberOfOCData; - --m_numberOfNodes; + --m_ocCacheSize; + --m_nodeCacheSize; it.m_node = next; if (it.m_node == 0) { @@ -115,7 +115,7 @@ ClusterNodeManager::~ClusterNodeManager() if (m_goal != 0) { delete m_goal; - --m_numberOfNodes; + --m_nodeCacheSize; } } @@ -263,7 +263,7 @@ ClusterNode* ClusterNodeManager::getNewNode(unsigned short cluster, ClusterNode* else { node = new ClusterNode(cluster, depth); - ++m_numberOfNodes; + ++m_nodeCacheSize; } node->m_parent = parent; return node; @@ -282,7 +282,7 @@ ClusterNode* ClusterNodeManager::getNewNode(ClusterNode* source) else { node = new ClusterNode(*source); - ++m_numberOfNodes; + ++m_nodeCacheSize; } return node; } @@ -405,7 +405,7 @@ ClusterNodeManager::OCData* ClusterNodeManager::getNewOCData() return data; } - ++m_numberOfOCData; + ++m_ocCacheSize; OCData* const data = new OCData; data->m_open = true; data->m_closed = false; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h index 37f34ccf3..010361ba7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNodeManager.h @@ -101,9 +101,9 @@ class ClusterNodeManager /* +20 */ Vec3 m_goalPosition; // the search's goal position /* +32 */ ClusterNode* m_goal; // = 0; setGoal's copy of the goal node /* +36 */ ClusterNode* m_freeNodes; // = 0 - /* +40 */ int m_numberOfNodes; // = 0 + /* +40 */ int m_nodeCacheSize; // = 0 // name: AIDLL_r assert 0x1018FDD0 (PE +0x28) /* +44 */ OCData* m_freeOCData; // = 0 the intrusive free list `recycleOCData` pushes to - /* +48 */ int m_numberOfOCData; // = 0 + /* +48 */ int m_ocCacheSize; // = 0 // name: AIDLL_r assert 0x1018FDD0 (PE +0x30) /* +52 */ Hash* m_ocDataHash; // new Hash(313), then ->this /* +56 */ std::vector m_pathNodes; // buildPath's goal-to-start scratch list /* +68 */ int m_costType; // the vehicle's cluster cost type; read as 16 bits diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp index 8005a1d6c..8ba17cb1a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp @@ -55,7 +55,7 @@ float normalAngle(const DoubleVec3& a, const DoubleVec3& b) } // ELF 0x2F2390 (C2), 0x2F2490 (C1). -GTSDataOptimiser::GTSDataOptimiser(ClusterGraph* graph) : m_current(), m_graph(graph) {} +GTSDataOptimiser::GTSDataOptimiser(ClusterGraph* graph) : m_current(), m_clusterGraph(graph) {} // ELF 0x2F24E0 (D2), 0x2F2550 (D1). GTSDataOptimiser::~GTSDataOptimiser() @@ -262,11 +262,11 @@ OptPolygon* GTSDataOptimiser::createPolygon() const { return checkPointer(new Op // ELF 0x2F3EF0. Only the two-to-one pass is enabled in the shipped optimiser. void GTSDataOptimiser::optimise(const std::vector& parts) { - m_graph->resetTempMemberSizes(); + m_clusterGraph->resetTempMemberSizes(); std::set removed; while (twoToOneMerge(removed)) {} - delete[] m_graph->m_tempMemberSizes; - m_graph->m_tempMemberSizes = 0; + delete[] m_clusterGraph->m_tempMemberSizes; + m_clusterGraph->m_tempMemberSizes = 0; setPolygonIndices(parts); } @@ -274,7 +274,7 @@ void GTSDataOptimiser::optimise(const std::vector& parts) void GTSDataOptimiser::setPolygonIndices(const std::vector& parts) { ClusterGraph::ClusterPolygonMap clusters; - const std::set& removed = m_graph->m_set18; + const std::set& removed = m_clusterGraph->m_set18; std::map oldParts; unsigned int part = 0; for (std::vector::const_iterator p = parts.begin(); p != parts.end(); ++p, ++part) @@ -288,7 +288,7 @@ void GTSDataOptimiser::setPolygonIndices(const std::vector& OptPolygon* polygon = *i; if (removed.find(polygon->m_index) == removed.end()) { - for (unsigned short cluster = 0; cluster < m_graph->m_numberOfClusters; ++cluster) + for (unsigned short cluster = 0; cluster < m_clusterGraph->m_numberOfClusters; ++cluster) if (polygon->m_cluster == cluster) { ClusterGraph::ClusterPolygonMap::iterator entry = clusters.find(cluster); @@ -310,7 +310,7 @@ void GTSDataOptimiser::setPolygonIndices(const std::vector& std::make_pair(entry->second, parts[entry->second]->m_initiallyWalkable))); polygon->m_index = index; } - m_graph->updateClustersAfterOptimisation(newParts, m_polygons, clusters); + m_clusterGraph->updateClustersAfterOptimisation(newParts, m_polygons, clusters); } // ELF 0x2F5D20. Dropping a previous list does not destroy its polygons, as shipped. @@ -484,8 +484,8 @@ bool GTSDataOptimiser::twoToOneMerge(std::set& removed) OptPolygon* discarded = polygon; unsigned short retainedCluster = neighbour->m_cluster; unsigned short discardedCluster = polygon->m_cluster; - unsigned int remaining = m_graph->m_tempMemberSizes[discardedCluster]; - const unsigned int otherSize = m_graph->m_tempMemberSizes[retainedCluster]; + unsigned int remaining = m_clusterGraph->m_tempMemberSizes[discardedCluster]; + const unsigned int otherSize = m_clusterGraph->m_tempMemberSizes[retainedCluster]; if (remaining <= otherSize) { retained = polygon; @@ -498,7 +498,7 @@ bool GTSDataOptimiser::twoToOneMerge(std::set& removed) if (retainedCluster != discardedCluster && remaining > 1) { std::set visited; - if (!m_graph->validateClusterConnectivityFromPolygon(discardedCluster, discarded, + if (!m_clusterGraph->validateClusterConnectivityFromPolygon(discardedCluster, discarded, remaining, visited, false)) { visited.clear(); @@ -508,8 +508,8 @@ bool GTSDataOptimiser::twoToOneMerge(std::set& removed) output = createPolygon(); output->m_index = retained->m_index; output->m_cluster = retainedCluster; - m_graph->m_set18.insert(discarded->m_index); - m_graph->m_tempMemberSizes[discardedCluster] = remaining; + m_clusterGraph->m_set18.insert(discarded->m_index); + m_clusterGraph->m_tempMemberSizes[discardedCluster] = remaining; std::list vertices; std::list neighbours; for (int corner = firstOther; corner != lastOther; corner = wrappedIndex(corner + 1, otherCount)) @@ -711,7 +711,7 @@ void GTSDataOptimiser::removeTooThinTriangles() } m_polygons.insert(m_polygons.end(), split[half]); } - ++m_graph->m_tempMemberSizes[across->m_cluster]; + ++m_clusterGraph->m_tempMemberSizes[across->m_cluster]; removed.insert(across); } if (before) before->changeNeighbour(polygon->m_vertices[opposite], polygon, split[0]); @@ -726,8 +726,8 @@ void GTSDataOptimiser::removeTooThinTriangles() { if (removed.find(*i) == removed.end()) { ++i; continue; } OptPolygon* polygon = *i; - m_graph->m_set18.insert(polygon->m_index); - --m_graph->m_tempMemberSizes[polygon->m_cluster]; + m_clusterGraph->m_set18.insert(polygon->m_index); + --m_clusterGraph->m_tempMemberSizes[polygon->m_cluster]; m_polygons.erase(i++); destroyPolygon(polygon); } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h index 0ea4e0fc7..8b357e509 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.h @@ -74,7 +74,7 @@ class GTSDataOptimiser /* +0x00 */ std::list m_polygons; /* +0x04 */ std::list::iterator m_current; - /* +0x08 */ ClusterGraph* m_graph; + /* +0x08 */ ClusterGraph* m_clusterGraph; // name: AIDLL_r assert 0x101F74E0 (PE +0x10) }; } } } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp index f0c255e05..a3ca45749 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp @@ -199,7 +199,7 @@ QTSearchNode* QTSearchNodeManager::getNeighbourOfNode(QTSearchNode* node, unsign while (neighbourPolygon == 0xFFFFFFFFu) { ++edge; - if (edge >= m_quadTree->getPolygon(node->m_key)->m_numberOfVertices) + if (edge >= m_quadTree->getPolygon(node->m_key)->vertexCount) { status = nodeStatus::kInvalid; return 0; @@ -225,7 +225,7 @@ QTSearchNode* QTSearchNodeManager::getNeighbourOfNode(QTSearchNode* node, unsign return neighbour; } - if (m_allowedClusters != 0 && m_allowedClusters->find(polygon->m_cluster) == m_allowedClusters->end()) + if (m_allowedClusters != 0 && m_allowedClusters->find(polygon->cluster) == m_allowedClusters->end()) { status = nodeStatus::kInvalid; return neighbour; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp index dcc8dcc8c..d6aa1747f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp @@ -62,9 +62,9 @@ void normalizeGTSNormal(Vector& normal, Scalar) void QuadTree::readGTSDataFromFileDoubles(io::File& file) { clean(); - file.read(m_numberOfVertices); + file.read(m_vertexCount); file.read(m_numberOfPolygons); - m_numberOfVertexIndices = m_numberOfPolygons * 3; + m_vertexIndexCount = m_numberOfPolygons * 3; m_numberOfNeighbours = m_numberOfPolygons * 3; file.read(m_double8C); file.read(m_double94); @@ -75,11 +75,11 @@ void QuadTree::readGTSDataFromFileDoubles(io::File& file) m_doubleAC = zSize > xSize ? zSize : xSize; m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); m_array88 = checkPointer(new DoublePolygon[m_numberOfPolygons]); - m_array84 = checkPointer(new DoubleVec3[m_numberOfVertices]()); - m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); + m_array84 = checkPointer(new DoubleVec3[m_vertexCount]()); + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); - file.read(m_array84, m_numberOfVertices * 24); - file.read(m_vertexIndices, m_numberOfVertexIndices * 4); + file.read(m_array84, m_vertexCount * 24); + file.read(m_vertexIndices, m_vertexIndexCount * 4); std::vector polygons; DoubleVec3* normals = checkPointer(new DoubleVec3[m_numberOfPolygons]()); file.read(normals, m_numberOfPolygons * 24); @@ -93,8 +93,8 @@ void QuadTree::readGTSDataFromFileDoubles(io::File& file) polygons.push_back(p); m_array88[p].m_numberOfVertices = 3; m_array88[p].m_firstIndex = p * 3; - m_polygons[p].m_numberOfVertices = 3; - m_polygons[p].m_firstIndex = p * 3; + m_polygons[p].vertexCount = 3; + m_polygons[p].vertexOffset = p * 3; const DoubleVec3& av = m_array84[m_vertexIndices[p * 3]]; const DoubleVec3& bv = m_array84[m_vertexIndices[p * 3 + 1]]; const DoubleVec3& cv = m_array84[m_vertexIndices[p * 3 + 2]]; @@ -128,9 +128,9 @@ void QuadTree::readGTSDataFromFileDoubles(io::File& file) void QuadTree::readGTSDataFromFile(io::File& file) { clean(); - file.read(m_numberOfVertices); + file.read(m_vertexCount); file.read(m_numberOfPolygons); - m_numberOfVertexIndices = m_numberOfPolygons * 3; + m_vertexIndexCount = m_numberOfPolygons * 3; m_numberOfNeighbours = m_numberOfPolygons * 3; file.read(m_min); file.read(m_max); @@ -138,11 +138,11 @@ void QuadTree::readGTSDataFromFile(io::File& file) const float zSize = m_max.y - m_min.y; m_size = zSize > xSize ? zSize : xSize; m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); - m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); - m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); + m_vertices = checkPointer(new Vec3[m_vertexCount]()); + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); - file.read(m_vertices, m_numberOfVertices * 12); - file.read(m_vertexIndices, m_numberOfVertexIndices * 4); + file.read(m_vertices, m_vertexCount * 12); + file.read(m_vertexIndices, m_vertexIndexCount * 4); std::vector polygons; Vec3* normals = checkPointer(new Vec3[m_numberOfPolygons]()); file.read(normals, m_numberOfPolygons * 12); @@ -154,8 +154,8 @@ void QuadTree::readGTSDataFromFile(io::File& file) for (unsigned int p = 0; p < m_numberOfPolygons; ++p) { polygons.push_back(p); - m_polygons[p].m_numberOfVertices = 3; - m_polygons[p].m_firstIndex = p * 3; + m_polygons[p].vertexCount = 3; + m_polygons[p].vertexOffset = p * 3; if (environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3]]) && environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3 + 1]]) && environment->isAiPositionInsideCombatArea(m_vertices[m_vertexIndices[p * 3 + 2]])) @@ -212,9 +212,9 @@ DoublePolygon* QuadTree::getPolygonDouble(unsigned int polygon) const void QuadTree::buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser) { m_numberOfPolygons = static_cast(optimiser->m_polygons.size()); - m_numberOfVertices = optimiser->getNumberOfVertices(); - m_numberOfVertexIndices = m_numberOfVertices; - m_numberOfNeighbours = m_numberOfVertices; + m_vertexCount = optimiser->getNumberOfVertices(); + m_vertexIndexCount = m_vertexCount; + m_numberOfNeighbours = m_vertexCount; m_min.x = static_cast(m_double8C); m_min.y = static_cast(m_double94); m_max.x = static_cast(m_double9C); @@ -225,9 +225,9 @@ void QuadTree::buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser) delete[] m_polygons; m_polygons = checkPointer(new Polygon[m_numberOfPolygons]); delete[] m_vertices; - m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); + m_vertices = checkPointer(new Vec3[m_vertexCount]()); delete[] m_vertexIndices; - m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); delete[] m_neighbours; m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); std::vector polygons; @@ -238,13 +238,13 @@ void QuadTree::buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser) if (p->m_material != 0) p->m_material = p->m_originalMaterial; polygons.push_back(polygon); - m_polygons[polygon].m_numberOfVertices = p->m_numberOfVertices; - m_polygons[polygon].m_firstIndex = first; + m_polygons[polygon].vertexCount = p->m_numberOfVertices; + m_polygons[polygon].vertexOffset = first; m_polygons[polygon].m_material = p->m_material; const DoubleVec3* normal = p->getNormal(); m_polygons[polygon].m_normal = Vec3{static_cast(normal->x), static_cast(normal->y), static_cast(normal->z)}; - m_polygons[polygon].m_cluster = p->m_cluster; + m_polygons[polygon].cluster = p->m_cluster; const unsigned char count = p->m_numberOfVertices; for (unsigned char corner = 0; corner < count; ++corner) { @@ -267,11 +267,11 @@ void QuadTree::buildQuadTreeMeshFromOptMesh(GTSDataOptimiser* optimiser) void QuadTree::removeDuplicateVerticesFromOptMesh() { std::vector > mapping( - m_numberOfVertexIndices, std::make_pair(false, 0u)); + m_vertexIndexCount, std::make_pair(false, 0u)); unsigned int count = 0; buildQuadTreesForDuplicateVertices(mapping, count); Vec3* vertices = checkPointer(new Vec3[count]()); - for (unsigned int i = 0; i < m_numberOfVertexIndices; ++i) + for (unsigned int i = 0; i < m_vertexIndexCount; ++i) { if (mapping[i].first) { @@ -288,7 +288,7 @@ void QuadTree::removeDuplicateVerticesFromOptMesh() } delete[] m_vertices; m_vertices = vertices; - m_numberOfVertices = count; + m_vertexCount = count; } // ELF 0x305360. @@ -332,7 +332,7 @@ void QuadTree::initialDivideQuadsAndTestForDuplicateVertices(std::vector* std::vector* indices, std::vector >& bounds) { appendDuplicateVertexQuadrants(m_min, m_max, bounds); - for (unsigned int i = 0; i < m_numberOfVertices; ++i) + for (unsigned int i = 0; i < m_vertexCount; ++i) { Vec3* vertex = m_vertices + i; for (unsigned int q = 0; q < 4; ++q) @@ -420,7 +420,7 @@ QuadTree::QuadTree(unsigned int island) : m_island(island) , m_numberOfPolygons(0) , m_numberOfNodePolygons(0) - , m_numberOfVertices(0) + , m_vertexCount(0) , m_nodes(0) , m_polygons(0) , m_nodePolygons(0) @@ -440,7 +440,7 @@ QuadTree::QuadTree(unsigned int island) m_max.x = 0.0f; m_max.y = 0.0f; - // m_size, m_numberOfNodes, m_numberOfVertexIndices and m_numberOfNeighbours deliberately not + // m_size, m_numberOfNodes, m_vertexIndexCount and m_numberOfNeighbours deliberately not // initialised - both binaries step over them. } @@ -463,8 +463,8 @@ void QuadTree::clean() m_numberOfNodes = 0; m_numberOfPolygons = 0; m_numberOfNodePolygons = 0; - m_numberOfVertices = 0; - m_numberOfVertexIndices = 0; + m_vertexCount = 0; + m_vertexIndexCount = 0; m_numberOfNeighbours = 0; m_nodes = 0; m_polygons = 0; @@ -522,13 +522,13 @@ void QuadTree::readFromFile(io::File& file) m_nodePolygons = checkPointer(new unsigned int[m_numberOfNodePolygons]); file.read(m_nodePolygons, sizeof(unsigned int) * m_numberOfNodePolygons); - file.read(m_numberOfVertices); - m_vertices = checkPointer(new Vec3[m_numberOfVertices]()); - file.read(m_vertices, sizeof(Vec3) * m_numberOfVertices); + file.read(m_vertexCount); + m_vertices = checkPointer(new Vec3[m_vertexCount]()); + file.read(m_vertices, sizeof(Vec3) * m_vertexCount); - file.read(m_numberOfVertexIndices); - m_vertexIndices = checkPointer(new unsigned int[m_numberOfVertexIndices]); - file.read(m_vertexIndices, sizeof(unsigned int) * m_numberOfVertexIndices); + file.read(m_vertexIndexCount); + m_vertexIndices = checkPointer(new unsigned int[m_vertexIndexCount]); + file.read(m_vertexIndices, sizeof(unsigned int) * m_vertexIndexCount); file.read(m_numberOfNeighbours); m_neighbours = checkPointer(new unsigned int[m_numberOfNeighbours]); @@ -559,7 +559,7 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons vec3ToVec2XZ(point, point2); unsigned char edge = 0; - if (polygon->m_numberOfVertices == 0) + if (polygon->vertexCount == 0) return true; do @@ -567,14 +567,14 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons Vec2 first; first.x = 0.0f; first.y = 0.0f; - vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->m_firstIndex + edge]], first); + vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->vertexOffset + edge]], first); Vec2 second; second.x = 0.0f; second.y = 0.0f; const unsigned char next = static_cast( - (edge + 1) % polygon->m_numberOfVertices); - vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->m_firstIndex + next]], second); + (edge + 1) % polygon->vertexCount); + vec3ToVec2XZ(m_vertices[m_vertexIndices[polygon->vertexOffset + next]], second); if ((second.y - first.y) * (point2.x - first.x) + (point2.y - first.y) * -(second.x - first.x) < -0.001f) @@ -582,7 +582,7 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons ++edge; } - while (edge < polygon->m_numberOfVertices); + while (edge < polygon->vertexCount); return true; } @@ -591,7 +591,7 @@ bool QuadTree::pointWithinPolygonEdges(Polygon* polygon, const Vec3& point) cons bool QuadTree::withinPolygon(Polygon* polygon, const Vec3& point, float& distanceSquared, float allowedHeightDiff) const { - const Vec3& first = m_vertices[m_vertexIndices[polygon->m_firstIndex]]; + const Vec3& first = m_vertices[m_vertexIndices[polygon->vertexOffset]]; Plane3 plane; plane.normal = polygon->m_normal; @@ -644,15 +644,15 @@ void QuadTree::getVerticiesOfPolygon(std::vector& vertices, { Polygon* const candidate = &m_polygons[polygon]; unsigned char corner = 0; - if (candidate->m_numberOfVertices == 0) + if (candidate->vertexCount == 0) return; do { - vertices.push_back(&m_vertices[m_vertexIndices[candidate->m_firstIndex + corner]]); + vertices.push_back(&m_vertices[m_vertexIndices[candidate->vertexOffset + corner]]); ++corner; } - while (corner < candidate->m_numberOfVertices); + while (corner < candidate->vertexCount); } // ELF 0x3081A0. Retail directly indexes the polygon array; there is no bounds or @@ -669,7 +669,7 @@ void QuadTree::setMaterialOfPolygon(unsigned int polygon, unsigned char material } // Polygon topology accessors. Each polygon's corners and neighbours share one run of indices -// starting at m_firstIndex: corner i is m_vertices[m_vertexIndices[first + i]], and the polygon +// starting at vertexOffset: corner i is m_vertices[m_vertexIndices[first + i]], and the polygon // across the edge from corner i to corner i + 1 is m_neighbours[first + i] (UINT_MAX on a border). // None of these checks the polygon id; the "safe" variants only wrap the corner index. @@ -685,9 +685,9 @@ Polygon* QuadTree::getPolygon(unsigned int polygon) const unsigned int QuadTree::getNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const { const Polygon* const record = &m_polygons[polygon]; - if (edge >= record->m_numberOfVertices) + if (edge >= record->vertexCount) return 0xFFFFFFFFu; - return m_neighbours[record->m_firstIndex + edge]; + return m_neighbours[record->vertexOffset + edge]; } // ELF 0x306F80. The start polygon is appended unconditionally (no sentinel or duplicate test, @@ -697,8 +697,8 @@ void QuadTree::getPolygonsInRadius(std::list& polygons, unsigned i { polygons.insert(polygons.end(), polygon); const Polygon* const record = &m_polygons[polygon]; - for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) - getPolygonsInRadiusInternal(polygons, m_neighbours[record->m_firstIndex + edge], centre, + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInRadiusInternal(polygons, m_neighbours[record->vertexOffset + edge], centre, radius); } @@ -719,9 +719,9 @@ void QuadTree::getPolygonsInRadiusInternal(std::list& polygons, const float radiusSqr = radius * radius; const Polygon* const record = &m_polygons[polygon]; - unsigned char previous = static_cast(record->m_numberOfVertices - 1); + unsigned char previous = static_cast(record->vertexCount - 1); - const Vec3& first = m_vertices[m_vertexIndices[record->m_firstIndex]]; + const Vec3& first = m_vertices[m_vertexIndices[record->vertexOffset]]; float dx = centre.x - first.x; float dy = centre.y - first.y; float dz = centre.z - first.z; @@ -729,10 +729,10 @@ void QuadTree::getPolygonsInRadiusInternal(std::list& polygons, if (!touches) { - for (unsigned char i = 0; i < record->m_numberOfVertices; ++i) + for (unsigned char i = 0; i < record->vertexCount; ++i) { - const Vec3& a = m_vertices[m_vertexIndices[record->m_firstIndex + i]]; - const Vec3& b = m_vertices[m_vertexIndices[record->m_firstIndex + previous]]; + const Vec3& a = m_vertices[m_vertexIndices[record->vertexOffset + i]]; + const Vec3& b = m_vertices[m_vertexIndices[record->vertexOffset + previous]]; dx = centre.x - b.x; dy = centre.y - b.y; @@ -773,8 +773,8 @@ void QuadTree::getPolygonsInRadiusInternal(std::list& polygons, } polygons.insert(polygons.end(), polygon); - for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) - getPolygonsInRadiusInternal(polygons, m_neighbours[record->m_firstIndex + edge], centre, + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInRadiusInternal(polygons, m_neighbours[record->vertexOffset + edge], centre, radius); } @@ -784,8 +784,8 @@ void QuadTree::getPolygonsInTriangle(std::list& polygons, unsigned { polygons.insert(polygons.end(), polygon); const Polygon* const record = &m_polygons[polygon]; - for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) - getPolygonsInTriangleInternal(polygons, m_neighbours[record->m_firstIndex + edge], a, b, c); + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInTriangleInternal(polygons, m_neighbours[record->vertexOffset + edge], a, b, c); } // ELF 0x306AA0. A polygon is taken when corner 0, or the corner `previous` of a pass, lies in the @@ -807,8 +807,8 @@ void QuadTree::getPolygonsInTriangleInternal(std::list& polygons, return; const Polygon* const record = &m_polygons[polygon]; - unsigned char previous = static_cast(record->m_numberOfVertices - 1); - const Vec3& first = m_vertices[m_vertexIndices[record->m_firstIndex]]; + unsigned char previous = static_cast(record->vertexCount - 1); + const Vec3& first = m_vertices[m_vertexIndices[record->vertexOffset]]; bool touches = pointWithinPolygon2d(first, triangle, 3); if (std::fabs(first.y - a.y) > 2.0f) return; @@ -825,10 +825,10 @@ void QuadTree::getPolygonsInTriangleInternal(std::list& polygons, if (!touches) { - for (unsigned char i = 0; i < record->m_numberOfVertices; ++i) + for (unsigned char i = 0; i < record->vertexCount; ++i) { - const Vec3& current = m_vertices[m_vertexIndices[record->m_firstIndex + i]]; - const Vec3& corner = m_vertices[m_vertexIndices[record->m_firstIndex + previous]]; + const Vec3& current = m_vertices[m_vertexIndices[record->vertexOffset + i]]; + const Vec3& corner = m_vertices[m_vertexIndices[record->vertexOffset + previous]]; if (std::fabs(corner.y - a.y) > 2.0f) return; if (pointWithinPolygon2d(corner, triangle, 3)) @@ -861,17 +861,17 @@ void QuadTree::getPolygonsInTriangleInternal(std::list& polygons, } polygons.insert(polygons.end(), polygon); - for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) - getPolygonsInTriangleInternal(polygons, m_neighbours[record->m_firstIndex + edge], a, b, c); + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) + getPolygonsInTriangleInternal(polygons, m_neighbours[record->vertexOffset + edge], a, b, c); } // ELF 0x3068F0. bool QuadTree::isNeighbourOfPolygon(unsigned int polygon, unsigned int neighbour) const { const Polygon* const record = &m_polygons[polygon]; - for (unsigned char edge = 0; edge < record->m_numberOfVertices; ++edge) + for (unsigned char edge = 0; edge < record->vertexCount; ++edge) { - if (m_neighbours[record->m_firstIndex + edge] == neighbour) + if (m_neighbours[record->vertexOffset + edge] == neighbour) return true; } return false; @@ -881,22 +881,22 @@ bool QuadTree::isNeighbourOfPolygon(unsigned int polygon, unsigned int neighbour unsigned int QuadTree::getSafeNeighbourOfPolygon(unsigned int polygon, unsigned char edge) const { const Polygon* const record = &m_polygons[polygon]; - return m_neighbours[record->m_firstIndex + edge % record->m_numberOfVertices]; + return m_neighbours[record->vertexOffset + edge % record->vertexCount]; } // ELF 0x307530. const Vec3* QuadTree::getVertexForPolygon(unsigned int polygon, unsigned char corner) const { - return &m_vertices[m_vertexIndices[m_polygons[polygon].m_firstIndex + corner]]; + return &m_vertices[m_vertexIndices[m_polygons[polygon].vertexOffset + corner]]; } // ELF 0x307560. bool QuadTree::isVertexOfPolygon(unsigned int polygon, unsigned int vertex) const { const Polygon* const record = &m_polygons[polygon]; - for (unsigned char corner = 0; corner < record->m_numberOfVertices; ++corner) + for (unsigned char corner = 0; corner < record->vertexCount; ++corner) { - if (m_vertexIndices[record->m_firstIndex + corner] == vertex) + if (m_vertexIndices[record->vertexOffset + corner] == vertex) return true; } return false; @@ -906,13 +906,13 @@ bool QuadTree::isVertexOfPolygon(unsigned int polygon, unsigned int vertex) cons const Vec3* QuadTree::getSafeVertexForPolygon(unsigned int polygon, unsigned char corner) const { const Polygon* const record = &m_polygons[polygon]; - return &m_vertices[m_vertexIndices[record->m_firstIndex + corner % record->m_numberOfVertices]]; + return &m_vertices[m_vertexIndices[record->vertexOffset + corner % record->vertexCount]]; } // ELF 0x307610. unsigned int QuadTree::getVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const { - return m_vertexIndices[m_polygons[polygon].m_firstIndex + corner]; + return m_vertexIndices[m_polygons[polygon].vertexOffset + corner]; } // ELF 0x307640. The corner index wraps modulo the corner count. @@ -920,7 +920,7 @@ unsigned int QuadTree::getSafeVertexIndexForPolygon(unsigned int polygon, unsigned char corner) const { const Polygon* const record = &m_polygons[polygon]; - return m_vertexIndices[record->m_firstIndex + corner % record->m_numberOfVertices]; + return m_vertexIndices[record->vertexOffset + corner % record->vertexCount]; } // ELF 0x307680. The corner average. A polygon without corners divides by zero, as in retail. @@ -930,14 +930,14 @@ void QuadTree::getCentreOfPolygon(Vec3& centre, unsigned int polygon) const centre.x = 0.0f; centre.y = 0.0f; centre.z = 0.0f; - for (unsigned char corner = 0; corner < record->m_numberOfVertices; ++corner) + for (unsigned char corner = 0; corner < record->vertexCount; ++corner) { - const Vec3& vertex = m_vertices[m_vertexIndices[record->m_firstIndex + corner]]; + const Vec3& vertex = m_vertices[m_vertexIndices[record->vertexOffset + corner]]; centre.x += vertex.x; centre.y += vertex.y; centre.z += vertex.z; } - const float inverse = 1.0f / static_cast(record->m_numberOfVertices); + const float inverse = 1.0f / static_cast(record->vertexCount); centre.x *= inverse; centre.y *= inverse; centre.z *= inverse; @@ -956,14 +956,14 @@ bool QuadTree::getNeighbourIndexForPolygon(unsigned char& edge, unsigned int pol { const Polygon* const record = &m_polygons[polygon]; edge = 0; - if (m_neighbours[record->m_firstIndex] == neighbour) + if (m_neighbours[record->vertexOffset] == neighbour) return true; for (;;) { ++edge; - if (edge >= record->m_numberOfVertices) + if (edge >= record->vertexCount) return false; - if (m_neighbours[record->m_firstIndex + edge] == neighbour) + if (m_neighbours[record->vertexOffset + edge] == neighbour) return true; } } @@ -1008,16 +1008,16 @@ bool QuadTree::getLineIntersectionOnEdgeInPolygon(Vec3& intersection, unsigned i const Polygon* const record = &m_polygons[polygon]; edge = 0; - if (record->m_numberOfVertices != 0) + if (record->vertexCount != 0) { do { if (previousPolygon == 0xFFFFFFFFu || - m_neighbours[record->m_firstIndex + edge] != previousPolygon) + m_neighbours[record->vertexOffset + edge] != previousPolygon) { - vec3ToVec2XZ(m_vertices[m_vertexIndices[record->m_firstIndex + edge]], corner); - vec3ToVec2XZ(m_vertices[m_vertexIndices[record->m_firstIndex + - (edge + 1) % record->m_numberOfVertices]], + vec3ToVec2XZ(m_vertices[m_vertexIndices[record->vertexOffset + edge]], corner); + vec3ToVec2XZ(m_vertices[m_vertexIndices[record->vertexOffset + + (edge + 1) % record->vertexCount]], nextCorner); const float scale = 1.0f; @@ -1101,7 +1101,7 @@ bool QuadTree::getLineIntersectionOnEdgeInPolygon(Vec3& intersection, unsigned i } ++edge; } - while (record->m_numberOfVertices > edge); + while (record->vertexCount > edge); } if (!(minInvalid > bestMiss)) @@ -1131,9 +1131,9 @@ void QuadTree::getPolygonsWithinBoundary(const Vec3& minimum, const Vec3& maximu for (unsigned int polygonId = 0; polygonId < m_numberOfPolygons; ++polygonId) { const Polygon& polygon = m_polygons[polygonId]; - for (unsigned int corner = 0; corner < polygon.m_numberOfVertices; ++corner) + for (unsigned int corner = 0; corner < polygon.vertexCount; ++corner) { - const Vec3& vertex = m_vertices[m_vertexIndices[polygon.m_firstIndex + corner]]; + const Vec3& vertex = m_vertices[m_vertexIndices[polygon.vertexOffset + corner]]; Vec3 local; local.x = inverse.m[0] * vertex.x + inverse.m[4] * vertex.y @@ -1165,9 +1165,9 @@ void QuadTree::getPolygonsWithinBoundaryDoubles(const Vec3& minimum, const Vec3& for (unsigned int polygonId = 0; polygonId < m_numberOfPolygons; ++polygonId) { const Polygon& polygon = m_polygons[polygonId]; - for (unsigned int corner = 0; corner < polygon.m_numberOfVertices; ++corner) + for (unsigned int corner = 0; corner < polygon.vertexCount; ++corner) { - const DoubleVec3& vertex = m_array84[m_vertexIndices[polygon.m_firstIndex + corner]]; + const DoubleVec3& vertex = m_array84[m_vertexIndices[polygon.vertexOffset + corner]]; Vec3 local; local.x = static_cast(inverse.m[0] * vertex.x + inverse.m[4] * vertex.y @@ -1189,7 +1189,7 @@ void QuadTree::getPolygonsWithinBoundaryDoubles(const Vec3& minimum, const Vec3& } // ELF 0x308860. -void QuadTree::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkable, +void QuadTree::initializeDestroyableMapPart(int pathfindingMapId, bool initiallyWalkable, const Vec3& minimum, const Vec3& maximum, const Mat4& transformation, ClusterGraph* graph, bool useDoubles) @@ -1230,16 +1230,16 @@ void QuadTree::initializeDestroyableMapPart(int mapPartId, bool initiallyWalkabl m_destroyableMapParts.push_back(part); part->m_initiallyWalkable = initiallyWalkable; if (!initiallyWalkable && !useDoubles) - restoreMapPart(mapPartId, graph); + restoreMapPart(pathfindingMapId, graph); part->m_destroyed = false; } // ELF 0x308C60. -void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) +void QuadTree::destroyMapPart(int pathfindingMapId, ClusterGraph* graph) { if (!m_destroyableMapParts.empty()) { - DestroyableMapPart* const part = m_destroyableMapParts[mapPartId]; + DestroyableMapPart* const part = m_destroyableMapParts[pathfindingMapId]; if (part && !part->m_destroyed) { for (unsigned int i = 0; i < part->m_polygons.size(); ++i) @@ -1251,7 +1251,7 @@ void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_walkable + graph->m_clusters[m_polygons[first].cluster].m_walkable = static_cast(!part->m_initiallyWalkable); } part->m_destroyed = true; @@ -1260,11 +1260,11 @@ void QuadTree::destroyMapPart(int mapPartId, ClusterGraph* graph) } // ELF 0x308D20. -void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) +void QuadTree::restoreMapPart(int pathfindingMapId, ClusterGraph* graph) { - if (mapPartId != -1) + if (pathfindingMapId != -1) { - DestroyableMapPart* const part = m_destroyableMapParts[mapPartId]; + DestroyableMapPart* const part = m_destroyableMapParts[pathfindingMapId]; if (part) { for (unsigned int i = 0; i < part->m_polygons.size(); ++i) @@ -1276,7 +1276,7 @@ void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_walkable + graph->m_clusters[m_polygons[first].cluster].m_walkable = static_cast(part->m_initiallyWalkable); } part->m_destroyed = false; @@ -1285,11 +1285,11 @@ void QuadTree::restoreMapPart(int mapPartId, ClusterGraph* graph) } // ELF 0x308E30. -void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterGraph* graph) +void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int pathfindingMapId, ClusterGraph* graph) { - if (mapPartId != -1) + if (pathfindingMapId != -1) { - DestroyableMapPart* const part = m_destroyableMapParts[mapPartId]; + DestroyableMapPart* const part = m_destroyableMapParts[pathfindingMapId]; if (part) { for (unsigned int i = 0; i < part->m_polygons.size(); ++i) @@ -1298,7 +1298,7 @@ void QuadTree::resetOriginalMaterialOfDestroyableMapPart(int mapPartId, ClusterG if (graph && !part->m_polygons.empty()) { const unsigned int first = part->m_polygons[0]; - graph->m_clusters[m_polygons[first].m_cluster].m_walkable + graph->m_clusters[m_polygons[first].cluster].m_walkable = static_cast(part->m_initiallyWalkable); } part->m_destroyed = false; @@ -1328,10 +1328,10 @@ void QuadTree::saveToFile(io::File& file) file.write(m_polygons, sizeof(Polygon) * m_numberOfPolygons); file.write(m_numberOfNodePolygons); file.write(m_nodePolygons, sizeof(unsigned int) * m_numberOfNodePolygons); - file.write(m_numberOfVertices); - file.write(m_vertices, sizeof(Vec3) * m_numberOfVertices); - file.write(m_numberOfVertexIndices); - file.write(m_vertexIndices, sizeof(unsigned int) * m_numberOfVertexIndices); + file.write(m_vertexCount); + file.write(m_vertices, sizeof(Vec3) * m_vertexCount); + file.write(m_vertexIndexCount); + file.write(m_vertexIndices, sizeof(unsigned int) * m_vertexIndexCount); file.write(m_numberOfNeighbours); file.write(m_neighbours, sizeof(unsigned int) * m_numberOfNeighbours); } @@ -1356,15 +1356,15 @@ void QuadTree::drawPolygon(unsigned int polygon, float* height, float time) { const Polygon* const candidate = &m_polygons[polygon]; unsigned char corner = 0; - if (candidate->m_numberOfVertices == 0) + if (candidate->vertexCount == 0) return; do { - Vec3 start = m_vertices[m_vertexIndices[candidate->m_firstIndex + corner]]; + Vec3 start = m_vertices[m_vertexIndices[candidate->vertexOffset + corner]]; const unsigned char next = static_cast( - (corner + 1) % candidate->m_numberOfVertices); - Vec3 end = m_vertices[m_vertexIndices[candidate->m_firstIndex + next]]; + (corner + 1) % candidate->vertexCount); + Vec3 end = m_vertices[m_vertexIndices[candidate->vertexOffset + next]]; if (height) { end.y = *height; @@ -1374,7 +1374,7 @@ void QuadTree::drawPolygon(unsigned int polygon, float* height, float time) ->createStaticLine(time, 0xFF0000u, start, end, 0.3f); ++corner; } - while (corner < candidate->m_numberOfVertices); + while (corner < candidate->vertexCount); } // ELF 0x3068A0. Empty in the shipped image. @@ -1392,7 +1392,7 @@ Vec3 QuadTree::getPolygonMidPoint(unsigned int polygon) midPoint.z = 0.0f; const Polygon* const candidate = &m_polygons[polygon]; - for (unsigned char corner = 0; corner < candidate->m_numberOfVertices; ++corner) + for (unsigned char corner = 0; corner < candidate->vertexCount; ++corner) { const Vec3* const vertex = getVertexForPolygon(polygon, corner); midPoint.x += vertex->x; @@ -1400,7 +1400,7 @@ Vec3 QuadTree::getPolygonMidPoint(unsigned int polygon) midPoint.z += vertex->z; } - const float scale = 1.0f / static_cast(candidate->m_numberOfVertices); + const float scale = 1.0f / static_cast(candidate->vertexCount); midPoint.x *= scale; midPoint.y *= scale; midPoint.z *= scale; @@ -1450,7 +1450,7 @@ void QuadTree::validateNeighbourRelations() const for (unsigned int polygon = 0; polygon < m_numberOfPolygons; ++polygon) { const Polygon& candidate = m_polygons[polygon]; - for (unsigned char edge = 0; edge < candidate.m_numberOfVertices; ++edge) + for (unsigned char edge = 0; edge < candidate.vertexCount; ++edge) { } } diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h index 1c05815c5..d52be58ed 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.h @@ -32,10 +32,10 @@ class Polygon public: Polygon() { m_normal.x = 0.0f; m_normal.y = 0.0f; m_normal.z = 0.0f; } - /* +0x00 */ unsigned char m_numberOfVertices; // bounds every corner / edge index (0x3068B0, 0x307560) + /* +0x00 */ unsigned char vertexCount; // bounds every corner / edge index (0x3068B0, 0x307560) // name: AIDLL_r assert "p.vertexCount" 0x101871C0 (+0) /* +0x01 */ unsigned char m_material; // get/setMaterialOfPolygon (0x3081A0 / 0x3081C0) - /* +0x02 */ unsigned short m_cluster; // ClusterGraph::getClusterId (0x314E10) - /* +0x04 */ unsigned int m_firstIndex; // into m_vertexIndices and m_neighbours + /* +0x02 */ unsigned short cluster; // ClusterGraph::getClusterId (0x314E10) // name: AIDLL_r assert "p->cluster == cId" (0x10175A40; +2) + /* +0x04 */ unsigned int vertexOffset; // into m_vertexIndices and m_neighbours // name: AIDLL_r assert "p.vertexOffset" 0x101871C0 (+4) /* +0x08 */ Vec3 m_normal; // getNormalOfPolygon returns its address (0x307760) }; @@ -180,8 +180,8 @@ class QuadTree /* +0x54 */ unsigned int m_numberOfNodes; /* +0x58 */ unsigned int m_numberOfPolygons; // getPolygon's bound (0x3069A0) /* +0x5C */ unsigned int m_numberOfNodePolygons; - /* +0x60 */ unsigned int m_numberOfVertices; - /* +0x64 */ unsigned int m_numberOfVertexIndices; + /* +0x60 */ unsigned int m_vertexCount; // name: AIDLL_r assert 0x1018C4A0 (PE +0x70) + /* +0x64 */ unsigned int m_vertexIndexCount; // name: AIDLL_r assert 0x1018CF30 (PE +0x74) /* +0x68 */ unsigned int m_numberOfNeighbours; /* +0x6C */ QuadTreeNode* m_nodes; /* +0x70 */ Polygon* m_polygons; diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp index cf502b48e..a718690f0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp @@ -49,7 +49,7 @@ void QuadTreeManager::DebugMesh::lockSize() // metadata. QuadTreeManager::QuadTreeManager() { - // m_numberOfIslands deliberately not initialised - the binary steps over it. + // m_treeCount deliberately not initialised - the binary steps over it. } // ELF 0x30DD40 (D2; D1 0x30DE30; first recovered on the client track, @@ -66,18 +66,18 @@ QuadTreeManager::~QuadTreeManager() // a valid island index. QuadTree* QuadTreeManager::getIsland(unsigned int island) const { - return m_islands[island].first; + return m_quadTrees[island].first; } ClusterGraph* QuadTreeManager::getClusterGraph(unsigned int island) const { - return m_islands[island].second; + return m_quadTrees[island].second; } // ELF 0x310F80. unsigned int QuadTreeManager::getNumberOfIslands() const { - return static_cast(m_islands.size()); + return static_cast(m_quadTrees.size()); } // ELF 0x30E240. Deletes both halves of every island's pair (each `delete` null-tests for itself), then @@ -88,26 +88,26 @@ unsigned int QuadTreeManager::getNumberOfIslands() const // with no islands at all. void QuadTreeManager::destroyQuadTrees() { - for (std::vector >::iterator it = m_islands.begin(); - it != m_islands.end(); ++it) + for (std::vector >::iterator it = m_quadTrees.begin(); + it != m_quadTrees.end(); ++it) { delete it->first; delete it->second; } - m_islands.resize(0); + m_quadTrees.resize(0); } // ELF 0x30A690. Deletes the matching quad tree while retaining its island entry and nulling its pointer. void QuadTreeManager::destroyQuadTree(QuadTree* quadTree) { - std::vector >::iterator it = m_islands.begin(); - for (; it != m_islands.end(); ++it) + std::vector >::iterator it = m_quadTrees.begin(); + for (; it != m_quadTrees.end(); ++it) { if (it->first == quadTree) break; } - if (it != m_islands.end()) + if (it != m_quadTrees.end()) { delete it->first; it->first = 0; @@ -132,8 +132,8 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) static_cast(0), 0)) return; - quadTreeFile.read(m_numberOfIslands); - if (m_numberOfIslands > 1) + quadTreeFile.read(m_treeCount); + if (m_treeCount > 1) { // [PLATFORM] ELF: signed `cmp edi, 1 / jg` at 0x30AF0A, `call abort` at 0x30B385. PE: signed // `cmp [ebx], 2 / jl` at , `int 3` at - which falls through into the @@ -145,7 +145,7 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) #endif } - for (unsigned int island = 0; island < static_cast(m_numberOfIslands); ++island) + for (unsigned int island = 0; island < static_cast(m_treeCount); ++island) { QuadTree* const quadTree = checkPointer(new QuadTree(island)); quadTree->readFromFile(quadTreeFile); @@ -153,13 +153,13 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) ClusterGraph* const clusterGraph = checkPointer(new ClusterGraph); clusterGraph->readFromFile(clusterFile); - m_islands.push_back(std::make_pair(quadTree, clusterGraph)); + m_quadTrees.push_back(std::make_pair(quadTree, clusterGraph)); } - for (unsigned int island = 0; island < static_cast(m_numberOfIslands); ++island) + for (unsigned int island = 0; island < static_cast(m_treeCount); ++island) { for (unsigned short cluster = 0; - cluster < m_islands[island].second->getNumberOfClusters(); + cluster < m_quadTrees[island].second->getNumberOfClusters(); ++cluster) { } @@ -170,7 +170,7 @@ void QuadTreeManager::loadQuadTrees(const std::string& name) } // ELF 0x30A700. Writes /AIPathFinding/.qtr and .clb: the island count (also stored in -// m_numberOfIslands) to the tree file, then each island's tree and graph. Nothing is written +// m_treeCount) to the tree file, then each island's tree and graph. Nothing is written // unless both files open. void QuadTreeManager::saveQuadTrees(const std::string& name) { @@ -187,10 +187,10 @@ void QuadTreeManager::saveQuadTrees(const std::string& name) static_cast(0), io::FILEACCESS_1, 0)) return; - m_numberOfIslands = static_cast(m_islands.size()); - quadTreeFile.write(m_numberOfIslands); - for (std::vector >::iterator it = m_islands.begin(); - it != m_islands.end(); ++it) + m_treeCount = static_cast(m_quadTrees.size()); + quadTreeFile.write(m_treeCount); + for (std::vector >::iterator it = m_quadTrees.begin(); + it != m_quadTrees.end(); ++it) { it->first->saveToFile(quadTreeFile); it->second->saveToFile(clusterFile); @@ -244,7 +244,7 @@ bool QuadTreeManager::loadGTSData(const std::string& name, int maxDepth, int min tree->optimiseGTSData(graph); graph->validateClusterGraphConnectivity(tree, false); graph->createPortals(map, tree, radius); - m_islands.push_back(std::make_pair(tree, graph)); + m_quadTrees.push_back(std::make_pair(tree, graph)); graph->calculatePortalCosts(map, island); ++island; } while (--count != 0); @@ -257,8 +257,8 @@ bool QuadTreeManager::loadGTSData(const std::string& name, int maxDepth, int min void QuadTreeManager::recalculatePortalCosts(int map) { unsigned int island = 0; - for (std::vector >::iterator it = m_islands.begin(); - it != m_islands.end(); ++it, ++island) + for (std::vector >::iterator it = m_quadTrees.begin(); + it != m_quadTrees.end(); ++it, ++island) it->second->calculatePortalCosts(map, island); } @@ -340,11 +340,11 @@ void QuadTreeManager::drawClusterNeighbourIndices(const Vec3& point) static_cast(CommonSingletonServer::m_iDPStaticCreator) ->createStaticCircle(60.0f, 0xFFFFFFu, raised, 0.5f, up, false, 255))); - const unsigned int islands = static_cast(m_islands.size()); + const unsigned int islands = static_cast(m_quadTrees.size()); for (unsigned int island = 0; island < islands; ++island) { - QuadTree* tree = m_islands[island].first; - ClusterGraph* graph = m_islands[island].second; + QuadTree* tree = m_quadTrees[island].first; + ClusterGraph* graph = m_quadTrees[island].second; MaterialManager* materials = static_cast(CommonSingletonServer::m_iaiSettings) ->getVehicleMaterialManager(1); @@ -387,23 +387,23 @@ void QuadTreeManager::buildDebugMeshes(const std::string&) std::list vertices; std::list materials; std::vector counts; - const unsigned int islands = static_cast(m_islands.size()); + const unsigned int islands = static_cast(m_quadTrees.size()); DebugMesh* mesh = checkPointer(new DebugMesh); int polygons = 0; unsigned int nextVertex = 0; for (unsigned int island = 0; island < islands; ++island) { - QuadTree* tree = m_islands[island].first; + QuadTree* tree = m_quadTrees[island].first; const unsigned int polygonCount = tree->m_numberOfPolygons; vertexMap.clear(); for (unsigned int polygon = 0; polygon < polygonCount; ++polygon) { const Polygon* p = tree->getPolygon(polygon); - counts.push_back(p->m_numberOfVertices); + counts.push_back(p->vertexCount); materials.push_back(p->m_material); - for (unsigned char corner = 0; corner < p->m_numberOfVertices; ++corner) + for (unsigned char corner = 0; corner < p->vertexCount; ++corner) { - const unsigned int index = tree->m_vertexIndices[p->m_firstIndex + corner]; + const unsigned int index = tree->m_vertexIndices[p->vertexOffset + corner]; std::map::iterator v = vertexMap.find(index); if (v == vertexMap.end()) { @@ -482,7 +482,7 @@ void QuadTreeManager::buildDebugMeshes(const std::string&) void QuadTreeManager::buildDebugClusterMeshes(const std::string&) { unloadDebugClusterMeshes(); - const unsigned int islands = static_cast(m_islands.size()); + const unsigned int islands = static_cast(m_quadTrees.size()); int polygons = 0; std::list indices; std::list vertices; @@ -495,8 +495,8 @@ void QuadTreeManager::buildDebugClusterMeshes(const std::string&) unsigned int nextVertex = 0; for (unsigned int island = 0; island < islands; ++island) { - QuadTree* tree = m_islands[island].first; - ClusterGraph* graph = m_islands[island].second; + QuadTree* tree = m_quadTrees[island].first; + ClusterGraph* graph = m_quadTrees[island].second; const unsigned int clusterCount = graph->m_numberOfClusters; vertexMap.clear(); for (unsigned short cluster = 0; cluster < clusterCount; ++cluster) @@ -509,13 +509,13 @@ void QuadTreeManager::buildDebugClusterMeshes(const std::string&) { const Polygon* p = tree->getPolygon(graph->m_clusterPolygons[first + polygon]); ++polygons; - counts.push_back(p->m_numberOfVertices); + counts.push_back(p->vertexCount); materials.push_back(static_cast(clusterTag)); base &= 0xE0E0E0E0u; colours.push_back((AIRandom::m_instance->next() & 0x1F1F1F1Fu) + base); - for (unsigned char corner = 0; corner < p->m_numberOfVertices; ++corner) + for (unsigned char corner = 0; corner < p->vertexCount; ++corner) { - const unsigned int index = tree->m_vertexIndices[p->m_firstIndex + corner]; + const unsigned int index = tree->m_vertexIndices[p->vertexOffset + corner]; std::map::iterator v = vertexMap.find(index); if (v == vertexMap.end()) { @@ -772,9 +772,9 @@ void QuadTreeManager::triangulateDebugMeshes(std::list& meshes) unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polygon, MaterialManager* materials, float allowedHeightDiff) { - for (unsigned int island = 0; island < m_islands.size(); ++island) + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) { - if (m_islands[island].first->findPolygon(point, polygon, materials, allowedHeightDiff)) + if (m_quadTrees[island].first->findPolygon(point, polygon, materials, allowedHeightDiff)) return island; } @@ -789,7 +789,7 @@ unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polyg MaterialManager* materials, float allowedHeightDiff) { if (knownIsland == 0xFFFFFFFFu || knownPolygon == 0xFFFFFFFFu - || !m_islands[knownIsland].first->isPointInPolygon( + || !m_quadTrees[knownIsland].first->isPointInPolygon( point, knownPolygon, allowedHeightDiff, materials)) return findPolygon(point, polygon, materials, allowedHeightDiff); @@ -801,15 +801,15 @@ unsigned int QuadTreeManager::findPolygon(const Vec3& point, unsigned int& polyg void QuadTreeManager::printPolygonsInNode(const Vec3& point, unsigned int& polygon, MaterialManager* materials, float allowedHeightDiff) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->printPolygonsInNode(point, polygon, materials, + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->printPolygonsInNode(point, polygon, materials, allowedHeightDiff); } // ELF 0x30E0F0. unsigned short QuadTreeManager::getCluster(unsigned int island, unsigned int polygon) const { - return m_islands[island].second->getClusterId(m_islands[island].first, polygon); + return m_quadTrees[island].second->getClusterId(m_quadTrees[island].first, polygon); } // ELF 0x30E140. @@ -817,7 +817,7 @@ void QuadTreeManager::getClusterPortals(unsigned int island, unsigned short clus unsigned short costType, std::list& portals) const { - m_islands[island].second->getClusterPortals(cluster, costType, portals); + m_quadTrees[island].second->getClusterPortals(cluster, costType, portals); } // ELF 0x30E190. The island's tree only; no bounds check. @@ -825,7 +825,7 @@ void QuadTreeManager::getPolygonsInRadius(std::list& polygons, uns unsigned int polygon, const Vec3& centre, float radius) const { - m_islands[island].first->getPolygonsInRadius(polygons, polygon, centre, radius); + m_quadTrees[island].first->getPolygonsInRadius(polygons, polygon, centre, radius); } // ELF 0x30E1E0. @@ -833,7 +833,7 @@ void QuadTreeManager::getPolygonsInTriangle(std::list& polygons, u unsigned int polygon, const Vec3& a, const Vec3& b, const Vec3& c) const { - m_islands[island].first->getPolygonsInTriangle(polygons, polygon, a, b, c); + m_quadTrees[island].first->getPolygonsInTriangle(polygons, polygon, a, b, c); } // ELF 0x30E320. Forward to every island in ascending order, re-reading the vector @@ -842,46 +842,46 @@ void QuadTreeManager::initializeDestroyableMapPart(int mapPartId, bool initially const Vec3& minimum, const Vec3& maximum, const Mat4& transformation) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->initializeDestroyableMapPart( + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->initializeDestroyableMapPart( mapPartId, initiallyWalkable, minimum, maximum, transformation, - m_islands[island].second, false); + m_quadTrees[island].second, false); } // ELF 0x30E3C0. void QuadTreeManager::destroyMapPart(int mapPartId) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->destroyMapPart(mapPartId, m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->destroyMapPart(mapPartId, m_quadTrees[island].second); } // ELF 0x30E420. void QuadTreeManager::restoreMapPart(int mapPartId) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->restoreMapPart(mapPartId, m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->restoreMapPart(mapPartId, m_quadTrees[island].second); } // ELF 0x30E480. void QuadTreeManager::resetOriginalMaterialOfDestroyableMapPart(int mapPartId) { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->resetOriginalMaterialOfDestroyableMapPart( - mapPartId, m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->resetOriginalMaterialOfDestroyableMapPart( + mapPartId, m_quadTrees[island].second); } // ELF 0x30E4E0. void QuadTreeManager::resetDestroyableMapParts() { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->resetDestroyableMapParts(m_islands[island].second); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->resetDestroyableMapParts(m_quadTrees[island].second); } // ELF 0x310F30. void QuadTreeManager::validateNeighbourRelations() const { - for (unsigned int island = 0; island < m_islands.size(); ++island) - m_islands[island].first->validateNeighbourRelations(); + for (unsigned int island = 0; island < m_quadTrees.size(); ++island) + m_quadTrees[island].first->validateNeighbourRelations(); } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h index 058e4b7c1..05f816713 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.h @@ -89,10 +89,10 @@ class QuadTreeManager // Offsets describe the original 32-byte ELF object; STL layouts vary by compiler. // One quad-tree/cluster-graph pointer pair per island; each original x86 pair is eight bytes. - /* +0 */ std::vector > m_islands; + /* +0 */ std::vector > m_quadTrees; // name: AIDLL_r asserts 0x10170D30, 0x10173C10 (PE +0, 8-byte entries) // Island count stored in the file, initialized by load or save. Runtime count queries - // use m_islands.size() instead; construction leaves this field unset. - /* +12 */ int m_numberOfIslands; + // use m_quadTrees.size() instead; construction leaves this field unset. + /* +12 */ int m_treeCount; // name: AIDLL_r assert 0x10173C10 (PE +0x10) /* +16 */ std::list m_debugMeshes; // node 12 /* +20 */ std::list m_debugClusterMeshes; // node 12 /* +24 */ std::list > m_drawnPairs; // node 16 [INFERRED] diff --git a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp index 9a95ff2bc..826089b4a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp @@ -107,7 +107,7 @@ bool QuadTreeNode::polygonInside(const Vec2& minimum, float size, QuadTree* tree {minimum.x + size, 0.0f, minimum.y + size}, {minimum.x, 0.0f, minimum.y + size}}; const Polygon* p = tree->m_polygons + polygon; - const int count = p->m_numberOfVertices; + const int count = p->vertexCount; for (int corner = 0; corner < count; ++corner) { const Vec3* v = tree->getVertexForPolygon(polygon, static_cast(corner)); @@ -274,7 +274,7 @@ void QuadTreeNode::printPolygonsInNode(const QuadTree* tree, const Vec2& minimum { const unsigned int candidate = tree->m_nodePolygons[m_firstPolygon + i]; const Polygon& candidatePolygon = tree->m_polygons[candidate]; - for (int corner = 0; corner < candidatePolygon.m_numberOfVertices; ++corner) + for (int corner = 0; corner < candidatePolygon.vertexCount; ++corner) tree->getVertexForPolygon(candidate, static_cast(corner)); } return; diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp index 96503fa70..bfbcb33cd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BAPInterpreter.cpp @@ -7,7 +7,7 @@ #include "BAPInterpreter.h" #include "BAPEntry.h" -#include "BotScript.h" +#include "../AIBotActionPlan/BotScript.h" #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPStatement.h" #include "../../../../Core/Debug.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp index 47cc2dd4a..5bc79b40c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/BoatControl.cpp @@ -11,7 +11,7 @@ #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp index 7c4845302..659a5f423 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CarControl.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotNavigation.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../Main/IAIPathfinding.h" @@ -435,7 +435,7 @@ int CarControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& di const float reach = clearance + 0.5f; const int vehicleNumber = mobile->getVehicleNumber(); const IPIMobile::ValidPos& otherValid = otherMobile->getLastValidPosition(vehicleNumber); - if (otherValid.polygon == 0xFFFFFFFFu || otherValid.quadTree == 0xFFFFFFFFu) + if (otherValid.polygon == 0xFFFFFFFFu || otherValid.island == 0xFFFFFFFFu) { avoidSide = 1; } @@ -447,11 +447,11 @@ int CarControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& di hitLeft.x = hitLeft.y = hitLeft.z = 0.0f; unsigned int sidePolygon; Vec3 sideTarget = alongFrom(otherValid.position, rightAxis(info->getTransformation()), reach); - pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, sideTarget, hitRight, sidePolygon, equipmentType, -1, 0.0f, 0, 0); float roomRight = isZeroVec3(hitRight) ? 0.0f : distanceVec3(hitRight, otherValid.position); sideTarget = backFrom(otherValid.position, rightAxis(info->getTransformation()), reach); - pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, sideTarget, hitLeft, sidePolygon, equipmentType, -1, 0.0f, 0, 0); float roomLeft = isZeroVec3(hitLeft) ? 0.0f : distanceVec3(hitLeft, otherValid.position); bool firstSide = roomRight < roomLeft; // before the obstacles shorten them diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp index bc2c85524..41d191fd4 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/CommonControls.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotNavigation.h" #include "../AIBot/CommunicationAgent.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" @@ -55,7 +55,7 @@ void CommonControls::updateSpaceWithObstacles(Bot* bot, const Vec3& origin, cons if (self == obstacle || obstacle == 0) continue; IPIPhysical* const physical = obstacle->getPhysical(); - if (physical == 0 || (obstacle->getObjectTypeFlags() & 0x200000u)) + if (physical == 0 || obstacle->isOfType(ITSoldier)) continue; const float radius = physical->getSmallestRadius(); const Vec3& position = obstacle->getPosition(); @@ -147,7 +147,7 @@ bool CommonControls::checkCollisions(Bot* bot, Information* info, IPIPhysical* p if (info == other || other == 0) continue; IPIPhysical* const otherPhysical = other->getPhysical(); - if (otherPhysical == 0 || (other->getObjectTypeFlags() & 0x200000u)) + if (otherPhysical == 0 || other->isOfType(ITSoldier)) continue; const float combinedRadius = otherPhysical->getRadius() + radius; const Vec3& ownPosition = info->getPosition(); @@ -356,7 +356,7 @@ float CommonControls::checkSlowDown(Bot* bot, Information* info, const Vec3& vel IPIPhysical* const otherPhysical = other->getPhysical(); if (otherPhysical == 0) continue; - if ((other->getObjectTypeFlags() & 0x200000u) && 0.0f >= otherPhysical->getHealth()) + if (other->isOfType(ITSoldier) && 0.0f >= otherPhysical->getHealth()) continue; IPIMobile* const otherMobile = other->getMobile(); if (otherMobile == 0) @@ -409,7 +409,7 @@ float CommonControls::checkSlowDown(Bot* bot, Information* info, const Vec3& vel miss.z = centre.z - projected.z; if (miss.x * miss.x + miss.y * miss.y + miss.z * miss.z > radii * radii) continue; - if (other->getObjectTypeFlags() & 0x200000u) + if (other->isOfType(ITSoldier)) { // 0x2B049C: a soldier ahead is only a horn candidate. if (along > 0.0f && info->getSide() == other->getSide()) diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp index caca2d08d..442fff5fe 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveTo.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp index 27e918c28..ebb1f3956 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatMoveToObject.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFGameEffector.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp index 900f610f8..8635fff91 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryBoatResetControls.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAResetControls.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/AIDllFrontier.h" #include "../../../../IO/Input/PlayerInput.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp index d1de33927..4e70bce67 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveTo.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../Main/CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp index e396e1c36..fd5d36ff2 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarMoveToObject.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp index 5f1a8632d..07da55945 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryCarResetControls.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAResetControls.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/AIDllFrontier.h" #include "../../../../IO/Input/PlayerInput.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp index ef2034667..2f7e8047c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliAimAt.cpp @@ -14,7 +14,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" @@ -81,7 +81,7 @@ bool EntryHeliAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) const float y = position.y - targetPosition.y; const float z = position.z - targetPosition.z; const float distance = std::sqrt(x * x + y * y + z * z); - const bool airborne = (target->getObjectTypeFlags() & 0x10) != 0; + const bool airborne = target->isOfType(ITAir); bool solved; if (airborne) { diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp index c8e4503d9..8aef04b00 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveAwayFromObject.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveAwayFrom3dObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp index d98730dd4..b4639fe34 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveTo.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo3d.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp index 71d81e1ac..3061354cf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToDirection.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo3dDirection.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp index 5916dc8cb..8033b9e77 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliMoveToObject.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo3dObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp index c12fcf293..baa4a0ae8 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryHeliResetControls.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAResetControls.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/AIDllFrontier.h" #include "../../../../IO/Input/PlayerInput.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp index bdcbc7a76..41eb27830 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveTo.cpp @@ -14,7 +14,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp index 5298337e8..bf26dd295 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryInfanteryMoveToObject.cpp @@ -12,7 +12,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFGameEffector.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp index c96b103ff..1a61d8e1b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryKeyTurretAimAt.cpp @@ -11,12 +11,12 @@ #include "../AIBotActionPlan/BAPAAimAt.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../Math/Mat4.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp index bdf536f3e..a01a5ca8a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretAimAt.cpp @@ -17,11 +17,11 @@ #include "../AIBotActionPlan/BAPAAimAt.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../../Math/Mat4.h" #include "../../../../Math/Vec3.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp index 3fa196ea1..07ef75eea 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMouseTurretLookAt.cpp @@ -14,7 +14,7 @@ #include "../AIBotActionPlan/BAPALook.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../../Math/Mat4.h" #include "../../../../Math/Vec3.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp index cca49cd54..4f6a458f8 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMedium.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp index 9ce85325e..8b74dfbdd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumBoat.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../Main/CommonSingletonServer.h" #include "../Main/IAIPathfinding.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp index 3b7872dad..b97ccf83b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToMediumSoldier.cpp @@ -13,7 +13,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp index 6e8bcd9f8..61791d003 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMedium.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp index c898b5ae7..06ec9d5a0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumBoat.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTerrain.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp index 0a9a3ad6b..c02caebf0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryMoveToObjectMediumSoldier.cpp @@ -13,7 +13,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp index aa6afbc80..ebde5f942 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneAimAt.cpp @@ -14,7 +14,7 @@ #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" @@ -83,7 +83,7 @@ bool EntryPlaneAimAt::execute(BotScript* script, Bot* bot, bool& ok, bool& done) float throttle = 1.0f; float distance; bool useForward = false; - if ((target->getObjectTypeFlags() & 0x10) != 0) + if (target->isOfType(ITAir)) { const bool indirect = weapon->getIndirect(); const float gravity = weapon->getGravityModifier(); diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp index 8b4857217..6d1beac66 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveTo.cpp @@ -9,7 +9,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo3d.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../../Math/Mat4.h" namespace dice { diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp index 8bb059c45..4db944e03 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneMoveToObject.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo3dObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../Math/Mat4.h" @@ -66,7 +66,7 @@ bool EntryPlaneMoveToObject::execute(BotScript* script, Bot* bot, bool& ok, bool const Mat4& transform = info->getTransformation(); const float speed = info->getMobile()->getSpeedMagnitude(); float throttle; - if ((target->getObjectTypeFlags() & 0x10) != 0) + if (target->isOfType(ITAir)) { io::PlayerInput* const input = bot->getInput(); throttle = ((input->mappingFlags >> 3) & 1ULL) ? input->inputs[3] : 0.0f; diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp index 8aecf36e7..06e63dc65 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneResetControls.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAResetControls.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/AIDllFrontier.h" #include "../../../../IO/Input/PlayerInput.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp index 5d355e4c3..02fa904da 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryPlaneRoll.cpp @@ -10,7 +10,7 @@ #include "../AIBotActionPlan/BAPARoll3d.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../../Math/Mat4.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp index aaed669aa..db6b63551 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntrySoldierPose.cpp @@ -12,7 +12,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPASoldierPose.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp index a0786d5cb..68b8e64cf 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveTo.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../Main/CommonSingletonServer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp index 7507f813c..5a3a0be0f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankMoveToObject.cpp @@ -11,7 +11,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAMoveTo.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp index 3e9e1aca8..524622a72 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankResetControls.cpp @@ -10,7 +10,7 @@ #include "../AIBot/BotMain.h" #include "../AIBotActionPlan/BAPAResetControls.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/AIDllFrontier.h" #include "../../../../IO/Input/PlayerInput.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp index d1949143d..ff73471c1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTankTurnTo.cpp @@ -11,7 +11,7 @@ #include "../AIBotActionPlan/BAPATurn.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp index a18f8b985..16861100a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTrigger.cpp @@ -16,11 +16,11 @@ #include "../AIBotActionPlan/BAPATrigger.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../Math/Vec3.h" @@ -112,7 +112,7 @@ bool EntryTrigger::execute(BotScript* script, Bot* bot, bool& ok, bool& done) if (!moving && weapon->getWeaponType() != 4) { SoldierPose pose = SPStanding; - if (info->getObjectTypeFlags() & 0x200000) + if (info->isOfType(ITSoldier)) { pose = weapon->getFiringPose(); if (armament->getActiveWeapon() == 0 @@ -155,7 +155,7 @@ bool EntryTrigger::execute(BotScript* script, Bot* bot, bool& ok, bool& done) if (!humanVehicle) skill = 1.0f - (1.0f - skill) * 0.5f; } - else if ((info->getObjectTypeFlags() & 0x200000) == 0) + else if (!info->isOfType(ITSoldier)) { skill = 1.0f - (1.0f - skill) * 0.8f; } @@ -172,12 +172,12 @@ bool EntryTrigger::execute(BotScript* script, Bot* bot, bool& ok, bool& done) skill = 1.0f; float scale = 1.0f; bool apply = true; - if ((info->getObjectTypeFlags() & 0x10) == 0) + if (!info->isOfType(ITAir)) { if (target == 0) apply = false; - else if ((target->getObjectTypeFlags() & 0x10) != 0 && !info->isPrimary() - && (info->getObjectTypeFlags() & 0x80) == 0) + else if (target->isOfType(ITAir) && !info->isPrimary() + && !info->isOfType(ITNaval)) scale = 3.0f; } if (apply) diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp index 2ff5983b3..848a92b86 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTriggerContinously.cpp @@ -16,11 +16,11 @@ #include "../AIBotActionPlan/BAPATriggerContinously.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../Math/Vec3.h" @@ -89,11 +89,11 @@ bool EntryTriggerContinously::execute(BotScript* script, Bot* bot, bool& ok, boo if (infantry_detail::inputValue(input, io::PIThrottle) == 0.0f && infantry_detail::inputValue(input, io::PIYaw) == 0.0f && infantry_detail::inputValue(input, io::PISprint) == 0.0f - && !(bot->getSpawnKit() == 4 && (info->getObjectTypeFlags() & 0x200000) != 0 + && !(bot->getSpawnKit() == 4 && info->isOfType(ITSoldier) && armament->getActiveWeapon() == 5)) { SoldierPose pose = SPStanding; - if (info->getObjectTypeFlags() & 0x200000) + if (info->isOfType(ITSoldier)) pose = weapon->getFiringPose(); const SoldierPose current = info->getSoldierPose(); if (current != SPSwimming && current != pose) @@ -113,7 +113,7 @@ bool EntryTriggerContinously::execute(BotScript* script, Bot* bot, bool& ok, boo if (!humanVehicle) skill = 1.0f - (1.0f - skill) * 0.5f; } - else if ((info->getObjectTypeFlags() & 0x200000) == 0) + else if (!info->isOfType(ITSoldier)) { skill = 1.0f - (1.0f - skill) * 0.8f; } @@ -125,12 +125,12 @@ bool EntryTriggerContinously::execute(BotScript* script, Bot* bot, bool& ok, boo skill = 1.0f; float scale = 1.0f; bool apply = true; - if ((info->getObjectTypeFlags() & 0x10) == 0) + if (!info->isOfType(ITAir)) { if (target == 0) apply = false; - else if ((target->getObjectTypeFlags() & 0x10) != 0 && !info->isPrimary() - && (info->getObjectTypeFlags() & 0x80) == 0) + else if (target->isOfType(ITAir) && !info->isPrimary() + && !info->isOfType(ITNaval)) scale = 3.0f; } if (apply) diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp index 1e88e17c0..2bdfb1231 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/EntryTurnToMedium.cpp @@ -11,7 +11,7 @@ #include "../AIBotActionPlan/BAPATurn.h" #include "../AIBotActionPlan/BAPCondition.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp index ef29057f1..05e46453e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/HeliControl.cpp @@ -8,10 +8,10 @@ #include "VehicleControlInline.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIControlInfo.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "VehicleControlInline.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../Math/Mat4.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp index bb46b7009..246ae5ccb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/InfanteryControl.cpp @@ -23,13 +23,13 @@ #include "../AIBot/BotNavigation.h" #include "../AIBot/SquadMember.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../../../../Core/Debug.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../Math/Mat4.h" @@ -358,10 +358,10 @@ bool updateInfantryMoveToPosWithObstacles(Bot* bot, const Vec2& target, const Ve if (!(info != ignored || includeIgnored) || info == 0) continue; IPIPhysical* physical = info->getPhysical(); - if (physical == 0 || (info->getObjectTypeFlags() & 0x200000) != 0) + if (physical == 0 || info->isOfType(ITSoldier)) continue; IPIMobile* mobile = info->getMobile(); - if (mobile == 0 && (info->getObjectTypeFlags() & 0x2000000) == 0) + if (mobile == 0 && !info->isOfType(ITObstacle)) continue; bool isTarget = false; @@ -369,7 +369,7 @@ bool updateInfantryMoveToPosWithObstacles(Bot* bot, const Vec2& target, const Ve isTarget = true; const float health = physical->getHealth(); bool damaged = false; - if ((info->getObjectTypeFlags() & 0x2000000) != 0 || health < IBotManager::instance->getVehicleBailValue()) + if (info->isOfType(ITObstacle) || health < IBotManager::instance->getVehicleBailValue()) damaged = true; float radius; if (!damaged || isTarget) @@ -452,14 +452,14 @@ bool updateInfantryMoveToPosWithObstacles(Bot* bot, const Vec2& target, const Ve to.x = normal3.x * 15.0f + valid.position.x; to.y = normal3.y * 15.0f + valid.position.y; to.z = normal3.z * 15.0f + valid.position.z; - pathfinding->trace(valid.polygon, valid.quadTree, vehicleNumber, valid.position, to, hitFront, polygon, + pathfinding->trace(valid.polygon, valid.island, vehicleNumber, valid.position, to, hitFront, polygon, equipmentType, -1, 0.0f, 0, 0); // retail: measured from the obstacle's position, not from the valid position traced from frontDist = isZeroVec(hitFront) ? 0.0f : distance(hitFront, bestPos3); to.x = valid.position.x - normal3.x * 15.0f; to.y = valid.position.y - normal3.y * 15.0f; to.z = valid.position.z - normal3.z * 15.0f; - pathfinding->trace(valid.polygon, valid.quadTree, vehicleNumber, valid.position, to, hitBack, polygon, + pathfinding->trace(valid.polygon, valid.island, vehicleNumber, valid.position, to, hitBack, polygon, equipmentType, -1, 0.0f, 0, 0); } const float backDist = isZeroVec(hitBack) ? 0.0f : distance(hitBack, bestPos3); diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp index d8ffa4a7d..2a1168990 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/MouseControl.cpp @@ -13,7 +13,7 @@ #include "../Main/CommonSingletonServer.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "InfanteryControl.h" #include "../../../../IO/Input/PlayerInput.h" @@ -105,7 +105,7 @@ void mouseControlLookAtDirection(Bot* bot, const Vec3& dir, const Mat4& camera, float maxX; Information* info = informationManager->getInformation(bot->getCurrentEquipment()); const float skill = static_cast(CommonSingletonServer::m_iaiSettings)->getBotSkill(); - if (info == 0 || (info->getObjectTypeFlags() & 0x200000) == 0) + if (info == 0 || !info->isOfType(ITSoldier)) { static float maxXInputNew = 1.0f; // ELF 0x4BDD10 maxY = (4.0f - maxYInputNew) * skill + maxYInputNew; diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp index d73672e0c..ade1c2c8b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/PlaneControl.cpp @@ -9,10 +9,10 @@ #include "VehicleControlInline.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/IPIControlInfo.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTerrain.h" #include "../../../../IO/Input/PlayerInput.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp index ab36dbb0f..8ec3ea5d7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/TankControl.cpp @@ -14,7 +14,7 @@ #include "../Main/IBotManager.h" #include "../../../../Math/LocalBoundingBox.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIControlInfo.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" @@ -476,7 +476,7 @@ int TankControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& d const float reach = clearance + 0.5f; const int vehicleNumber = mobile->getVehicleNumber(); const IPIMobile::ValidPos& otherValid = otherMobile->getLastValidPosition(vehicleNumber); - if (otherValid.polygon == 0xFFFFFFFFu || otherValid.quadTree == 0xFFFFFFFFu) + if (otherValid.polygon == 0xFFFFFFFFu || otherValid.island == 0xFFFFFFFFu) { avoidSide = 1; } @@ -488,11 +488,11 @@ int TankControl::actionStatusDecision(Bot* bot, Information* info, const Vec2& d hitLeft.x = hitLeft.y = hitLeft.z = 0.0f; unsigned int sidePolygon; Vec3 sideTarget = alongFrom(otherValid.position, rightAxis(info->getTransformation()), reach); - pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, sideTarget, hitRight, sidePolygon, equipmentType, -1, 0.0f, 0, 0); float roomRight = isZeroVec3(hitRight) ? 0.0f : distanceVec3(hitRight, otherValid.position); sideTarget = backFrom(otherValid.position, rightAxis(info->getTransformation()), reach); - pathfinding->trace(otherValid.polygon, otherValid.quadTree, vehicleNumber, otherValid.position, + pathfinding->trace(otherValid.polygon, otherValid.island, vehicleNumber, otherValid.position, sideTarget, hitLeft, sidePolygon, equipmentType, -1, 0.0f, 0, 0); float roomLeft = isZeroVec3(hitLeft) ? 0.0f : distanceVec3(hitLeft, otherValid.position); bool firstSide = roomRight < roomLeft; // before the obstacles shorten them diff --git a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h index c639917c0..0bd6c0423 100644 --- a/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h +++ b/Code/BF2/AI/AIDLL/AI/AIPlanInterpreter/VehicleControlInline.h @@ -5,7 +5,7 @@ #ifndef AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H #define AI_AIDLL_AI_AIPLANINTERPRETER_VEHICLECONTROLINLINE_H -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../../../../Math/Mat4.h" #include "../../../../Math/Vec3.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp index f90f5fef5..1a3af6d74 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.cpp @@ -20,7 +20,7 @@ #include "../Main/CommonSingletonServer.h" #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/UnitPredicate.h" @@ -301,9 +301,9 @@ SAI* ISAI::create(int side, int gridWidth, int gridHeight, Vec2 min, Vec2 max) // Starts the three integer states at -1 and the float accumulator at zero. SAI::BotInfo::BotInfo(Bot* bot) : m_bot(bot) - , m_int04(-1) - , m_int08(-1) - , m_int0C(-1) + , m_currentlyOrderedSquare(-1) + , m_lastOrderedSquare(-1) + , m_currentlyOccupiedSquare(-1) , m_float10(0.0f) , m_double14(0.0) { @@ -326,10 +326,10 @@ void SAI::clearStates(float* a, float* b) // retained in the signature but unused. +0xE0 is not constructed (no store in either body). SAI::SAI(int side, int, int, Vec2, Vec2) : m_flagAC(true) - , m_behaviourIdle(0) - , m_behaviourMoveTo(0) - , m_behaviourAvoid(0) - , m_behaviourFire(0) + , m_idleBehaviourId(0) + , m_moveToBehaviourId(0) + , m_avoidBehaviourId(0) + , m_fireBehaviourId(0) , m_intD8(0) , m_intDC(0) // The strategy cursor starts at `m_strategies.end`, which on a freshly built empty vector is @@ -361,10 +361,10 @@ SAI::SAI(int side, int, int, Vec2, Vec2) { m_commander = checkPointer(new CommanderInterface()); - m_behaviourIdle = BotBehaviourManager::m_instance->getBehaviourId(std::string("Idle")); - m_behaviourMoveTo = BotBehaviourManager::m_instance->getBehaviourId(std::string("MoveTo")); - m_behaviourAvoid = BotBehaviourManager::m_instance->getBehaviourId(std::string("Avoid")); - m_behaviourFire = BotBehaviourManager::m_instance->getBehaviourId(std::string("Fire")); + m_idleBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("Idle")); + m_moveToBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("MoveTo")); + m_avoidBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("Avoid")); + m_fireBehaviourId = BotBehaviourManager::m_instance->getBehaviourId(std::string("Fire")); // four deadlines off one clock read. Three at a minute out and one at ten seconds, with the // fifth left at zero - so three slow reviews and one fast one, all stamped at construction. @@ -401,16 +401,16 @@ SAI::SAI(int side, int, int, Vec2, Vec2) const IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); - m_botInfo.resize(settings->getMaxNBots()); + m_bots.resize(settings->getMaxNBots()); for (int i = 0; i < settings->getMaxNBots(); ++i) - m_botInfo[i] = 0; + m_bots[i] = 0; } // ELF 0x3257A0 (D2; D1 0x325E70, D0 0x326540; from BF2AI::clear): deletes the commander interface // (+0x1F8), the two EnemyStatistics (+0x124/+0x128), delete[]s the four state rows (+0x1E4..+0x1F0), // each tested for null; every container member then goes in reverse declaration order. The -// BotInfo pointers in m_botInfo are not deleted (no BotInfo destructor call in the body). +// BotInfo pointers in m_bots are not deleted (no BotInfo destructor call in the body). SAI::~SAI() { if (m_commander) @@ -448,7 +448,7 @@ void SAI::addStrategy(Strategy* strategy) container.m_f04 = 0.0f; container.m_startTime = 0.0f; container.m_i0C = 1; - container.m_strategy = strategy; + container.strategy = strategy; m_strategies.push_back(container); m_activeStrategy = &m_strategies[0]; } @@ -463,7 +463,7 @@ void SAI::update(double budget) const double start = timer->getUpdateTime(); updateRequestDenyTimers(); - for (std::vector::iterator it = m_botInfo.begin(); it != m_botInfo.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { if (*it) { @@ -648,20 +648,20 @@ void SAI::setBotIsDead(int botId) } // ELF 0x328DB0: a known bot leaves the strategic bookkeeping (BotInfo::remove); its assigned -// object (m_int04, read before the removal) and spawn kit (+0x104) are recorded in the dead-bot +// object (m_currentlyOrderedSquare, read before the removal) and spawn kit (+0x104) are recorded in the dead-bot // map (+0x5C, insert_unique), its player's spawn group is reset to 0 (IAIPlayer +0x38), and the // record is marked dead. void SAI::handleDeadBot(int botId) { - BotInfo* const info = m_botInfo[botId]; + BotInfo* const info = m_bots[botId]; if (!info) return; const int kit = info->m_bot->getSpawnKit(); - const int object = m_botInfo[botId]->m_int04; - m_botInfo[botId]->remove(this); + const int object = m_bots[botId]->m_currentlyOrderedSquare; + m_bots[botId]->remove(this); m_map5C.insert(std::make_pair(botId, std::make_pair(object, kit))); - m_botInfo[botId]->m_bot->getPlayer()->setSpawnGroup(0); - m_botInfo[botId]->setAsDead(this); + m_bots[botId]->m_bot->getPlayer()->setSpawnGroup(0); + m_bots[botId]->setAsDead(this); } // ELF 0x328AE0: a known, living bot is placed at the closest strategic object to its current @@ -670,17 +670,17 @@ void SAI::handleDeadBot(int botId) // match erased. The first spawn after a reset (+0xAC) resets the bridges. void SAI::setBotIsAlive(int botId) { - if (!m_botInfo[botId]) + if (!m_bots[botId]) return; if (m_flagAC) { AIStrategicObjectManager::getInstance()->resetBridges(); m_flagAC = false; } - if (m_botInfo[botId]->m_bot->isDead()) + if (m_bots[botId]->m_bot->isDead()) return; Information* const information = - informationManager->getInformation(m_botInfo[botId]->m_bot->getCurrentEquipment()); + informationManager->getInformation(m_bots[botId]->m_bot->getCurrentEquipment()); if (!information || !information->getUnit()) return; int vehicle = -1; @@ -690,7 +690,7 @@ void SAI::setBotIsAlive(int botId) const Vec3& position = information->getPosition(); AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getClosestObject(position, equipment, vehicle, m_side); - m_botInfo[botId]->respawn(object, this); + m_bots[botId]->respawn(object, this); for (std::map >::iterator it = m_map5C.begin(); it != m_map5C.end(); ++it) { if (it->first == botId) @@ -706,7 +706,7 @@ void SAI::setBotIsAlive(int botId) void SAI::removeBot(Bot* bot) { const int id = bot->getBotId(); - if (!m_botInfo[id]) + if (!m_bots[id]) return; std::map >::iterator it = m_map5C.begin(); for (; it != m_map5C.end(); ++it) @@ -715,9 +715,9 @@ void SAI::removeBot(Bot* bot) if (it != m_map5C.end()) m_map5C.erase(it); else - m_botInfo[id]->remove(this); - delete m_botInfo[id]; - m_botInfo[id] = 0; + m_bots[id]->remove(this); + delete m_bots[id]; + m_bots[id] = 0; } // Both test the requested bit; x86 masks shift count. @@ -767,31 +767,31 @@ void SAI::setBotHasChangedEquipment(int botId) } // ELF 0x328FE0: a bot that is not in the free set gives up its assignment - an assigned object -// (m_int04) is left through removeAssigned(release) + free(false), else a current object -// (m_int0C) through free(true). Its last ordered square becomes -1, and when its current +// (m_currentlyOrderedSquare) is left through removeAssigned(release) + free(false), else a current object +// (m_currentlyOccupiedSquare) through free(true). Its last ordered square becomes -1, and when its current // equipment's closest strategic object differs from the current one it moves there (occupy). void SAI::handleChangingBot(int botId) { - if (!m_botInfo[botId]) + if (!m_bots[botId]) return; - if (m_set44.find(botId) == m_set44.end()) + if (m_freeBots.find(botId) == m_freeBots.end()) { - BotInfo* const info = m_botInfo[botId]; - if (info->m_int04 != -1) + BotInfo* const info = m_bots[botId]; + if (info->m_currentlyOrderedSquare != -1) { AIStrategicObject* const object = - AIStrategicObjectManager::getInstance()->getStrategicObject(info->m_int04); - m_botInfo[botId]->removeAssigned(object, true, this); - m_botInfo[botId]->free(false, this); + AIStrategicObjectManager::getInstance()->getStrategicObject(info->m_currentlyOrderedSquare); + m_bots[botId]->removeAssigned(object, true, this); + m_bots[botId]->free(false, this); } - else if (info->m_int0C != -1) + else if (info->m_currentlyOccupiedSquare != -1) { info->free(true, this); } } - m_botInfo[botId]->setLastOrderedSquare(-1); + m_bots[botId]->setLastOrderedSquare(-1); Information* const information = - informationManager->getInformation(m_botInfo[botId]->m_bot->getCurrentEquipment()); + informationManager->getInformation(m_bots[botId]->m_bot->getCurrentEquipment()); if (!information || !information->getUnit()) return; IPIMobile* const mobile = information->getMobile(); @@ -802,9 +802,9 @@ void SAI::handleChangingBot(int botId) const int equipment = information->getUnit()->getEquipmentType(); AIStrategicObject* const closest = manager->getClosestObject(information->getPosition(), equipment, vehicle, m_side); - if (closest->getIndex() == m_botInfo[botId]->m_int0C) + if (closest->getIndex() == m_bots[botId]->m_currentlyOccupiedSquare) return; - m_botInfo[botId]->occupy(manager->getStrategicObject(m_botInfo[botId]->m_int0C), closest, this); + m_bots[botId]->occupy(manager->getStrategicObject(m_bots[botId]->m_currentlyOccupiedSquare), closest, this); } // find, update the second member of the existing pair, or do nothing. @@ -1228,7 +1228,7 @@ int SAI::releaseSquadsFromObject(int object, int side) } // ELF 0x32D6D0: the unit leaves the object's assigned set and SAI's occupied set, then -// m_botInfo[*it]->free(false) runs - with the iterator removeAssigned has already advanced, so +// m_bots[*it]->free(false) runs - with the iterator removeAssigned has already advanced, so // the image frees the *next* assigned unit (`movl (%esi),%eax` reloads it after the call). // [CHOSEN, not recovered] When the released unit was the last one, the image reads the old // libstdc++ header node's stale value as a bot index; here that second call is skipped. @@ -1236,9 +1236,9 @@ int SAI::releaseSquadsFromObject(int object, int side) bool SAI::releaseUnitFromObject(int object, std::set::iterator& it, int) { AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); - m_botInfo[*it]->removeAssigned(target, it, true, this); + m_bots[*it]->removeAssigned(target, it, true, this); if (it != target->getAssignedUnits(m_side).end()) - m_botInfo[*it]->free(false, this); + m_bots[*it]->free(false, this); return true; } @@ -1266,12 +1266,12 @@ void SAI::equipmentChangedFinished(int botId) m_setB0.erase(it); } -// ELF 0x32D870: answers the bot's current object index (m_int0C, read first). +// ELF 0x32D870: answers the bot's current object index (m_currentlyOccupiedSquare, read first). int SAI::assignBot(std::set::iterator& it, int object, int botId, bool attacker) { - const int current = m_botInfo[botId]->m_int0C; + const int current = m_bots[botId]->m_currentlyOccupiedSquare; AIStrategicObject* const target = AIStrategicObjectManager::getInstance()->getStrategicObject(object); - m_botInfo[botId]->assignToObject(it, target, attacker, this); + m_bots[botId]->assignToObject(it, target, attacker, this); return current; } @@ -1308,8 +1308,8 @@ std::string SAI::listStrategies() std::ostringstream out; for (unsigned int i = 0; i < m_strategies.size(); ++i) { - if (m_strategies[i].m_strategy) - out << i << " " << m_strategies[i].m_strategy->getName() << std::endl; + if (m_strategies[i].strategy) + out << i << " " << m_strategies[i].strategy->getName() << std::endl; } return out.str(); } @@ -1317,7 +1317,7 @@ std::string SAI::listStrategies() // ELF 0x32EA90: the active container's strategy, unguarded. Strategy* SAI::getActiveStrategy() { - return m_activeStrategy->m_strategy; + return m_activeStrategy->strategy; } // ELF 0x32EAB0: the active container's three floats (zero, with no active container) and its @@ -1336,19 +1336,19 @@ Strategy* SAI::getActiveStrategy(float& a, float& b, float& c) b = 0.0f; c = 0.0f; } - return m_activeStrategy->m_strategy; + return m_activeStrategy->strategy; } // ELF 0x32E2D0: membership in the free set (+0x44). bool SAI::isBotFree(int botId) const { - return m_set44.find(botId) != m_set44.end(); + return m_freeBots.find(botId) != m_freeBots.end(); } // ELF 0x32E320: membership in the occupied set (+0xFC). bool SAI::isBotAssigned(int botId) const { - return m_setFC.find(botId) != m_setFC.end(); + return m_assignedBots.find(botId) != m_assignedBots.end(); } // ELF 0x32CEE0: empty. @@ -1386,25 +1386,25 @@ int SAI::getSpawnsToPoint(int point) const return it->second; } -// ELF 0x32E240 / 0x32E270 / 0x32E2A0: the bot's current object (m_int0C), ordered object -// (m_int04) and last ordered square (m_int08) - indices, not positions (eax, no sret). An unknown +// ELF 0x32E240 / 0x32E270 / 0x32E2A0: the bot's current object (m_currentlyOccupiedSquare), ordered object +// (m_currentlyOrderedSquare) and last ordered square (m_lastOrderedSquare) - indices, not positions (eax, no sret). An unknown // bot answers -22, -44 and -1 (`movl $0xffffffea/$0xffffffd4/$0xffffffff,%edx`). int SAI::getBotCurrentPos(int botId) const { - const BotInfo* const info = m_botInfo[botId]; - return info ? info->m_int0C : -22; + const BotInfo* const info = m_bots[botId]; + return info ? info->m_currentlyOccupiedSquare : -22; } int SAI::getBotOrderedPos(int botId) const { - const BotInfo* const info = m_botInfo[botId]; - return info ? info->m_int04 : -44; + const BotInfo* const info = m_bots[botId]; + return info ? info->m_currentlyOrderedSquare : -44; } int SAI::getBotLastOrderedPos(int botId) const { - const BotInfo* const info = m_botInfo[botId]; - return info ? info->m_int08 : -1; + const BotInfo* const info = m_bots[botId]; + return info ? info->m_lastOrderedSquare : -1; } // Accumulate into the previous totals, then decay; no initial clear. @@ -1602,7 +1602,7 @@ void SAI::prepareUpdate() if (bot) { BotInfo* const info = checkPointer(new BotInfo(bot)); - m_botInfo[bot->getBotId()] = info; + m_bots[bot->getBotId()] = info; if (bot->isDead()) { m_map5C.insert(std::make_pair(static_cast(bot->getBotId()), std::make_pair(-1, 13))); @@ -1611,7 +1611,7 @@ void SAI::prepareUpdate() } else setBotIsAlive(bot->getBotId()); - (void)m_setFC.find(bot->getBotId()); // shipped discarded lookup + (void)m_assignedBots.find(bot->getBotId()); // shipped discarded lookup } } @@ -1631,7 +1631,7 @@ void SAI::prepareUpdate() m_friendlyStrengths[i] = 0.0f; m_friendlyCounts[i] = 0.0f; } - for (std::vector::iterator it = m_botInfo.begin(); it != m_botInfo.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { if (*it && !(*it)->m_bot->isDead()) { @@ -1662,7 +1662,7 @@ void SAI::prepareUpdate() for (std::map >::iterator it = m_map5C.begin(); it != m_map5C.end();) { IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); - BotInfo* const info = m_botInfo[it->first]; + BotInfo* const info = m_bots[it->first]; if (!info) { std::map >::iterator removed = it++; @@ -1680,11 +1680,11 @@ void SAI::prepareUpdate() for (std::vector::iterator it = m_vectorA0.begin(); it != m_vectorA0.end(); ++it) { - if (m_botInfo[(*it)->getBotId()]) + if (m_bots[(*it)->getBotId()]) { - m_botInfo[(*it)->getBotId()]->remove(this); - delete m_botInfo[(*it)->getBotId()]; - m_botInfo[(*it)->getBotId()] = 0; + m_bots[(*it)->getBotId()]->remove(this); + delete m_bots[(*it)->getBotId()]; + m_bots[(*it)->getBotId()] = 0; } } #if defined(_MSC_VER) @@ -1705,8 +1705,8 @@ void SAI::clearSpawnsToPoints() void SAI::BotInfo::remove(SAI* sai) { const int id = m_bot->getBotId(); - AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); - AIStrategicObject* const assigned = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int04); + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); + AIStrategicObject* const assigned = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOrderedSquare); if (assigned) { removeAssigned(assigned, true, sai); @@ -1714,13 +1714,13 @@ void SAI::BotInfo::remove(SAI* sai) } else if (current) { - if (sai->m_setFC.find(id) != sai->m_setFC.end()) + if (sai->m_assignedBots.find(id) != sai->m_assignedBots.end()) free(true, sai); current->removeAsPresentUnit(id, sai->m_side); } - std::set::iterator it = sai->m_set44.find(id); - if (it != sai->m_set44.end()) - sai->m_set44.erase(it); + std::set::iterator it = sai->m_freeBots.find(id); + if (it != sai->m_freeBots.end()) + sai->m_freeBots.erase(it); } void SAI::BotInfo::removeAssigned(AIStrategicObject* object, bool release, SAI* sai) @@ -1737,10 +1737,10 @@ void SAI::BotInfo::occupy(AIStrategicObject* from, AIStrategicObject* to, SAI* s void SAI::BotInfo::assignToObject(std::set::iterator& it, AIStrategicObject* object, bool attacker, SAI* sai) { - m_int04 = object->getIndex(); - m_int08 = object->getIndex(); + m_currentlyOrderedSquare = object->getIndex(); + m_lastOrderedSquare = object->getIndex(); m_double14 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); if (attacker) current->unregisterAvailableAttacker(it, sai->m_side); else @@ -1750,45 +1750,45 @@ void SAI::BotInfo::assignToObject(std::set::iterator& it, AIStrategicObject void SAI::BotInfo::assignToObject(AIStrategicObject* object, bool attacker, SAI* sai) { - std::set::iterator it = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C)-> + std::set::iterator it = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare)-> getAvailableBots(attacker, sai->m_side).find(m_bot->getBotId()); assignToObject(it, object, attacker, sai); } void SAI::BotInfo::assign(bool attacker, SAI* sai) { - std::set::iterator it = sai->m_set44.find(m_bot->getBotId()); + std::set::iterator it = sai->m_freeBots.find(m_bot->getBotId()); assign(it, attacker, sai); } void SAI::BotInfo::setAsDead(SAI*) { - m_int04 = -1; - m_int08 = -1; - m_int0C = -1; + m_currentlyOrderedSquare = -1; + m_lastOrderedSquare = -1; + m_currentlyOccupiedSquare = -1; m_float10 = 0.0f; } void SAI::BotInfo::setAsFree(SAI* sai) { - sai->m_set44.insert(m_bot->getBotId()); + sai->m_freeBots.insert(m_bot->getBotId()); } // ELF 0x328EF0: with a suitable spawn group the bot enters its transition phase (+0x180), // is handled as dead, gets the group and is respawned through the game effector (+0x1C). void SAI::handleTeleportingBot(int botId) { - if (!m_botInfo[botId]) + if (!m_bots[botId]) return; AIStrategicObject* object; - const int group = BotSpawner::findSuitableSpawnGroup(m_side, object, m_botInfo[botId]->m_bot); + const int group = BotSpawner::findSuitableSpawnGroup(m_side, object, m_bots[botId]->m_bot); if (!group) return; - m_botInfo[botId]->m_bot->setIsInTransitionPhase(true); + m_bots[botId]->m_bot->setIsInTransitionPhase(true); handleDeadBot(botId); - m_botInfo[botId]->m_bot->getPlayer()->setSpawnGroup(group); + m_bots[botId]->m_bot->getPlayer()->setSpawnGroup(group); static_cast(CommonSingletonServer::m_iaiGameEffector) - ->respawnBot(m_botInfo[botId]->m_bot->getPlayer()); + ->respawnBot(m_bots[botId]->m_bot->getPlayer()); } bool SAI::updateStrategicObjects() @@ -1855,17 +1855,17 @@ void SAI::chooseStrategy() if (forced) { forced->calculatePrerequisite(m_int1F4 ? m_stateB : m_stateA, m_int1F4 ? m_stateD : m_stateC, - m_activeStrategy->m_strategy, m_side); + m_activeStrategy->strategy, m_side); for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) - if (it->m_strategy == forced) + if (it->strategy == forced) changeStrategy(it); return; } for (std::vector::iterator it = m_strategies.begin(); it != m_strategies.end(); ++it) { - it->m_f04 = it->m_strategy->calculatePrerequisite( + it->m_f04 = it->strategy->calculatePrerequisite( m_int1F4 ? m_stateB : m_stateA, m_int1F4 ? m_stateD : m_stateC, - m_activeStrategy->m_strategy, m_side); + m_activeStrategy->strategy, m_side); if (total > it->m_f04) // total is still 0 here it->m_f04 = total; float ratio; @@ -1878,7 +1878,7 @@ void SAI::chooseStrategy() } if (!changed) { - const float limit = m_activeStrategy->m_strategy->m_f20; + const float limit = m_activeStrategy->strategy->m_f20; const float p = powf(0.5f, static_cast(m_activeStrategy->m_i0C)); const float d = 0.5f - p; const double threshold = ((d + d) + 1.0f) * limit; @@ -1921,10 +1921,10 @@ void SAI::changeStrategy(std::vector::iterator& it) (*object)->releaseAssignedResources(m_side); std::set& attackers = (*object)->getAvailableAttackers(m_side); for (unit = attackers.begin(); unit != attackers.end();) - m_botInfo[*unit]->free(*object, true, unit, this); + m_bots[*unit]->free(*object, true, unit, this); std::set& defenders = (*object)->getAvailableDefenders(m_side); for (unit = defenders.begin(); unit != defenders.end();) - m_botInfo[*unit]->free(*object, false, unit, this); + m_bots[*unit]->free(*object, false, unit, this); } StrategyContainer* const active = m_activeStrategy; active->m_i0C = 1; @@ -1939,8 +1939,8 @@ void SAI::BotInfo::free(AIStrategicObject* object, bool attacker, std::set: object->unregisterAvailableAttacker(it, sai->m_side); else object->unregisterAvailableDefender(it, sai->m_side); - sai->m_setFC.erase(sai->m_setFC.find(id)); - sai->m_set44.insert(m_bot->getBotId()); + sai->m_assignedBots.erase(sai->m_assignedBots.find(id)); + sai->m_freeBots.insert(m_bot->getBotId()); } // ELF 0x3299A0: every strategic object (no null check) applies the active strategy's @@ -1950,7 +1950,7 @@ void SAI::modifyStrategicObjectsTemperatures() const std::vector& objects = AIStrategicObjectManager::getInstance()->getStrategicObjects(); for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) - (*it)->updateTemperature(m_activeStrategy->m_strategy, m_side); + (*it)->updateTemperature(m_activeStrategy->strategy, m_side); } // ELF 0x32F290. The occupied-set find result is unused in the image. @@ -1970,9 +1970,9 @@ void SAI::BotInfo::occupy(std::set::iterator& it, AIStrategicObject* from, moved = true; } if (moved) - sai->m_setFC.find(id); + sai->m_assignedBots.find(id); from->removeAsPresentUnit(it, sai->m_side); - m_int0C = to->getIndex(); + m_currentlyOccupiedSquare = to->getIndex(); } // ELF 0x32D910. Per strategic area (getType 0): a present bot whose equipment fits a neighbour @@ -2025,7 +2025,7 @@ void SAI::updateBotPositions() if (best == *object) ++unit; else - m_botInfo[*unit]->occupy(unit, *object, best, this); + m_bots[*unit]->occupy(unit, *object, best, this); } const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); @@ -2047,14 +2047,14 @@ void SAI::updateBotPositions() WaypointList* const waypoints = bot->getWaypoints(); if (!waypoints->m_flag5 || waypoints->getId() != 1) continue; - if (!(now - m_botInfo[*it]->m_double14 > wait)) + if (!(now - m_bots[*it]->m_double14 > wait)) continue; if (bot->getSensedObjects().size() > 1) continue; if (!(*object)->isPresentUnit(*it, m_side)) continue; (*object)->retainBot(m_side, *it, this); - m_botInfo[*it]->m_double14 = now; + m_bots[*it]->m_double14 = now; } } } @@ -2063,14 +2063,14 @@ void SAI::updateBotPositions() void SAI::BotInfo::free(bool release, SAI* sai) { const int id = m_bot->getBotId(); - AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); if (release) { if (!object->unregisterAvailableAttacker(id, sai->m_side)) object->unregisterAvailableDefender(id, sai->m_side); - sai->m_setFC.erase(sai->m_setFC.find(id)); + sai->m_assignedBots.erase(sai->m_assignedBots.find(id)); } - sai->m_set44.insert(m_bot->getBotId()); + sai->m_freeBots.insert(m_bot->getBotId()); } namespace { @@ -2115,7 +2115,7 @@ void SAI::updateDistribution() { while ((*object)->getAvailableAttackers(m_side).size()) { - m_botInfo[*(*object)->getAvailableAttackers(m_side).begin()]->free(true, this); + m_bots[*(*object)->getAvailableAttackers(m_side).begin()]->free(true, this); m_flag1CE = true; } } @@ -2135,7 +2135,7 @@ void SAI::updateDistribution() { while ((*object)->getAvailableDefenders(m_side).size()) { - m_botInfo[*(*object)->getAvailableDefenders(m_side).begin()]->free(true, this); + m_bots[*(*object)->getAvailableDefenders(m_side).begin()]->free(true, this); m_flag1CE = true; } } @@ -2182,21 +2182,21 @@ void SAI::updateDistribution() void SAI::BotInfo::respawn(AIStrategicObject* object, SAI* sai) { - m_int0C = object->getIndex(); + m_currentlyOccupiedSquare = object->getIndex(); object->setAsPresentUnit(m_bot->getBotId(), sai->m_side); - sai->m_setFC.find(m_bot->getBotId()); // result unused in the image - sai->m_set44.insert(m_bot->getBotId()); + sai->m_assignedBots.find(m_bot->getBotId()); // result unused in the image + sai->m_freeBots.insert(m_bot->getBotId()); } void SAI::BotInfo::assign(std::set::iterator& it, bool attacker, SAI* sai) { - AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); if (attacker) object->registerAvailableAttacker(m_bot->getBotId(), sai->m_side); else object->registerAvailableDefender(m_bot->getBotId(), sai->m_side); - sai->m_set44.erase(it++); - sai->m_setFC.insert(m_bot->getBotId()); + sai->m_freeBots.erase(it++); + sai->m_assignedBots.insert(m_bot->getBotId()); } void SAI::BotInfo::removeAssigned(AIStrategicObject* object, std::set::iterator& it, bool release, SAI* sai) @@ -2204,24 +2204,24 @@ void SAI::BotInfo::removeAssigned(AIStrategicObject* object, std::set::iter object->getAssignedUnits(sai->m_side).erase(it++); if (release) { - sai->m_setFC.erase(sai->m_setFC.find(m_bot->getBotId())); + sai->m_assignedBots.erase(sai->m_assignedBots.find(m_bot->getBotId())); } else { - AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_int0C); + AIStrategicObject* const current = AIStrategicObjectManager::getInstance()->getStrategicObject(m_currentlyOccupiedSquare); if (current->isAttack(sai->m_side)) current->registerAvailableAttacker(m_bot->getBotId(), sai->m_side); else current->registerAvailableDefender(m_bot->getBotId(), sai->m_side); } - m_int04 = -1; + m_currentlyOrderedSquare = -1; m_double14 = 0.0; } int SAI::BotInfo::setLastOrderedSquare(int square) { m_double14 = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); - m_int08 = square; + m_lastOrderedSquare = square; return square; } @@ -2260,13 +2260,13 @@ void SAI::distributeResources() } else { - attackShare = m_activeStrategy->m_strategy->getAggression(); - defenceShare = 1.0f - m_activeStrategy->m_strategy->getAggression(); + attackShare = m_activeStrategy->strategy->getAggression(); + defenceShare = 1.0f - m_activeStrategy->strategy->getAggression(); } - for (std::set::iterator it = m_set44.begin(); it != m_set44.end();) + for (std::set::iterator it = m_freeBots.begin(); it != m_freeBots.end();) { - BotInfo* const info = m_botInfo[*it]; + BotInfo* const info = m_bots[*it]; if (!info) { ++it; @@ -2278,7 +2278,7 @@ void SAI::distributeResources() ++it; continue; } - AIStrategicObject* object = manager->getStrategicObject(info->m_int0C); + AIStrategicObject* object = manager->getStrategicObject(info->m_currentlyOccupiedSquare); if (!object) { if (!information->getUnit()) @@ -2296,16 +2296,16 @@ void SAI::distributeResources() ++it; continue; } - m_botInfo[*it]->respawn(object, this); + m_bots[*it]->respawn(object, this); } else { object->setAsPresentUnit(*it, m_side); } - if (object->getIndex() != m_botInfo[*it]->m_int08) + if (object->getIndex() != m_bots[*it]->m_lastOrderedSquare) { object->retainBot(m_side, *it, this); - m_botInfo[*it]->setLastOrderedSquare(object->getIndex()); + m_bots[*it]->setLastOrderedSquare(object->getIndex()); } IPIUnit* const unit = information->getUnit(); // not null-checked on this path const int attack = m_intD8; @@ -2325,7 +2325,7 @@ void SAI::distributeResources() m_intDC = static_cast(unit->getStrategicStrengths()[1]) + defence; m_intE0 -= static_cast(meanStrength(unit)); lastWasDefence = !toAttack; - m_botInfo[*it]->assign(it, toAttack, this); + m_bots[*it]->assign(it, toAttack, this); } const float total = static_cast(m_intD8 + m_intDC + m_intE0); @@ -2362,7 +2362,7 @@ void SAI::distributeResources() // strategy runs no defences. void SAI::distributeDefence() { - if (!m_activeStrategy->m_strategy->getNumberOfDefences()) + if (!m_activeStrategy->strategy->getNumberOfDefences()) return; AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); if (!manager->getNumberOfCategories()) @@ -2412,7 +2412,7 @@ void SAI::categoryDistributeDefence(const std::vector& objec for (; it != squares.end(); ++it) { ++rank; - const unsigned int keep = m_activeStrategy->m_strategy->getNumberOfDefences() * 2; + const unsigned int keep = m_activeStrategy->strategy->getNumberOfDefences() * 2; if (rank == keep) threshold = it->m_value; else if (rank > keep && threshold * 0.9f > it->m_value) @@ -2453,7 +2453,7 @@ void SAI::categoryDistributeDefence(const std::vector& objec object->setAttack(false, m_side); queue.push(object); ++count; - if (!(m_activeStrategy->m_strategy->getNumberOfDefences() > count)) + if (!(m_activeStrategy->strategy->getNumberOfDefences() > count)) break; } while (!queue.empty()) @@ -2469,7 +2469,7 @@ void SAI::categoryDistributeDefence(const std::vector& objec // strategy runs no attacks. void SAI::distributeAttack() { - if (!m_activeStrategy->m_strategy->getNumberOfAttacks()) + if (!m_activeStrategy->strategy->getNumberOfAttacks()) return; AIStrategicObjectManager* const manager = AIStrategicObjectManager::getInstance(); if (!manager->getNumberOfCategories()) @@ -2522,9 +2522,9 @@ void SAI::categoryDistributeAttack(const std::vector& object while (it != squares.end()) { ++rank; - if (rank <= m_activeStrategy->m_strategy->getNumberOfAttacks()) + if (rank <= m_activeStrategy->strategy->getNumberOfAttacks()) threshold = it->m_value; - else if (rank > m_activeStrategy->m_strategy->getNumberOfAttacks() * 2 + else if (rank > m_activeStrategy->strategy->getNumberOfAttacks() * 2 || threshold * 0.8f > it->m_value) break; ++it; @@ -2561,7 +2561,7 @@ void SAI::categoryDistributeAttack(const std::vector& object } it = squares.begin(); - while (it != squares.end() && !(chosen.size() > m_activeStrategy->m_strategy->getNumberOfAttacks())) + while (it != squares.end() && !(chosen.size() > m_activeStrategy->strategy->getNumberOfAttacks())) { AIStrategicObject* const object = AIStrategicObjectManager::getInstance()->getStrategicObject(it->m_index); if (object && object->isAttack(m_side)) @@ -2575,7 +2575,7 @@ void SAI::categoryDistributeAttack(const std::vector& object } } it = squares.begin(); - while (!(chosen.size() > m_activeStrategy->m_strategy->getNumberOfAttacks()) && it != squares.end()) + while (!(chosen.size() > m_activeStrategy->strategy->getNumberOfAttacks()) && it != squares.end()) { chosen.push_back(*it); ++it; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h index 93b1e5a12..33c039230 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h @@ -35,7 +35,7 @@ struct StrategyContainer float m_f04; // +0x04, [UNRESOLVED] role; SAI::reset zeroes it float m_startTime; // +0x08, [INFERRED] name int m_i0C; // +0x0C, = 1 [UNRESOLVED] - Strategy* m_strategy; // +0x10, borrowed; owned by the StrategyManager + Strategy* strategy; // +0x10, borrowed; owned by the StrategyManager; name: AIDLL_r assert "stratIter->strategy != 0" (0x1015BA90) }; // Running weighted averages over a fixed number of strength categories. @@ -171,14 +171,14 @@ class SAI : public ISAI // ELF 0x32F5B0: removeAssigned through object->getAssignedUnits(side).find(id) (no end // check in the image). void removeAssigned(AIStrategicObject* object, bool release, SAI* sai); - // ELF 0x32FF30: m_int04/m_int08/m_int0C = -1, m_float10 = 0.0f. + // ELF 0x32FF30: m_currentlyOrderedSquare/m_lastOrderedSquare/m_currentlyOccupiedSquare = -1, m_float10 = 0.0f. void setAsDead(SAI* sai); // ELF 0x32FF70: the id enters the free set (+0x44). void setAsFree(SAI* sai); // ELF 0x32FDF0: unregister the bot from the object's attacker/defender set (advancing // it), move its id from SAI's occupied set (+0xFC) to the free set (+0x44). void free(AIStrategicObject* object, bool attacker, std::set::iterator& it, SAI* sai); - // ELF 0x32FC80: with release, unregister from the current object (m_int0C) and leave the + // ELF 0x32FC80: with release, unregister from the current object (m_currentlyOccupiedSquare) and leave the // occupied set; the id always enters the free set (+0x44). void free(bool release, SAI* sai); // ELF 0x32F0E0: the bot respawned at an object: present there, id into the free set. @@ -189,14 +189,14 @@ class SAI : public ISAI int setLastOrderedSquare(int square); // ELF 0x32FFD0; stamps m_double14 // ELF 0x32F660: leave the object's assigned set (erasing under the iterator); with // release also SAI's occupied set (+0xFC), otherwise become an available attacker or - // defender of the current object (m_int0C). Clears m_int04 and m_double14. + // defender of the current object (m_currentlyOccupiedSquare). Clears m_currentlyOrderedSquare and m_double14. void removeAssigned(AIStrategicObject* object, std::set::iterator& it, bool release, SAI* sai); // ELF 0x32F290: the bot moves from one object's present set (advancing it) to another's, - // keeping its attacker/defender role there; m_int0C becomes the new object's index. + // keeping its attacker/defender role there; m_currentlyOccupiedSquare becomes the new object's index. void occupy(std::set::iterator& it, AIStrategicObject* from, AIStrategicObject* to, SAI* sai); // ELF 0x32F1F0: the iterator overload with from->getPresentUnits(side).find(id). void occupy(AIStrategicObject* from, AIStrategicObject* to, SAI* sai); - // ELF 0x32F950: ordered to the object (m_int04 = m_int08 = its index, m_double14 = now); + // ELF 0x32F950: ordered to the object (m_currentlyOrderedSquare = m_lastOrderedSquare = its index, m_double14 = now); // leaves the current object's attackers/defenders under the iterator and joins the // object's assigned set. void assignToObject(std::set::iterator& it, AIStrategicObject* object, bool attacker, SAI* sai); @@ -207,9 +207,9 @@ class SAI : public ISAI void assign(bool attacker, SAI* sai); /* +0x00 */ Bot* m_bot; - /* +0x04 */ int m_int04; // = -1 - /* +0x08 */ int m_int08; // = -1 - /* +0x0C */ int m_int0C; // = -1 + /* +0x04 */ int m_currentlyOrderedSquare; // = -1 // name: AIDLL_r asserts 0x10157690, 0x10159C00 (+4) + /* +0x08 */ int m_lastOrderedSquare; // = -1 // name: AIDLL_r assert 0x101596A0 (+8) + /* +0x0C */ int m_currentlyOccupiedSquare; // = -1 // name: AIDLL_r asserts 0x10157250, 0x10159C00 (+0xC) /* +0x10 */ float m_float10; // = 0.0f; update accumulates the frame interval here /* +0x14 */ double m_double14; // = 0.0 }; @@ -321,8 +321,8 @@ class SAI : public ISAI /* +0x02C */ std::vector m_vector2C; // 4-byte element; type [UNRESOLVED] /* +0x038 */ std::vector m_vector38; // 4-byte element; type [UNRESOLVED] - /* +0x044 */ std::set m_set44; - /* +0x050 */ std::vector m_botInfo; // resized to getMaxNBots by the constructor + /* +0x044 */ std::set m_freeBots; // name: AIDLL_r assert "sai->m_freeBots" 0x10157AB0 (PE +0x4C) + /* +0x050 */ std::vector m_bots; // resized to getMaxNBots by the constructor // name: AIDLL_r assert "m_bots[botId] != 0" 0x1015CF40 (PE +0x58) /* +0x05C */ std::map > m_map5C; // Five doubles. Four are stamped from the timer at construction: three at now + 60 and one at @@ -342,17 +342,17 @@ class SAI : public ISAI // four behaviour IDS resolved by name at construction, through BotBehaviourManager. If a // behaviour is missing the manager returns -1 and the id is stored anyway. - /* +0x0C8 */ int m_behaviourIdle; // "Idle" - /* +0x0CC */ int m_behaviourMoveTo; // "MoveTo" - /* +0x0D0 */ int m_behaviourAvoid; // "Avoid" - /* +0x0D4 */ int m_behaviourFire; // "Fire" + /* +0x0C8 */ int m_idleBehaviourId; // "Idle" // name: AIDLL_r assert 0x10160AB0 (PE +0xEC) + /* +0x0CC */ int m_moveToBehaviourId; // "MoveTo" // name: AIDLL_r assert 0x10160AB0 (PE +0xF0) + /* +0x0D0 */ int m_avoidBehaviourId; // "Avoid" // name: AIDLL_r assert 0x10160AB0 (PE +0xF4) + /* +0x0D4 */ int m_fireBehaviourId; // "Fire" // name: AIDLL_r assert 0x10160AB0 (PE +0xF8) /* +0x0D8 */ int m_intD8; // [UNRESOLVED] - the ctor zeroes it /* +0x0DC */ int m_intDC; // [UNRESOLVED] - the ctor zeroes it /* +0x0E0 */ int m_intE0; // [UNRESOLVED]; not constructed, updateDistribution zeroes it /* +0x0E4 */ std::map > m_mapE4; // a map of maps - node 32 /* +0x0F0 */ std::set m_setF0; - /* +0x0FC */ std::set m_setFC; + /* +0x0FC */ std::set m_assignedBots; // name: AIDLL_r assert "sai->m_assignedBots" 0x10157AB0 (PE +0x120) /* +0x108 */ std::list m_list108; // 4-byte element; type [UNRESOLVED] /* +0x10C */ std::list m_list10C; // 4-byte element; type [UNRESOLVED] /* +0x110 */ std::list m_list110; // teleporter ids (registerTeleporter) diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp index b779e3be9..4943eab53 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.cpp @@ -14,7 +14,7 @@ #include "../Main/IAIPathfinding.h" #include "../AIBot/SquadManager.h" #include "../AIBot/SquadCoordinator.h" -#include "../AIBotBehaviour/CustomCurve.h" +#include "../AIUtils/CustomCurve.h" #include "../AIStrategic/SAI.h" #include "../AIStrategic/Strategy.h" #include "AIStrategicObjectManager.h" @@ -22,7 +22,7 @@ #include "../Main/IBotManager.h" #include "../Main/AIMain.h" // IAIMain::m_instance->getSAI #include "../AIKnowledge/BFInformationEnvironment.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" @@ -33,7 +33,7 @@ #include "../Main/AIRandom.h" #include "SAWayPoint.h" #include "AILandingZone.h" -#include "AILandingZoneManager.h" +#include "../Main/AILandingZoneManager.h" #include "../AIKnowledge/AIInformationGrid.h" #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame - the control-point queries #include "../../../AIInterface/BFKnowledge/BFTerrain.h" // IAITerrain::getTerrainAltitude @@ -71,8 +71,7 @@ class FreeUnitPred : public IAIInformationGridPredicate { if (!information->getUnit() || !information->hasMobile()) return false; - const unsigned int flags = information->getObjectTypeFlags(); - if ((flags & 0x80u) || (flags & 0x200000u)) + if (information->isOfType(ITNaval) || information->isOfType(ITSoldier)) return false; int iterator = information->getFirstSecondaryObjectIterator(); @@ -101,7 +100,7 @@ AIStrategicArea::AIStrategicArea(const std::string& name, Vec2 topLeft, Vec2 cen : AIStrategicObject(radius, height) , m_list268() , m_centre(topLeft) - , m_mapData(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) + , m_orderPos(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) , m_neighbours() , m_neighbouringObjects() , m_name(name) @@ -129,7 +128,7 @@ AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int controlPo : AIStrategicObject(radius, -666.0f) , m_list268() , m_centre() - , m_mapData(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) + , m_orderPos(checkPointer(new MapData[IAIPathfinding::instance->getNumberOfMaps()])) , m_neighbours() , m_neighbouringObjects() , m_name(name) @@ -157,7 +156,7 @@ AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int controlPo // vectors and the name (+0x188 down to +0x10C) then go in reverse declaration order, then the base. AIStrategicArea::~AIStrategicArea() { - delete[] m_mapData; + delete[] m_orderPos; delete[] m_flagsA; delete[] m_flagsB; delete[] m_listsA; @@ -385,7 +384,7 @@ void AIStrategicArea::initOrderPoses() for (int i = 0; i < pathfinding->getNumberOfMaps(); ++i) { - MapData& data = m_mapData[i]; + MapData& data = m_orderPos[i]; unsigned int polygon = 0; unsigned int island = 0; @@ -395,7 +394,7 @@ void AIStrategicArea::initOrderPoses() data.m_offset.y = data.m_offset.y - areaPosition.y; data.m_offset.z = data.m_offset.z - areaPosition.z; - data.m_island = island; + data.island = island; } m_orderPosesInitialised = true; @@ -415,7 +414,7 @@ Vec3 AIStrategicArea::getOrderPos(int map, int unused) const if (map != -1) { - const MapData& data = m_mapData[map]; + const MapData& data = m_orderPos[map]; position.x += data.m_offset.x; position.y += data.m_offset.y; position.z += data.m_offset.z; @@ -560,13 +559,13 @@ void AIStrategicArea::update(int side, ISAI* sai, bool& changed) return; if (sai->isFriend(information->getSide())) { - if (!root || (information->getObjectTypeFlags() & 0x10u) == 0) + if (!root || !information->isOfType(ITAir)) ++friendlyUnits; friendly = static_cast(static_cast(security) * strength + friendly); } else if (sai->isEnemy(information->getSide())) { - if (!root || (information->getObjectTypeFlags() & 0x10u) == 0) + if (!root || !information->isOfType(ITAir)) ++enemyUnits; enemy = static_cast(static_cast(security) * strength + enemy); IPIPhysical* const physical = information->getPhysical(); @@ -1163,7 +1162,7 @@ float AIStrategicArea::gravity(const Vec2& position, int side) // present-set find and the local object list are unused in the image. bool AIStrategicArea::retainBot(int side, int unit, ISAI*) { - m_set92[side - 1].find(unit); + m_presentUnits[side - 1].find(unit); Bot* const bot = IBotManager::instance->getBotFromId(unit); Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); if (!information || !information->getMobile() || !information->getUnit()) @@ -1245,7 +1244,7 @@ void AIStrategicArea::getControlpointPos(AIStrategicObject* object, int side, in const float dz = centre.z - from.z; const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); if (0.8f * radius > distance - && pathfinding->isValidPosition(map, unit, from, m_mapData[map].m_island, true)) + && pathfinding->isValidPosition(map, unit, from, m_orderPos[map].island, true)) { position = from; return; @@ -1266,7 +1265,7 @@ void AIStrategicArea::getControlpointPos(AIStrategicObject* object, int side, in const float dz = centre.z - from.z; const float distance = std::sqrt(dx * dx + dy * dy + dz * dz); if (twice > distance - && pathfinding->isValidPosition(map, unit, from, m_mapData[map].m_island, true)) + && pathfinding->isValidPosition(map, unit, from, m_orderPos[map].island, true)) { position = from; return; @@ -1280,7 +1279,7 @@ void AIStrategicArea::getControlpointPos(AIStrategicObject* object, int side, in object->randomizeControlpointPos(scale, spread, position); for (; tries <= 19; ++tries) { - if (pathfinding->isValidPosition(map, unit, position, m_mapData[map].m_island, true)) + if (pathfinding->isValidPosition(map, unit, position, m_orderPos[map].island, true)) return; position.x = centre.x; position.y = m_f148; @@ -1298,7 +1297,7 @@ void AIStrategicArea::orderBot(int side, const std::list& ob { Bot* const bot = IBotManager::instance->getBotFromId(unit); Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); - if (information->getObjectTypeFlags() & 0x10u) + if (information->isOfType(ITAir)) { orderAirBot(side, objects, unit, sai); return; @@ -1319,7 +1318,7 @@ void AIStrategicArea::orderAirBot(int side, const std::list& Bot* const bot = IBotManager::instance->getBotFromId(unit); Information* const information = informationManager->getInformation(bot->getCurrentEquipment()); const IAITerrain* const terrain = static_cast(CommonSingletonServer::m_iaiTerrain); - const float clearance = (information->getObjectTypeFlags() & 0x20u) ? 4.0f : 40.0f; + const float clearance = information->isOfType(ITHelicopter) ? 4.0f : 40.0f; const std::size_t count = objects.size(); if (count == 0 || count == 1) { @@ -1405,7 +1404,7 @@ void findOrderPosition(const AIStrategicArea* area, AIStrategicObject* object, i object->randomizePos(side, 0.8f, position); for (int tries = 0; tries <= 19; ++tries) { - if (pathfinding->isValidPosition(map, equipment, position, area->m_mapData[map].m_island, true)) + if (pathfinding->isValidPosition(map, equipment, position, area->m_orderPos[map].island, true)) return; object->randomizePos(side, 0.8f, position); } @@ -1496,7 +1495,7 @@ void AIStrategicArea::orderNormalBot(int side, const std::listisValidPosition(map, equipment, information->getPosition(), - m_mapData[map].m_island, true)) + m_orderPos[map].island, true)) { position = information->getPosition(); found = true; @@ -1801,7 +1800,7 @@ bool AIStrategicArea::setOrderPos(int map, const Vec3& position) { if (!m_orderPosesInitialised) { - m_mapData[map].m_offset = position; + m_orderPos[map].m_offset = position; return true; } @@ -1814,14 +1813,14 @@ bool AIStrategicArea::setOrderPos(int map, const Vec3& position) unsigned int polygon; unsigned int island; - IAIPathfinding::instance->getPolygon(m_mapData[map].m_offset, map, polygon, island, 1); + IAIPathfinding::instance->getPolygon(m_orderPos[map].m_offset, map, polygon, island, 1); Vec3 delta; delta.x = position.x - areaPosition.x; delta.y = position.y - areaPosition.y; delta.z = position.z - areaPosition.z; - m_mapData[map].m_offset = delta; - m_mapData[map].m_island = island; + m_orderPos[map].m_offset = delta; + m_orderPos[map].island = island; return true; } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h index e0bfae3b5..0125189ef 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h @@ -37,7 +37,7 @@ class AIStrategicArea : public AIStrategicObject } /* +0 */ Vec3 m_offset; // absolute until `initOrderPoses`, a delta afterwards - /* +12 */ unsigned int m_island; + /* +12 */ unsigned int island; // name: AIDLL_r assert "m_orderPos[vehicle].island" (0x100E45C0; PE +0x120 array, 16-byte entries) }; // [UNRESOLVED] List payloads whose original element types have not been identified. @@ -178,7 +178,7 @@ class AIStrategicArea : public AIStrategicObject // The top-left corner: the bounded constructor and setTopLeftCorner store it; [INFERRED] // name kept from the control-point path, which derives it from the control-point radius. /* +272 */ Vec2 m_centre; // getXExtent/getZExtent subtract it - /* +280 */ MapData* m_mapData; // new MapData[IAIPathfinding::getNumberOfMaps] + /* +280 */ MapData* m_orderPos; // new MapData[IAIPathfinding::getNumberOfMaps] // name: AIDLL_r assert 0x100E45C0 (PE +0x120) // Separate vectors for neighboring areas and other neighboring strategic objects. /* +284 */ std::vector m_neighbours; /* +296 */ std::vector m_neighbouringObjects; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp index a45fc1324..ef09d39fb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.cpp @@ -17,7 +17,7 @@ #include "../Main/IBotManager.h" #include "../AIBot/BotMain.h" // Bot::getCurrentEquipment #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" namespace dice { namespace hfe { @@ -35,14 +35,14 @@ AIStrategicObject::AIStrategicObject(float radius, float f148) m_statistics[3] = new EnemyStatistics(2); const std::set empty; - m_set20[0] = empty; - m_set20[1] = empty; - m_set44[0] = empty; - m_set44[1] = empty; + m_availableAttackers[0] = empty; + m_availableAttackers[1] = empty; + m_availableDefenders[0] = empty; + m_availableDefenders[1] = empty; m_set68[0] = empty; m_set68[1] = empty; - m_set92[0] = empty; - m_set92[1] = empty; + m_presentUnits[0] = empty; + m_presentUnits[1] = empty; m_status[0] = StatusMap::Neutral; m_status[1] = StatusMap::Neutral; @@ -134,26 +134,26 @@ int AIStrategicObject::releaseAssignedResources(int side) std::set& AIStrategicObject::getAvailableBots(bool attackers, int side) { if (attackers) - return m_set20[side - 1]; - return m_set44[side - 1]; + return m_availableAttackers[side - 1]; + return m_availableDefenders[side - 1]; } // ELF 0x3422D0. std::set& AIStrategicObject::getAvailableAttackers(int side) { - return m_set20[side - 1]; + return m_availableAttackers[side - 1]; } // ELF 0x3422F0. std::set& AIStrategicObject::getAvailableDefenders(int side) { - return m_set44[side - 1]; + return m_availableDefenders[side - 1]; } // ELF 0x3426E0. bool AIStrategicObject::unregisterAvailableAttacker(std::set::iterator& it, int side) { - std::set& units = m_set20[side - 1]; + std::set& units = m_availableAttackers[side - 1]; if (it == units.end()) return false; units.erase(it++); @@ -163,7 +163,7 @@ bool AIStrategicObject::unregisterAvailableAttacker(std::set::iterator& it, // ELF 0x342780. bool AIStrategicObject::unregisterAvailableDefender(std::set::iterator& it, int side) { - std::set& units = m_set44[side - 1]; + std::set& units = m_availableDefenders[side - 1]; if (it == units.end()) return false; units.erase(it++); @@ -173,28 +173,28 @@ bool AIStrategicObject::unregisterAvailableDefender(std::set::iterator& it, // ELF 0x341FF0. bool AIStrategicObject::registerAvailableAttacker(int unit, int side) { - m_set20[side - 1].insert(unit); + m_availableAttackers[side - 1].insert(unit); return true; } // ELF 0x342040. bool AIStrategicObject::registerAvailableDefender(int unit, int side) { - m_set44[side - 1].insert(unit); + m_availableDefenders[side - 1].insert(unit); return true; } // ELF 0x342600. bool AIStrategicObject::unregisterAvailableAttacker(int unit, int side) { - std::set::iterator it = m_set20[side - 1].find(unit); + std::set::iterator it = m_availableAttackers[side - 1].find(unit); return unregisterAvailableAttacker(it, side); } // ELF 0x342670. bool AIStrategicObject::unregisterAvailableDefender(int unit, int side) { - std::set::iterator it = m_set44[side - 1].find(unit); + std::set::iterator it = m_availableDefenders[side - 1].find(unit); return unregisterAvailableDefender(it, side); } @@ -207,32 +207,32 @@ std::set& AIStrategicObject::getAssignedUnits(int side) // ELF 0x3423E0. std::set& AIStrategicObject::getPresentUnits(int side) { - return m_set92[side - 1]; + return m_presentUnits[side - 1]; } // ELF 0x342400. bool AIStrategicObject::isPresentUnit(int unit, int side) const { - return m_set92[side - 1].find(unit) != m_set92[side - 1].end(); + return m_presentUnits[side - 1].find(unit) != m_presentUnits[side - 1].end(); } // ELF 0x342460. std::pair::iterator, bool> AIStrategicObject::setAsPresentUnit(int unit, int side) { - return m_set92[side - 1].insert(unit); + return m_presentUnits[side - 1].insert(unit); } // ELF 0x342550. void AIStrategicObject::removeAsPresentUnit(std::set::iterator& it, int side) { - m_set92[side - 1].erase(it++); + m_presentUnits[side - 1].erase(it++); } // ELF 0x3424C0. std::set::iterator AIStrategicObject::removeAsPresentUnit(int unit, int side) { - std::set::iterator it = m_set92[side - 1].find(unit); - if (it != m_set92[side - 1].end()) + std::set::iterator it = m_presentUnits[side - 1].find(unit); + if (it != m_presentUnits[side - 1].end()) removeAsPresentUnit(it, side); return it; } @@ -442,9 +442,9 @@ bool AIStrategicObject::bookBot(bool attacker, int side, std::set::iterator { const int unit = *it; if (attacker) - m_set20[side - 1].find(unit); + m_availableAttackers[side - 1].find(unit); else - m_set44[side - 1].find(unit); + m_availableDefenders[side - 1].find(unit); Bot* const bot = IBotManager::instance->getBotFromId(unit); InformationManager* const manager = informationManager; Information* const information = manager->getInformation(bot->getCurrentEquipment()); @@ -455,26 +455,26 @@ bool AIStrategicObject::bookBot(bool attacker, int side, std::set::iterator int AIStrategicObject::getNumberOfAvailableBots(bool attackers, int side) const { if (attackers) - return static_cast(m_set20[side - 1].size()); - return static_cast(m_set44[side - 1].size()); + return static_cast(m_availableAttackers[side - 1].size()); + return static_cast(m_availableDefenders[side - 1].size()); } // ELF 0x342360. int AIStrategicObject::getNumberOfAvailableAttackers(int side) const { - return static_cast(m_set20[side - 1].size()); + return static_cast(m_availableAttackers[side - 1].size()); } // ELF 0x342380. int AIStrategicObject::getNumberOfAvailableDefenders(int side) const { - return static_cast(m_set44[side - 1].size()); + return static_cast(m_availableDefenders[side - 1].size()); } // ELF 0x3423C0. int AIStrategicObject::getNumberOfPresentUnits(int side) const { - return static_cast(m_set92[side - 1].size()); + return static_cast(m_presentUnits[side - 1].size()); } // ELF 0x3425F0. @@ -486,16 +486,16 @@ EnemyStatistics& AIStrategicObject::getStrategicStatistics(int side) const // ELF 0x342820. int AIStrategicObject::unregisterAllAvailableAttackers(int side) { - const int count = static_cast(m_set20[side - 1].size()); - m_set20[side - 1].clear(); + const int count = static_cast(m_availableAttackers[side - 1].size()); + m_availableAttackers[side - 1].clear(); return count; } // ELF 0x3428B0. int AIStrategicObject::unregisterAllAvailableDefenders(int side) { - const int count = static_cast(m_set44[side - 1].size()); - m_set44[side - 1].clear(); + const int count = static_cast(m_availableDefenders[side - 1].size()); + m_availableDefenders[side - 1].clear(); return count; } diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h index e7dc5992b..34933ebcc 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObject.h @@ -149,7 +149,7 @@ class AIStrategicObject // Borrowed mutable statistics at m_statistics[side - 1]; reference spelling is [INFERRED]. EnemyStatistics& getBattleStatistics(int side) const; int releaseAssignedResources(int side); - // ELF 0x3422A0..0x342300: the per-side available-unit sets (m_set20 attackers, m_set44 + // ELF 0x3422A0..0x342300: the per-side available-unit sets (m_availableAttackers attackers, m_availableDefenders // defenders), one-based side. Reference spelling [INFERRED]. std::set& getAvailableBots(bool attackers, int side); std::set& getAvailableAttackers(int side); @@ -161,7 +161,7 @@ class AIStrategicObject bool registerAvailableDefender(int unit, int side); // ELF 0x342040; always true bool unregisterAvailableAttacker(int unit, int side); // ELF 0x342600 bool unregisterAvailableDefender(int unit, int side); // ELF 0x342670 - // ELF 0x342310 / 0x3423E0..0x342550: assigned (m_set68) and present (m_set92) units. + // ELF 0x342310 / 0x3423E0..0x342550: assigned (m_set68) and present (m_presentUnits) units. std::set& getAssignedUnits(int side); std::set& getPresentUnits(int side); bool isPresentUnit(int unit, int side) const; @@ -193,10 +193,10 @@ class AIStrategicObject /* +4 */ EnemyStatistics* m_statistics[4]; // new EnemyStatistics(6), (6), (2), (2) in order // Per-side strategic-object sets. [UNRESOLVED] Exact roles of these four pairs remain // unidentified; at least two pairs represent neighboring areas and objects. - /* +20 */ std::set m_set20[2]; - /* +44 */ std::set m_set44[2]; + /* +20 */ std::set m_availableAttackers[2]; // name: AIDLL_r assert 0x100E8A80 (PE +0x14) + /* +44 */ std::set m_availableDefenders[2]; // name: AIDLL_r assert 0x100E8A80 (PE +0x2C) /* +68 */ std::set m_set68[2]; // assigned units, one-based side accessor - /* +92 */ std::set m_set92[2]; + /* +92 */ std::set m_presentUnits[2]; // name: AIDLL_r assert 0x100E3E80 (PE +0x5C) // All four set to 2. `StatusMap::Status(2)` is `Neutral`, which is the only reason this member // carries that name - [INFERRED], on the strength of one coincidence. diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp index 7180e795e..00312a001 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp @@ -11,7 +11,7 @@ #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../AIBot/SquadManager.h" // haveHumanPlayerOnOwnSide -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../../../../Math/Mat4.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" @@ -86,8 +86,8 @@ AIStrategicObject* AIStrategicObjectManager::getClosestObject(const Vec3& positi // ELF 0x346D40: the active-area cursor is the lookup result, end() when not found. bool AIStrategicObjectManager::setActive(std::string name) { - m_activeArea = m_strategicAreas.find(name); - return m_activeArea != m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.find(name); + return m_activeArea != m_strategicAreaMap.end(); } // "Closest" is the greatest virtual gravity @@ -162,7 +162,7 @@ const std::vector& AIStrategicObjectManager::WPContainer::getWayPoi const std::vector& AIStrategicObjectManager::getWaypoints(int type, int a, int b) const { const std::pair key(a < b ? a : b, a > b ? a : b); - return m_wayPoints.find(key)->second.getWayPoints(type); + return m_waypointMap.find(key)->second.getWayPoints(type); } // ELF 0x348EB0: by the two areas' indices (+0xF0). @@ -181,14 +181,14 @@ AIStrategicObjectManager::AIStrategicObjectManager() , m_wayPointsToDrawSecond(-1) { m_strategicObjects.resize(0); - m_objectsByCategory.resize(0); + m_objectsPerCategory.resize(0); if (!m_instance) m_instance = this; - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); - m_categoryNames.resize(0); + m_categoryToNames.resize(0); } // Deletes owned areas, waypoints and bridges, and clears the singleton if it refers to this object. @@ -198,17 +198,17 @@ AIStrategicObjectManager::~AIStrategicObjectManager() if (m_instance == this) m_instance = 0; - for (std::map::iterator area = m_strategicAreas.begin(); - area != m_strategicAreas.end(); ) + for (std::map::iterator area = m_strategicAreaMap.begin(); + area != m_strategicAreaMap.end(); ) { if (area->second) delete area->second; - m_strategicAreas.erase(area++); + m_strategicAreaMap.erase(area++); } - for (std::map, WPContainer>::iterator entry = m_wayPoints.begin(); - entry != m_wayPoints.end(); ++entry) + for (std::map, WPContainer>::iterator entry = m_waypointMap.begin(); + entry != m_waypointMap.end(); ++entry) { std::vector& first = entry->second.getWayPoints(0); @@ -240,8 +240,8 @@ void AIStrategicObjectManager::postLoadInitAreas() { WPContainer prototype; - for (std::map::iterator entry = m_strategicAreas.begin(); - entry != m_strategicAreas.end(); ++entry) + for (std::map::iterator entry = m_strategicAreaMap.begin(); + entry != m_strategicAreaMap.end(); ++entry) { AIStrategicArea* const area = entry->second; @@ -256,14 +256,14 @@ void AIStrategicObjectManager::postLoadInitAreas() const int low = (mine < other) ? mine : other; const int high = (mine >= other) ? mine : other; - m_wayPoints.insert( + m_waypointMap.insert( std::pair, WPContainer>(std::pair(low, high), prototype)); } } - for (std::map, WPContainer>::iterator entry = m_wayPoints.begin(); - entry != m_wayPoints.end(); ++entry) + for (std::map, WPContainer>::iterator entry = m_waypointMap.begin(); + entry != m_waypointMap.end(); ++entry) { std::vector& first = entry->second.getWayPoints(0); @@ -308,7 +308,7 @@ void AIStrategicObjectManager::createBridgeSegment(IAIObject* object) { BridgeSegment* const segment = new BridgeSegment; // zeroes the position only - +4 stays unset segment->m_object = object; - segment->m_destroyed = false; + segment->isDestroyed = false; // The position is zeroed again, as its own statement: the PE stores it a second time outside // the new-expression's null-checked constructor block, the ELF copies a zeroed 12-byte temporary. const Vec3 origin = { 0.0f, 0.0f, 0.0f }; @@ -340,7 +340,7 @@ void AIStrategicObjectManager::bridgeSegmentDestroyed(IAIObject* object, int val { if ((*i)->m_object == object) { - (*i)->m_destroyed = true; + (*i)->isDestroyed = true; (*i)->m_i4 = value; return; } @@ -366,7 +366,7 @@ IAIObject* AIStrategicObjectManager::getClosestDestroyedBridgeSegment(Vec3 from, { BridgeSegment* const segment = *i; segmentPosition = informationManager->getInformation(segment->m_object->getInformation(1))->getPosition(); - if (!segment->m_destroyed) + if (!segment->isDestroyed) continue; bool ownHuman = false; IAIPlayer* const destroyer = players->getPlayerFromId(segment->m_i4); // +0x20 @@ -405,7 +405,7 @@ void AIStrategicObjectManager::bridgeSegmentRepaired(IAIObject* object) { if ((*i)->m_object == object) { - (*i)->m_destroyed = false; + (*i)->isDestroyed = false; return; } } @@ -419,21 +419,21 @@ void AIStrategicObjectManager::bridgeSegmentRepaired(IAIObject* object) bool AIStrategicObjectManager::reset() { m_debugEnabled = false; - for (std::map::iterator area = m_strategicAreas.begin(); - area != m_strategicAreas.end();) + for (std::map::iterator area = m_strategicAreaMap.begin(); + area != m_strategicAreaMap.end();) { if (area->second) delete area->second; - m_strategicAreas.erase(area++); + m_strategicAreaMap.erase(area++); } if (!m_areaNames.empty()) m_areaNames.clear(); - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); m_strategicObjects.resize(0, 0); - m_objectsByCategory.resize(0, std::vector()); - m_categoryNames.resize(0, std::string()); - for (std::map::iterator category = m_categories.begin(); category != m_categories.end();) - m_categories.erase(category++); + m_objectsPerCategory.resize(0, std::vector()); + m_categoryToNames.resize(0, std::string()); + for (std::map::iterator category = m_namesToCategory.begin(); category != m_namesToCategory.end();) + m_namesToCategory.erase(category++); return true; } @@ -441,8 +441,8 @@ bool AIStrategicObjectManager::reset() bool AIStrategicObjectManager::resetAreas() { m_debugEnabled = false; - for (std::map::iterator it = m_strategicAreas.begin(); - it != m_strategicAreas.end(); ++it) + for (std::map::iterator it = m_strategicAreaMap.begin(); + it != m_strategicAreaMap.end(); ++it) it->second->resetStatus(); return true; } @@ -458,7 +458,7 @@ void AIStrategicObjectManager::resetBridges() for (std::list::iterator it = m_bridgeSegments.begin(); it != m_bridgeSegments.end(); ++it) { BridgeSegment* const segment = *it; - segment->m_destroyed = false; + segment->isDestroyed = false; Information* const information = informationManager->getInformation(segment->m_object->getHandle(1)); const Vec3 position = information->getPosition(); @@ -535,27 +535,27 @@ int AIStrategicObjectManager::getNumberOfStrategicObjects() const const std::vector& AIStrategicObjectManager::getStrategicObjectsOfCategory(int category) const { - return m_objectsByCategory[category]; + return m_objectsPerCategory[category]; } // - same shape, four bytes per `std::string`, again unchecked. // ELF 0x347910. const std::string& AIStrategicObjectManager::getCategoryName(int category) const { - return m_categoryNames[category]; + return m_categoryToNames[category]; } // ELF 0x345610. int AIStrategicObjectManager::getNumberOfCategories() { - return (int)m_categoryNames.size(); + return (int)m_categoryToNames.size(); } // - `return (char *)this + 32;` // ELF 0x3476A0. const std::map& AIStrategicObjectManager::getStrategicAreas() const { - return m_strategicAreas; + return m_strategicAreaMap; } // Returns null while no area is active - `m_activeArea` starts at `end` and @@ -563,7 +563,7 @@ const std::map& AIStrategicObjectManager::getStra // ELF 0x345630. AIStrategicArea* AIStrategicObjectManager::getActiveArea() { - if (m_activeArea != m_strategicAreas.end()) + if (m_activeArea != m_strategicAreaMap.end()) return m_activeArea->second; return 0; @@ -585,8 +585,8 @@ AIStrategicObject* AIStrategicObjectManager::getStrategicObject(int index) const // ELF 0x344940 (added by air/s2 for GuardPosition::update): the named area, null when unknown. AIStrategicObject* AIStrategicObjectManager::getStrategicObject(const std::string& name) const { - const std::map::const_iterator it = m_strategicAreas.find(name); - if (it != m_strategicAreas.end()) + const std::map::const_iterator it = m_strategicAreaMap.find(name); + if (it != m_strategicAreaMap.end()) return it->second; return 0; } @@ -612,8 +612,8 @@ void AIStrategicObjectManager::clearWaypointToDraw() // ELF 0x349040: every waypoint container (+0x58), type 0 then type 1, undraws each waypoint. void AIStrategicObjectManager::undrawWayPoints() const { - for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); - it != m_wayPoints.end(); ++it) + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) { for (int type = 0; type < 2; ++type) { @@ -629,7 +629,7 @@ void AIStrategicObjectManager::undrawWayPoints() const // ELF 0x347930. int AIStrategicObjectManager::getCategoryFromName(const std::string& name) const { - return m_categories.find(name)->second; + return m_namesToCategory.find(name)->second; } // Adds an object to the category table and assigns its index. The object and category must be valid. @@ -643,14 +643,14 @@ void AIStrategicObjectManager::addStrategicObject(AIStrategicObject* object) m_strategicObjects[index] = object; object->m_index = index; - for (int category = 0; category < (int)m_objectsByCategory.size(); ++category) + for (int category = 0; category < (int)m_objectsPerCategory.size(); ++category) { - m_objectsByCategory[category].resize(index + 1); + m_objectsPerCategory[category].resize(index + 1); if (category == object->m_category) - m_objectsByCategory[category][index] = object; + m_objectsPerCategory[category][index] = object; else - m_objectsByCategory[category][index] = 0; + m_objectsPerCategory[category][index] = 0; } if (AIRenderUtil::m_instance) @@ -661,8 +661,8 @@ void AIStrategicObjectManager::addStrategicObject(AIStrategicObject* object) // ELF 0x345590. void AIStrategicObjectManager::initAreas() { - for (std::map::iterator i = m_strategicAreas.begin(); - i != m_strategicAreas.end(); ++i) + for (std::map::iterator i = m_strategicAreaMap.begin(); + i != m_strategicAreaMap.end(); ++i) { if (!i->second->m_fromControlPoint) i->second->init(); @@ -677,16 +677,16 @@ bool AIStrategicObjectManager::createFromControlPoint(const std::string& name, float radius, const std::string& category) { - if (m_strategicAreas.find(name) != m_strategicAreas.end()) + if (m_strategicAreaMap.find(name) != m_strategicAreaMap.end()) { - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); return false; } AIStrategicArea* const area = checkPointer(new AIStrategicArea(name, controlPointId, radius)); if (!area) { - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); return false; } @@ -697,9 +697,9 @@ bool AIStrategicObjectManager::createFromControlPoint(const std::string& name, AIStrategicObjectManager::getInstance()->addStrategicObject(area); - m_strategicAreas[name] = area; + m_strategicAreaMap[name] = area; m_areaNames[area] = name; - m_activeArea = m_strategicAreas.find(name); + m_activeArea = m_strategicAreaMap.find(name); return true; } @@ -708,7 +708,7 @@ AIStrategicObject* AIStrategicObjectManager::getStrategicObjectOfCategory(int in { if (index < 0 || index >= static_cast(m_strategicObjects.size())) return 0; - return m_objectsByCategory[category][index]; + return m_objectsPerCategory[category][index]; } // ELF 0x344A40: as getStrategicObjectOfCategory, but only an area (getType() == 0). @@ -716,9 +716,9 @@ AIStrategicArea* AIStrategicObjectManager::getStrategicAreaOfCategory(int index, { if (index < 0 || index >= static_cast(m_strategicObjects.size())) return 0; - if (!m_objectsByCategory[category][index] || m_objectsByCategory[category][index]->getType() != 0) + if (!m_objectsPerCategory[category][index] || m_objectsPerCategory[category][index]->getType() != 0) return 0; - return static_cast(m_objectsByCategory[category][index]); + return static_cast(m_objectsPerCategory[category][index]); } // ELF 0x344D00: clears the object's category slot (when its category is in range) and erases the @@ -730,8 +730,8 @@ AIStrategicObject* AIStrategicObjectManager::removeStrategicObject(int index) AIStrategicObject* const object = m_strategicObjects[index]; const int category = object->m_category; - if (category >= 0 && category < static_cast(m_objectsByCategory.size())) - m_objectsByCategory[category][index] = 0; + if (category >= 0 && category < static_cast(m_objectsPerCategory.size())) + m_objectsPerCategory[category][index] = 0; for (std::vector::iterator it = m_strategicObjects.begin(); it != m_strategicObjects.end(); ++it) @@ -755,10 +755,10 @@ AIStrategicObject* AIStrategicObjectManager::getClosestObjectinCategory(const Ve float bestGravity = 0.0f; const int group = static_cast(CommonSingletonServer::m_iaiSettings)->getVehicleGroup(equipment); - if (category < 0 || category >= static_cast(m_objectsByCategory.size())) + if (category < 0 || category >= static_cast(m_objectsPerCategory.size())) return best; - const std::vector& objects = m_objectsByCategory[category]; + const std::vector& objects = m_objectsPerCategory[category]; for (std::vector::const_iterator it = objects.begin(); it != objects.end(); ++it) { if (!(*it)->isAllowedVehicleGroup(group) || (*it)->isExpelledUnit(equipment)) @@ -786,9 +786,9 @@ void AIStrategicObjectManager::setFlankPosition(Vec3 first, Vec3 second) bool AIStrategicObjectManager::create(std::string name, Vec2 topLeft, Vec2 centre, float height, float radius, const std::string& category) { - if (m_strategicAreas.find(name) != m_strategicAreas.end()) + if (m_strategicAreaMap.find(name) != m_strategicAreaMap.end()) { - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); return false; } @@ -796,7 +796,7 @@ bool AIStrategicObjectManager::create(std::string name, Vec2 topLeft, Vec2 centr checkPointer(new AIStrategicArea(name, topLeft, centre, height, radius)); if (!area) { - m_activeArea = m_strategicAreas.end(); + m_activeArea = m_strategicAreaMap.end(); return false; } @@ -807,9 +807,9 @@ bool AIStrategicObjectManager::create(std::string name, Vec2 topLeft, Vec2 centr AIStrategicObjectManager::getInstance()->addStrategicObject(area); - m_strategicAreas[name] = area; + m_strategicAreaMap[name] = area; m_areaNames[area] = name; - m_activeArea = m_strategicAreas.find(name); + m_activeArea = m_strategicAreaMap.find(name); return true; } @@ -817,7 +817,7 @@ bool AIStrategicObjectManager::create(std::string name, Vec2 topLeft, Vec2 centr // rendering and its object slot, then deletes it. AIRenderUtil::m_instance is not null-checked. bool AIStrategicObjectManager::removeActive() { - if (m_activeArea == m_strategicAreas.end()) + if (m_activeArea == m_strategicAreaMap.end()) return false; AIStrategicArea* area = m_activeArea->second; if (!area) @@ -830,8 +830,8 @@ bool AIStrategicObjectManager::removeActive() std::map::iterator name = m_areaNames.find(area); if (name != m_areaNames.end()) m_areaNames.erase(name); - m_strategicAreas.erase(m_activeArea); - m_activeArea = m_strategicAreas.end(); + m_strategicAreaMap.erase(m_activeArea); + m_activeArea = m_strategicAreaMap.end(); AIRenderUtil::m_instance->unrenderStrategicArea(area); AIRenderUtil::m_instance->updateNumberOfStrategicAreas(); @@ -844,8 +844,8 @@ bool AIStrategicObjectManager::removeActive() // area gains the active one as a neighbouring object. bool AIStrategicObjectManager::addNeighbour(std::string name) { - std::map::iterator it = m_strategicAreas.find(name); - if (it == m_strategicAreas.end()) + std::map::iterator it = m_strategicAreaMap.find(name); + if (it == m_strategicAreaMap.end()) return false; if (m_activeArea->second->m_i400 != it->second->m_i400) return false; @@ -857,11 +857,11 @@ bool AIStrategicObjectManager::addNeighbour(std::string name) // ELF 0x346460: both directions, in the image's call order. bool AIStrategicObjectManager::addTwoWayNeighbour(std::string first, std::string second) { - std::map::iterator a = m_strategicAreas.find(first); - if (a == m_strategicAreas.end()) + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) return false; - std::map::iterator b = m_strategicAreas.find(second); - if (b == m_strategicAreas.end()) + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) return false; if (a->second->m_i400 != b->second->m_i400) return false; @@ -875,7 +875,7 @@ bool AIStrategicObjectManager::addTwoWayNeighbour(std::string first, std::string // ELF 0x346590. void AIStrategicObjectManager::removeAllNeighbours() { - if (m_activeArea != m_strategicAreas.end()) + if (m_activeArea != m_strategicAreaMap.end()) m_activeArea->second->removeAllNeighbours(); } @@ -883,7 +883,7 @@ void AIStrategicObjectManager::removeAllNeighbours() // active area). The neighbour list is copied first; the name lookups are unchecked. std::string AIStrategicObjectManager::getNeighbours() { - if (m_activeArea == m_strategicAreas.end()) + if (m_activeArea == m_strategicAreaMap.end()) return ""; const std::vector neighbours = m_activeArea->second->m_neighbours; @@ -900,7 +900,7 @@ std::string AIStrategicObjectManager::getNeighbours() // ELF 0x3467B0. int AIStrategicObjectManager::addObjectTypeFlag(AIStrategicObject::StrategicObjectType type) { - if (m_activeArea == m_strategicAreas.end() || type == 27) + if (m_activeArea == m_strategicAreaMap.end() || type == 27) return -1; return m_activeArea->second->addObjectTypeFlag(type); } @@ -908,7 +908,7 @@ int AIStrategicObjectManager::addObjectTypeFlag(AIStrategicObject::StrategicObje // ELF 0x346800. Shipped defect, preserved: the bit is toggled (xor), not cleared. int AIStrategicObjectManager::removeObjectTypeFlag(AIStrategicObject::StrategicObjectType type) { - if (m_activeArea == m_strategicAreas.end() || type == 27) + if (m_activeArea == m_strategicAreaMap.end() || type == 27) return -1; return m_activeArea->second->m_objectTypeFlags ^= 1 << type; } @@ -916,7 +916,7 @@ int AIStrategicObjectManager::removeObjectTypeFlag(AIStrategicObject::StrategicO // ELF 0x346850. int AIStrategicObjectManager::setObjectTypeFlags(int flags) { - if (m_activeArea == m_strategicAreas.end()) + if (m_activeArea == m_strategicAreaMap.end()) return -1; return m_activeArea->second->setObjectTypeFlags(flags); } @@ -924,7 +924,7 @@ int AIStrategicObjectManager::setObjectTypeFlags(int flags) // ELF 0x3468A0: through the virtual getter (slot 18). int AIStrategicObjectManager::getObjectTypeFlags() { - if (m_activeArea == m_strategicAreas.end()) + if (m_activeArea == m_strategicAreaMap.end()) return -1; return m_activeArea->second->getObjectTypeFlags(); } @@ -932,7 +932,7 @@ int AIStrategicObjectManager::getObjectTypeFlags() // ELF 0x3468D0. void AIStrategicObjectManager::removeAllObjectTypeFlags() { - if (m_activeArea != m_strategicAreas.end()) + if (m_activeArea != m_strategicAreaMap.end()) m_activeArea->second->m_objectTypeFlags = 0; } @@ -948,7 +948,7 @@ std::string AIStrategicObjectManager::getObjectTypeFlagMapping() const // ELF 0x346DB0: the active area's name, "" without one. std::string AIStrategicObjectManager::getActive() const { - if (m_activeArea == m_strategicAreas.end()) + if (m_activeArea == m_strategicAreaMap.end()) return ""; return m_activeArea->first; } @@ -957,8 +957,8 @@ std::string AIStrategicObjectManager::getActive() const std::string AIStrategicObjectManager::list() const { std::stringstream stream; - for (std::map::const_iterator it = m_strategicAreas.begin(); - it != m_strategicAreas.end(); ++it) + for (std::map::const_iterator it = m_strategicAreaMap.begin(); + it != m_strategicAreaMap.end(); ++it) { const std::string name = it->first; stream << name << std::endl; @@ -969,7 +969,7 @@ std::string AIStrategicObjectManager::list() const // ELF 0x3471A0: false without an active area or pathfinding, or for an unknown map name. bool AIStrategicObjectManager::setOrderPosition(std::string map, const Vec3& position) { - if (m_activeArea == m_strategicAreas.end() || !IAIPathfinding::instance) + if (m_activeArea == m_strategicAreaMap.end() || !IAIPathfinding::instance) return false; const int id = IAIPathfinding::instance->getMapIdFromName(map); if (id == -1) @@ -984,7 +984,7 @@ Vec3 AIStrategicObjectManager::getOrderPosition(std::string map) position.x = 0.0f; position.y = 0.0f; position.z = 0.0f; - if (m_activeArea == m_strategicAreas.end() || !IAIPathfinding::instance) + if (m_activeArea == m_strategicAreaMap.end() || !IAIPathfinding::instance) return position; const int id = IAIPathfinding::instance->getMapIdFromName(map); if (id == -1) @@ -996,7 +996,7 @@ Vec3 AIStrategicObjectManager::getOrderPosition(std::string map) // active area or pathfinding. The image inlines the x/y/z stream operator. std::string AIStrategicObjectManager::listOrderPositions() { - if (m_activeArea == m_strategicAreas.end() || !IAIPathfinding::instance) + if (m_activeArea == m_strategicAreaMap.end() || !IAIPathfinding::instance) return ""; std::ostringstream stream; @@ -1015,8 +1015,8 @@ std::string AIStrategicObjectManager::listOrderPositions() std::string AIStrategicObjectManager::getStrategicAreaNames() { std::string names; - for (std::map::const_iterator it = m_strategicAreas.begin(); - it != m_strategicAreas.end(); ++it) + for (std::map::const_iterator it = m_strategicAreaMap.begin(); + it != m_strategicAreaMap.end(); ++it) names = names.empty() ? it->first : names + "\n" + it->first; return names; } @@ -1030,19 +1030,19 @@ Vec2 AIStrategicObjectManager::getPosition() const // ELF 0x347980: a new last category, its name index and an object row as long as the object list. void AIStrategicObjectManager::createNewCategory(const std::string& name) { - const int index = static_cast(m_categoryNames.size()); - m_categoryNames.resize(index + 1); - m_categoryNames[index] = name; - m_categories.insert(std::make_pair(name, index)); - m_objectsByCategory.resize(index + 1); - m_objectsByCategory[index].resize(m_strategicObjects.size()); + const int index = static_cast(m_categoryToNames.size()); + m_categoryToNames.resize(index + 1); + m_categoryToNames[index] = name; + m_namesToCategory.insert(std::make_pair(name, index)); + m_objectsPerCategory.resize(index + 1); + m_objectsPerCategory[index].resize(m_strategicObjects.size()); } // ELF 0x347C80: false for an unknown area name. bool AIStrategicObjectManager::isInside(const std::string& name, const Vec2& position) { - std::map::iterator it = m_strategicAreas.find(name); - if (it == m_strategicAreas.end()) + std::map::iterator it = m_strategicAreaMap.find(name); + if (it == m_strategicAreaMap.end()) return false; return it->second->isInside(position); } @@ -1052,15 +1052,15 @@ bool AIStrategicObjectManager::isInside(const std::string& name, const Vec2& pos void AIStrategicObjectManager::addWayPoint(const Vec3& position, const std::string& map, const std::string& first, const std::string& second) { - std::map::iterator a = m_strategicAreas.find(first); - if (a == m_strategicAreas.end()) + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1144, "") << first << " is not the name of a valid strategic area."; return; } - std::map::iterator b = m_strategicAreas.find(second); - if (b == m_strategicAreas.end()) + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1151, "") << second << " is not the name of a valid strategic area."; @@ -1083,7 +1083,7 @@ void AIStrategicObjectManager::addWayPoint(const Vec3& position, const std::stri WPContainer container; std::map, WPContainer>::iterator it = - m_wayPoints.insert(std::make_pair(std::make_pair(low->m_index, high->m_index), container)).first; + m_waypointMap.insert(std::make_pair(std::make_pair(low->m_index, high->m_index), container)).first; const int id = IAIPathfinding::instance->getMapIdFromName(map); std::vector& points = it->second.getWayPoints(id); points.push_back(checkPointer(new SAWayPoint(position, id))); @@ -1095,15 +1095,15 @@ void AIStrategicObjectManager::addWayPoint(const Vec3& position, const std::stri bool AIStrategicObjectManager::removeWayPoint(const Vec3& position, const std::string& map, const std::string& first, const std::string& second) { - std::map::iterator a = m_strategicAreas.find(first); - if (a == m_strategicAreas.end()) + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1191, "") << first << " is not the name of a valid strategic area."; return false; } - std::map::iterator b = m_strategicAreas.find(second); - if (b == m_strategicAreas.end()) + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1198, "") << second << " is not the name of a valid strategic area."; @@ -1119,7 +1119,7 @@ bool AIStrategicObjectManager::removeWayPoint(const Vec3& position, const std::s } const std::pair key(low->m_index, high->m_index); - std::map, WPContainer>::iterator it = m_wayPoints.find(key); + std::map, WPContainer>::iterator it = m_waypointMap.find(key); const int id = IAIPathfinding::instance->getMapIdFromName(map); std::vector& points = it->second.getWayPoints(id); @@ -1151,15 +1151,15 @@ bool AIStrategicObjectManager::removeWayPoint(const Vec3& position, const std::s void AIStrategicObjectManager::clearWayPoints(const std::string& map, const std::string& first, const std::string& second) { - std::map::iterator a = m_strategicAreas.find(first); - if (a == m_strategicAreas.end()) + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1253, "") << first << " is not the name of a valid strategic area."; return; } - std::map::iterator b = m_strategicAreas.find(second); - if (b == m_strategicAreas.end()) + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1260, "") << second << " is not the name of a valid strategic area."; @@ -1175,7 +1175,7 @@ void AIStrategicObjectManager::clearWayPoints(const std::string& map, const std: } const std::pair key(low->m_index, high->m_index); - std::map, WPContainer>::iterator it = m_wayPoints.find(key); + std::map, WPContainer>::iterator it = m_waypointMap.find(key); const int id = IAIPathfinding::instance->getMapIdFromName(map); std::vector& points = it->second.getWayPoints(id); for (std::vector::iterator wp = points.begin(); wp != points.end(); ++wp) @@ -1190,7 +1190,7 @@ void AIStrategicObjectManager::drawWayPoints() const if (m_wayPointsToDrawFirst != -1 && m_wayPointsToDrawSecond != -1) { const std::pair key(m_wayPointsToDrawFirst, m_wayPointsToDrawSecond); - const WPContainer& container = m_wayPoints.find(key)->second; + const WPContainer& container = m_waypointMap.find(key)->second; const std::vector& infantry = container.getWayPoints(0); for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) (*wp)->draw(); @@ -1200,8 +1200,8 @@ void AIStrategicObjectManager::drawWayPoints() const return; } - for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); - it != m_wayPoints.end(); ++it) + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) { const std::vector& infantry = it->second.getWayPoints(0); for (std::vector::const_iterator wp = infantry.begin(); wp != infantry.end(); ++wp) @@ -1215,15 +1215,15 @@ void AIStrategicObjectManager::drawWayPoints() const // ELF 0x349100: selects the pair (lower, higher index) whose waypoints drawWayPoints shows. void AIStrategicObjectManager::setWayPointsToDraw(const std::string& first, const std::string& second) { - std::map::iterator a = m_strategicAreas.find(first); - if (a == m_strategicAreas.end()) + std::map::iterator a = m_strategicAreaMap.find(first); + if (a == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1371, "") << first << " is not the name of a valid strategic area."; return; } - std::map::iterator b = m_strategicAreas.find(second); - if (b == m_strategicAreas.end()) + std::map::iterator b = m_strategicAreaMap.find(second); + if (b == m_strategicAreaMap.end()) { Debug(DebugTypeError, "AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.cpp", 1378, "") << second << " is not the name of a valid strategic area."; @@ -1265,8 +1265,8 @@ bool checkLayerStrList(const std::string& list, int layer) void AIStrategicObjectManager::streamWaypoints(std::ostringstream& out, const std::string& excludedLayers) const { - for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); - it != m_wayPoints.end(); ++it) + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) { AIStrategicArea* const first = getStrategicArea(it->first.first); if (!excludedLayers.empty() && checkLayerStrList(excludedLayers, first->m_i400)) @@ -1310,8 +1310,8 @@ void AIStrategicObjectManager::checkAllOrderPositions() const // loops; whatever they checked is compiled out). void AIStrategicObjectManager::checkAllWayPoints() const { - for (std::map, WPContainer>::const_iterator it = m_wayPoints.begin(); - it != m_wayPoints.end(); ++it) + for (std::map, WPContainer>::const_iterator it = m_waypointMap.begin(); + it != m_waypointMap.end(); ++it) { for (int type = 0; type < 2; ++type) { diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h index faa61eefa..437cd839c 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicObjectManager.h @@ -55,7 +55,7 @@ class AIStrategicObjectManager m_position.z = 0.0f; } - /* +0 */ bool m_destroyed; // 0 at creation; `bridgeSegmentDestroyed` sets it to 1 + /* +0 */ bool isDestroyed; // 0 at creation; `bridgeSegmentDestroyed` sets it to 1 // name: AIDLL_r assert "bridge->isDestroyed" (0x10086E40; +0) /* +4 */ int m_i4; // [UNRESOLVED] - written only by `bridgeSegmentDestroyed` /* +8 */ IAIObject* m_object; // the search key for all three of the methods above /* +12 */ Vec3 m_position; // [INFERRED] - three zeroed floats, never read here @@ -175,27 +175,27 @@ class AIStrategicObjectManager // MSVC's `sizeof` will differ - libstdc++ 3.x puts a `_Rb_tree` in twelve bytes (a header-node // pointer, a node count and four bytes of empty comparator) and a `std::list` in four. /* +4 */ std::vector m_strategicObjects; - /* +16 */ std::vector > m_objectsByCategory; + /* +16 */ std::vector > m_objectsPerCategory; // name: AIDLL_r assert 0x10086290 (PE +0x14) public: // [CHOSEN, not recovered] Visibility for the generated inline debug control. /* +28 */ bool m_debugEnabled; // false; console enableDebug private: - /* +32 */ std::map m_strategicAreas; + /* +32 */ std::map m_strategicAreaMap; // name: AIDLL_r assert 0x1008B6F0 (PE +0x28) // The reverse index. Its value type is `std::string` - read straight off the destructor's // `_Rb_tree, ...>` teardown. /* +44 */ std::map m_areaNames; - // An iterator, not a pointer - one word in this libstdc++, initialised to `m_strategicAreas.end` + // An iterator, not a pointer - one word in this libstdc++, initialised to `m_strategicAreaMap.end` // by the constructor and compared against `end` by every reader (`getActiveArea` // `getObjectTypeFlags`, `setOrderPosition`, `getPosition`). /* +56 */ std::map::iterator m_activeArea; - /* +60 */ std::map m_categories; - /* +72 */ std::vector m_categoryNames; + /* +60 */ std::map m_namesToCategory; // name: AIDLL_r assert 0x100892D0 (PE +0x44) + /* +72 */ std::vector m_categoryToNames; // name: AIDLL_r assert 0x100867B0 (PE +0x50) public: // [CHOSEN, not recovered] Visibility for the generated inline drawing control. /* +84 */ bool m_drawVehicleSearchRadii; // false; console drawVehicleSearchRadi private: - /* +88 */ std::map, WPContainer> m_wayPoints; - // The two halves of a `m_wayPoints` key, both -1 for "nothing selected". + /* +88 */ std::map, WPContainer> m_waypointMap; // name: AIDLL_r assert 0x10089680 (PE +0x64) + // The two halves of a `m_waypointMap` key, both -1 for "nothing selected". // `clearWaypointToDraw` resets only the first of the two; `drawWayPoints` tests both. /* +100 */ int m_wayPointsToDrawFirst; /* +104 */ int m_wayPointsToDrawSecond; diff --git a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.cpp similarity index 95% rename from Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp rename to Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.cpp index 5983eecc9..862acad81 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.cpp @@ -1,11 +1,12 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIStrategicEntity\UserOrders\UserOrderManager.cpp" (asserts in 0x1007C7E0 / 0x1007C920). // static init: ELF 0x3521D0 (__tcf_0 0x352230, _GLOBAL__I 0x352260): 's Init object only. #include #include "UserOrderManager.h" -#include "../AIUtils/checkPointer.h" -#include "../AIStrategicEntity/GuardPosition.h" -#include "../AIStrategicEntity/PatrolPath.h" +#include "../../AIUtils/checkPointer.h" +#include "../GuardPosition.h" +#include "../PatrolPath.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.h similarity index 93% rename from Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h rename to Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.h index 33d9c3694..f6789ca7f 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/UserOrderManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.h @@ -1,5 +1,5 @@ // Owns patrol paths and guard positions and assigns bots to user orders. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIStrategicEntity/UserOrders/UserOrderManager.cpp: asserts in 0x1007C7E0 / 0x1007C920). #ifndef AI_AIDLL_AI_MAIN_USERORDERMANAGER_H #define AI_AIDLL_AI_MAIN_USERORDERMANAGER_H @@ -7,7 +7,7 @@ #include #include -#include "AIDllTypes.h" +#include "../../Main/AIDllTypes.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp index effdebf8f..579e6fe4a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.cpp @@ -18,7 +18,7 @@ #include "../AIKnowledge/AIInformationGrid.h" #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIUtils/VehicleOccupancy.h" @@ -52,8 +52,7 @@ class FreeUnitPred : public IAIInformationGridPredicate { if (!information->getUnit() || !information->hasMobile()) return false; - const unsigned int flags = information->getObjectTypeFlags(); - if ((flags & 0x80u) || (flags & 0x200000u)) + if (information->isOfType(ITNaval) || information->isOfType(ITSoldier)) return false; bool anyFree = false; diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp index 86202a165..bb4a0350f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIStrategicMap/SAIMap.cpp @@ -15,7 +15,7 @@ #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIStrategic/SAI.h" #include "../AIStrategic/StatusMap.h" #include "../AIUtils/checkPointer.h" @@ -187,7 +187,7 @@ bool SAIMap::update(SAI* sai, double budget) return false; } Information* information = informationManager->getInformation(m_updateState->m_ids[index]); - if (!information || (information->getObjectTypeFlags() & 0x800000)) + if (!information || information->isOfType(ITNoTemperature)) continue; if (information->getSecurity() == 0.0f) continue; @@ -197,7 +197,7 @@ bool SAIMap::update(SAI* sai, double budget) secondary; secondary = informationManager->getInformation(information->getSecondaryObject(it, m_side))) { - if (!(secondary->getObjectTypeFlags() & 0x800000) && secondary->getSecurity() > 0.0f) + if (!secondary->isOfType(ITNoTemperature) && secondary->getSecurity() > 0.0f) updateInformation(secondary, sai, buffer); } } diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp index bd9ce8ba3..c12c66fda 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/AimerHelper.cpp @@ -6,7 +6,7 @@ #include "AimerHelper.h" #include "checkPointer.h" -#include "../AIBot/Aimer.h" +#include "../AIBotActionPlan/Aimer.h" #include "../Main/CommonSingletonServer.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.cpp similarity index 76% rename from Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp rename to Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.cpp index ad4c4c13f..40bbf04e0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.cpp @@ -1,10 +1,10 @@ -// [INFERRED] Source placement. +// Source placement: retail libaidll.so 1.50 embeds "AI/AIDLL/AI/AIUtils/CustomCurve.cpp" (CustomCurve's asserts). #include "CustomCurve.h" #include // CustomCurve: the image asserts -#include // isfinite - SCurve's guard only +#include #include // static init: ELF 0x36E0E0, 0x36E140, 0x36E170: CustomCurve.cpp's iostream Init only. @@ -12,23 +12,12 @@ namespace dice { namespace hfe { namespace ai { -float* SCurve::curveValues = 0; +// SCurve lives in SCurve.cpp (AIDLL_r __FILE__). float* JCurve::curveValues = 0; float* DecleiningSlopeCurve::curveValues = 0; // Builds the shared table on construction and frees it on destruction. // Destruction retains the null guard and does not clear the shared pointer. -SCurve::SCurve() -{ - init(); -} - -SCurve::~SCurve() -{ - if (curveValues) - delete[] curveValues; -} - JCurve::JCurve() { init(); @@ -51,24 +40,6 @@ DecleiningSlopeCurve::~DecleiningSlopeCurve() delete[] curveValues; } -// Returns zero for non-finite input and clamps x >= 1 to one before interpolation. -// [PLATFORM] Uses the standard isfinite name for the original finite predicate. -float SCurve::calculate(float x) -{ - if (!std::isfinite(x)) - return 0.0f; - if (x >= 1.0f) - return 1.0f; - if (x < 0.0f) - return 0.0f; - - const float scaled = x * 100.0f; - const int index = static_cast(scaled); - const float frac = scaled - static_cast(index); - - return frac * curveValues[index + 1] + (1.0f - frac) * curveValues[index]; -} - // Extrapolates above one and has no NaN guard. At x == 1, interpolation reads one // element beyond the 101-entry table even though its coefficient is zero. float JCurve::calculate(float x) @@ -101,125 +72,6 @@ float DecleiningSlopeCurve::calculate(float x) return (1.0f - frac) * curveValues[index] + frac * curveValues[index + 1]; } -// 101 constants, transcribed. -void SCurve::init() -{ - curveValues = new float[101]; // operator new[](0x194) = 101 * 4 - - curveValues[ 0] = 0.0f; - curveValues[ 1] = 0.00224938989f; - curveValues[ 2] = 0.00338781998f; - curveValues[ 3] = 0.00463052979f; - curveValues[ 4] = 0.00598675013f; - curveValues[ 5] = 0.00746650994f; - curveValues[ 6] = 0.00908064004f; - curveValues[ 7] = 0.0108407997f; - curveValues[ 8] = 0.0127597004f; - curveValues[ 9] = 0.0148508996f; - - curveValues[ 10] = 0.0171288997f; - curveValues[ 11] = 0.0196096003f; - curveValues[ 12] = 0.0223098006f; - curveValues[ 13] = 0.0252474006f; - curveValues[ 14] = 0.0284416005f; - curveValues[ 15] = 0.0319131017f; - curveValues[ 16] = 0.0356835015f; - curveValues[ 17] = 0.0397756994f; - curveValues[ 18] = 0.0442142002f; - curveValues[ 19] = 0.0490242988f; - - curveValues[ 20] = 0.0542327985f; - curveValues[ 21] = 0.0598676018f; - curveValues[ 22] = 0.0659573004f; - curveValues[ 23] = 0.0725317001f; - curveValues[ 24] = 0.0796212032f; - curveValues[ 25] = 0.0872564986f; - curveValues[ 26] = 0.0954684988f; - curveValues[ 27] = 0.104287997f; - curveValues[ 28] = 0.113744996f; - curveValues[ 29] = 0.123869002f; - - curveValues[ 30] = 0.134688005f; - curveValues[ 31] = 0.146227002f; - curveValues[ 32] = 0.158509001f; - curveValues[ 33] = 0.171553999f; - curveValues[ 34] = 0.185376003f; - curveValues[ 35] = 0.199987993f; - curveValues[ 36] = 0.215393007f; - curveValues[ 37] = 0.231592f; - curveValues[ 38] = 0.248576f; - curveValues[ 39] = 0.266330004f; - - curveValues[ 40] = 0.284830987f; - curveValues[ 41] = 0.304048002f; - curveValues[ 42] = 0.323940992f; - curveValues[ 43] = 0.344460994f; - curveValues[ 44] = 0.365550995f; - curveValues[ 45] = 0.387147993f; - curveValues[ 46] = 0.409179002f; - curveValues[ 47] = 0.431564987f; - curveValues[ 48] = 0.45422399f; - curveValues[ 49] = 0.477064997f; - - curveValues[ 50] = 0.5f; - curveValues[ 51] = 0.52293402f; - curveValues[ 52] = 0.54577601f; - curveValues[ 53] = 0.568435013f; - curveValues[ 54] = 0.590821028f; - curveValues[ 55] = 0.612851977f; - curveValues[ 56] = 0.634449005f; - curveValues[ 57] = 0.655538976f; - curveValues[ 58] = 0.676059008f; - curveValues[ 59] = 0.695951998f; - - curveValues[ 60] = 0.715167999f; - curveValues[ 61] = 0.733669996f; - curveValues[ 62] = 0.751424015f; - curveValues[ 63] = 0.768408f; - curveValues[ 64] = 0.784606993f; - curveValues[ 65] = 0.800011992f; - curveValues[ 66] = 0.814624012f; - curveValues[ 67] = 0.828445971f; - curveValues[ 68] = 0.841490984f; - curveValues[ 69] = 0.853772998f; - - curveValues[ 70] = 0.86531198f; - curveValues[ 71] = 0.876130998f; - curveValues[ 72] = 0.886255026f; - curveValues[ 73] = 0.895712018f; - curveValues[ 74] = 0.904532015f; - curveValues[ 75] = 0.912743986f; - curveValues[ 76] = 0.920378983f; - curveValues[ 77] = 0.927468002f; - curveValues[ 78] = 0.93404299f; - curveValues[ 79] = 0.940132022f; - - curveValues[ 80] = 0.945766985f; - curveValues[ 81] = 0.950976014f; - curveValues[ 82] = 0.95578599f; - curveValues[ 83] = 0.960223973f; - curveValues[ 84] = 0.964317024f; - curveValues[ 85] = 0.968087018f; - curveValues[ 86] = 0.971557975f; - curveValues[ 87] = 0.974753022f; - curveValues[ 88] = 0.977689981f; - curveValues[ 89] = 0.980390012f; - - curveValues[ 90] = 0.982870996f; - curveValues[ 91] = 0.985149026f; - curveValues[ 92] = 0.987240016f; - curveValues[ 93] = 0.989158988f; - curveValues[ 94] = 0.990918994f; - curveValues[ 95] = 0.992533982f; - curveValues[ 96] = 0.994013011f; - curveValues[ 97] = 0.995369017f; - curveValues[ 98] = 0.996612012f; - curveValues[ 99] = 0.997750998f; - - curveValues[100] = 1.0f; - -} - // 101 constants, transcribed. void JCurve::init() { diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h similarity index 86% rename from Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h rename to Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h index 8186b6b52..e17f6c616 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h @@ -1,28 +1,18 @@ // Samples a supplied curve function into a table for later evaluation. // [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path retail libaidll.so 1.50 embeds (AIUtils/CustomCurve.cpp). #ifndef AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H // [INFERRED] guard style #define AI_AIDLL_AI_AIBOTBEHAVIOUR_CUSTOMCURVE_H #include +#include "SCurve.h" // SCurve (AIUtils/SCurve.cpp); kept reachable through this header + namespace dice { namespace hfe { namespace ai { -// Static curve table with no per-instance state. Construction initializes the shared -// table and destruction releases it. -class SCurve -{ -public: - SCurve(); // - calls init, nothing else - ~SCurve(); - static void init(); - static float calculate(float x); // - the only one with a NaN guard - static float* curveValues; -}; - class JCurve { public: diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp index 2296868fd..9ef447331 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/AIRenderUtil.cpp @@ -20,7 +20,7 @@ #include "../../AIStrategicEntity/PatrolPath.h" #include "../checkPointer.h" #include "../../AIStrategicEntity/AILandingZone.h" -#include "../../AIStrategicEntity/AILandingZoneManager.h" +#include "../../Main/AILandingZoneManager.h" #include "../../AIStrategicEntity/AIStrategicObjectManager.h" #include "../../AIStrategicEntity/AIStrategicArea.h" #include "../../DrawPrimitives/DPManager.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp index 4c182f110..8ce626fab 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp @@ -14,7 +14,7 @@ #include "../../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../AIBot/BotMain.h" #include "../../AIKnowledge/Information.h" -#include "../../AIKnowledge/InformationManager.h" +#include "../../Main/InformationManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp index a0bc09816..b7d383575 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp @@ -12,7 +12,7 @@ #include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" #include "../../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../AIKnowledge/Information.h" -#include "../../AIKnowledge/InformationManager.h" +#include "../../Main/InformationManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp index 6d737c986..580d96499 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp @@ -14,7 +14,7 @@ #include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" #include "../../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../AIKnowledge/Information.h" -#include "../../AIKnowledge/InformationManager.h" +#include "../../Main/InformationManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp index f39c47626..b9184baf1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamic3dText.cpp @@ -12,7 +12,7 @@ #include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" #include "../../AIBot/BotMain.h" #include "../../AIKnowledge/Information.h" -#include "../../AIKnowledge/InformationManager.h" +#include "../../Main/InformationManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp index fff96db50..bdecceee6 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicCircle.cpp @@ -12,7 +12,7 @@ #include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" #include "../../AIBot/BotMain.h" #include "../../AIKnowledge/Information.h" -#include "../../AIKnowledge/InformationManager.h" +#include "../../Main/InformationManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp index 235508ae2..159e2de4a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/DebugRendering/DPDynamicLine.cpp @@ -14,7 +14,7 @@ #include "../../../../AIInterface/BFKnowledge/DebugRenderer.h" #include "../../AIBot/BotMain.h" #include "../../AIKnowledge/Information.h" -#include "../../AIKnowledge/InformationManager.h" +#include "../../Main/InformationManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp new file mode 100644 index 000000000..40ddc9481 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.cpp @@ -0,0 +1,168 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" (SCurve::calculate +// 0x101AA8E0 asserts "dep: SCurve::calculate() saw NaN value -- fix me"; retail 1.50 has no assert +// and returns 0). Split out of CustomCurve.cpp; the functions are unchanged. In the ELF SCurve's +// functions follow JCurve's (0x36EEE0..0x36F500) without a static-init block of their own. + +#include "SCurve.h" + +#include // isfinite - SCurve's guard + +namespace dice { +namespace hfe { +namespace ai { + +float* SCurve::curveValues = 0; + +// Builds the shared table on construction and frees it on destruction. +// Destruction retains the null guard and does not clear the shared pointer. +SCurve::SCurve() +{ + init(); +} + +SCurve::~SCurve() +{ + if (curveValues) + delete[] curveValues; +} + +// Returns zero for non-finite input and clamps x >= 1 to one before interpolation. +// [PLATFORM] Uses the standard isfinite name for the original finite predicate. +float SCurve::calculate(float x) +{ + if (!std::isfinite(x)) + return 0.0f; + if (x >= 1.0f) + return 1.0f; + if (x < 0.0f) + return 0.0f; + + const float scaled = x * 100.0f; + const int index = static_cast(scaled); + const float frac = scaled - static_cast(index); + + return frac * curveValues[index + 1] + (1.0f - frac) * curveValues[index]; +} + +// 101 constants, transcribed. +void SCurve::init() +{ + curveValues = new float[101]; // operator new[](0x194) = 101 * 4 + + curveValues[ 0] = 0.0f; + curveValues[ 1] = 0.00224938989f; + curveValues[ 2] = 0.00338781998f; + curveValues[ 3] = 0.00463052979f; + curveValues[ 4] = 0.00598675013f; + curveValues[ 5] = 0.00746650994f; + curveValues[ 6] = 0.00908064004f; + curveValues[ 7] = 0.0108407997f; + curveValues[ 8] = 0.0127597004f; + curveValues[ 9] = 0.0148508996f; + + curveValues[ 10] = 0.0171288997f; + curveValues[ 11] = 0.0196096003f; + curveValues[ 12] = 0.0223098006f; + curveValues[ 13] = 0.0252474006f; + curveValues[ 14] = 0.0284416005f; + curveValues[ 15] = 0.0319131017f; + curveValues[ 16] = 0.0356835015f; + curveValues[ 17] = 0.0397756994f; + curveValues[ 18] = 0.0442142002f; + curveValues[ 19] = 0.0490242988f; + + curveValues[ 20] = 0.0542327985f; + curveValues[ 21] = 0.0598676018f; + curveValues[ 22] = 0.0659573004f; + curveValues[ 23] = 0.0725317001f; + curveValues[ 24] = 0.0796212032f; + curveValues[ 25] = 0.0872564986f; + curveValues[ 26] = 0.0954684988f; + curveValues[ 27] = 0.104287997f; + curveValues[ 28] = 0.113744996f; + curveValues[ 29] = 0.123869002f; + + curveValues[ 30] = 0.134688005f; + curveValues[ 31] = 0.146227002f; + curveValues[ 32] = 0.158509001f; + curveValues[ 33] = 0.171553999f; + curveValues[ 34] = 0.185376003f; + curveValues[ 35] = 0.199987993f; + curveValues[ 36] = 0.215393007f; + curveValues[ 37] = 0.231592f; + curveValues[ 38] = 0.248576f; + curveValues[ 39] = 0.266330004f; + + curveValues[ 40] = 0.284830987f; + curveValues[ 41] = 0.304048002f; + curveValues[ 42] = 0.323940992f; + curveValues[ 43] = 0.344460994f; + curveValues[ 44] = 0.365550995f; + curveValues[ 45] = 0.387147993f; + curveValues[ 46] = 0.409179002f; + curveValues[ 47] = 0.431564987f; + curveValues[ 48] = 0.45422399f; + curveValues[ 49] = 0.477064997f; + + curveValues[ 50] = 0.5f; + curveValues[ 51] = 0.52293402f; + curveValues[ 52] = 0.54577601f; + curveValues[ 53] = 0.568435013f; + curveValues[ 54] = 0.590821028f; + curveValues[ 55] = 0.612851977f; + curveValues[ 56] = 0.634449005f; + curveValues[ 57] = 0.655538976f; + curveValues[ 58] = 0.676059008f; + curveValues[ 59] = 0.695951998f; + + curveValues[ 60] = 0.715167999f; + curveValues[ 61] = 0.733669996f; + curveValues[ 62] = 0.751424015f; + curveValues[ 63] = 0.768408f; + curveValues[ 64] = 0.784606993f; + curveValues[ 65] = 0.800011992f; + curveValues[ 66] = 0.814624012f; + curveValues[ 67] = 0.828445971f; + curveValues[ 68] = 0.841490984f; + curveValues[ 69] = 0.853772998f; + + curveValues[ 70] = 0.86531198f; + curveValues[ 71] = 0.876130998f; + curveValues[ 72] = 0.886255026f; + curveValues[ 73] = 0.895712018f; + curveValues[ 74] = 0.904532015f; + curveValues[ 75] = 0.912743986f; + curveValues[ 76] = 0.920378983f; + curveValues[ 77] = 0.927468002f; + curveValues[ 78] = 0.93404299f; + curveValues[ 79] = 0.940132022f; + + curveValues[ 80] = 0.945766985f; + curveValues[ 81] = 0.950976014f; + curveValues[ 82] = 0.95578599f; + curveValues[ 83] = 0.960223973f; + curveValues[ 84] = 0.964317024f; + curveValues[ 85] = 0.968087018f; + curveValues[ 86] = 0.971557975f; + curveValues[ 87] = 0.974753022f; + curveValues[ 88] = 0.977689981f; + curveValues[ 89] = 0.980390012f; + + curveValues[ 90] = 0.982870996f; + curveValues[ 91] = 0.985149026f; + curveValues[ 92] = 0.987240016f; + curveValues[ 93] = 0.989158988f; + curveValues[ 94] = 0.990918994f; + curveValues[ 95] = 0.992533982f; + curveValues[ 96] = 0.994013011f; + curveValues[ 97] = 0.995369017f; + curveValues[ 98] = 0.996612012f; + curveValues[ 99] = 0.997750998f; + + curveValues[100] = 1.0f; + +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h new file mode 100644 index 000000000..9b1bbfbd6 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/SCurve.h @@ -0,0 +1,27 @@ +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIUtils/SCurve.cpp). +// Split out of CustomCurve.h; CustomCurve.h includes it so existing users still see SCurve. + +#ifndef AI_AIDLL_AI_AIUTILS_SCURVE_H +#define AI_AIDLL_AI_AIUTILS_SCURVE_H + +namespace dice { +namespace hfe { +namespace ai { + +// Static curve table with no per-instance state. Construction initializes the shared +// table and destruction releases it. +class SCurve +{ +public: + SCurve(); // - calls init, nothing else + ~SCurve(); + static void init(); + static float calculate(float x); // - the only one with a NaN guard + static float* curveValues; +}; + +} // namespace ai +} // namespace hfe +} // namespace dice + +#endif // AI_AIDLL_AI_AIUTILS_SCURVE_H diff --git a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp index e46d325c0..b24862039 100644 --- a/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp @@ -6,7 +6,7 @@ // 0x36CE90, __tcf_0 0x36CEF0, _GLOBAL__I 0x36CF20). #include #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "../Main/InformationManager.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIBot/SquadManager.h" #include "../AIBot/SquadMember.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.cpp similarity index 94% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp rename to Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.cpp index ab4216158..9cbaac07a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.cpp @@ -1,8 +1,8 @@ -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\AIUtils\WeaponInfoManager.cpp" (0x1007D910). #include "WeaponInfoManager.h" -#include "../AIUtils/checkPointer.h" +#include "checkPointer.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h similarity index 92% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h rename to Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h index d28de4b32..a4ddd521f 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h @@ -1,6 +1,6 @@ // Handle pool for weapon information. The singleton keeps the first instance. // setInformation and changeInformation perform the same guarded store; only changeInformation returns success. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (AIUtils/WeaponInfoManager.cpp). #ifndef AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOMANAGER_H #define AI_AIDLL_AI_AIKNOWLEDGE_WEAPONINFOMANAGER_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp index ff72736b4..7583af743 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AICollisionHandler.cpp @@ -18,12 +18,12 @@ #include "../AIBot/SquadManager.h" #include "../AIKnowledge/FireObject.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../AIKnowledge/IPIArmament.h" #include "../AIKnowledge/IPIPhysical.h" #include "../AIKnowledge/IPIUnit.h" #include "../AIKnowledge/WeaponInfo.h" -#include "../AIKnowledge/WeaponInfoManager.h" +#include "../AIUtils/WeaponInfoManager.h" #include "../AIUtils/AIVectorMath.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp index be9954e10..b5d02f7af 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIConsole.cpp @@ -15,7 +15,7 @@ #include "../AIBot/WPPatrol.h" #include "../AIBot/WPAltitudePatrol.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../AIPathFinding/NavMesh/MapProperties.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" @@ -369,7 +369,7 @@ void AIConsole::botMoveTo(float radius, Vec3 position, int id) positions.push_back(position); Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); WaypointList* waypoints; - if (equipment && (equipment->getObjectTypeFlags() & 0x10)) + if (equipment && equipment->isOfType(ITAir)) waypoints = new WPAltitudeMoveTo(radius, radius, radius, 1, positions); else waypoints = new WPMoveTo(radius, 60.0f, 1, positions, -1); @@ -385,7 +385,7 @@ void AIConsole::botFlyTo(int id, float first, float second, float third, Vec3 po std::list positions; positions.push_back(position); Information* const equipment = informationManager->getInformation(bot->getCurrentEquipment()); - if (equipment && (equipment->getObjectTypeFlags() & 0x10)) + if (equipment && equipment->isOfType(ITAir)) bot->setWaypoints(new WPAltitudeMoveTo(first, second, third, 1, positions)); } diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h b/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h index b0455e2ff..ab629e392 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIDllTypes.h @@ -19,8 +19,8 @@ class MissileLockMessage; namespace ai { // knowledge records -class Information; // the SpHandlePool payload; see AIKnowledge/InformationManager.h -class WeaponInfo; // likewise; see AIKnowledge/WeaponInfoManager.h +class Information; // the SpHandlePool payload; see Main/InformationManager.h +class WeaponInfo; // likewise; see AIUtils/WeaponInfoManager.h // the bot itself // `Bot*` and `unsigned int` appear as alternative first arguments on the same DPManager creators diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp index 662adb64d..bee618aca 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIEventCourier.cpp @@ -22,7 +22,7 @@ #include "../AIBot/BotMain.h" // event_isRepaired #include "../AIStrategic/SAI.h" // the commander and request events #include "../AIKnowledge/Information.h" // eventManDown -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../AIKnowledge/IPIPhysical.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit - eventMissileLock diff --git a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp index 9a3268cbf..9a3d0b2cc 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AILODManager.cpp @@ -10,7 +10,7 @@ #include "IBotManager.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../AIKnowledge/IPIMobile.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.cpp similarity index 97% rename from Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp rename to Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.cpp index 448b9fcf9..e65447ce8 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.cpp @@ -1,4 +1,4 @@ -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\AILandingZoneManager.cpp" (0x10081FA0). // static init: ELF 0x39AA80, __tcf_0 0x39AB10, _GLOBAL__I 0x39AB40: stream Init precedes the manager. #include @@ -7,7 +7,7 @@ #include -#include "AILandingZone.h" +#include "../AIStrategicEntity/AILandingZone.h" #include "../AIUtils/checkPointer.h" #include "../AIUtils/DebugRendering/AIRenderUtil.h" // updateNumberOfLandingZones diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.h similarity index 96% rename from Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h rename to Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.h index bb029d795..076df21e0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AILandingZoneManager.h @@ -1,6 +1,6 @@ // Owns AI landing zones. Constructed when the DLL loads and destroyed by BF2AI::clear. // reset is its only virtual method; the destructor is nonvirtual. -// [INFERRED] Source placement. +// Header placement [INFERRED]: beside its .cpp, whose path AIDLL_r.dll confirms (Main/AILandingZoneManager.cpp). #ifndef AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H // [INFERRED] guard style #define AI_AIDLL_AI_AISTRATEGICENTITY_AILANDINGZONEMANAGER_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp index 3c58a5fd7..06498f0df 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIMain.cpp @@ -10,7 +10,7 @@ #include #include "../AIUtils/checkPointer.h" // the ctor's dead null check -#include "../AIBotBehaviour/CustomCurve.h" // SCurve / JCurve / DecleiningSlopeCurve +#include "../AIUtils/CustomCurve.h" // SCurve / JCurve / DecleiningSlopeCurve #include "../../../AIInterface/Module/BFConsole.h" // IBFModuleCourier::aiMainInit #include "BotManager.h" // getNumberOfActiveBots #include "CommonSingletonServer.h" // m_iaiGame / Settings / Effector @@ -18,7 +18,7 @@ #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame #include "../../../AIInterface/BFKnowledge/BFGameEffector.h" // IAIGameEffector::addBot #include "IAIPathfinding.h" // IAIPathfindingSetup::instance -#include "../AIStrategicMap/AerialHeightMap.h" // readHeightMapFromFile +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" // readHeightMapFromFile #include "../AIKnowledge/BFInformationEnvironment.h" // built and dropped by init #include "../AIUtils/DebugRendering/AIRenderUtil.h" // built and dropped by init #include "../AIStrategic/SAI.h" // ISAI::create, one per side @@ -27,13 +27,13 @@ #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer - newPlayerCreated #include "../AIBot/BotMain.h" // Bot - switchSides #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // isValidPlayerId -#include "UserOrderManager.h" // recruitBot's first refusal +#include "../AIStrategicEntity/UserOrders/UserOrderManager.h" // recruitBot's first refusal #include // the per-bot pair series #include "../../../AIInterface/BFKnowledge/AIPlayerFactory.h" // getPlayerFromId, the id sweep #include "../../../AIInterface/BFKnowledge/BFTimer.h" // action's three timer methods #include "../../../AIInterface/BFKnowledge/BFCollisionHandler.h" // updateBotProjectiles #include "../AIBot/SquadManager.h" // update(double) -#include "AIMineManager.h" +#include "../AIKnowledge/AIMineManager.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" // updateAIObject, vehicle changes #include "../../../AIInterface/BFKnowledge/IAIObjectPlugIn.h" // IAIObjectUnit #include "CommunicationHub.h" // resetLevel // IAIMineManager::update @@ -42,23 +42,7 @@ namespace dice { namespace hfe { namespace ai { -// Active IAIMain instance; construction replaces it unconditionally. -IAIMain* IAIMain::m_instance = 0; - -// Construction replaces the active IAIMain pointer. Destruction clears it unconditionally. -// Only one IAIMain may be alive when callers use this singleton. -// ELF 0x3E6790 / 0x3E67C0 -IAIMain::IAIMain() -{ - m_instance = this; -} - -// ELF 0x3E67F0 / 0x3E6820 / 0x3E6850 -IAIMain::~IAIMain() -{ - m_instance = 0; -} - +// IAIMain's constructor, destructor and m_instance live in IAIMain.cpp (AIDLL_r __FILE__). // Returns whether initialization has completed. [INFERRED] State-field name. // ELF 0x39F9F0 diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp index 25945520c..b741a0a6c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIModule.cpp @@ -21,13 +21,13 @@ #include "../AIStrategic/Strategy.h" #include "../AIStrategic/StrategyCondition.h" #include "../AIStrategicEntity/AILandingZone.h" -#include "../AIStrategicEntity/AILandingZoneManager.h" +#include "AILandingZoneManager.h" #include "../AIStrategicEntity/AIStrategicArea.h" #include "../AIStrategicEntity/AIStrategicObjectManager.h" #include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" #include "../AIStrategicEntity/GuardPosition.h" #include "../AIStrategicEntity/PatrolPath.h" -#include "../AIStrategicMap/AerialHeightMap.h" +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../DrawPrimitives/DPManager.h" #include "AIConsole.h" #include "AILODManager.h" @@ -43,7 +43,7 @@ #include "IAIPathfinding.h" #include "IBotManager.h" #include "StrategyManager.h" -#include "UserOrderManager.h" +#include "../AIStrategicEntity/UserOrders/UserOrderManager.h" namespace dice { namespace hfe { diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp index 5f2b53236..1daf04d88 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.cpp @@ -26,7 +26,7 @@ #include "../AIPathFinding/NavMesh/QTSearchNodeManager.h" // init builds one per local search #include "../AIStrategicEntity/AIStrategicObjectManager.h" // loadQuadTrees' tail calls initAreas #include "../AIUtils/checkPointer.h" -#include "AIMineManager.h" // loadQuadTrees / loadGTSData call IAIMineManager::init +#include "../AIKnowledge/AIMineManager.h" // loadQuadTrees / loadGTSData call IAIMineManager::init #include "AISettingsInterfaces.h" // IAISettings::getVehicle / getVehicleMaterialManager #include "CommonSingletonServer.h" @@ -53,7 +53,7 @@ AIPathfinding::AIPathfinding() : m_activatePathfindingDebugTool(false) , m_pathfindingDebugToolVehicleId(0) , m_searchPointToSet(0) - , m_debugPath(0) + , m_path(0) , m_debugClusterPath(0) , m_d36(-1000.0) , m_clusterSearch(false) @@ -65,8 +65,8 @@ AIPathfinding::AIPathfinding() , m_maxWaterDepth(0.5f) , m_locking(false) { - m_debugPath = new QTPath(); - checkPointer(m_debugPath); + m_path = new QTPath(); + checkPointer(m_path); m_debugClusterPath = new ClusterNodePath(); checkPointer(m_debugClusterPath); @@ -95,7 +95,7 @@ AIPathfinding::~AIPathfinding() delete m_engine; delete m_clusterEngine; - delete m_debugPath; + delete m_path; delete m_debugClusterPath; delete m_searchPoint[0]; delete m_searchPoint[1]; @@ -115,9 +115,9 @@ int AIPathfinding::reset() m_d36 = -1000.0; m_searchPointToSet = 0; - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0; m_debugClusterPath->m_nodes.resize(0); m_debugClusterPath->m_i0 = 0; @@ -305,7 +305,7 @@ int AIPathfinding::getSearchPointToSet() const // ELF 0x3A6720. QTPath* AIPathfinding::getDebugPath() const { - return m_debugPath; + return m_path; } // ELF 0x3A6730. @@ -421,7 +421,7 @@ void AIPathfinding::getPortalCost(std::vector& costs, unsigned short cost acquireResource(resource, 2000); const int vehicleId = settings->getVehicle(m_maps[map]->m_clusterCostVehicles[costType]); - QTPath* const path = m_debugPath; + QTPath* const path = m_path; path->m_nodes.resize(0); path->m_i0 = 0; path->m_i20 = 0.0f; @@ -447,7 +447,7 @@ void AIPathfinding::getPortalCost(std::vector& costs, unsigned short cost manager->m_usePathTopologySmoothing = true; if (localSearch(resource, map, island, fromPolygon, from, toPolygon, to, vehicleId, - m_debugPath) == astarStatus::kFound) + m_path) == astarStatus::kFound) { const float dx = to.x - from.x; const float dy = to.y - from.y; @@ -460,9 +460,9 @@ void AIPathfinding::getPortalCost(std::vector& costs, unsigned short cost while (m_engine->m_searches[resource]->m_status == astarStatus::kSearching) m_engine->update(10.0f); if (localSearch(resource, map, island, fromPolygon, from, toPolygon, to, - vehicleId, m_debugPath) != astarStatus::kFound) - m_debugPath->m_i20 = -1.0f; - costs.push_back(m_debugPath->m_i20); + vehicleId, m_path) != astarStatus::kFound) + m_path->m_i20 = -1.0f; + costs.push_back(m_path->m_i20); } } } @@ -470,7 +470,7 @@ void AIPathfinding::getPortalCost(std::vector& costs, unsigned short cost releaseResource(resource, 2000); } -// ELF 0x3A63B0. Runs the portal-to-portal search on the shared debug path (m_debugPath is +// ELF 0x3A63B0. Runs the portal-to-portal search on the shared debug path (m_path is // emptied first: resize(0), step and cost zeroed) with the vehicle of cluster cost type // `costType`. Both polygons must exist and carry a material valid for that vehicle, else the cost // is -1 (true). The search is limited to `allowedClusters`; topology smoothing is switched on @@ -487,7 +487,7 @@ bool AIPathfinding::getPortalCost(float& cost, unsigned int resource, int map, u IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); QuadTree* const quadTree = m_maps[map]->m_quadTreeManager->getIsland(island); - QTPath* const path = m_debugPath; + QTPath* const path = m_path; path->m_nodes.resize(0); path->m_i0 = 0; path->m_i20 = 0.0f; @@ -514,7 +514,7 @@ bool AIPathfinding::getPortalCost(float& cost, unsigned int resource, int map, u manager->m_usePathTopologySmoothing = true; const int status = localSearch(resource, map, island, fromPolygon, from, toPolygon, to, - vehicleId, m_debugPath); + vehicleId, m_path); if (status == astarStatus::kSearching) return false; if (status != astarStatus::kFound) @@ -522,7 +522,7 @@ bool AIPathfinding::getPortalCost(float& cost, unsigned int resource, int map, u cost = -1.0f; return true; } - if (m_debugPath->m_i20 == 0.0f) + if (m_path->m_i20 == 0.0f) { const float dx = to.x - from.x; const float dy = to.y - from.y; @@ -531,7 +531,7 @@ bool AIPathfinding::getPortalCost(float& cost, unsigned int resource, int map, u cost = materials->getMaterialCost(fromMaterial) * cost; return true; } - cost = m_debugPath->m_i20; + cost = m_path->m_i20; return true; } @@ -1001,7 +1001,7 @@ bool AIPathfinding::MapContainer::getEdge(Vec3& first, Vec3& second, unsigned in first = *quadTree->getVertexForPolygon(polygon, index); second = *quadTree->getVertexForPolygon( - polygon, static_cast((index + 1) % record->m_numberOfVertices)); + polygon, static_cast((index + 1) % record->vertexCount)); return true; } @@ -1264,9 +1264,9 @@ int AIPathfinding::clusterSearch(int resource, int map, unsigned int island, manager->setClusterGraph(m_maps[map]->m_quadTreeManager->getClusterGraph(island)); ClusterNode* const startNode = - manager->getNewNode(quadTree->getPolygon(startPolygon)->m_cluster, 0, 0); + manager->getNewNode(quadTree->getPolygon(startPolygon)->cluster, 0, 0); ClusterNode* const goalNode = - manager->getNewNode(quadTree->getPolygon(goalPolygon)->m_cluster, 0, 0); + manager->getNewNode(quadTree->getPolygon(goalPolygon)->cluster, 0, 0); manager->m_start = start; manager->m_goalPosition = goal; manager->m_costType = m_maps[map]->m_clusterCostTypes[vehicleId]; @@ -1495,7 +1495,7 @@ bool AIPathfinding::getLineIntersectionWithPolygon(Vec3& intersection, int map, // retail. int AIPathfinding::getClusterOfPolygon(int map, unsigned int island, unsigned int polygon) const { - return m_maps[map]->m_quadTreeManager->getIsland(island)->getPolygon(polygon)->m_cluster; + return m_maps[map]->m_quadTreeManager->getIsland(island)->getPolygon(polygon)->cluster; } // ELF 0x3A7FD0. @@ -1815,9 +1815,9 @@ void AIPathfinding::searchPointSelected(bool resetPoints) { m_d36 = -1000.0; m_searchPointToSet = 0; - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0.0f; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; if (resetPoints) return; } @@ -1853,7 +1853,7 @@ void AIPathfinding::searchPointSelected(bool resetPoints) const int type = m_maps[m_pathfindingDebugToolVehicleId != 3] ->m_clusterCostTypes[m_pathfindingDebugToolVehicleId]; m_maps[m_pathfindingDebugToolVehicleId != 3]->m_quadTreeManager - ->getClusterGraph(island)->drawCluster(polygon->m_cluster, type); + ->getClusterGraph(island)->drawCluster(polygon->cluster, type); } unsigned int toPolygon; // shipped defect: this also queries the second endpoint before the first click completes. @@ -1875,18 +1875,18 @@ void AIPathfinding::searchPointSelected(bool resetPoints) return; if (!m_clusterSearch) { - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0.0f; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; if (localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, *m_searchPoint[0], toPolygon, *m_searchPoint[1], - m_pathfindingDebugToolVehicleId, m_debugPath) != 2) + m_pathfindingDebugToolVehicleId, m_path) != 2) { while (m_engine->m_searches[resource]->m_status == 1) m_engine->update(10.0); localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, *m_searchPoint[0], toPolygon, *m_searchPoint[1], - m_pathfindingDebugToolVehicleId, m_debugPath); + m_pathfindingDebugToolVehicleId, m_path); } } else @@ -1921,9 +1921,9 @@ void AIPathfinding::tryPath(const Vec3& from, const Vec3& to) m_d36 = -1000.0; *m_searchPoint[0] = from; *m_searchPoint[1] = to; - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0.0f; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; unsigned int fromPolygon, island, toPolygon; getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, fromPolygon, island, m_pathfindingDebugToolVehicleId); @@ -1933,18 +1933,18 @@ void AIPathfinding::tryPath(const Vec3& from, const Vec3& to) toPolygon, island, m_pathfindingDebugToolVehicleId); if (toPolygon == 0xFFFFFFFFu) return; - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0.0f; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; if (localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, *m_searchPoint[0], toPolygon, *m_searchPoint[1], - m_pathfindingDebugToolVehicleId, m_debugPath) != 2) + m_pathfindingDebugToolVehicleId, m_path) != 2) { while (m_engine->m_searches[resource]->m_status == 1) m_engine->update(10.0); localSearch(resource, m_pathfindingDebugToolVehicleId != 3, island, fromPolygon, *m_searchPoint[0], toPolygon, *m_searchPoint[1], - m_pathfindingDebugToolVehicleId, m_debugPath); + m_pathfindingDebugToolVehicleId, m_path); } releaseResource(resource, 2000); } @@ -1960,9 +1960,9 @@ void AIPathfinding::tryClusterPath(const Vec3& from, const Vec3& to) m_d36 = -1000.0; *m_searchPoint[0] = from; *m_searchPoint[1] = to; - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0.0f; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; unsigned int fromPolygon, island, toPolygon; getPolygon(*m_searchPoint[0], m_pathfindingDebugToolVehicleId != 3, fromPolygon, island, m_pathfindingDebugToolVehicleId); @@ -1993,9 +1993,9 @@ void AIPathfinding::setActivatePathfindingDebugTool(bool active) m_activatePathfindingDebugTool = active; if (!active) { - m_debugPath->m_nodes.resize(0); - m_debugPath->m_i0 = 0; - m_debugPath->m_i20 = 0.0f; + m_path->m_nodes.resize(0); + m_path->m_i0 = 0; + m_path->m_i20 = 0.0f; m_searchPointToSet = 0; } } diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h index 0420f6243..6c72b24e7 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPathfinding.h @@ -245,7 +245,7 @@ class AIPathfinding : public IAIPathfinding, public IAIPathfindingSetup // Both elements are separately heap-allocated zeroed `Vec3`s; `tryPath` writes the caller's two // positions straight into them. /* +20 */ Vec3* m_searchPoint[2]; - /* +28 */ QTPath* m_debugPath; // = new QTPath + /* +28 */ QTPath* m_path; // = new QTPath // name: AIDLL_r asserts 0x100A70E0 (PE +0x1C) /* +32 */ ClusterNodePath* m_debugClusterPath; // = new ClusterNodePath /* +36 */ double m_d36; // Last debug endpoint selection time; reset sentinel -1000.0. /* +44 */ bool m_clusterSearch; // = false; the debug tool's cluster/local toggle diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp index a827732aa..65c69ee1f 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIPlayerCourier.cpp @@ -11,7 +11,7 @@ #include "IBotManager.h" #include "../AIBot/BotMain.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" namespace dice { diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp b/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp index 8e028c860..5ae0ddcff 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettings.cpp @@ -59,25 +59,25 @@ bool AISettings::getOverrideMenuSettings() const // ELF 0x3BEF90. int AISettings::getNumberOfBehaviours() const { - return m_numberOfBehaviours; + return m_behaviourCount; } // ELF 0x3BEFA0. int AISettings::getNumberOfVehicles() const { - return static_cast(m_behaviours.size()); + return static_cast(m_behaviourPool.size()); } // ELF 0x3C0EF0. -float* AISettings::getVehicleMods(int vehicle) const +float* AISettings::getVehicleMods(int vehicleTypeId) const { - return m_vehicleMods[vehicle]; + return m_vehicleMods[vehicleTypeId]; } // ELF 0x3BF640. BotBehaviour* AISettings::getBehaviour(int vehicle, int index) const { - return m_behaviours[vehicle][index]; + return m_behaviourPool[vehicle][index]; } // ELF 0x3BF670. @@ -85,20 +85,20 @@ BotBehaviour* AISettings::getDefaultBehaviour(int vehicle) const { const int index = m_defaultBehaviour[vehicle]; if (index != -1) - return m_behaviours[vehicle][index]; + return m_behaviourPool[vehicle][index]; return 0; } // ELF 0x3BF6B0. PlanInterpreter* AISettings::getPlanInterpreter(int vehicle) const { - return m_planInterpreters[vehicle]; + return m_planInterpreterPool[vehicle]; } // ELF 0x3BF6D0. PlanGenerator* AISettings::getPlanGenerator(int vehicle, int index) const { - return m_planGenerators[vehicle][index]; + return m_planGeneratorPool[vehicle][index]; } // ELF 0x3C0230. @@ -156,8 +156,8 @@ const std::string& AISettings::getVehicle(int vehicle) const int AISettings::getVehicle(const std::string& name) const { // (!) guarded, and the sibling below is not. Same map type, same find, opposite discipline. - const std::map::const_iterator i = m_vehicleIndex.find(name); - if (i == m_vehicleIndex.end()) + const std::map::const_iterator i = m_vehicleIdMap.find(name); + if (i == m_vehicleIdMap.end()) return -1; return i->second; } @@ -166,7 +166,7 @@ int AISettings::getVehicle(const std::string& name) const // ELF 0x3BF500. const std::string& AISettings::getVehicleClusterMapping(const std::string& name) const { - const int vehicle = m_vehicleIndex.find(name)->second; + const int vehicle = m_vehicleIdMap.find(name)->second; return m_vehicleNames[m_clusterCostTypes[vehicle]]; } @@ -198,7 +198,7 @@ int AISettings::getVehicleGroup(int index) const int AISettings::getVehicleGroup(const std::string& name) const { // Requires an existing group name; the lookup result is dereferenced without checking end(). - return m_vehicleGroupIndex.find(name)->second; + return m_namesToVehicleGroups.find(name)->second; } // ELF 0x3C09E0. @@ -254,7 +254,7 @@ ISensingAgentPattern* AISettings::getSensingAgentPattern(int id) const // ELF 0x3C0E70. ISensingAgentPattern* AISettings::getSensingAgentNullPattern() const { - return m_sensingAgentNullPattern; + return m_nullPattern; } // ELF 0x3C0FD0. @@ -267,25 +267,25 @@ int AISettings::getManDownEquipmentType() // ELF 0x3C1090. bool AISettings::isValidMaterial(int vehicle, unsigned char material) const { - return m_vehicleMaterialManagers[vehicle]->isValidMaterial(material); + return m_materialManagers[vehicle]->isValidMaterial(material); } // ELF 0x3C1110. float AISettings::getVehicleMaterialCost(const std::string& name, unsigned char material) const { - return m_vehicleMaterialManagers[getVehicle(name)]->getMaterialCost(material); + return m_materialManagers[getVehicle(name)]->getMaterialCost(material); } // ELF 0x3C10D0. float AISettings::getVehicleMaterialCost(int vehicle, unsigned char material) const { - return m_vehicleMaterialManagers[vehicle]->getMaterialCost(material); + return m_materialManagers[vehicle]->getMaterialCost(material); } // ELF 0x3C1170. MaterialManager* AISettings::getVehicleMaterialManager(int vehicle) const { - return m_vehicleMaterialManagers[vehicle]; + return m_materialManagers[vehicle]; } // Returns the next bot name and rotates the roster for the following request. @@ -303,7 +303,7 @@ const std::string& AISettings::getBotName() const void AISettings::setMaxNumberOfBehaviours(int count) { BotMain::setNBehaviours(static_cast(count)); - m_numberOfBehaviours = count; + m_behaviourCount = count; } // ELF 0x3C0F10: grows the table to the vehicle (new slots null), then stores the set. @@ -315,88 +315,88 @@ void AISettings::setVehicleMods(int vehicle, float* mods) } // ELF 0x3BF730. -void AISettings::addBehaviour(int vehicle, int index, BotBehaviour* behaviour) +void AISettings::addBehaviour(int vehicleTypeId, int behaviourId, BotBehaviour* behaviour) { - prepareBehaviourPool(vehicle, index); - m_behaviours[vehicle][index] = behaviour; + prepareBehaviourPool(vehicleTypeId, behaviourId); + m_behaviourPool[vehicleTypeId][behaviourId] = behaviour; } // ELF 0x3BF7A0: the pool is prepared for (vehicle, index) although only the default slot is set. -void AISettings::setDefaultBehaviour(int vehicle, int index) +void AISettings::setDefaultBehaviour(int vehicleTypeId, int behaviourId) { - prepareBehaviourPool(vehicle, index); - m_defaultBehaviour[vehicle] = index; + prepareBehaviourPool(vehicleTypeId, behaviourId); + m_defaultBehaviour[vehicleTypeId] = behaviourId; } // ELF 0x3BF870: BAPInterpreter::addEntry(entry) on the vehicle's interpreter. -void AISettings::addInterpreterEntry(int vehicle, BAPEntry* entry) +void AISettings::addInterpreterEntry(int vehicleTypeId, BAPEntry* entry) { - preparePlanInterpreterPool(vehicle); - static_cast(m_planInterpreters[vehicle])->addEntry(entry); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->addEntry(entry); } // ELF 0x3BF8D0. -void AISettings::addInterpreterEntry(int vehicle, BotLodLevel lod, BAPEntry* entry) +void AISettings::addInterpreterEntry(int vehicleTypeId, BotLodLevel lod, BAPEntry* entry) { - preparePlanInterpreterPool(vehicle); - static_cast(m_planInterpreters[vehicle])->addEntry(lod, entry); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->addEntry(lod, entry); } // ELF 0x3BF930. -void AISettings::removeInterpreterEntry(int vehicle, BotLodLevel lod, BAPEntry* entry) +void AISettings::removeInterpreterEntry(int vehicleTypeId, BotLodLevel lod, BAPEntry* entry) { - preparePlanInterpreterPool(vehicle); - static_cast(m_planInterpreters[vehicle])->removeEntry(lod, entry); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->removeEntry(lod, entry); } // ELF 0x3BF990. -void AISettings::activateDefaultInterpreter(int vehicle, BAPStatementType type, BotLodLevel lod) +void AISettings::activateDefaultInterpreter(int vehicleTypeId, BAPStatementType type, BotLodLevel lod) { - preparePlanInterpreterPool(vehicle); - static_cast(m_planInterpreters[vehicle])->activateEntry(type, lod); + preparePlanInterpreterPool(vehicleTypeId); + static_cast(m_planInterpreterPool[vehicleTypeId])->activateEntry(type, lod); } // ELF 0x3BF800. -void AISettings::addGenerator(int vehicle, int index, PlanGenerator* generator) +void AISettings::addGenerator(int vehicleTypeId, int behaviourId, PlanGenerator* generator) { - preparePlanGeneratorPool(vehicle, index); - m_planGenerators[vehicle][index] = generator; + preparePlanGeneratorPool(vehicleTypeId, behaviourId); + m_planGeneratorPool[vehicleTypeId][behaviourId] = generator; } // ELF 0x3BFA20: one behaviour list per vehicle up to `vehicle`; a list too short for `index` is // sized to the number of behaviours (not to index + 1); the default table grows with -1 entries. // Every size test is signed (`cmpl ...; jg`). -void AISettings::prepareBehaviourPool(int vehicle, int index) +void AISettings::prepareBehaviourPool(int vehicleTypeId, int behaviourId) { - if (static_cast(m_behaviours.size()) <= vehicle) - m_behaviours.resize(vehicle + 1, std::vector()); - std::vector& behaviours = m_behaviours[vehicle]; - if (static_cast(behaviours.size()) <= index) - behaviours.resize(m_numberOfBehaviours, 0); - prepareVehicleGroup(vehicle); - if (static_cast(m_defaultBehaviour.size()) <= vehicle) - m_defaultBehaviour.resize(vehicle + 1, -1); + if (static_cast(m_behaviourPool.size()) <= vehicleTypeId) + m_behaviourPool.resize(vehicleTypeId + 1, std::vector()); + std::vector& behaviours = m_behaviourPool[vehicleTypeId]; + if (static_cast(behaviours.size()) <= behaviourId) + behaviours.resize(m_behaviourCount, 0); + prepareVehicleGroup(vehicleTypeId); + if (static_cast(m_defaultBehaviour.size()) <= vehicleTypeId) + m_defaultBehaviour.resize(vehicleTypeId + 1, -1); } // ELF 0x3BFC50: as prepareBehaviourPool, with the vehicle group prepared before the inner list. -void AISettings::preparePlanGeneratorPool(int vehicle, int index) +void AISettings::preparePlanGeneratorPool(int vehicleTypeId, int behaviourId) { - if (static_cast(m_planGenerators.size()) <= vehicle) - m_planGenerators.resize(vehicle + 1, std::vector()); - prepareVehicleGroup(vehicle); - std::vector& generators = m_planGenerators[vehicle]; - if (static_cast(generators.size()) <= index) - generators.resize(m_numberOfBehaviours, 0); + if (static_cast(m_planGeneratorPool.size()) <= vehicleTypeId) + m_planGeneratorPool.resize(vehicleTypeId + 1, std::vector()); + prepareVehicleGroup(vehicleTypeId); + std::vector& generators = m_planGeneratorPool[vehicleTypeId]; + if (static_cast(generators.size()) <= behaviourId) + generators.resize(m_behaviourCount, 0); } // ELF 0x3BFDE0: one `new BAPInterpreter(45)` (operator new 0x10; 45 statement types) per missing // vehicle, each checked (checkPointer, the Debug at line 46) and pushed back. void AISettings::preparePlanInterpreterPool(int vehicle) { - if (static_cast(m_planInterpreters.size()) <= vehicle) + if (static_cast(m_planInterpreterPool.size()) <= vehicle) { - for (unsigned int i = m_planInterpreters.size(); i < static_cast(vehicle + 1); ++i) - m_planInterpreters.push_back(checkPointer(new BAPInterpreter(45))); + for (unsigned int i = m_planInterpreterPool.size(); i < static_cast(vehicle + 1); ++i) + m_planInterpreterPool.push_back(checkPointer(new BAPInterpreter(45))); } prepareVehicleGroup(vehicle); } @@ -467,10 +467,10 @@ void AISettings::setRespawnAllowed(bool allowed) // ELF 0x3BEFC0. void AISettings::setVehicle(const std::string& name) { - const int id = static_cast(m_vehicleIndex.size()); - m_vehicleIndex.insert(std::make_pair(name, id)); + const int id = static_cast(m_vehicleIdMap.size()); + m_vehicleIdMap.insert(std::make_pair(name, id)); m_vehicleNames.push_back(name); - m_vehicleMaterialManagers.push_back(checkPointer(new MaterialManager)); + m_materialManagers.push_back(checkPointer(new MaterialManager)); m_clusterCostTypes.push_back(-1); } @@ -479,8 +479,8 @@ void AISettings::setVehicle(const std::string& name) void AISettings::setVehicleClusterMapping(const std::string& vehicle, const std::string& clusterVehicle) { - const int vehicleId = m_vehicleIndex.find(vehicle)->second; - const int clusterVehicleId = m_vehicleIndex.find(clusterVehicle)->second; + const int vehicleId = m_vehicleIdMap.find(vehicle)->second; + const int clusterVehicleId = m_vehicleIdMap.find(clusterVehicle)->second; m_clusterCostTypes[vehicleId] = clusterVehicleId; } @@ -490,7 +490,7 @@ void AISettings::createVehicleGroup(const std::string& name) { const int id = static_cast(m_vehicleGroupNames.size()); m_vehicleGroupNames.resize(m_vehicleGroupNames.size() + 1, name); - m_vehicleGroupIndex.insert(std::make_pair(name, id)); + m_namesToVehicleGroups.insert(std::make_pair(name, id)); } // ELF 0x3C0790. @@ -549,7 +549,7 @@ void AISettings::setSensingAgentPatternName(const std::string& name) // ELF 0x3C0D80. void AISettings::setSensingAgentNullPattern(ISensingAgentPattern* pattern) { - m_sensingAgentNullPattern = pattern; + m_nullPattern = pattern; } // ELF 0x3C0DA0: insert_unique(vehicle, pattern) into the +0x6C map. @@ -569,7 +569,7 @@ void AISettings::setVehicleMaterialCost(const std::string& vehicle, unsigned char material, float cost) { - m_vehicleMaterialManagers[getVehicle(vehicle)]->setMaterialCost(material, cost); + m_materialManagers[getVehicle(vehicle)]->setMaterialCost(material, cost); } // Adds a name to the bot-name roster used by getBotName. @@ -610,7 +610,7 @@ void AISettings::setBotNameUnused(const std::string&) // ELF 0x3BD020 / 0x3BD5B0. Initializes AI settings and their default values. AISettings::AISettings() : m_maxNBots(-1) - , m_numberOfBehaviours(0) + , m_behaviourCount(0) , m_viewDistance(-1.0f) , m_statsViewDistance(30.0f) , m_botSkill(0.75f) @@ -625,7 +625,7 @@ AISettings::AISettings() , m_overrideMenuSettings(false) , m_drawBotStats(true) { - // Defect 1: m_sensingAgentNullPattern is deliberately not initialised here. See above. + // Defect 1: m_nullPattern is deliberately not initialised here. See above. // Both arrays are indexed [side - 1]; the constructor nulls all four words. m_standardMoralAdmin[0] = 0; @@ -811,25 +811,25 @@ bool AISettings::reset() if (AIRadio::m_instance) AIRadio::m_instance->reset(); // shipped defect: deleted entries stay in their vectors and can be deleted again. - for (unsigned int row = 0; row < m_behaviours.size(); ++row) - for (unsigned int i = 0; i < m_behaviours[row].size(); ++i) - if (m_behaviours[row][i]) - delete m_behaviours[row][i]; - for (unsigned int row = 0; row < m_planGenerators.size(); ++row) - for (unsigned int i = 0; i < m_planGenerators[row].size(); ++i) - if (m_planGenerators[row][i]) - delete m_planGenerators[row][i]; - for (unsigned int i = 0; i < m_planInterpreters.size(); ++i) - if (m_planInterpreters[i]) - delete m_planInterpreters[i]; - m_vehicleIndex.clear(); + for (unsigned int row = 0; row < m_behaviourPool.size(); ++row) + for (unsigned int i = 0; i < m_behaviourPool[row].size(); ++i) + if (m_behaviourPool[row][i]) + delete m_behaviourPool[row][i]; + for (unsigned int row = 0; row < m_planGeneratorPool.size(); ++row) + for (unsigned int i = 0; i < m_planGeneratorPool[row].size(); ++i) + if (m_planGeneratorPool[row][i]) + delete m_planGeneratorPool[row][i]; + for (unsigned int i = 0; i < m_planInterpreterPool.size(); ++i) + if (m_planInterpreterPool[i]) + delete m_planInterpreterPool[i]; + m_vehicleIdMap.clear(); m_vehicleNames.resize(0); m_sensingAgentPatternIds.clear(); m_sensingAgentPatterns.clear(); m_maxNBots = -1; // [UNRESOLVED] Types/names of the two words at +0x10/+0x14; both are zeroed here. std::memset(m_gap16, 0, sizeof(m_gap16)); - m_numberOfBehaviours = 0; + m_behaviourCount = 0; m_informationGridDimension = 32; m_viewDistance = 600.0f; m_nSides = 0; @@ -857,20 +857,20 @@ bool AISettings::reset() AISettings::~AISettings() { delete AIRadio::m_instance; - for (unsigned int row = 0; row < m_behaviours.size(); ++row) - for (unsigned int i = 0; i < m_behaviours[row].size(); ++i) - if (m_behaviours[row][i]) - delete m_behaviours[row][i]; - for (unsigned int row = 0; row < m_planGenerators.size(); ++row) - for (unsigned int i = 0; i < m_planGenerators[row].size(); ++i) - if (m_planGenerators[row][i]) - delete m_planGenerators[row][i]; - for (unsigned int i = 0; i < m_planInterpreters.size(); ++i) - if (m_planInterpreters[i]) - delete m_planInterpreters[i]; - for (unsigned int i = 0; i < m_vehicleMaterialManagers.size(); ++i) - if (m_vehicleMaterialManagers[i]) - delete m_vehicleMaterialManagers[i]; + for (unsigned int row = 0; row < m_behaviourPool.size(); ++row) + for (unsigned int i = 0; i < m_behaviourPool[row].size(); ++i) + if (m_behaviourPool[row][i]) + delete m_behaviourPool[row][i]; + for (unsigned int row = 0; row < m_planGeneratorPool.size(); ++row) + for (unsigned int i = 0; i < m_planGeneratorPool[row].size(); ++i) + if (m_planGeneratorPool[row][i]) + delete m_planGeneratorPool[row][i]; + for (unsigned int i = 0; i < m_planInterpreterPool.size(); ++i) + if (m_planInterpreterPool[i]) + delete m_planInterpreterPool[i]; + for (unsigned int i = 0; i < m_materialManagers.size(); ++i) + if (m_materialManagers[i]) + delete m_materialManagers[i]; } } // namespace ai diff --git a/Code/BF2/AI/AIDLL/AI/Main/AISettings.h b/Code/BF2/AI/AIDLL/AI/Main/AISettings.h index 34ccac5d6..07b2a7848 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AISettings.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AISettings.h @@ -139,14 +139,14 @@ class AISettings : public IAISettings, public IAISettingsModifier private: // Non-virtual pool helpers (direct PLT calls), ELF 0x3BFA20 / 0x3BFC50 / 0x3BFDE0 / 0x3C0040. - void prepareBehaviourPool(int vehicle, int index); - void preparePlanGeneratorPool(int vehicle, int index); + void prepareBehaviourPool(int vehicleTypeId, int behaviourId); + void preparePlanGeneratorPool(int vehicleTypeId, int behaviourId); void preparePlanInterpreterPool(int vehicle); void prepareVehicleGroup(int vehicle); // Field offsets describe retail x86 layout; native STL sizes may differ. /* 8 */ int m_maxNBots; // = -1 getMaxNBots / setMaxNBots - /* 12 */ int m_numberOfBehaviours; // = 0 getNumberOfBehaviours + /* 12 */ int m_behaviourCount; // = 0 getNumberOfBehaviours // name: AIDLL_r assert 0x100C2690 (PE +0xC) /* 16 */ char m_gap16[8]; // [UNRESOLVED] two words reset zeroes; ctor leaves them alone /* 24 */ float m_viewDistance; // = -1.0f getViewDistance /* 28 */ float m_statsViewDistance; // = 30.0f get/setStatsViewDistance @@ -165,19 +165,19 @@ class AISettings : public IAISettings, public IAISettingsModifier /* 56 */ std::string m_manDownEquipment; // the size of this vector is `getNumberOfVehicles`. The AI counts vehicles by counting - // behaviour lists, one per vehicle; `getBehaviour(vehicle, i)` is `m_behaviours[vehicle][i]`. - /* 60 */ std::vector > m_behaviours; - /* 72 */ std::vector m_defaultBehaviour; // index into m_behaviours[v]; -1 = none - /* 84 */ std::vector > m_planGenerators; - /* 96 */ std::vector m_planInterpreters; // each a BAPInterpreter (vector::_M_insert_aux) + // behaviour lists, one per vehicle; `getBehaviour(vehicle, i)` is `m_behaviourPool[vehicle][i]`. + /* 60 */ std::vector > m_behaviourPool; // name: AIDLL_r assert 0x100C2980 (PE +0x50) + /* 72 */ std::vector m_defaultBehaviour; // index into m_behaviourPool[v]; -1 = none + /* 84 */ std::vector > m_planGeneratorPool; // name: AIDLL_r assert 0x100C2DD0 (PE +0x70) + /* 96 */ std::vector m_planInterpreterPool; // each a BAPInterpreter (vector::_M_insert_aux) // name: AIDLL_r assert 0x100C0DF0 (PE +0x80) /* 108 */ std::map m_sensingAgentPatterns; - /* 120 */ std::vector m_vehicleMaterialManagers; + /* 120 */ std::vector m_materialManagers; // name: AIDLL_r assert 0x100BD950 (PE +0xA0) // Uninitialized until setSensingAgentNullPattern is called; callers must set it before use. - /* 132 */ ISensingAgentPattern* m_sensingAgentNullPattern; + /* 132 */ ISensingAgentPattern* m_nullPattern; // name: AIDLL_r assert "m_nullPattern != 0" (0x100BA3F0) /* 136 */ std::vector m_vehicleGroupNames; // size == getNumberOfVehicleGroups - /* 148 */ std::map m_vehicleGroupIndex; // createVehicleGroup inserts here + /* 148 */ std::map m_namesToVehicleGroups; // createVehicleGroup inserts here // name: AIDLL_r assert 0x100BED20 (PE +0xC4) /* 160 */ std::vector m_vehicleGroups; // Two per-side arrays indexed by side - 1; callers must supply side 1 or 2. @@ -185,7 +185,7 @@ class AISettings : public IAISettings, public IAISettingsModifier /* 180 */ float* m_standardPersonality[2]; /* 188 */ std::vector m_vehicleMods; - /* 200 */ std::map m_vehicleIndex; // setVehicle inserts; getVehicle(name) reads + /* 200 */ std::map m_vehicleIdMap; // setVehicle inserts; getVehicle(name) reads // name: AIDLL_r assert 0x100BE960 (PE +0x100) /* 212 */ std::vector m_vehicleNames; // setVehicle push_backs the same name here /* 224 */ std::vector m_clusterCostTypes; /* 236 */ std::string m_sensingAgentPatternName; // [INFERRED] setSensingAgentPatternName diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp index fdd229400..680519add 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/AIStreamOperators.cpp @@ -879,6 +879,9 @@ std::ostream& operator<<(std::ostream& out, StrategyCondition::Conditional value return out; } +// Kit types: AIDLL_r.dll's operator<< (0x100D4D70, jump table 0x100D4F40) confirms every value: +// 0 KTSpecops, 1 KTSniper, 2 KTAssault, 3 KTSupport, 4 KTEngineer, 5 KTMedic, 6 KTAT (anti-tank), +// 7..12 KTExtended1..6. hfe::KitType itself is declared opaque (Game/Objects/Game/KitTemplate.h). static const char* const kKitNames[] = { "KTSpecops", "KTSniper", diff --git a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp index 3dc7150e4..55dab1b44 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BF2AI.cpp @@ -15,19 +15,19 @@ #include "../AIKnowledge/BFInformationCourier.h" // step 4 #include "../AIKnowledge/BFInformationEnvironment.h" #include "../AIKnowledge/InformationFactory.h" // step 8 -#include "../AIKnowledge/InformationManager.h" // step 1, and clear's table teardown -#include "../AIKnowledge/WeaponInfoManager.h" // step 2 +#include "InformationManager.h" // step 1, and clear's table teardown +#include "../AIUtils/WeaponInfoManager.h" // step 2 #include "../AIStrategicMap/BFStrategicEnvironment.h" // step 6 #include "../DrawPrimitives/DPManager.h" // step 7 #include "../AIUtils/checkPointer.h" #include "AICollisionHandler.h" // step 10 #include "AIEventCourier.h" // step 11 #include "AIMain.h" -#include "AIMineManager.h" // step 13 +#include "../AIKnowledge/AIMineManager.h" // step 13 #include "AIPlayerCourier.h" // step 12 #include "AIConsole.h" // step 15 #include "../AIUtils/DebugRendering/AIRenderUtil.h" // clear: the debug renderer -#include "../AIStrategicEntity/AILandingZoneManager.h" // clear: the landing-zone manager +#include "AILandingZoneManager.h" // clear: the landing-zone manager #include "BotBehaviourManager.h" // step 16 #include "../AIStrategicEntity/AIStrategicObjectManager.h" // step 17 #include "../AIStrategicEntity/CoverPosition/CoverPositionManager.h" // step 18 @@ -37,9 +37,9 @@ #include "AIRandom.h" // step 22, and clear #include "AISettings.h" // step 9 #include "BFPathfindingCourier.h" // step 5 -#include "UserOrderManager.h" // step 14 +#include "../AIStrategicEntity/UserOrders/UserOrderManager.h" // step 14 #include "StrategyManager.h" // step 19, and clear -#include "../AIStrategicMap/AerialHeightMap.h" // step 20, and clear +#include "../AIPathFinding/AerialHeightMap/AerialHeightMap.h" // step 20, and clear #include "CommunicationHub.h" // step 23, and clear #include "AISettingsInterfaces.h" // IAISettings / IAISettingsModifier #include "../../../AIInterface/BFKnowledge/BFGame.h" // IAIGame::getAISettingsFromGame @@ -347,7 +347,7 @@ bool BF2AI::clear() // both, with no destructor call on either - which is what establishes that `SpHandlePool` is // trivially destructible and that `InformationManager` owns nothing else. Written as the two // raw frees the binary makes rather than as `delete informationManager`, because a typed delete - // would call the destructor the binary does not call. See AIKnowledge/InformationManager.h. + // would call the destructor the binary does not call. See Main/InformationManager.h. if (informationManager) { if (informationManager->getPool()) diff --git a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp index 661379a32..ed0fdf874 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BFPathfindingCourier.cpp @@ -20,7 +20,7 @@ #include "../AIBot/SquadMember.h" #include "../AIKnowledge/IPIMobile.h" #include "../AIKnowledge/Information.h" -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" #include "../../../AIInterface/BFKnowledge/BFGame.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" // IAISettings::getVehicle - findClosestValidInfantryPolygon diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp index 030842cae..0fce9a4f3 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp @@ -20,7 +20,7 @@ #include "../AIBot/BotMain.h" // the preallocated pool #include "../AIBot/BotMemory.h" #include "../AIBot/BotOrder.h" -#include "../AIBotBehaviour/UrgencyMerger.h" +#include "../AIBot/UrgencyMerger.h" #include "BotBehaviourManager.h" #include "../AIUtils/checkPointer.h" #include "CommonSingletonServer.h" @@ -32,7 +32,7 @@ #include "../AIBot/BotNavigation.h" // actionComAgent / actionUpdateNavPoints #include "../AIBot/CommunicationAgent.h" // actionComAgent #include "../AIKnowledge/Information.h" // updateDamages -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../AIKnowledge/IPIMobile.h" // actionExecutePlan's stall test, actionPathfinding #include "IAIPathfinding.h" // actionPathfinding hands the searcher its share #include "../../../AIInterface/BFKnowledge/BFObjectEnvironment.h" // actionHearing's object list @@ -130,14 +130,14 @@ void BotManager::updateDamages() { IAIGameEffector* const effector = static_cast(CommonSingletonServer::m_iaiGameEffector); - for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { if (!(*it)->m_bot->isDead() && (*it)->m_damage > 0.0f) { world::IPlayer* const from = - m_botInfos[(*it)->m_attackerIndex]->m_bot->getPlayer()->getPlayer(); + m_bots[(*it)->m_attackerIndex]->m_bot->getPlayer()->getPlayer(); #if defined(_WIN32) - Bot* const attacker = m_botInfos[(*it)->m_attackerIndex]->m_bot; + Bot* const attacker = m_bots[(*it)->m_attackerIndex]->m_bot; const unsigned int handle = (*it)->m_bot->getCurrentEquipment(); Information* const information = (handle & 0xffffu) ? informationManager->getInformation(handle) : nullptr; @@ -146,7 +146,7 @@ void BotManager::updateDamages() effector->giveDamage(target, from, attacker->getSide(), damage); #else BotInfo* const info = *it; - const int side = m_botInfos[info->m_attackerIndex]->m_bot->getSide(); + const int side = m_bots[info->m_attackerIndex]->m_bot->getSide(); InformationManager* const manager = informationManager; const unsigned int handle = (*it)->m_bot->getCurrentEquipment(); Information* const information = manager->getInformation(handle); @@ -163,23 +163,23 @@ void BotManager::updateDamages() void BotManager::actionComAgent() { const unsigned int start = m_comAgentCursor; - if (m_botInfos.empty()) + if (m_bots.empty()) return; - Bot* bot = m_botInfos[m_comAgentCursor]->m_bot; + Bot* bot = m_bots[m_comAgentCursor]->m_bot; for (;;) { if (!bot->isDead() && !bot->getManDown() && !bot->getBotNavigation()->isPathSearchPending()) { bot->getCommunicationAgent()->update(); - if (++m_comAgentCursor >= m_botInfos.size()) + if (++m_comAgentCursor >= m_bots.size()) m_comAgentCursor = 0; return; } - if (++m_comAgentCursor >= m_botInfos.size()) + if (++m_comAgentCursor >= m_bots.size()) m_comAgentCursor = 0; if (start == m_comAgentCursor) return; - bot = m_botInfos[m_comAgentCursor]->m_bot; + bot = m_bots[m_comAgentCursor]->m_bot; } } @@ -200,14 +200,14 @@ void BotManager::actionExecutePlan(const double& slice) IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); const double deadline = timer->getUpdateTime() + slice; - m_queuePriorityA->clear(); - m_queuePriorityB->clear(); - m_queueSensing->clear(); + m_planned->clear(); + m_unplanned->clear(); + m_sensingQueue->clear(); m_planExecutionsThisTick = 0; m_tickCount180 = 0; m_tickCount184 = 0; - const unsigned int size = static_cast(m_botInfos.size()); + const unsigned int size = static_cast(m_bots.size()); m_planHalfToggle = !m_planHalfToggle; unsigned int count = size / 2 + 1; if (count > size) @@ -218,7 +218,7 @@ void BotManager::actionExecutePlan(const double& slice) unsigned int processed = 0; while (processed < count) { - BotInfo* info = m_botInfos[m_planCursor]; + BotInfo* info = m_bots[m_planCursor]; Bot* const bot = info->m_bot; if (!bot || bot->isDead() || bot->isDeactivated() || !bot->getSquadMember()) { @@ -297,13 +297,13 @@ void BotManager::actionExecutePlan(const double& slice) if (bot->hasPlan() && !bot->hasDefaultPlan()) { if (info->m_double24 > m_plannedDecisionMakingThresholdFull) - m_queuePriorityA->push(info); + m_planned->push(info); } else if (info->m_double24 > m_unplannedDecisionMakingThresholdFull) { - m_queuePriorityB->push(info); + m_unplanned->push(info); } - m_queueSensing->push(info); + m_sensingQueue->push(info); bot->updatePlayerAction(!inBudget); if (!executed) break; @@ -312,7 +312,7 @@ void BotManager::actionExecutePlan(const double& slice) } for (unsigned int i = 0; i < size - processed; ++i) - m_botInfos[m_planCursor]->m_bot->updatePlayerAction(false); + m_bots[m_planCursor]->m_bot->updatePlayerAction(false); } // [INFERRED] Visits at most one roster circuit and refreshes at most size/16 + 1 active @@ -321,17 +321,17 @@ void BotManager::actionExecutePlan(const double& slice) // ELF 0x3DD980 void BotManager::actionUpdateNavPoints() { - if (m_botInfos.empty()) + if (m_bots.empty()) return; - const unsigned int limit = static_cast(m_botInfos.size() >> 4) + 1; + const unsigned int limit = static_cast(m_bots.size() >> 4) + 1; unsigned int updated = 0; unsigned int visited = 0; - while (updated < limit && visited < m_botInfos.size()) + while (updated < limit && visited < m_bots.size()) { - Bot* const bot = m_botInfos[m_navPointCursor]->m_bot; + Bot* const bot = m_bots[m_navPointCursor]->m_bot; if (!bot) continue; - m_navPointCursor = (m_navPointCursor + 1) % static_cast(m_botInfos.size()); + m_navPointCursor = (m_navPointCursor + 1) % static_cast(m_bots.size()); ++visited; if (bot->isDead() || bot->getManDown()) continue; @@ -355,16 +355,16 @@ void BotManager::actionDecisionMaking(const double& slice) static_cast(CommonSingletonServer::m_iBFTimer)->getUpdateTime() + slice; int spare = static_cast(m_plannedDecisionMakingInterleave) - - static_cast(m_queuePriorityA->size()); + - static_cast(m_planned->size()); if (spare < 0) spare = 0; const unsigned int unplannedLimit = m_unplannedDecisionMakingInterleave + spare; m_selectedBots.resize(0); - while (!m_queuePriorityB->empty() && m_selectedBots.size() < unplannedLimit) + while (!m_unplanned->empty() && m_selectedBots.size() < unplannedLimit) { - BotInfo* info = m_queuePriorityB->top(); - m_queuePriorityB->pop(); + BotInfo* info = m_unplanned->top(); + m_unplanned->pop(); switch (info->m_bot->getLodLevel()) { case BotLodFull: @@ -383,10 +383,10 @@ void BotManager::actionDecisionMaking(const double& slice) } unsigned int planned = 0; - while (!m_queuePriorityA->empty() && planned++ < m_plannedDecisionMakingInterleave) + while (!m_planned->empty() && planned++ < m_plannedDecisionMakingInterleave) { - BotInfo* info = m_queuePriorityA->top(); - m_queuePriorityA->pop(); + BotInfo* info = m_planned->top(); + m_planned->pop(); switch (info->m_bot->getLodLevel()) { case BotLodFull: @@ -456,13 +456,13 @@ void BotManager::actionPathfinding(const double& slice) const double now = timer->getUpdateTime(); const double deadline = now + slice; const double botDeadline = now + slice * 0.1; - const unsigned int size = static_cast(m_botInfos.size()); + const unsigned int size = static_cast(m_bots.size()); for (unsigned int visited = 0; visited < size; ++visited) { if (timer->getUpdateTime() > botDeadline) break; - BotInfo* const info = m_botInfos[m_pathfindingCursor]; + BotInfo* const info = m_bots[m_pathfindingCursor]; Bot* const bot = info->m_bot; if (bot && !bot->isDead() && !bot->isDeactivated() && bot->getSquadMember() && info->m_bot->getBotNavigation()->isSearchActive() @@ -487,7 +487,7 @@ void BotManager::actionPathfinding(const double& slice) for (unsigned int i = 0; i < size; ++i) { - BotInfo* const info = m_botInfos[i]; + BotInfo* const info = m_bots[i]; Bot* const bot = info->m_bot; if (bot && !bot->isDead() && !bot->isDeactivated() && bot->getSquadMember() && info->m_bot->getBotNavigation()->isSearchActive() @@ -589,10 +589,10 @@ void BotManager::actionSensing(const double& slice) unsigned int medium = 0; unsigned int light = 0; unsigned int taken = 0; - while (!m_queueSensing->empty() && taken <= 1) + while (!m_sensingQueue->empty() && taken <= 1) { - BotInfo* info = m_queueSensing->top(); - m_queueSensing->pop(); + BotInfo* info = m_sensingQueue->top(); + m_sensingQueue->pop(); Bot* const bot = info->m_bot; if (!informationManager->getInformation(info->m_bot->getCurrentEquipment())) continue; @@ -655,9 +655,9 @@ void BotManager::actionSensing(const double& slice) // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotManager operation. BotManager::BotManager() // The IBotManager and IBotManagerModifier bases construct their own interface subobjects. - : m_queuePriorityA(new BotQueue) - , m_queuePriorityB(new BotQueue) - , m_queueSensing(new SensingQueue) + : m_planned(new BotQueue) + , m_unplanned(new BotQueue) + , m_sensingQueue(new SensingQueue) , m_comAgentCursor(0) // cached, not looked UP later. Every later use of the AI main goes through this copy, so a // BotManager built before an AIMain exists caches a null and never notices. @@ -708,7 +708,7 @@ BotManager::BotManager() IAISettings* const settings = static_cast(CommonSingletonServer::m_iaiSettings); if (settings->getMaxNBots() != -1) { - m_botInfos.reserve(settings->getMaxNBots()); + m_bots.reserve(settings->getMaxNBots()); // Re-queries the maximum bot count on every iteration, independently of the reserve call. for (int i = 0; i < settings->getMaxNBots(); ++i) @@ -731,7 +731,7 @@ BotManager::BotManager() new BotMain(0, static_cast(i), 0, 1.0f, 1, 0, memory, 0, 0, merger, generators)); - m_bots.insert(m_bots.end(), bot); + m_preallocatedBots.insert(m_preallocatedBots.end(), bot); } } @@ -818,9 +818,9 @@ void BotManager::setSystemQuotient(unsigned a, unsigned b, unsigned c) BotManager::~BotManager() { reset(); - delete m_queuePriorityA; - delete m_queuePriorityB; - delete m_queueSensing; + delete m_planned; + delete m_unplanned; + delete m_sensingQueue; } // - the vector's byte span shifted right by two, i.e. its element count. @@ -829,14 +829,14 @@ BotManager::~BotManager() // ELF 0x3DB060 int BotManager::getBotCount() const { - return static_cast(m_botInfos.size()); + return static_cast(m_bots.size()); } // Reports the bot counts from the managed roster. // ELF 0x3DB080 int BotManager::getNumberOfActiveBots() const { - return static_cast(m_botInfos.size()) - static_cast(m_deactivatedBots.size()); + return static_cast(m_bots.size()) - static_cast(m_deactivatedBots.size()); } // ELF 0x3DB0D0 @@ -849,16 +849,16 @@ int BotManager::getNumberOfDeactivedBots() const // ELF 0x3DB100 Bot* BotManager::getBot(unsigned int index) const { - return m_botInfos[index]->m_bot; + return m_bots[index]->m_bot; } // Bot-ID lookup checks bounds; player lookup requires a valid association. // ELF 0x3DB1A0 Bot* BotManager::getBotFromId(unsigned int id) const { - if (id < m_botInfos.size()) + if (id < m_bots.size()) { - BotInfo* const info = m_botInfos[id]; + BotInfo* const info = m_bots[id]; if (info) return info->m_bot; @@ -881,7 +881,7 @@ Bot* BotManager::getBotFromPlayerId(int playerId) const // ELF 0x3DB1D0: the first record whose player's name (IAIPlayer +0x18) equals the argument. Bot* BotManager::getBotFromName(const std::string& name) const { - for (std::vector::const_iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + for (std::vector::const_iterator it = m_bots.begin(); it != m_bots.end(); ++it) { if ((*it)->m_bot->getPlayer()->getName() == name) return (*it)->m_bot; @@ -911,7 +911,7 @@ bool exitAddBot(int playerId) // ELF 0x3DB320 bool BotManager::addBot(int playerId, int side, float* personality, IAIObject* object) { - const std::size_t rosterSize = m_botInfos.size(); + const std::size_t rosterSize = m_bots.size(); if (rosterSize >= static_cast( static_cast(CommonSingletonServer::m_iaiSettings)->getMaxNBots())) return exitAddBot(playerId); @@ -938,7 +938,7 @@ bool BotManager::addBot(int playerId, int side, float* personality, IAIObject* o const int count = static_cast(CommonSingletonServer::m_iaiSettings)->getNumberOfBehaviours(); BotMain* bot; - if (m_bots.empty()) + if (m_preallocatedBots.empty()) { UrgencyGenerator** const generators = checkPointer(new UrgencyGenerator*[count]); UrgencyMerger* const merger = checkPointer(new UrgencyMerger(count, personality, generators)); @@ -948,12 +948,12 @@ bool BotManager::addBot(int playerId, int side, float* personality, IAIObject* o BotOrder* const order = checkPointer(new BotOrder(weights, static_cast( BotBehaviourManager::m_instance->getBehaviourId("Idle")))); player->setViewDistance(static_cast(CommonSingletonServer::m_iaiSettings)->getViewDistance()); - bot = checkPointer(new BotMain(player, static_cast(m_botInfos.size()), + bot = checkPointer(new BotMain(player, static_cast(m_bots.size()), personality, 1.0f, 1, order, new BotMemory(), 0, side, merger, generators)); } else { - bot = static_cast(m_bots.front()); + bot = static_cast(m_preallocatedBots.front()); bot->setPlayer(player); bot->m_basicWeights = personality; bot->setSide(side); @@ -963,7 +963,7 @@ bool BotManager::addBot(int playerId, int side, float* personality, IAIObject* o BotOrder* const order = checkPointer(new BotOrder(weights, static_cast( BotBehaviourManager::m_instance->getBehaviourId("Idle")))); bot->recieveOrder(order); - m_bots.erase(m_bots.begin()); + m_preallocatedBots.erase(m_preallocatedBots.begin()); } bot->updateBotVehicle(0); @@ -973,7 +973,7 @@ bool BotManager::addBot(int playerId, int side, float* personality, IAIObject* o return exitAddBot(playerId); information->setStrength(information->getStrength() + 1.0f); bot->setWaypoints(checkPointer(new WPEmpty(information->getPosition()))); - m_botInfos.push_back(checkPointer(new BotInfo(bot))); + m_bots.push_back(checkPointer(new BotInfo(bot))); // shipped defect: grows to playerId, then writes element playerId; the first lookup is unchecked too. if (static_cast(m_botByPlayerId.size()) < playerId) m_botByPlayerId.resize(playerId, -1); @@ -991,7 +991,7 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) ->getNumberOfBehaviours(); BotMain* bot; - if (m_bots.empty()) + if (m_preallocatedBots.empty()) { UrgencyGenerator** const generators = checkPointer(new UrgencyGenerator*[count]); UrgencyMerger* const merger = checkPointer(new UrgencyMerger(count, personality, generators)); @@ -1004,12 +1004,12 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) ->getPlayerFromId(playerId); // BotMain storage is allocated before this nested BotMemory construction in both images. // Unlike the preallocation constructor, this path does not checkPointer the memory. - bot = checkPointer(new BotMain(player, static_cast(m_botInfos.size()), + bot = checkPointer(new BotMain(player, static_cast(m_bots.size()), personality, 1.0f, 1, order, new BotMemory(), 0, side, merger, generators)); } else { - bot = static_cast(m_bots.front()); + bot = static_cast(m_preallocatedBots.front()); bot->setPlayer(static_cast(CommonSingletonServer::m_iaiPlayerFactory) ->getPlayerFromId(playerId)); bot->setSide(side); @@ -1021,10 +1021,10 @@ bool BotManager::addUnspawnedBot(int playerId, int side, float* personality) BotBehaviourManager::m_instance->getBehaviourId("Idle")))); bot->recieveOrder(order); // Reload begin after the virtual calls, as retail does. - m_bots.erase(m_bots.begin()); + m_preallocatedBots.erase(m_preallocatedBots.begin()); } - m_botInfos.push_back(checkPointer(new BotInfo(bot))); + m_bots.push_back(checkPointer(new BotInfo(bot))); if (static_cast(m_botByPlayerId.size()) < playerId) m_botByPlayerId.resize(playerId, -1); m_botByPlayerId[playerId] = static_cast(bot->getBotId()); @@ -1041,9 +1041,9 @@ int BotManager::deactivateBot(int side) { unsigned int index = 0; bool found = false; - for (unsigned int i = 0; i < m_botInfos.size(); ++i) + for (unsigned int i = 0; i < m_bots.size(); ++i) { - Bot* const bot = m_botInfos[i]->m_bot; + Bot* const bot = m_bots[i]->m_bot; if (bot && bot->getSide() == side && bot->isDead()) { index = i; @@ -1053,9 +1053,9 @@ int BotManager::deactivateBot(int side) } if (!found) { - for (unsigned int i = 0; i < m_botInfos.size(); ++i) + for (unsigned int i = 0; i < m_bots.size(); ++i) { - Bot* const bot = m_botInfos[i]->m_bot; + Bot* const bot = m_bots[i]->m_bot; if (bot && bot->getSide() == side) { index = i; @@ -1064,11 +1064,11 @@ int BotManager::deactivateBot(int side) } } static_cast(CommonSingletonServer::m_iaiSettingsModifier) - ->setBotNameUnused(m_botInfos[index]->m_bot->getPlayer()->getName()); + ->setBotNameUnused(m_bots[index]->m_bot->getPlayer()->getName()); m_deactivatedBots.push_back(index); - m_botByPlayerId[m_botInfos[index]->m_bot->getPlayerId()] = -1; - m_botInfos[index]->m_bot->getPlayer()->setPlayer(static_cast(0)); - m_botInfos[index]->m_bot->setAsDeactivated(true); + m_botByPlayerId[m_bots[index]->m_bot->getPlayerId()] = -1; + m_bots[index]->m_bot->getPlayer()->setPlayer(static_cast(0)); + m_bots[index]->m_bot->setAsDeactivated(true); return static_cast(index); } @@ -1105,7 +1105,7 @@ bool BotManager::reactivateBot(int playerId, int side, const std::string& name) const std::list::iterator oldest = m_deactivatedBots.begin(); const unsigned int botId = *oldest; - Bot* const bot = m_botInfos[botId]->m_bot; + Bot* const bot = m_bots[botId]->m_bot; bot->getPlayer()->setPlayer(playerId); bot->setSide(side); @@ -1131,7 +1131,7 @@ Bot* BotManager::getBot(IAIObject* object) const const std::map::const_iterator it = m_vehicleBots.find(object); if (it == m_vehicleBots.end()) return 0; - BotInfo* const info = m_botInfos[it->second]; + BotInfo* const info = m_bots[it->second]; return info ? info->m_bot : 0; } @@ -1210,7 +1210,7 @@ void BotManager::setBotIsDead(int playerId) bot->setIsInTransitionPhase(true); bot->getBotNavigation()->resetAll(); static_cast(bot)->resetAssignedAreas(); - BotInfo* const info = m_botInfos[bot->getBotId()]; + BotInfo* const info = m_bots[bot->getBotId()]; IAIMain::m_instance->getSAI(info->m_bot->getSide()); info->m_word4 = 1; info->m_bot->reset(); @@ -1235,7 +1235,7 @@ void BotManager::setBotIsAlive(int playerId) bot->updateBotVehicle(0); bot->updateBot(); bot->setLastChangeTime(-1000000.0f); - BotInfo* const info = m_botInfos[bot->getBotId()]; + BotInfo* const info = m_bots[bot->getBotId()]; info->m_priority = 0; info->m_double24 = 0.0f; info->m_word4 = 0; @@ -1352,8 +1352,8 @@ void BotManager::setBotTeamKilled(int playerId, int) // ELF 0x3E0AC0: unchecked index; updateDamages applies and clears the sum each tick. void BotManager::registerDamageOnBot(float damage, int botIndex, int attackerIndex) { - m_botInfos[botIndex]->m_damage += damage; - m_botInfos[botIndex]->m_attackerIndex = attackerIndex; + m_bots[botIndex]->m_damage += damage; + m_bots[botIndex]->m_attackerIndex = attackerIndex; } // ELF 0x3DAD10: `flds 0xE8(this)`. @@ -1365,7 +1365,7 @@ float BotManager::getVehicleBailValue() // ELF 0x3DB280: every bot targeting the mine (BotMain +0x1FC) gets target -1 (+0x1F8). void BotManager::removeMineTarget(unsigned int handle) { - for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { BotMain* const bot = static_cast((*it)->m_bot); if (bot->getMineTarget() == handle) @@ -1382,7 +1382,7 @@ void BotManager::removeMineTarget(unsigned int handle) bool BotManager::reset() { m_planCursor = 0; // +0x104 - for (std::vector::iterator info = m_botInfos.begin(); info != m_botInfos.end(); ++info) + for (std::vector::iterator info = m_bots.begin(); info != m_bots.end(); ++info) { if (*info) { @@ -1391,10 +1391,10 @@ bool BotManager::reset() delete *info; } } - m_botInfos.resize(0, 0); m_bots.resize(0, 0); - delete m_queuePriorityA; - delete m_queuePriorityB; + m_preallocatedBots.resize(0, 0); + delete m_planned; + delete m_unplanned; m_list56.clear(); // +0x38 setLodLevelTicks(3, 2, 1); // +0x8C setLodLevelPriority(3, 2, 1); // +0x90 @@ -1403,8 +1403,8 @@ bool BotManager::reset() setDecisionMakingInterleave(2, 2); // +0x9C setSensingQuotient(1, 1); // +0xA0 setSystemQuotient(30, 40, 30); // +0xA4 - m_queuePriorityA = new BotQueue; - m_queuePriorityB = new BotQueue; + m_planned = new BotQueue; + m_unplanned = new BotQueue; m_hearingResumeId = 0; // +0xBC return true; } @@ -1428,7 +1428,7 @@ void BotManager::writeBotPlans() const std::string levelPath = static_cast(CommonSingletonServer::m_iaiGame)->getLevelPath(); io::IStream* file = io::fileManager->open(levelPath + "../../../AI/BotPlans.cpp", static_cast(0), static_cast(2), 0); - for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { Bot* const bot = (*it)->m_bot; if (bot->isDead()) @@ -1595,7 +1595,7 @@ double BotManager::getSystemSensingQuotient() const // ELF 0x3DFA80: every record's four counters (+0x20..+0x2C) and three run times (+0x30..+0x40). void BotManager::resetStatistics() { - for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) { BotInfo* const info = *it; info->m_behaviourUpdateCount = 0; @@ -1609,9 +1609,9 @@ void BotManager::resetStatistics() } // ELF 0x3DFAF0: the same for one unchecked index (the records are reached through pointers). -void BotManager::resetStatistics(unsigned int index) const +void BotManager::resetStatistics(unsigned int botIndex) const { - BotInfo* const info = m_botInfos[index]; + BotInfo* const info = m_bots[botIndex]; info->m_behaviourUpdateCount = 0; info->m_word36 = 0; info->m_word40 = 0; @@ -1622,75 +1622,75 @@ void BotManager::resetStatistics(unsigned int index) const } // ELF 0x3DFB50 (+0x24), unchecked index. -unsigned BotManager::getPlanExecutionUpdateCount(unsigned int index) const +unsigned BotManager::getPlanExecutionUpdateCount(unsigned int botIndex) const { - return m_botInfos[index]->m_word36; + return m_bots[botIndex]->m_word36; } // ELF 0x3DFB70 (+0x28), unchecked index. -unsigned BotManager::getDecisionMakingUpdateCount(unsigned int index) const +unsigned BotManager::getDecisionMakingUpdateCount(unsigned int botIndex) const { - return m_botInfos[index]->m_word40; + return m_bots[botIndex]->m_word40; } // ELF 0x3DFB90 (+0x2C), unchecked index. -unsigned BotManager::getSensingUpdateCount(unsigned int index) const +unsigned BotManager::getSensingUpdateCount(unsigned int botIndex) const { - return m_botInfos[index]->m_word44; + return m_bots[botIndex]->m_word44; } // ELF 0x3DFCC0 (+0x20), unchecked index. -unsigned BotManager::getDecisionMakingBehaviourUpdateCount(unsigned int index) const +unsigned BotManager::getDecisionMakingBehaviourUpdateCount(unsigned int botIndex) const { - return m_botInfos[index]->m_behaviourUpdateCount; + return m_bots[botIndex]->m_behaviourUpdateCount; } // ELF 0x3DFBB0 (+0x30), unchecked index. -double BotManager::getPlanExecutionRunTime(unsigned int index) const +double BotManager::getPlanExecutionRunTime(unsigned int botIndex) const { - return m_botInfos[index]->m_double48; + return m_bots[botIndex]->m_double48; } // ELF 0x3DFBD0 (+0x38), unchecked index. -double BotManager::getDecisionMakingRunTime(unsigned int index) const +double BotManager::getDecisionMakingRunTime(unsigned int botIndex) const { - return m_botInfos[index]->m_double56; + return m_bots[botIndex]->m_double56; } // ELF 0x3DFBF0 (+0x40), unchecked index. -double BotManager::getSensingRunTime(unsigned int index) const +double BotManager::getSensingRunTime(unsigned int botIndex) const { - return m_botInfos[index]->m_double64; + return m_bots[botIndex]->m_double64; } // ELF 0x3DFC10 (+0x14), unchecked index. -bool BotManager::isPathfinding(unsigned int index) const +bool BotManager::isPathfinding(unsigned int botIndex) const { - return m_botInfos[index]->m_flag20; + return m_bots[botIndex]->m_flag20; } // ELF 0x3DFC40 (+0x48), unchecked index. -bool BotManager::getLastPathfindingSucceeded(unsigned int index) const +bool BotManager::getLastPathfindingSucceeded(unsigned int botIndex) const { - return m_botInfos[index]->m_flag72; + return m_bots[botIndex]->m_flag72; } // ELF 0x3DFC70 (+0x49), unchecked index. -bool BotManager::getPathfindingStall(unsigned int index) const +bool BotManager::getPathfindingStall(unsigned int botIndex) const { - return m_botInfos[index]->m_flag73; + return m_bots[botIndex]->m_flag73; } // ELF 0x3DFCA0 (+0x4C), unchecked index. -double BotManager::getLastPathfindingRunTime(unsigned int index) const +double BotManager::getLastPathfindingRunTime(unsigned int botIndex) const { - return m_botInfos[index]->m_double76; + return m_bots[botIndex]->m_double76; } // ELF 0x3E0C40 void BotManager::enableBotScriptDebugger(bool enable) { - for (std::vector::iterator it = m_botInfos.begin(); it != m_botInfos.end(); ++it) + for (std::vector::iterator it = m_bots.begin(); it != m_bots.end(); ++it) (*it)->m_bot->enableBotScriptDebugger(enable); } diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotManager.h b/Code/BF2/AI/AIDLL/AI/Main/BotManager.h index c7d22f7a2..3a1e73c60 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/BotManager.h @@ -50,7 +50,7 @@ class BotManager : public IBotManager, public IBotManagerModifier { explicit BotInfo(Bot* bot); // * +0 - // one dereferences the record: `return *(Bot)m_botInfos[index];`. So the first word + // one dereferences the record: `return *(Bot)m_bots[index];`. So the first word // of a BotInfo is the bot it describes. Bot* m_bot; // +0 unsigned m_word4; // +4 = 0 [UNRESOLVED] @@ -182,18 +182,18 @@ class BotManager : public IBotManager, public IBotManagerModifier virtual double getSystemPathfindingQuotient() const; // +0x0EC virtual double getSystemSensingQuotient() const; // +0x0F0 virtual void resetStatistics(); // +0x0F4 - virtual void resetStatistics(unsigned int index) const; // +0x0F8 - virtual unsigned getPlanExecutionUpdateCount(unsigned int index) const; // +0x0FC - virtual unsigned getDecisionMakingUpdateCount(unsigned int index) const; // +0x100 - virtual unsigned getSensingUpdateCount(unsigned int index) const; // +0x104 - virtual unsigned getDecisionMakingBehaviourUpdateCount(unsigned int index) const; // +0x108 - virtual double getPlanExecutionRunTime(unsigned int index) const; // +0x10C - virtual double getDecisionMakingRunTime(unsigned int index) const; // +0x110 - virtual double getSensingRunTime(unsigned int index) const; // +0x114 - virtual bool isPathfinding(unsigned int index) const; // +0x118 - virtual bool getLastPathfindingSucceeded(unsigned int index) const; // +0x11C - virtual bool getPathfindingStall(unsigned int index) const; // +0x120 - virtual double getLastPathfindingRunTime(unsigned int index) const; // +0x124 + virtual void resetStatistics(unsigned int botIndex) const; // +0x0F8 + virtual unsigned getPlanExecutionUpdateCount(unsigned int botIndex) const; // +0x0FC + virtual unsigned getDecisionMakingUpdateCount(unsigned int botIndex) const; // +0x100 + virtual unsigned getSensingUpdateCount(unsigned int botIndex) const; // +0x104 + virtual unsigned getDecisionMakingBehaviourUpdateCount(unsigned int botIndex) const; // +0x108 + virtual double getPlanExecutionRunTime(unsigned int botIndex) const; // +0x10C + virtual double getDecisionMakingRunTime(unsigned int botIndex) const; // +0x110 + virtual double getSensingRunTime(unsigned int botIndex) const; // +0x114 + virtual bool isPathfinding(unsigned int botIndex) const; // +0x118 + virtual bool getLastPathfindingSucceeded(unsigned int botIndex) const; // +0x11C + virtual bool getPathfindingStall(unsigned int botIndex) const; // +0x120 + virtual double getLastPathfindingRunTime(unsigned int botIndex) const; // +0x124 virtual void enableBotScriptDebugger(bool enable); // +0x128 // population, and not part of either base @@ -213,16 +213,16 @@ class BotManager : public IBotManager, public IBotManagerModifier private: // Three priority queues hold pending bot work. Native container sizes depend on the compiler ABI. - /* 8 */ BotQueue* m_queuePriorityA; - /* 12 */ BotQueue* m_queuePriorityB; - /* 16 */ SensingQueue* m_queueSensing; - /* 20 */ std::list m_bots; // the ctor inserts every preallocated BotMain - /* 24 */ std::vector m_botInfos; // reserve(getMaxNBots) - // Deactivated bot ids in oldest-first order; values index m_botInfos. + /* 8 */ BotQueue* m_planned; // name: AIDLL_r assert 0x101A6170 (PE +8) + /* 12 */ BotQueue* m_unplanned; // name: AIDLL_r assert 0x101A6170 (PE +0xC) + /* 16 */ SensingQueue* m_sensingQueue; // name: AIDLL_r assert 0x101A6810 (PE +0x10) + /* 20 */ std::list m_preallocatedBots; // the ctor inserts every preallocated BotMain [INFERRED] name: AIDLL_r names the BotInfo vector m_bots (0x101A2880) + /* 24 */ std::vector m_bots; // reserve(getMaxNBots) // name: AIDLL_r asserts "botIndex < m_bots.size()" 0x101A2880.. (PE +0x20) + // Deactivated bot ids in oldest-first order; values index m_bots. /* 36 */ std::list m_deactivatedBots; // bot ids, oldest first // [CHOSEN name] Player-id to bot-index table, sized to 256 and initialized to -1. /* 40 */ std::vector m_botByPlayerId; - // actionComAgent's round-robin position in m_botInfos (ELF +0x34 / PE +0x4C); unsigned from + // actionComAgent's round-robin position in m_bots (ELF +0x34 / PE +0x4C); unsigned from // its `jb` wrap test. Name [INFERRED]. /* 52 */ unsigned int m_comAgentCursor; // = 0 /* 56 */ std::list m_list56; // allocate(12) -> a 4-byte element. [UNRESOLVED] type diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp index e0710fcc4..0bfe8edb4 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.cpp @@ -19,7 +19,7 @@ #include "../AIBot/CommunicationAgent.h" #include "../AIKnowledge/Information.h" #include "../AIKnowledge/IPIPhysical.h" -#include "../AIKnowledge/InformationManager.h" +#include "InformationManager.h" #include "../../../AIInterface/BFKnowledge/IAIObject.h" #include "../../../AIInterface/BFKnowledge/BFTimer.h" #include "../../../AIInterface/BFKnowledge/AIPlayer.h" // IAIPlayer @@ -60,8 +60,8 @@ CommunicationHub::~CommunicationHub() void CommunicationHub::reset() { const double never = -1000.0; - m_type2SentTime[0] = never; - m_type2SentTime[1] = never; + m_lastReqPickupSendTime[0] = never; + m_lastReqPickupSendTime[1] = never; m_time44 = never; const int areas = static_cast(AIStrategicObjectManager::getInstance()->getStrategicAreas().size()); if (m_combatStrength[0].empty()) @@ -173,9 +173,9 @@ void CommunicationHub::filterAndSendAIRadioMessage(BotMain*, int senderPlayerId, const double now = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); if (type == 2) { - if (!(20.0f > now - m_type2SentTime[side - 1])) + if (!(20.0f > now - m_lastReqPickupSendTime[side - 1])) { - m_type2SentTime[side - 1] = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); + m_lastReqPickupSendTime[side - 1] = static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime(); } else { diff --git a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h index c61287fcc..e24fdb10c 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h +++ b/Code/BF2/AI/AIDLL/AI/Main/CommunicationHub.h @@ -55,7 +55,7 @@ class CommunicationHub // These timestamps are uninitialized until reset is called. // Game time of each side's last sent type-2 message (indexed side - 1); reset: -1000.0. - /* +4 */ double m_type2SentTime[2]; + /* +4 */ double m_lastReqPickupSendTime[2]; // name: AIDLL_r assert (0x10079AD0) // Two per-side combat-strength vectors. Each original ELF element occupies 12 bytes. /* +20 */ std::vector > m_combatStrength[2]; // enemySpottedByAI: last report of a strength-type 4/5 enemy, either side; reset: -1000.0. diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp b/Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp new file mode 100644 index 000000000..826f6644f --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIMain.cpp @@ -0,0 +1,31 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IAIMain.cpp" (the constructor +// 0x10055900 asserts "!m_instance", "Singleton already created"; asserts are compiled out of retail +// 1.50). Split out of AIMain.cpp; the functions are unchanged. The ELF also keeps them apart from +// AIMain.cpp's functions (0x3E6790.. against AIMain's 0x39xxxx). + +#include "AIMain.h" + +namespace dice { +namespace hfe { +namespace ai { + +// Active IAIMain instance; construction replaces it unconditionally. +IAIMain* IAIMain::m_instance = 0; + +// Construction replaces the active IAIMain pointer. Destruction clears it unconditionally. +// Only one IAIMain may be alive when callers use this singleton. +// ELF 0x3E6790 / 0x3E67C0 +IAIMain::IAIMain() +{ + m_instance = this; +} + +// ELF 0x3E67F0 / 0x3E6820 / 0x3E6850 +IAIMain::~IAIMain() +{ + m_instance = 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp index 9d6a5ce3a..19fc139e0 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfinding.cpp @@ -1,12 +1,11 @@ #include #include "IAIPathfinding.h" +// IAIPathfindingSetup lives in IAIPathfindingSetup.cpp (AIDLL_r __FILE__). namespace { -// The two original translation units are combined here; local object names are [INFERRED]. +// Local object name [INFERRED]. // static init: ELF 0x3E6990 (__tcf_0 0x3E69F0, _GLOBAL__I 0x3E6A20), IAIPathfinding.cpp. std::ios_base::Init pathfindingStreamInit; -// static init: ELF 0x3E6B40 (__tcf_0 0x3E6BA0, _GLOBAL__I 0x3E6BD0), IAIPathfindingSetup.cpp. -std::ios_base::Init pathfindingSetupStreamInit; } namespace dice { @@ -27,29 +26,6 @@ IAIPathfinding::~IAIPathfinding() instance = 0; } -// Setup has its own singleton pointer, replaced on construction and cleared on destruction. -// An AIPathfinding instance publishes both interfaces. -IAIPathfindingSetup* IAIPathfindingSetup::instance = 0; - -IAIPathfindingSetup::IAIPathfindingSetup() -{ - instance = this; -} - -IAIPathfindingSetup::~IAIPathfindingSetup() -{ - instance = 0; -} - -// Stateless map-container interface with no registry entry or custom lifecycle work. -IAIPathfindingSetup::IMapContainer::IMapContainer() -{ -} - -IAIPathfindingSetup::IMapContainer::~IMapContainer() -{ -} - } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp new file mode 100644 index 000000000..e07f2abc8 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp @@ -0,0 +1,42 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IAIPathfindingSetup.cpp" (the +// constructor 0x100CE290 asserts "!instance", "Singleton already created"; asserts are compiled out +// of retail 1.50). Split out of IAIPathfinding.cpp; the functions are unchanged. +#include +#include "IAIPathfinding.h" + +namespace { +// Local object name [INFERRED]. +// static init: ELF 0x3E6B40 (__tcf_0 0x3E6BA0, _GLOBAL__I 0x3E6BD0), IAIPathfindingSetup.cpp. +std::ios_base::Init pathfindingSetupStreamInit; +} + +namespace dice { +namespace hfe { +namespace ai { + +// Setup has its own singleton pointer, replaced on construction and cleared on destruction. +// An AIPathfinding instance publishes both interfaces. +IAIPathfindingSetup* IAIPathfindingSetup::instance = 0; + +IAIPathfindingSetup::IAIPathfindingSetup() +{ + instance = this; +} + +IAIPathfindingSetup::~IAIPathfindingSetup() +{ + instance = 0; +} + +// Stateless map-container interface with no registry entry or custom lifecycle work. +IAIPathfindingSetup::IMapContainer::IMapContainer() +{ +} + +IAIPathfindingSetup::IMapContainer::~IMapContainer() +{ +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp index 04a2da041..5025a7ce3 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/IBotManager.cpp @@ -1,4 +1,5 @@ -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IBotManager.cpp" (constructor 0x100CE370). +// IBotManagerModifier lives in IBotManagerModifier.cpp (AIDLL_r __FILE__). // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining IBotManager operations. #include "IBotManager.h" @@ -8,7 +9,6 @@ namespace hfe { namespace ai { IBotManager* IBotManager::instance = 0; -IBotManagerModifier* IBotManagerModifier::instance = 0; // Each interface publishes its singleton unconditionally and clears it on destruction. // Destroying a displaced manager can clear the pointer to a newer instance. @@ -23,16 +23,6 @@ IBotManager::~IBotManager() instance = 0; } -IBotManagerModifier::IBotManagerModifier() -{ - instance = this; -} - -IBotManagerModifier::~IBotManagerModifier() -{ - instance = 0; -} - } // namespace ai } // namespace hfe } // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/Main/IBotManagerModifier.cpp b/Code/BF2/AI/AIDLL/AI/Main/IBotManagerModifier.cpp new file mode 100644 index 000000000..74757af08 --- /dev/null +++ b/Code/BF2/AI/AIDLL/AI/Main/IBotManagerModifier.cpp @@ -0,0 +1,26 @@ +// Source placement: AIDLL_r.dll __FILE__ "Code\BF2\AI\AIDLL\AI\Main\IBotManagerModifier.cpp" (the +// constructor 0x100DB450 asserts "instance == 0", "IBotManagerModifier is singleton"; asserts are +// compiled out of retail 1.50). Split out of IBotManager.cpp; the functions are unchanged. + +#include "IBotManager.h" + +namespace dice { +namespace hfe { +namespace ai { + +IBotManagerModifier* IBotManagerModifier::instance = 0; + +// Publishes its singleton unconditionally and clears it on destruction, like IBotManager. +IBotManagerModifier::IBotManagerModifier() +{ + instance = this; +} + +IBotManagerModifier::~IBotManagerModifier() +{ + instance = 0; +} + +} // namespace ai +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.cpp similarity index 85% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp rename to Code/BF2/AI/AIDLL/AI/Main/InformationManager.cpp index 7080102c0..82955fa52 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.cpp @@ -1,4 +1,4 @@ -// [INFERRED] Source placement. +// [INFERRED] Source placement: beside its header, whose path AIDLL_r.dll confirms (Main/InformationManager.h). #include "InformationManager.h" diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h similarity index 91% rename from Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h rename to Code/BF2/AI/AIDLL/AI/Main/InformationManager.h index 2d9a4a5ff..99d2870c7 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h @@ -1,6 +1,6 @@ // Handle pool for AI information. The pool does not own the referenced information objects. // [INFERRED] Method names represent the observed pool operations. -// [INFERRED] Source placement. +// Source placement: AIDLL_r.dll __FILE__ "Code/BF2//AI/AIDLL/AI/Main/InformationManager.h" (an inline assert). #ifndef AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONMANAGER_H #define AI_AIDLL_AI_AIKNOWLEDGE_INFORMATIONMANAGER_H diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp index c4370fa5b..7472bc1f2 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFCollisionHandler.cpp @@ -24,7 +24,7 @@ #include "../../../Game/Objects/IObjectTemplateComponent.h" // getClassID +0x10 #include "../../../Game/Objects/Projectiles/GenericProjectile.h" // IProjectileObject's implementor #include "../../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" -#include "../../AIDLL/AI/Main/AIMineManager.h" // minePlaced +0x18 / mineRemoved +0x14 +#include "../../AIDLL/AI/AIKnowledge/AIMineManager.h" // minePlaced +0x18 / mineRemoved +0x14 #include namespace dice { diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp index 8dc64ecda..abd2c4b49 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponObject.cpp @@ -122,7 +122,7 @@ void WeaponObject::init(world::IObject* object) if (projectileTemplate->getComponentFromClassID(world::CID_ResurrectCollisionCompTemplate)) weaponType = WTResurrect; // +0x60 else if (projectileTemplate->getComponentFromClassID(world::CID_StickyCollisionCompTemplate)) - weaponType = WTSticky; + weaponType = WTC4; } float gravityModifier = 1.0f; diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h index 9cb52a47b..aef2bad4b 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/WeaponTemplate.h @@ -18,10 +18,12 @@ namespace ai { class IWeapon; // ai::WeaponType - the name is the mangled parameter type of WeaponTemplate::init; the enumerator -// names are [CHOSEN], from how WeaponObject::init derives each value: a replenishing ammo component -// gives 1 (ReplenishingType RTHeal) or 2 (RTAmmo), a projectile with a resurrect collision component -// gives 3, with a sticky collision component 4 (checked in that order, overriding the ammo answer) -// anything else 0. AIObjectArmament counts only type-0 weapons into a unit's battle strength, and +// names 0..3 are [CHOSEN], from how WeaponObject::init derives each value: a replenishing ammo +// component gives 1 (ReplenishingType RTHeal) or 2 (RTAmmo), a projectile with a resurrect collision +// component gives 3, with a sticky collision component 4 (checked in that order, overriding the ammo +// answer), anything else 0. 4 is DICE's `WTC4`: AIDLL_r.dll (BoosterPack2 debug build) BBC4.cpp asserts +// "wInfo->getWeaponType() == WTC4" ("Expected C4 weapon type"), string at 0x1029E0AC. +// AIObjectArmament counts only type-0 weapons into a unit's battle strength, and // WeaponObject::getReplenishRadius answers only for 1 and 2. enum WeaponType { @@ -29,7 +31,7 @@ enum WeaponType WTHeal = 1, WTAmmo = 2, WTResurrect = 3, - WTSticky = 4 + WTC4 = 4 }; // ai::WeaponGuidingSystem - mangled name attested; enumerators [CHOSEN] after world::TargetSystem diff --git a/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp b/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp index 2858d7dbd..41bf3169d 100644 --- a/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp +++ b/Code/BF2/AI/AIInterface/Main/AIEventListener.cpp @@ -19,7 +19,7 @@ #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/Main/AIEventCourier.h" // IAIEventCourier - 55 named slots #include "../../AIDLL/AI/Main/AISettingsInterfaces.h" // IAISettings::getDraw -#include "../../AIDLL/AI/Main/AIMineManager.h" // IAIMineManager::mineRemoved +#include "../../AIDLL/AI/AIKnowledge/AIMineManager.h" // IAIMineManager::mineRemoved #include "../../../Game/GameServer/ServerSettings.h" // the team-ratio inversion below #include "../../../Scene/Object/PlayerManager.h" // the three lookups it needs #include "../../AIDLL/AI/DrawPrimitives/DPManager.h"// IDPManager::drawAll / nodrawUpdate diff --git a/Code/Build/aidll_sources.txt b/Code/Build/aidll_sources.txt index 05548c92a..0cdd9d5b7 100644 --- a/Code/Build/aidll_sources.txt +++ b/Code/Build/aidll_sources.txt @@ -17,7 +17,7 @@ AI/AIDLL/AI/AIBot/SquadCoordinator.cpp AI/AIDLL/AI/AIBot/SquadFormation.cpp AI/AIDLL/AI/AIBot/SquadManager.cpp AI/AIDLL/AI/AIBot/SquadMember.cpp -AI/AIDLL/AI/AIBotBehaviour/UrgencyMerger.cpp +AI/AIDLL/AI/AIBot/UrgencyMerger.cpp AI/AIDLL/AI/AIBot/WPAltitudeCloseTo.cpp AI/AIDLL/AI/AIBot/WPAltitudeMoveTo.cpp AI/AIDLL/AI/AIBot/WPAltitudePatrol.cpp @@ -28,9 +28,12 @@ AI/AIDLL/AI/AIBot/WPMoveTo.cpp AI/AIDLL/AI/AIBot/WPMoveToBeachLanding.cpp AI/AIDLL/AI/AIBot/WPPatrol.cpp AI/AIDLL/AI/AIBot/SensingAgent.cpp -AI/AIDLL/AI/AIBot/SensingAgentPatterns.cpp +AI/AIDLL/AI/AIBot/SensingAgentMouseFreeLookPattern.cpp +AI/AIDLL/AI/AIBot/SensingAgentNullPattern.cpp +AI/AIDLL/AI/AIBot/SensingAgentSoldierPattern.cpp +AI/AIDLL/AI/AIBot/SensingAgentTurretPattern.cpp AI/AIDLL/AI/AIBot/CommunicationAgent.cpp -AI/AIDLL/AI/AIBot/Aimer.cpp +AI/AIDLL/AI/AIBotActionPlan/Aimer.cpp AI/AIDLL/AI/AIPlanInterpreter/BAPContext.cpp AI/AIDLL/AI/AIPlanInterpreter/PrettyPrinter.cpp # S0 behaviour-system skeleton @@ -298,10 +301,10 @@ AI/AIDLL/AI/AIKnowledge/InformationFactory.cpp AI/AIDLL/AI/AIKnowledge/InformationKnown.cpp AI/AIDLL/AI/AIKnowledge/InformationReal.cpp AI/AIDLL/AI/AIKnowledge/WeaponInfo.cpp -AI/AIDLL/AI/Main/AIMineManager.cpp +AI/AIDLL/AI/AIKnowledge/AIMineManager.cpp AI/AIDLL/AI/AIKnowledge/BFInformationCourier.cpp AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp -AI/AIDLL/AI/AIKnowledge/InformationManager.cpp +AI/AIDLL/AI/Main/InformationManager.cpp AI/AIDLL/AI/Main/BFPathfindingCourier.cpp AI/AIDLL/AI/AIStrategicMap/BFStrategicEnvironment.cpp AI/AIDLL/AI/AIUtils/IgnoreListPredicate.cpp @@ -321,7 +324,7 @@ AI/AIDLL/AI/AIKnowledge/IPIPhysicalKnown.cpp AI/AIDLL/AI/AIKnowledge/IPIPhysicalReal.cpp AI/AIDLL/AI/AIKnowledge/IPIUnit.cpp AI/AIDLL/AI/AIKnowledge/WeaponInfoKnown.cpp -AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.cpp +AI/AIDLL/AI/AIUtils/WeaponInfoManager.cpp AI/AIDLL/AI/AIKnowledge/WeaponInfoReal.cpp Math/DoubleVec3.cpp AI/AIDLL/AI/AIPathFinding/NavMesh/GTSDataOptimiser.cpp @@ -333,7 +336,7 @@ AI/AIDLL/AI/AIPathFinding/NavMesh/QTSearchNodeManager.cpp AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTree.cpp AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeManager.cpp AI/AIDLL/AI/AIPathFinding/NavMesh/QuadTreeNode.cpp -AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.cpp +AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.cpp AI/AIDLL/AI/AIPathFinding/Cluster/Cluster.cpp AI/AIDLL/AI/AIPathFinding/Cluster/ClusterGraph.cpp AI/AIDLL/AI/AIPathFinding/Cluster/ClusterNode.cpp @@ -361,7 +364,7 @@ AI/AIDLL/AI/AIStrategicEntity/GuardPositionBotSCB.cpp AI/AIDLL/AI/AIStrategicEntity/PatrolPath.cpp AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotDCB.cpp AI/AIDLL/AI/AIStrategicEntity/PatrolPathBotSCB.cpp -AI/AIDLL/AI/Main/UserOrderManager.cpp +AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.cpp AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPosition.cpp AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CoverPositionManager.cpp AI/AIDLL/AI/AIStrategicEntity/CoverPosition/CPNode.cpp @@ -384,7 +387,8 @@ AI/AIDLL/AI/AIUtils/Opening.cpp AI/AIInterface/BFKnowledge/PlanePolygon.cpp AI/AIDLL/AI/AIUtils/TraceUtils.cpp AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp -AI/AIDLL/AI/AIBotBehaviour/CustomCurve.cpp +AI/AIDLL/AI/AIUtils/CustomCurve.cpp +AI/AIDLL/AI/AIUtils/SCurve.cpp AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObject3dText.cpp AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectCircle.cpp AI/AIDLL/AI/AIUtils/DebugRendering/DPAIObjectLine.cpp @@ -403,10 +407,11 @@ AI/AIDLL/AI/DrawPrimitives/DrawPrimitive.cpp AI/AIDLL/AI/Main/AICollisionHandler.cpp AI/AIDLL/AI/Main/AIConsole.cpp AI/AIDLL/AI/Main/AIEventCourier.cpp -AI/AIDLL/AI/AIStrategicEntity/AILandingZoneManager.cpp +AI/AIDLL/AI/Main/AILandingZoneManager.cpp AI/AIDLL/AI/AIStrategicEntity/AreaDistanceInfo.cpp AI/AIDLL/AI/Main/AILODManager.cpp AI/AIDLL/AI/Main/AIMain.cpp +AI/AIDLL/AI/Main/IAIMain.cpp AI/AIDLL/AI/Main/AIPathfinding.cpp AI/AIDLL/AI/Main/AIPlayerCourier.cpp AI/AIDLL/AI/Main/AIRadio.cpp @@ -420,12 +425,14 @@ AI/AIDLL/AI/Main/BotManager.cpp AI/AIDLL/AI/Main/BotPlacementManager.cpp AI/AIDLL/AI/Main/CommunicationHub.cpp AI/AIDLL/AI/Main/IAIPathfinding.cpp +AI/AIDLL/AI/Main/IAIPathfindingSetup.cpp AI/AIDLL/AI/Main/StrategyManager.cpp AI/AIDLL/AI/Main/BF2AI.cpp AI/AIDLL/AI/Main/AIModule.cpp AI/AIDLL/AI/Main/AISingletonServer.cpp AI/AIDLL/AI/Main/CommonSingletonServer.cpp AI/AIDLL/AI/Main/IBotManager.cpp +AI/AIDLL/AI/Main/IBotManagerModifier.cpp # the ConsoleClassN base - the ai.init binding Core/ConsoleObjectBase.cpp # demands them (census/00_statically_linked_engine_code.tsv confirms each one is really there) diff --git a/Code/Tests/aidll/action_runtime.h b/Code/Tests/aidll/action_runtime.h index be950c461..8d30cb2ef 100644 --- a/Code/Tests/aidll/action_runtime.h +++ b/Code/Tests/aidll/action_runtime.h @@ -4,7 +4,7 @@ #include "../../BF2/AI/AIDLL/AI/Main/BotManager.h" #include "../../BF2/AI/AIDLL/AI/Main/CommonSingletonServer.h" #include "../../BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h" -#include "../../BF2/AI/AIDLL/AI/Main/AIMineManager.h" +#include "../../BF2/AI/AIDLL/AI/AIKnowledge/AIMineManager.h" #include "../../BF2/AI/AIDLL/AI/AIBot/BotMain.h" #include "../../BF2/AI/AIDLL/AI/AIBot/SquadManager.h" #include "../../BF2/AI/AIDLL/AI/AIStrategic/SAI.h" diff --git a/Code/Tests/aidll/action_runtime.py b/Code/Tests/aidll/action_runtime.py index e5a9be279..349f36130 100644 --- a/Code/Tests/aidll/action_runtime.py +++ b/Code/Tests/aidll/action_runtime.py @@ -58,7 +58,7 @@ def generate(out): {"getNSides": 'return observeSides();'}), ("IBFCollisionHandler", "AI/AIInterface/BFKnowledge/BFCollisionHandler.h", "ObservedCollision", '', {"updateBotProjectiles": 'observeCollision();'}), - ("IAIMineManager", AI + "Main/AIMineManager.h", "ObservedMines", '', + ("IAIMineManager", AI + "AIKnowledge/AIMineManager.h", "ObservedMines", '', {"update": 'trace("mines");'}), ("IAIObjectEnvironment", "AI/AIInterface/BFKnowledge/BFObjectEnvironment.h", "ObservedEnvironment", '', {"damageSeverelyDamagedVehicles": 'trace("damage");'}), diff --git a/Code/Tests/aidll/area_update_runtime.cmd b/Code/Tests/aidll/area_update_runtime.cmd index f6df1b426..658713e81 100644 --- a/Code/Tests/aidll/area_update_runtime.cmd +++ b/Code/Tests/aidll/area_update_runtime.cmd @@ -13,11 +13,12 @@ cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%BF2_AREA_UPDATE_OUT%\a if errorlevel 1 goto failed cl %TASK_FLAGS% /I"%BF2_AREA_UPDATE_OUT%" /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%~dp0area_update_runtime.cpp" /Fo"%BF2_AREA_UPDATE_OUT%\fixture.obj" >>"%BF2_AREA_UPDATE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_AREA_UPDATE_OUT%\pool.obj" >>"%BF2_AREA_UPDATE_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_AREA_UPDATE_OUT%\pool.obj" >>"%BF2_AREA_UPDATE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" /Fo"%BF2_AREA_UPDATE_OUT%\curve.obj" >>"%BF2_AREA_UPDATE_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\CustomCurve.cpp" /Fo"%BF2_AREA_UPDATE_OUT%\curve.obj" >>"%BF2_AREA_UPDATE_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" /Fo"%BF2_AREA_UPDATE_OUT%\SCurve.obj" >>"%BF2_AREA_UPDATE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -link /nologo /OPT:REF /INCREMENTAL:NO /MANIFEST:EMBED /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /SUBSYSTEM:CONSOLE /OUT:"%BF2_AREA_UPDATE_OUT%\area_update_runtime.exe" "%BF2_AREA_UPDATE_OUT%\actual.obj" "%BF2_AREA_UPDATE_OUT%\fixture.obj" "%BF2_AREA_UPDATE_OUT%\pool.obj" "%BF2_AREA_UPDATE_OUT%\curve.obj" >"%BF2_AREA_UPDATE_OUT%\link.log" 2>&1 +link /nologo /OPT:REF /INCREMENTAL:NO /MANIFEST:EMBED /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /SUBSYSTEM:CONSOLE /OUT:"%BF2_AREA_UPDATE_OUT%\area_update_runtime.exe" "%BF2_AREA_UPDATE_OUT%\actual.obj" "%BF2_AREA_UPDATE_OUT%\fixture.obj" "%BF2_AREA_UPDATE_OUT%\pool.obj" "%BF2_AREA_UPDATE_OUT%\curve.obj" "%BF2_AREA_UPDATE_OUT%\SCurve.obj" >"%BF2_AREA_UPDATE_OUT%\link.log" 2>&1 if errorlevel 1 goto failed python -I "%~dp0area_update_runtime.py" run "%BF2_AREA_UPDATE_OUT%\area_update_runtime.exe" exit /b %errorlevel% diff --git a/Code/Tests/aidll/area_update_runtime.h b/Code/Tests/aidll/area_update_runtime.h index b0b30612c..8bcb60a55 100644 --- a/Code/Tests/aidll/area_update_runtime.h +++ b/Code/Tests/aidll/area_update_runtime.h @@ -4,11 +4,11 @@ #include "../../BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h" #include "../../BF2/AI/AIDLL/AI/AIStrategic/SAI.h" #include "../../BF2/AI/AIDLL/AI/AIBot/SquadManager.h" -#include "../../BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h" +#include "../../BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" #include "../../BF2/AI/AIDLL/AI/Main/CommonSingletonServer.h" diff --git a/Code/Tests/aidll/area_update_runtime.py b/Code/Tests/aidll/area_update_runtime.py index e79db0338..6fdc94527 100644 --- a/Code/Tests/aidll/area_update_runtime.py +++ b/Code/Tests/aidll/area_update_runtime.py @@ -85,8 +85,8 @@ def generate(out): lines.append(signature+' { unexpected("'+base+'::'+method+'"); }') lines.append('} } }') (out/'mocks.inl').write_text('\n'.join(lines),encoding='utf-8') - whole=[AI+'AIBotBehaviour/CustomCurve.cpp',AI+'AIBotBehaviour/CustomCurve.h', - AI+'AIKnowledge/InformationManager.cpp',AI+'AIKnowledge/InformationManager.h','Core/SpHandlePool.h'] + whole=[AI+'AIUtils/CustomCurve.cpp',AI+'AIUtils/SCurve.cpp',AI+'AIUtils/SCurve.h',AI+'AIUtils/CustomCurve.h', + AI+'Main/InformationManager.cpp',AI+'Main/InformationManager.h','Core/SpHandlePool.h'] (out/'whole_sources.json').write_text(json.dumps({p:hashlib.sha256((CODE/'BF2'/p).read_bytes()).hexdigest() for p in whole},indent=2)) (out/'fixture_sources.json').write_text(json.dumps({Path(__file__).with_suffix(s).name:hashlib.sha256(Path(__file__).with_suffix(s).read_bytes()).hexdigest() for s in ('.cpp','.h','.py','.cmd')},indent=2)) (out/'cases.json').write_text(json.dumps(MODES,indent=2)) diff --git a/Code/Tests/aidll/bot_selector_runtime.cmd b/Code/Tests/aidll/bot_selector_runtime.cmd index c068d2496..75eb8d4b0 100644 --- a/Code/Tests/aidll/bot_selector_runtime.cmd +++ b/Code/Tests/aidll/bot_selector_runtime.cmd @@ -18,13 +18,14 @@ for %%F in (Information IPIUnit WeaponInfoManager) do ( if errorlevel 1 goto failed ) rem IPIUnit's recovered nonvirtual occupancy helpers require its whole implementation and helpers. -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" /Fo"%BF2_BOT_SELECTOR_OUT%\CustomCurve.obj" >>"%BF2_BOT_SELECTOR_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\CustomCurve.cpp" /Fo"%BF2_BOT_SELECTOR_OUT%\CustomCurve.obj" >>"%BF2_BOT_SELECTOR_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" /Fo"%BF2_BOT_SELECTOR_OUT%\SCurve.obj" >>"%BF2_BOT_SELECTOR_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Core\%%F.cpp" /Fo"%BF2_BOT_SELECTOR_OUT%\%%F.obj" >>"%BF2_BOT_SELECTOR_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed ) -link /nologo /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%BF2_BOT_SELECTOR_OUT%\bot_selector_runtime.exe" "%BF2_BOT_SELECTOR_OUT%\actual.obj" "%BF2_BOT_SELECTOR_OUT%\fixture.obj" "%BF2_BOT_SELECTOR_OUT%\Information.obj" "%BF2_BOT_SELECTOR_OUT%\IPIUnit.obj" "%BF2_BOT_SELECTOR_OUT%\WeaponInfoManager.obj" "%BF2_BOT_SELECTOR_OUT%\CustomCurve.obj" "%BF2_BOT_SELECTOR_OUT%\Debug.obj" "%BF2_BOT_SELECTOR_OUT%\StringUtil.obj" >"%BF2_BOT_SELECTOR_OUT%\link.log" 2>&1 +link /nologo /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%BF2_BOT_SELECTOR_OUT%\bot_selector_runtime.exe" "%BF2_BOT_SELECTOR_OUT%\actual.obj" "%BF2_BOT_SELECTOR_OUT%\fixture.obj" "%BF2_BOT_SELECTOR_OUT%\Information.obj" "%BF2_BOT_SELECTOR_OUT%\IPIUnit.obj" "%BF2_BOT_SELECTOR_OUT%\WeaponInfoManager.obj" "%BF2_BOT_SELECTOR_OUT%\CustomCurve.obj" "%BF2_BOT_SELECTOR_OUT%\SCurve.obj" "%BF2_BOT_SELECTOR_OUT%\Debug.obj" "%BF2_BOT_SELECTOR_OUT%\StringUtil.obj" >"%BF2_BOT_SELECTOR_OUT%\link.log" 2>&1 if errorlevel 1 goto failed python -I "%~dp0bot_selector_runtime.py" run "%BF2_BOT_SELECTOR_OUT%\bot_selector_runtime.exe" exit /b %errorlevel% diff --git a/Code/Tests/aidll/bot_selector_runtime.cpp b/Code/Tests/aidll/bot_selector_runtime.cpp index 60af73a2b..c14fa8bbb 100644 --- a/Code/Tests/aidll/bot_selector_runtime.cpp +++ b/Code/Tests/aidll/bot_selector_runtime.cpp @@ -211,7 +211,7 @@ AIStrategicObject* AIStrategicObjectManager::getClosestObject(const Vec3& positi const int index=points[currentGroup].object; return index<0 ? nullptr : objects[index]; } -SquadCoordinator::SquadCoordinator(int side,int index):m_squadIndex(index),m_side(side),m_i96(0),m_formation(nullptr) +SquadCoordinator::SquadCoordinator(int side,int index):m_squadIndex(index),m_side(side),m_squadLeaderIndex(0),m_formation(nullptr) { m_v108=Vec3{0,0,0}; } SquadMember::SquadMember(SquadCoordinator* squad,IAIPlayer* player,int,int,int):m_isSquadLeader(false),m_player(player),m_squad(squad) {} SquadMember::~SquadMember() {} diff --git a/Code/Tests/aidll/bot_selector_runtime.h b/Code/Tests/aidll/bot_selector_runtime.h index c2564fcec..b46913612 100644 --- a/Code/Tests/aidll/bot_selector_runtime.h +++ b/Code/Tests/aidll/bot_selector_runtime.h @@ -7,7 +7,7 @@ #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" #include "../../BF2/AI/AIDLL/AI/Main/AIDllFrontier.h" #include diff --git a/Code/Tests/aidll/closest_slots_runtime.cpp b/Code/Tests/aidll/closest_slots_runtime.cpp index b7965660a..a00937ad6 100644 --- a/Code/Tests/aidll/closest_slots_runtime.cpp +++ b/Code/Tests/aidll/closest_slots_runtime.cpp @@ -38,7 +38,7 @@ void operator delete(void* pointer, std::size_t) noexcept { ::operator delete(po namespace dice { namespace hfe { namespace ai { // [CHOSEN, not recovered] Native lifetime only. Actual constructor is not under test. SquadFormation::SquadFormation(SquadCoordinator* coordinator) - : m_coordinator(coordinator), m_formation(0), m_direction{}, m_maxSquadMembers(0), + : m_coordinator(coordinator), m_formation(0), m_direction{}, m_numberOfSlots(0), m_b36(false), m_formationMaxSpeed(0), m_side(0), m_i48(0), m_f52(0), m_b56(false), m_v60{}, m_v72{}, m_b84(false), m_b85(false), m_i88(0), m_d92(0), m_trailingPosition{} @@ -47,7 +47,7 @@ SquadFormation::SquadFormation(SquadCoordinator* coordinator) static void fill(Slot& s, int n) { - s.m_occupied = (n & 1) != 0; + s.hasSquadMemberAssigned = (n & 1) != 0; s.m_memberIndex = -1000 - n; s.m_offset = {float(n), float(n + 10), float(n + 20)}; s.m_i20 = n + 30; @@ -57,7 +57,7 @@ static void fill(Slot& s, int n) } static void sameUnswapped(const Slot& a, const Slot& b) { - check(a.m_occupied == b.m_occupied, "occupied retained"); + check(a.hasSquadMemberAssigned == b.hasSquadMemberAssigned, "occupied retained"); check(a.m_offset.x == b.m_offset.x && a.m_offset.y == b.m_offset.y && a.m_offset.z == b.m_offset.z, "offset retained"); check(a.m_i20 == b.m_i20, "i20 retained"); @@ -94,10 +94,10 @@ int SquadFormation::getClosestSlotIndex(int index) if (!std::strcmp(scenario, "same")) return index; if (!std::strcmp(scenario, "zero")) return 0; if (!std::strcmp(scenario, "cross")) return index == 1 ? 2 : -1; - if (!std::strcmp(scenario, "shrink")) { m_maxSquadMembers = 2; return -1; } + if (!std::strcmp(scenario, "shrink")) { m_numberOfSlots = 2; return -1; } if (!std::strcmp(scenario, "grow")) { - if (index == 1) { m_slots.push_back(callbackNewSlot); m_maxSquadMembers = 3; } + if (index == 1) { m_slots.push_back(callbackNewSlot); m_numberOfSlots = 3; } return -1; } if (!std::strcmp(scenario, "replace")) @@ -107,13 +107,13 @@ int SquadFormation::getClosestSlotIndex(int index) } if (!std::strcmp(scenario, "clear_next")) { - if (index == 1) m_slots[2]->m_occupied = false; + if (index == 1) m_slots[2]->hasSquadMemberAssigned = false; return -1; } if (!std::strcmp(scenario, "replace_current")) { m_slots[1] = callbackNewSlot; - m_maxSquadMembers = 2; + m_numberOfSlots = 2; return 2; } std::abort(); @@ -131,7 +131,7 @@ int main(int argc, char** argv) Slot a, b, c, d, e; fill(a, 1); fill(b, 2); fill(c, 3); fill(d, 4); fill(e, 5); f.m_slots = {&a, &b, &c}; - f.m_maxSquadMembers = 3; + f.m_numberOfSlots = 3; const Slot savedA = a, savedB = b, savedC = c, savedD = d, savedE = e; if (!std::strcmp(mode, "swap") || !std::strcmp(mode, "swap_same") || @@ -162,9 +162,9 @@ int main(int argc, char** argv) else if (!std::strcmp(mode, "max_zero") || !std::strcmp(mode, "max_one") || !std::strcmp(mode, "all_free")) { - if (!std::strcmp(mode, "max_zero")) { f.m_slots.clear(); f.m_maxSquadMembers = 0; } - else if (!std::strcmp(mode, "max_one")) { f.m_slots.resize(1); f.m_maxSquadMembers = 1; } - else { b.m_occupied = false; c.m_occupied = false; } + if (!std::strcmp(mode, "max_zero")) { f.m_slots.clear(); f.m_numberOfSlots = 0; } + else if (!std::strcmp(mode, "max_one")) { f.m_slots.resize(1); f.m_numberOfSlots = 1; } + else { b.hasSquadMemberAssigned = false; c.hasSquadMemberAssigned = false; } f.updateClosestSlots(); samePayload(a, savedA); sameUnswapped(a, savedA); check(allocations == 0, "no swap allocation"); @@ -177,7 +177,7 @@ int main(int argc, char** argv) } else if (!std::strcmp(mode, "outer_frontier")) { - b.m_occupied = true; + b.hasSquadMemberAssigned = true; f.updateClosestSlots(); return 92; } @@ -186,10 +186,10 @@ int main(int argc, char** argv) else { scenario = mode; - b.m_occupied = c.m_occupied = d.m_occupied = true; + b.hasSquadMemberAssigned = c.hasSquadMemberAssigned = d.hasSquadMemberAssigned = true; callbackNewSlot = &d; - if (!std::strcmp(mode, "grow")) { f.m_slots.resize(2); f.m_slots.shrink_to_fit(); f.m_maxSquadMembers = 2; } - if (!std::strcmp(mode, "zero") || !std::strcmp(mode, "replace_current")) f.m_maxSquadMembers = 2; + if (!std::strcmp(mode, "grow")) { f.m_slots.resize(2); f.m_slots.shrink_to_fit(); f.m_numberOfSlots = 2; } + if (!std::strcmp(mode, "zero") || !std::strcmp(mode, "replace_current")) f.m_numberOfSlots = 2; f.updateClosestSlots(); check(count >= 1 && observed[0] == 1, "slot zero skipped"); check(observedMember[0] == savedB.m_memberIndex, "first input slot member"); diff --git a/Code/Tests/aidll/coordinator_tail_runtime.cpp b/Code/Tests/aidll/coordinator_tail_runtime.cpp index 72d21e4c8..442ffe576 100644 --- a/Code/Tests/aidll/coordinator_tail_runtime.cpp +++ b/Code/Tests/aidll/coordinator_tail_runtime.cpp @@ -93,11 +93,11 @@ AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int id, float : AIStrategicObject(radius, 0.0f), m_name(name), m_controlPointId(id) {} AIStrategicArea::~AIStrategicArea() {} SquadCoordinator::SquadCoordinator(int side, int index) - : m_squadIndex(index), m_side(side), m_strategicAreaAssignment(nullptr), m_i40(4), m_i96(0), + : m_squadIndex(index), m_side(side), m_strategicAreaAssignment(nullptr), m_i40(4), m_squadLeaderIndex(0), m_formation(nullptr), m_d124(0.0), m_b172(false), m_b196(false), m_needOrderMessageTimer(100.0) { m_v28 = {}; m_v108 = {4, 4, 4}; m_v176 = {}; m_d188 = 0.0; } SquadFormation::SquadFormation(SquadCoordinator* coordinator) - : m_coordinator(coordinator), m_maxSquadMembers(6), m_b56(false), m_b84(false), m_b85(false), m_d92(0.0) + : m_coordinator(coordinator), m_numberOfSlots(6), m_b56(false), m_b84(false), m_b85(false), m_d92(0.0) { m_v60 = {}; m_v72 = {1, 2, 3}; } SquadMember::SquadMember(SquadCoordinator* squad, IAIPlayer* player, int squadIndex, int side, int index) : m_squadIndex(squadIndex), m_memberIndex(index), m_isSquadLeader(false), m_playerId(0), m_player(player), @@ -188,7 +188,7 @@ int main(int argc, char** argv) for (int i = 0; i < 4; ++i) m[i].m_position = {10.0f * i + 1, 2, 3}; std::string expected; if (mode == "position_anchor") { fx.slots[0].m_memberIndex = 2; expected = "alive2"; } - else if (mode == "position_leader") { fx.slots[0].m_memberIndex = -1; squad.m_i96 = 1; expected = "alive1"; } + else if (mode == "position_leader") { fx.slots[0].m_memberIndex = -1; squad.m_squadLeaderIndex = 1; expected = "alive1"; } else if (mode == "position_first_alive") { alive = [](int id) { return id == 2; }; @@ -208,7 +208,7 @@ int main(int argc, char** argv) else if (mode.rfind("shots_", 0) == 0) { squad.m_d124 = 50.0; - fx.slots[0].m_occupied = true; // make the forced movement update observable + fx.slots[0].hasSquadMemberAssigned = true; // make the forced movement update observable int resets = 0; std::size_t left = 0; if (mode == "shots_empty") {} else if (mode == "shots_invalid") { m[1].m_positionValid = false; squad.m_list12.push_back(fire(&m[1], 60.0, m[1].m_position)); } diff --git a/Code/Tests/aidll/coordinator_tick_runtime.cpp b/Code/Tests/aidll/coordinator_tick_runtime.cpp index 7a54f50df..e353c5d15 100644 --- a/Code/Tests/aidll/coordinator_tick_runtime.cpp +++ b/Code/Tests/aidll/coordinator_tick_runtime.cpp @@ -42,7 +42,7 @@ namespace dice { namespace hfe { namespace ai { // [CHOSEN, not recovered] Native field/STL lifetimes without publication or deep construction. SquadCoordinator::SquadCoordinator(int side, int index) : m_squadIndex(index), m_side(side), m_strategicAreaAssignment(nullptr), m_i40(4), - m_i44(789), m_formation(nullptr), m_i120(0), m_d124(-999.0) {} + m_i44(789), m_formation(nullptr), m_missionStatus(0), m_d124(-999.0) {} SquadMember::SquadMember(SquadCoordinator* squad, IAIPlayer* player, int squadIndex, int side, int index) : m_squadIndex(squadIndex), m_memberIndex(index), m_player(player), m_bot(nullptr), m_squad(squad), m_side(side), m_havePath(true), m_request(nullptr), m_flag4A(false) {} @@ -205,7 +205,7 @@ int main(int argc, char** argv) } else { - if (mode == "empty") squad.m_i120 = 258; + if (mode == "empty") squad.m_missionStatus = 258; else if (mode == "timestamp_bits") { const unsigned long long bits = 0x7ff8000000001234ULL; @@ -252,7 +252,7 @@ int main(int argc, char** argv) } else { - squad.m_i120 = 2; squad.m_i40 = 0; squad.m_strategicAreaAssignment = &area; + squad.m_missionStatus = 2; squad.m_i40 = 0; squad.m_strategicAreaAssignment = &area; area.m_status[0] = area.m_status[1] = StatusMap::Hostile; expectedCalls = "m0:1,c0"; if (mode == "commander") @@ -341,7 +341,7 @@ int main(int argc, char** argv) require(calls == expectedCalls, "exact query order and arguments"); if (tail) require(squad.m_i44 == 789, "no unassignment on a tail case"); else if (expectedUnassigned) - require(!squad.m_strategicAreaAssignment && squad.m_i40 == 4 && squad.m_i44 == 0 && squad.m_i120 == 0, + require(!squad.m_strategicAreaAssignment && squad.m_i40 == 4 && squad.m_i44 == 0 && squad.m_missionStatus == 0, "all four real unassignment stores"); else require(squad.m_i44 == 789, "no unassignment when refused"); } diff --git a/Code/Tests/aidll/destroyable_map_part_runtime.cpp b/Code/Tests/aidll/destroyable_map_part_runtime.cpp index 56f0cd864..ab3871194 100644 --- a/Code/Tests/aidll/destroyable_map_part_runtime.cpp +++ b/Code/Tests/aidll/destroyable_map_part_runtime.cpp @@ -58,14 +58,14 @@ struct TreeVertexCountTag typedef unsigned int QuadTree::* type; friend type access(TreeVertexCountTag); }; -template struct PrivateMember; +template struct PrivateMember; struct TreeVertexIndexCountTag { typedef unsigned int QuadTree::* type; friend type access(TreeVertexIndexCountTag); }; -template struct PrivateMember; +template struct PrivateMember; struct TreePolygonsTag { @@ -199,10 +199,10 @@ struct TreeFixture unexpected("fixture float/double vertex counts differ"); NavPolygon polygon; - polygon.m_numberOfVertices = static_cast(floatVertices.size()); + polygon.vertexCount = static_cast(floatVertices.size()); polygon.m_material = material; - polygon.m_cluster = cluster; - polygon.m_firstIndex = static_cast(indices.size()); + polygon.cluster = cluster; + polygon.vertexOffset = static_cast(indices.size()); polygon.m_normal.x = 0.0f; polygon.m_normal.y = 1.0f; polygon.m_normal.z = 0.0f; @@ -593,8 +593,8 @@ void testManagerPairingAndForwarders() secondGraph.fill(0x52); QuadTreeManager* manager = new QuadTreeManager; - manager->m_islands.push_back(std::make_pair(first.tree, firstGraph.graph)); - manager->m_islands.push_back(std::make_pair(second.tree, secondGraph.graph)); + manager->m_quadTrees.push_back(std::make_pair(first.tree, firstGraph.graph)); + manager->m_quadTrees.push_back(std::make_pair(second.tree, secondGraph.graph)); manager->initializeDestroyableMapPart(0, false, minimum, maximum, transform); CHECK(parts(*first.tree).size() == 1); CHECK(parts(*second.tree).size() == 1); @@ -644,15 +644,15 @@ void testManagerPairingAndForwarders() empty->restoreMapPart(0); empty->resetOriginalMaterialOfDestroyableMapPart(0); empty->resetDestroyableMapParts(); - CHECK(empty->m_islands.empty()); + CHECK(empty->m_quadTrees.empty()); TreeFixture noPolygonsA(0); TreeFixture noPolygonsB(1); noPolygonsA.publish(); noPolygonsB.publish(); QuadTreeManager* emptyTrees = new QuadTreeManager; - emptyTrees->m_islands.push_back(std::make_pair(noPolygonsA.tree, firstGraph.graph)); - emptyTrees->m_islands.push_back(std::make_pair(noPolygonsB.tree, secondGraph.graph)); + emptyTrees->m_quadTrees.push_back(std::make_pair(noPolygonsA.tree, firstGraph.graph)); + emptyTrees->m_quadTrees.push_back(std::make_pair(noPolygonsB.tree, secondGraph.graph)); emptyTrees->initializeDestroyableMapPart(0, true, minimum, maximum, transform); CHECK(parts(*noPolygonsA.tree).size() == 1); CHECK(parts(*noPolygonsB.tree).size() == 1); @@ -676,8 +676,8 @@ void testManagerAscendingOrder() firstGraph.state(0) = 0x61; secondGraph.state(0) = 0x62; QuadTreeManager* manager = new QuadTreeManager; - manager->m_islands.push_back(std::make_pair(fixture.tree, firstGraph.graph)); - manager->m_islands.push_back(std::make_pair(fixture.tree, secondGraph.graph)); + manager->m_quadTrees.push_back(std::make_pair(fixture.tree, firstGraph.graph)); + manager->m_quadTrees.push_back(std::make_pair(fixture.tree, secondGraph.graph)); manager->destroyMapPart(0); // The first island destroys the shared record; the second sees destroyed=true and does nothing. CHECK(firstGraph.state(0) == 0); diff --git a/Code/Tests/aidll/formation_membership_runtime.cpp b/Code/Tests/aidll/formation_membership_runtime.cpp index 1a2ba1967..d66f7dcde 100644 --- a/Code/Tests/aidll/formation_membership_runtime.cpp +++ b/Code/Tests/aidll/formation_membership_runtime.cpp @@ -39,7 +39,7 @@ void* CommonSingletonServer::m_iBFTimer = nullptr; IBFTimer::IBFTimer() {} IBFTimer::~IBFTimer() {} SquadFormation::SquadFormation(SquadCoordinator* squad) - : m_coordinator(squad), m_maxSquadMembers(6), m_b56(true), m_d92(-9.0) + : m_coordinator(squad), m_numberOfSlots(6), m_b56(true), m_d92(-9.0) { m_v60 = {-8,-9,-10}; m_v72 = {11,12,13}; m_trailingPosition = {21,22,23}; } SquadCoordinator::SquadCoordinator(int side, int index) : m_squadIndex(index), m_side(side), m_formation(nullptr) @@ -54,16 +54,16 @@ SquadMember::~SquadMember() {} static bool equal(Vec3 a, Vec3 b) { return a.x == b.x && a.y == b.y && a.z == b.z; } static void resetExpected(SquadFormation::Slot& s) -{ s.m_occupied=false; s.m_memberIndex=-1; s.m_i20=-1; s.m_b24=false; s.m_i28=0; } +{ s.hasSquadMemberAssigned=false; s.m_memberIndex=-1; s.m_i20=-1; s.m_b24=false; s.m_i28=0; } static void movedExpected(SquadFormation::Slot& to, const SquadFormation::Slot& from, bool copyPosition) { - to.m_occupied=from.m_occupied; to.m_memberIndex=from.m_memberIndex; + to.hasSquadMemberAssigned=from.hasSquadMemberAssigned; to.m_memberIndex=from.m_memberIndex; to.m_i20=from.m_i20; to.m_b24=from.m_b24; to.m_i28=from.m_i28; if (copyPosition) to.m_offset=from.m_offset; } static void compareSlot(const SquadFormation::Slot& actual, const SquadFormation::Slot& expected) { - require(actual.m_occupied==expected.m_occupied, "occupied field"); + require(actual.hasSquadMemberAssigned==expected.hasSquadMemberAssigned, "occupied field"); require(actual.m_memberIndex==expected.m_memberIndex, "member identity field"); require(actual.m_i20==expected.m_i20, "slot index field"); require(actual.m_b24==expected.m_b24, "slot Boolean payload"); @@ -91,18 +91,18 @@ int main(int argc, char** argv) { members[i].m_bot=reinterpret_cast(&botIdentity); squad.m_squadMembers.push_back(&members[i]); - slots[i].m_occupied=true; slots[i].m_memberIndex=i; + slots[i].hasSquadMemberAssigned=true; slots[i].m_memberIndex=i; slots[i].m_i20=100+i; slots[i].m_b24=(i&1)!=0; slots[i].m_i28=20.25f+i; slots[i].m_offset={30.0f+i,40.0f+i,50.0f+i}; slots[i].m_referenceSlot=200+i; formation.m_slots.push_back(&slots[i]); - formation.m_slotTargets.push_back({true,{300.0f+i,400.0f+i,500.0f+i}}); + formation.m_trailingPositions.push_back({true,{300.0f+i,400.0f+i,500.0f+i}}); } if (mode=="membership") { - formation.m_maxSquadMembers=0; + formation.m_numberOfSlots=0; require(!formation.isInFormation(0), "zero count returns false without slots"); - formation.m_maxSquadMembers=3; - slots[1].m_occupied=false; slots[1].m_memberIndex=-1; + formation.m_numberOfSlots=3; + slots[1].hasSquadMemberAssigned=false; slots[1].m_memberIndex=-1; require(formation.isInFormation(-1), "unoccupied minus-one slot matches"); require(formation.isInFormation(2) && !formation.isInFormation(5), "captured count bounds scan"); slots[2].m_memberIndex=(std::numeric_limits::min)(); @@ -114,7 +114,7 @@ int main(int argc, char** argv) for(int i=0;i<6;++i) expected[i]=slots[i]; resetExpected(expected[3]); formation.resetSlot(3); for(int i=0;i<6;++i) compareSlot(slots[i],expected[i]); - require(clockCalls==0 && formation.m_slotTargets[3].first, "reset leaves timer and target flag"); + require(clockCalls==0 && formation.m_trailingPositions[3].first, "reset leaves timer and target flag"); } else { @@ -124,10 +124,10 @@ int main(int argc, char** argv) else if(mode=="last") removed=5; else if(mode=="middle" || mode=="duplicate" || mode=="timer_mutation") { removed=2; selected=5; if(mode=="duplicate") slots[4].m_memberIndex=2; } - else if(mode=="next_empty") { removed=2; slots[3].m_occupied=false; } + else if(mode=="next_empty") { removed=2; slots[3].hasSquadMemberAssigned=false; } else if(mode=="only_zero" || mode=="zero_two" || mode=="trailing_stop") { - for(int i=(mode=="only_zero"?1:2);i<6;++i) slots[i].m_occupied=false; + for(int i=(mode=="only_zero"?1:2);i<6;++i) slots[i].hasSquadMemberAssigned=false; resetTrailing=true; if(mode!="only_zero") selected=1; if(mode=="trailing_stop") squad.m_v108={1,0,0}; @@ -188,7 +188,7 @@ int main(int argc, char** argv) if(resetTrailing) for(auto& s:expected) s.m_i20=-1; if(mode=="timer_mutation") clockCallback=[&] { - require(slots[2].m_memberIndex==5 && !slots[5].m_occupied && !members[5].m_havePath, "all moves and path invalidation before clock"); + require(slots[2].m_memberIndex==5 && !slots[5].hasSquadMemberAssigned && !members[5].m_havePath, "all moves and path invalidation before clock"); formation.m_v72={77,78,79}; }; formation.leaveFormation(removed); @@ -197,14 +197,14 @@ int main(int argc, char** argv) { compareSlot(slots[i],expected[i]); require(formation.m_slots[i]==&slots[i], "slot pointers not moved or replaced"); - require(formation.m_slotTargets[i].first==!resetTrailing, "only trailing reset clears target flags"); - require(equal(formation.m_slotTargets[i].second,{300.0f+i,400.0f+i,500.0f+i}), "target positions untouched"); + require(formation.m_trailingPositions[i].first==!resetTrailing, "only trailing reset clears target flags"); + require(equal(formation.m_trailingPositions[i].second,{300.0f+i,400.0f+i,500.0f+i}), "target positions untouched"); const bool moved=(selected==i || replacement==i); require(members[i].m_havePath==!moved && members[i].m_flag4A==moved, "only moved members get both real path flags"); } require(equal(formation.m_trailingPosition,resetTrailing?Vec3{11,12,13}:Vec3{21,22,23}), "trailing position reset policy"); - require(clockCalls==(slots[0].m_occupied?1:0), "movement timer only for occupied slot0"); - if(slots[0].m_occupied) + require(clockCalls==(slots[0].hasSquadMemberAssigned?1:0), "movement timer only for occupied slot0"); + if(slots[0].hasSquadMemberAssigned) require(formation.m_b56 && formation.m_d92==10.125+0.2 && equal(formation.m_v60,formation.m_v72), "forced movement timestamp and fresh position"); else require(formation.m_b56 && formation.m_d92==-9.0 && equal(formation.m_v60,{-8,-9,-10}), "empty slot0 preserves previous movement state"); } diff --git a/Code/Tests/aidll/formation_tick_runtime.cpp b/Code/Tests/aidll/formation_tick_runtime.cpp index 363a10e31..ae9d3574a 100644 --- a/Code/Tests/aidll/formation_tick_runtime.cpp +++ b/Code/Tests/aidll/formation_tick_runtime.cpp @@ -39,7 +39,7 @@ static std::uint32_t toBits(float value){std::uint32_t bits;std::memcpy(&bits,&v static Vec3 vecBits(std::uint32_t x,std::uint32_t y,std::uint32_t z){return Vec3{fromBits(x),fromBits(y),fromBits(z)};} static void sameSlot(const SquadFormation::Slot& a,const SquadFormation::Slot& b) { - require(a.m_occupied==b.m_occupied,"occupied");require(a.m_memberIndex==b.m_memberIndex,"member index"); + require(a.hasSquadMemberAssigned==b.hasSquadMemberAssigned,"occupied");require(a.m_memberIndex==b.m_memberIndex,"member index"); require(equal(a.m_offset,b.m_offset),"offset unchanged");require(a.m_i20==b.m_i20,"trailing index"); require(a.m_b24==b.m_b24,"flag24");require(a.m_i28==b.m_i28,"float28"); require(a.m_referenceSlot==b.m_referenceSlot,"reference slot unchanged"); @@ -65,11 +65,11 @@ void* CommonSingletonServer::m_iBFTimer=nullptr; IBFTimer::IBFTimer(){} IBFTimer::~IBFTimer(){} IAIPlayer::~IAIPlayer(){} SquadFormation::SquadFormation(SquadCoordinator* c) - :m_coordinator(c),m_formation(3),m_maxSquadMembers(6),m_b36(false),m_formationMaxSpeed(17), + :m_coordinator(c),m_formation(3),m_numberOfSlots(6),m_b36(false),m_formationMaxSpeed(17), m_side(0),m_i48(77),m_f52(2),m_b56(true),m_b84(false),m_b85(false),m_i88(88),m_d92(30) {m_direction={1,2,3};m_v60={4,5,6};m_v72={7,8,9};m_trailingPosition={10,11,12};} SquadCoordinator::SquadCoordinator(int side,int index) - :m_squadIndex(index),m_side(side),m_formation(nullptr),m_i96(4) + :m_squadIndex(index),m_side(side),m_formation(nullptr),m_squadLeaderIndex(4) {m_v108={};} SquadMember::SquadMember(SquadCoordinator* c,IAIPlayer* p,int squad,int side,int index) :m_squadIndex(squad),m_memberIndex(index),m_player(p),m_bot(nullptr),m_squad(c),m_side(side), @@ -77,7 +77,7 @@ SquadMember::SquadMember(SquadCoordinator* c,IAIPlayer* p,int squad,int side,int {m_position={};} SquadMember::~SquadMember(){} #if defined(LEAF_OBSERVERS) -SquadMember* SquadCoordinator::getSquadLeader(){event("leader",nullptr,this);return m_squadMembers[m_i96];} +SquadMember* SquadCoordinator::getSquadLeader(){event("leader",nullptr,this);return m_squadMembers[m_squadLeaderIndex];} void SquadCoordinator::getSquadPosition(Vec3& p){event("squadpos",nullptr,this);p=m_v108;} SquadMember* SquadCoordinator::getSquadMember(int i){event("member"+std::to_string(i),nullptr,this);return m_squadMembers[i];} bool SquadCoordinator::squadHasPosition(){event("valid",nullptr,this);return false;} @@ -120,7 +120,7 @@ struct State { other.m_squadMembers.push_back(&members[i]);slots[i].m_memberIndex=i;slots[i].m_i20=100+i; slots[i].m_b24=true;slots[i].m_i28=20.25f+i;slots[i].m_referenceSlot=200+i; slots[i].m_offset={30.0f+i,40.0f+i,50.0f+i}; - f.m_slots.push_back(&slots[i]);f.m_slotTargets.push_back({true,{60.0f+i,70.0f+i,80.0f+i}});path[i]=true; + f.m_slots.push_back(&slots[i]);f.m_trailingPositions.push_back({true,{60.0f+i,70.0f+i,80.0f+i}});path[i]=true; } squad.m_formation=&f;tested=&f; } @@ -130,8 +130,8 @@ struct State { void verify(){ for(int i=0;i<6;++i){sameSlot(slots[i],expected[i]);require(members[i].m_havePath==path[i],"path state"); require(members[i].m_flag4A==!path[i],"inverse path state"); - require(f.m_slotTargets[i].first==!reset,"target valid state"); - require(equal(f.m_slotTargets[i].second,{60.0f+i,70.0f+i,80.0f+i}),"target coordinates retained");} + require(f.m_trailingPositions[i].first==!reset,"target valid state"); + require(equal(f.m_trailingPositions[i].second,{60.0f+i,70.0f+i,80.0f+i}),"target coordinates retained");} require(equal(f.m_trailingPosition,reset?f.m_v72:Vec3{10,11,12}),"trailing position copy"); require(f.m_b85==expected85,"only promotion clears flag85"); require(f.m_i88==expectedCycle&&f.m_formation==expectedFormation,"scheduler suffix state"); @@ -139,7 +139,7 @@ struct State { // Expected m_i20 per slot after a trailing-slot re-deal; everything else must be untouched. void verifyTrailIndices(const int (&indices)[6]){ for(int i=0;i<6;++i){SquadFormation::Slot want=expected[i];want.m_i20=indices[i];sameSlot(slots[i],want);} - for(int i=0;i<6;++i)require(f.m_slotTargets[i].first&&equal(f.m_slotTargets[i].second,{60.0f+i,70.0f+i,80.0f+i}),"trail slots leave crumbs alone"); + for(int i=0;i<6;++i)require(f.m_trailingPositions[i].first&&equal(f.m_trailingPositions[i].second,{60.0f+i,70.0f+i,80.0f+i}),"trail slots leave crumbs alone"); require(equal(f.m_trailingPosition,{10,11,12}),"trail slots leave the newest crumb alone"); } }; @@ -167,13 +167,13 @@ int main(int argc,char** argv) #elif defined(LEAF_OBSERVERS) std::string expectedTrace="leader,index,bot,squadpos";int paths=0; if(mode=="entry_capture"){ - f.m_maxSquadMembers=0; + f.m_numberOfSlots=0; hook=[&](const std::string& n,SquadMember* m,SquadCoordinator* c){ if(n=="index"){require(m==&s.members[4],"entry leader retained");s.squad.m_squadMembers[4]=&s.members[5];} if(n=="bot"){require(m==&s.members[4],"same leader after roster replacement");f.m_coordinator=&s.other;} if(n=="squadpos")require(c==&s.other,"fresh coordinator for position");}; }else if(mode.rfind("near_",0)==0){ - s.slots[0].m_occupied=true;s.slots[2].m_occupied=true;s.slots[2].m_memberIndex=4; + s.slots[0].hasSquadMemberAssigned=true;s.slots[2].hasSquadMemberAssigned=true;s.slots[2].m_memberIndex=4; s.members[4].m_position={1,0,0}; if(mode=="near_flag")s.members[4].m_position={100,0,0}; expectedTrace+=",position,member4,path,member0,path,reset"; @@ -193,7 +193,7 @@ int main(int argc,char** argv) if(n=="reset")require(paths==2,"reset after two path clears"); }; }else if(mode=="hidden_pointers"||mode=="hidden_indices"){ - s.slots[0].m_occupied=s.slots[5].m_occupied=true;s.slots[0].m_memberIndex=4;f.m_b84=true; + s.slots[0].hasSquadMemberAssigned=s.slots[5].hasSquadMemberAssigned=true;s.slots[0].m_memberIndex=4;f.m_b84=true; expectedTrace+=mode=="hidden_indices"?",reset,member3,path,member2,path":",reset,member5,path,member4,path"; hook=[&](const std::string& n,SquadMember*,SquadCoordinator*){ if(n=="reset"){ @@ -204,12 +204,12 @@ int main(int argc,char** argv) } }; }else if(mode=="match_live"||mode=="match_retained"||mode=="match_clear_order"){ - s.slots[0].m_occupied=s.slots[1].m_occupied=true;s.members[0].m_bot=nullptr; - if(mode=="match_live"){s.members[1].m_bot=nullptr;f.m_maxSquadMembers=2;} + s.slots[0].hasSquadMemberAssigned=s.slots[1].hasSquadMemberAssigned=true;s.members[0].m_bot=nullptr; + if(mode=="match_live"){s.members[1].m_bot=nullptr;f.m_numberOfSlots=2;} expectedTrace+=mode=="match_live"?",member0,bot,member1,bot,member2,bot,member2,path,reset":",member0,bot,member1,bot,member1,path,reset"; hook=[&](const std::string& n,SquadMember* m,SquadCoordinator*){ if(n=="bot"&&m==&s.members[1]){ - if(mode=="match_live"){f.m_maxSquadMembers=3;s.slots[2].m_occupied=true;f.m_slots.reserve(64);} + if(mode=="match_live"){f.m_numberOfSlots=3;s.slots[2].hasSquadMemberAssigned=true;f.m_slots.reserve(64);} if(mode=="match_retained"){s.spare=s.slots[1];s.spare.m_memberIndex=3;f.m_slots[1]=&s.spare;} } if(n=="path"){++paths;require(!s.members[0].m_flag4A,"only new zero path clears");} @@ -238,14 +238,14 @@ int main(int argc,char** argv) if(axis==0){a.x=50;b.x=std::ldexp(1.0f,-22);}if(axis==1){a.y=50;b.y=std::ldexp(1.0f,-22);}if(axis==2){a.z=50;b.z=std::ldexp(1.0f,-22);}} require(fixtureFormationRange(a,b)==expected,"wide delta and ordered strict range"); }else if(mode.rfind("wait_",0)==0){ - if(mode=="wait_zero")f.m_maxSquadMembers=0; - if(mode=="wait_skip_zero")s.slots[0].m_occupied=true; - if(mode=="wait_occupied_stop")s.slots[3].m_occupied=true; + if(mode=="wait_zero")f.m_numberOfSlots=0; + if(mode=="wait_skip_zero")s.slots[0].hasSquadMemberAssigned=true; + if(mode=="wait_occupied_stop")s.slots[3].hasSquadMemberAssigned=true; s.snapshot();abortCheck=[&]{require(f.m_b36,"wait flag written before occupied frontier");s.verify();require(clockCalls==0,"no timer before frontier");}; f.updateWaitForSquadMembers(originalTime);require(f.m_b36,"wait flag true");s.verify();require(clockCalls==0,"empty wait skips timing"); }else if(mode=="scheduler_slot_stop"||mode=="scheduler_speed_stop"){ - if(mode=="scheduler_slot_stop"){s.slots[0].m_occupied=true;s.squad.m_v108={1,0,0};} - if(mode=="scheduler_speed_stop")s.slots[0].m_occupied=true; + if(mode=="scheduler_slot_stop"){s.slots[0].hasSquadMemberAssigned=true;s.squad.m_v108={1,0,0};} + if(mode=="scheduler_speed_stop")s.slots[0].hasSquadMemberAssigned=true; s.snapshot();abortCheck=[&]{ require(f.m_i88==88&&f.m_formation==3,"suffix counter/selection untouched"); if(mode=="scheduler_slot_stop")require(!f.m_b36&&f.m_b56&&f.m_formationMaxSpeed==17&&clockCalls==0,"first nested stop prevents following helpers"); @@ -288,7 +288,7 @@ int main(int argc,char** argv) require(vehicleCalls==0&&calls.empty(),"empty anchor returns before any member or owner call"); require(f.m_i48==77&&f.m_f52==2,"forward vector untouched"); }else{ - s.slots[0].m_occupied=true;s.slots[0].m_memberIndex=2;s.members[2].m_player=&player; + s.slots[0].hasSquadMemberAssigned=true;s.slots[0].m_memberIndex=2;s.members[2].m_player=&player; abortCheck=[&]{require(vehicleCalls==1&&vehiclePlayer==&player,"anchor member's player gives its current vehicle once"); require(f.m_i48==77&&f.m_f52==2,"no forward write before the owner query");}; f.updateFormationForwardVector();unexpected("occupied forward vector should stop"); @@ -299,44 +299,44 @@ int main(int argc,char** argv) else if(mode=="trail_nan_anchor")f.m_v72={std::numeric_limits::quiet_NaN(),0,0}; else if(mode=="trail_seed"){f.m_trailingPosition={0,0,0};seeded=true;} else if(mode=="trail_unoccupied"){} - else if(mode=="trail_equal"){s.slots[0].m_occupied=true;f.m_trailingPosition={13,8,9};} + else if(mode=="trail_equal"){s.slots[0].hasSquadMemberAssigned=true;f.m_trailingPosition={13,8,9};} else if(mode=="trail_far"||mode=="trail_one_slot"){ - s.slots[0].m_occupied=true;f.m_trailingPosition={13.5f,8,9};shifted=true; - f.m_slotTargets[2].first=false;f.m_slotTargets[4].first=false; - if(mode=="trail_one_slot")f.m_maxSquadMembers=1; + s.slots[0].hasSquadMemberAssigned=true;f.m_trailingPosition={13.5f,8,9};shifted=true; + f.m_trailingPositions[2].first=false;f.m_trailingPositions[4].first=false; + if(mode=="trail_one_slot")f.m_numberOfSlots=1; }else unexpected("trail mode"); - s.snapshot();const auto oldTargets=f.m_slotTargets;const Vec3 before=f.m_trailingPosition; + s.snapshot();const auto oldTargets=f.m_trailingPositions;const Vec3 before=f.m_trailingPosition; f.updateTrailingPositions(); for(int i=0;i<6;++i)sameSlot(s.slots[i],s.expected[i]); require(clockCalls==0,"no clock in the breadcrumb pass"); if(seeded){require(equal(f.m_trailingPosition,f.m_v72),"unset crumb seeded from the anchor"); - for(int i=0;i<6;++i)require(sameTarget(f.m_slotTargets[i],oldTargets[i]),"seed leaves the history");} + for(int i=0;i<6;++i)require(sameTarget(f.m_trailingPositions[i],oldTargets[i]),"seed leaves the history");} else if(shifted){ const int moved=mode=="trail_one_slot"?0:5; - for(int i=1;i<6;++i)require(sameTarget(f.m_slotTargets[i],i<=moved?oldTargets[i-1]:oldTargets[i]),"history shifts back one place"); - require(f.m_slotTargets[0].first&&equal(f.m_slotTargets[0].second,before),"old crumb pushed at the front"); + for(int i=1;i<6;++i)require(sameTarget(f.m_trailingPositions[i],i<=moved?oldTargets[i-1]:oldTargets[i]),"history shifts back one place"); + require(f.m_trailingPositions[0].first&&equal(f.m_trailingPositions[0].second,before),"old crumb pushed at the front"); require(equal(f.m_trailingPosition,f.m_v72),"anchor becomes the newest crumb"); }else{ require(equal(f.m_trailingPosition,before),"crumb unchanged"); - for(int i=0;i<6;++i)require(sameTarget(f.m_slotTargets[i],oldTargets[i]),"history unchanged"); + for(int i=0;i<6;++i)require(sameTarget(f.m_trailingPositions[i],oldTargets[i]),"history unchanged"); } }else if(mode.rfind("slots_",0)==0||mode=="witness_member_wide"){ f.m_v72={0,0,0}; - auto occupy=[&](int slot,float x,float y){s.slots[slot].m_occupied=true;s.members[s.slots[slot].m_memberIndex].m_position={x,y,0};}; + auto occupy=[&](int slot,float x,float y){s.slots[slot].hasSquadMemberAssigned=true;s.members[s.slots[slot].m_memberIndex].m_position={x,y,0};}; int want[6]={100,101,102,103,104,105}; if(mode=="slots_empty"){} - else if(mode=="slots_unclaimed"){s.slots[1].m_occupied=true;s.slots[1].m_i20=-1;s.slots[2].m_i20=5;want[1]=-1;want[2]=5;} + else if(mode=="slots_unclaimed"){s.slots[1].hasSquadMemberAssigned=true;s.slots[1].m_i20=-1;s.slots[2].m_i20=5;want[1]=-1;want[2]=5;} else{ for(int& w:want)w=-1; if(mode=="slots_sorted"){occupy(1,3,0);occupy(2,1,0);occupy(3,2,0);want[2]=0;want[3]=1;want[1]=2;} else if(mode=="slots_tie"){occupy(1,2,0);occupy(2,1,0);occupy(3,0,2);want[2]=0;want[1]=1;want[3]=2;} else if(mode=="slots_zero_member"){occupy(0,1,0);occupy(2,2,0);want[5]=0;want[2]=1;} - else if(mode=="slots_single"){f.m_maxSquadMembers=1;occupy(0,1,0);for(int i=1;i<6;++i)want[i]=100+i;want[0]=0;} + else if(mode=="slots_single"){f.m_numberOfSlots=1;occupy(0,1,0);for(int i=1;i<6;++i)want[i]=100+i;want[0]=0;} else if(mode=="slots_invalid_position"){occupy(1,5,0);s.members[1].m_positionValid=false;occupy(2,1,0);want[2]=0;want[1]=1;} else if(mode=="witness_member_wide"){ // PE keys 0x3F7FFFB1 (p) > 0x3F7FFFB0 (q): q first, although wide deltas would order them the other way. f.m_v72=vecBits(855638016u,0,0); - s.slots[1].m_occupied=s.slots[2].m_occupied=true; + s.slots[1].hasSquadMemberAssigned=s.slots[2].hasSquadMemberAssigned=true; s.members[1].m_position=vecBits(1065353176u,964689920u,0);s.members[2].m_position=vecBits(1065353177u,0,0); want[2]=0;want[1]=1; }else unexpected("slots mode"); @@ -353,7 +353,7 @@ int main(int argc,char** argv) }else if(mode=="join_leader"){ f.m_b84=true;f.m_b85=false;f.joinSquadLeader(); require(f.m_b85&&!f.m_b84&&f.m_b56&&clockCalls==0,"unoccupied anchor: flags only, movement flag untouched"); - s.slots[0].m_occupied=true;f.m_b84=true;f.m_b85=false;f.joinSquadLeader(); + s.slots[0].hasSquadMemberAssigned=true;f.m_b84=true;f.m_b85=false;f.joinSquadLeader(); require(f.m_b85&&!f.m_b84&&f.m_b56&&clockCalls==1,"forced movement stamp"); require(f.m_d92==20.125+0.2&&equal(f.m_v60,f.m_v72),"stamp time and anchor copy"); }else if(mode=="witness_trail_set"){ @@ -375,35 +375,35 @@ int main(int argc,char** argv) }else{ bool promotion=false,hidden=false,matching=false,change=false,nested=false; if(mode=="unoccupied"){} - else if(mode=="zero_count_storage")f.m_maxSquadMembers=0; - else if(mode=="leader_zero"){s.slots[0].m_occupied=true;s.slots[0].m_memberIndex=4;} + else if(mode=="zero_count_storage")f.m_numberOfSlots=0; + else if(mode=="leader_zero"){s.slots[0].hasSquadMemberAssigned=true;s.slots[0].m_memberIndex=4;} else if(mode.rfind("hidden_",0)==0){ - hidden=true;f.m_b84=true;f.m_b85=true;s.slots[0].m_occupied=true;s.slots[0].m_memberIndex=4; - if(mode=="hidden_nonzero"){s.slots[0].m_memberIndex=0;s.slots[2].m_occupied=true;s.slots[2].m_memberIndex=4;} + hidden=true;f.m_b84=true;f.m_b85=true;s.slots[0].hasSquadMemberAssigned=true;s.slots[0].m_memberIndex=4; + if(mode=="hidden_nonzero"){s.slots[0].m_memberIndex=0;s.slots[2].hasSquadMemberAssigned=true;s.slots[2].m_memberIndex=4;} else if(mode!="hidden_only"){ - s.slots[1].m_occupied=true;s.slots[5].m_occupied=true;change=true; - if(mode=="hidden_holes"){s.slots[5].m_occupied=false;s.slots[3].m_occupied=true;} + s.slots[1].hasSquadMemberAssigned=true;s.slots[5].hasSquadMemberAssigned=true;change=true; + if(mode=="hidden_holes"){s.slots[5].hasSquadMemberAssigned=false;s.slots[3].hasSquadMemberAssigned=true;} if(mode=="hidden_duplicate")s.slots[5].m_memberIndex=4; if(mode=="hidden_reset_stop"){s.squad.m_v108={1,0,0};nested=true;} } }else if(mode.rfind("match_",0)==0){ - matching=true;s.slots[0].m_occupied=true;s.members[0].m_bot=nullptr;s.slots[1].m_occupied=true;change=true;f.m_b85=true; + matching=true;s.slots[0].hasSquadMemberAssigned=true;s.members[0].m_bot=nullptr;s.slots[1].hasSquadMemberAssigned=true;change=true;f.m_b85=true; if(mode=="match_human"){s.members[4].m_bot=nullptr;s.members[0].m_bot=s.members[2].m_bot;s.members[1].m_bot=nullptr;} if(mode=="match_same"){s.members[0].m_bot=s.members[1].m_bot;change=false;} if(mode=="match_none"){s.members[1].m_bot=nullptr;change=false;} - if(mode=="match_skip"){s.slots[1].m_occupied=false;s.slots[3].m_occupied=true;} - if(mode=="match_first")s.slots[3].m_occupied=true; + if(mode=="match_skip"){s.slots[1].hasSquadMemberAssigned=false;s.slots[3].hasSquadMemberAssigned=true;} + if(mode=="match_first")s.slots[3].hasSquadMemberAssigned=true; if(mode=="match_reset_stop"){s.squad.m_v108={1,0,0};nested=true;} }else{ - promotion=true;s.slots[0].m_occupied=true;s.slots[2].m_occupied=true;s.slots[2].m_memberIndex=4; + promotion=true;s.slots[0].hasSquadMemberAssigned=true;s.slots[2].hasSquadMemberAssigned=true;s.slots[2].m_memberIndex=4; s.members[4].m_position={1,0,0};change=true; if(mode=="equal"||mode=="force_equal"){s.members[4].m_position.x=50;change=false;} if(mode=="far"){s.members[4].m_position.x=51;change=false;} if(mode=="nan"||mode=="force_nan"){s.members[4].m_position.x=std::numeric_limits::quiet_NaN();change=false;} if(mode=="force_equal"||mode=="force_nan"){f.m_b85=true;change=true;} if(mode=="invalid_position")s.members[4].m_positionValid=false; - if(mode=="empty_anchor")s.slots[0].m_occupied=false; - if(mode=="duplicate_leader"){s.slots[1].m_occupied=true;s.slots[1].m_memberIndex=4;} + if(mode=="empty_anchor")s.slots[0].hasSquadMemberAssigned=false; + if(mode=="duplicate_leader"){s.slots[1].hasSquadMemberAssigned=true;s.slots[1].m_memberIndex=4;} if(mode=="near_reset_stop"){s.squad.m_v108={1,0,0};nested=true;} } s.snapshot(); @@ -411,8 +411,8 @@ int main(int argc,char** argv) if(hidden){const int other=mode=="hidden_holes"?3:5;const int id=s.slots[other].m_memberIndex;s.payload(0,id);s.payload(other,4); if(!nested){s.path[id]=false;s.path[4]=false;s.expectReset();}} if(matching){const int other=mode=="match_skip"?3:1;s.payload(0,other);s.payload(other,0);s.path[other]=false;if(!nested)s.expectReset();} - if(promotion){const int oldSlot=mode=="duplicate_leader"?1:2;const bool occupied=s.slots[0].m_occupied; - s.payload(0,4);s.expected[0].m_occupied=true;s.payload(oldSlot,0);s.expected[oldSlot].m_occupied=occupied; + if(promotion){const int oldSlot=mode=="duplicate_leader"?1:2;const bool occupied=s.slots[0].hasSquadMemberAssigned; + s.payload(0,4);s.expected[0].hasSquadMemberAssigned=true;s.payload(oldSlot,0);s.expected[oldSlot].hasSquadMemberAssigned=occupied; s.path[4]=s.path[0]=false;s.expected85=false;if(!nested)s.expectReset();} } if(nested)abortCheck=[&]{s.verify();require(clockCalls==0,"nested world-position stop precedes timer");}; diff --git a/Code/Tests/aidll/free_unit_predicate_runtime.cmd b/Code/Tests/aidll/free_unit_predicate_runtime.cmd index f2615b04c..033b6ce9a 100644 --- a/Code/Tests/aidll/free_unit_predicate_runtime.cmd +++ b/Code/Tests/aidll/free_unit_predicate_runtime.cmd @@ -11,7 +11,7 @@ if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%BF2_FREE_PREDICATE_OUT%\predicate_actual.cpp" /Fo"%BF2_FREE_PREDICATE_OUT%\actual.obj" >"%BF2_FREE_PREDICATE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_FREE_PREDICATE_OUT%\manager.obj" >>"%BF2_FREE_PREDICATE_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_FREE_PREDICATE_OUT%\manager.obj" >>"%BF2_FREE_PREDICATE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Core\%%F.cpp" /Fo"%BF2_FREE_PREDICATE_OUT%\%%F.obj" >>"%BF2_FREE_PREDICATE_OUT%\compile.log" 2>&1 diff --git a/Code/Tests/aidll/free_unit_predicate_runtime.h b/Code/Tests/aidll/free_unit_predicate_runtime.h index 2aa6e9505..d89f464e6 100644 --- a/Code/Tests/aidll/free_unit_predicate_runtime.h +++ b/Code/Tests/aidll/free_unit_predicate_runtime.h @@ -2,7 +2,7 @@ #pragma once #include "../../BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" #include "../../BF2/AI/AIDLL/AI/Main/AIDllFrontier.h" #include diff --git a/Code/Tests/aidll/information_factory_runtime.cmd b/Code/Tests/aidll/information_factory_runtime.cmd index bf170aeef..c02e631ca 100644 --- a/Code/Tests/aidll/information_factory_runtime.cmd +++ b/Code/Tests/aidll/information_factory_runtime.cmd @@ -18,10 +18,12 @@ for %%F in (InformationFactory BFInformationCourier Information InformationReal cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIInterface\BFKnowledge\PlanePolygon.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\PlanePolygon.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\IAIPathfinding.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\IAIPathfinding.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\IAIPathfindingSetup.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\IAIPathfindingSetup.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Math\Vec3.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\Vec3.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\CustomCurve.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\CustomCurve.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\CustomCurve.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\SCurve.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Core\%%F.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\%%F.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 @@ -30,7 +32,7 @@ for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /I"%BF2_INFORMATION_FACTORY_OUT%" /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%~dp0information_factory_runtime.cpp" /Fo"%BF2_INFORMATION_FACTORY_OUT%\fixture.obj" >>"%BF2_INFORMATION_FACTORY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed set "O=%BF2_INFORMATION_FACTORY_OUT%" -link /nologo /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%O%\information_factory_runtime.exe" "%O%\InformationFactory.obj" "%O%\BFInformationCourier.obj" "%O%\Information.obj" "%O%\InformationReal.obj" "%O%\IPIPhysicalReal.obj" "%O%\IPIArmament.obj" "%O%\IPIArmamentReal.obj" "%O%\IPICover.obj" "%O%\IPIMobile.obj" "%O%\IPIMobileReal.obj" "%O%\IPIMobileKnown.obj" "%O%\IPIUnit.obj" "%O%\InformationManager.obj" "%O%\WeaponInfo.obj" "%O%\WeaponInfoReal.obj" "%O%\WeaponInfoManager.obj" "%O%\PlanePolygon.obj" "%O%\IAIPathfinding.obj" "%O%\Vec3.obj" "%O%\CustomCurve.obj" "%O%\Debug.obj" "%O%\StringUtil.obj" "%O%\fixture.obj" >"%O%\link.log" 2>&1 +link /nologo /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%O%\information_factory_runtime.exe" "%O%\InformationFactory.obj" "%O%\BFInformationCourier.obj" "%O%\Information.obj" "%O%\InformationReal.obj" "%O%\IPIPhysicalReal.obj" "%O%\IPIArmament.obj" "%O%\IPIArmamentReal.obj" "%O%\IPICover.obj" "%O%\IPIMobile.obj" "%O%\IPIMobileReal.obj" "%O%\IPIMobileKnown.obj" "%O%\IPIUnit.obj" "%O%\InformationManager.obj" "%O%\WeaponInfo.obj" "%O%\WeaponInfoReal.obj" "%O%\WeaponInfoManager.obj" "%O%\PlanePolygon.obj" "%O%\IAIPathfinding.obj" "%O%\IAIPathfindingSetup.obj" "%O%\Vec3.obj" "%O%\CustomCurve.obj" "%O%\SCurve.obj" "%O%\Debug.obj" "%O%\StringUtil.obj" "%O%\fixture.obj" >"%O%\link.log" 2>&1 if errorlevel 1 goto failed python -I "%~dp0information_factory_runtime.py" run "%BF2_INFORMATION_FACTORY_OUT%\information_factory_runtime.exe" exit /b %errorlevel% diff --git a/Code/Tests/aidll/information_factory_runtime.cpp b/Code/Tests/aidll/information_factory_runtime.cpp index 9f96c3d19..d02c5cc8e 100644 --- a/Code/Tests/aidll/information_factory_runtime.cpp +++ b/Code/Tests/aidll/information_factory_runtime.cpp @@ -7,7 +7,7 @@ #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIArmamentReal.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPICover.h" @@ -15,9 +15,9 @@ #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfo.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoReal.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h" -#include "../../BF2/AI/AIDLL/AI/AIBotBehaviour/CustomCurve.h" -#include "../../BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h" +#include "../../BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h" +#include "../../BF2/AI/AIDLL/AI/AIUtils/CustomCurve.h" +#include "../../BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../../BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h" #include "../../BF2/AI/AIDLL/AI/Main/CommonSingletonServer.h" #include "../../BF2/AI/AIInterface/BFKnowledge/BFTimer.h" diff --git a/Code/Tests/aidll/information_factory_runtime.py b/Code/Tests/aidll/information_factory_runtime.py index da17091ba..b6cbaf050 100644 --- a/Code/Tests/aidll/information_factory_runtime.py +++ b/Code/Tests/aidll/information_factory_runtime.py @@ -108,7 +108,7 @@ SOURCES += [BFK + 'IWeapon.h', BFK + 'IAIObject.h', BFK + 'IAIObjectPlugIn.h', BFK + 'PlanePolygon.cpp', BFK + 'PlanePolygon.h', 'Math/Vec3.cpp', 'Math/Vec3.h', AI + 'Main/AISettingsInterfaces.h', - AI + 'Main/IAIPathfinding.cpp', AI + 'Main/IAIPathfinding.h'] + AI + 'Main/IAIPathfinding.cpp', AI + 'Main/IAIPathfindingSetup.cpp', AI + 'Main/IAIPathfinding.h'] def generate(out): diff --git a/Code/Tests/aidll/information_frontiers_runtime.cmd b/Code/Tests/aidll/information_frontiers_runtime.cmd index f826c130b..7900bd48b 100644 --- a/Code/Tests/aidll/information_frontiers_runtime.cmd +++ b/Code/Tests/aidll/information_frontiers_runtime.cmd @@ -12,7 +12,7 @@ if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\Information.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\actual.obj" >"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\manager.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\manager.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\IPIUnit.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\IPIUnit.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed @@ -24,9 +24,10 @@ cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIIn if errorlevel 1 goto failed cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Math\Vec3.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\Vec3.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoManager.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\WeaponInfoManager.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\WeaponInfoManager.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\WeaponInfoManager.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\CustomCurve.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\CustomCurve.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\CustomCurve.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\SCurve.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Core\%%F.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\%%F.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 @@ -34,7 +35,7 @@ for %%F in (Debug StringUtil) do ( ) cl %TASK_FLAGS% /I"%BF2_INFORMATION_FRONTIERS_OUT%" /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%~dp0information_frontiers_runtime.cpp" /Fo"%BF2_INFORMATION_FRONTIERS_OUT%\fixture.obj" >>"%BF2_INFORMATION_FRONTIERS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -link /nologo /MACHINE:X86 /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%BF2_INFORMATION_FRONTIERS_OUT%\information_frontiers_runtime.exe" "%BF2_INFORMATION_FRONTIERS_OUT%\actual.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\manager.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\IPIUnit.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\IPICover.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\IPIMobile.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\PlanePolygon.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\Vec3.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\WeaponInfoManager.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\CustomCurve.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\Debug.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\StringUtil.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\fixture.obj" >"%BF2_INFORMATION_FRONTIERS_OUT%\link.log" 2>&1 +link /nologo /MACHINE:X86 /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%BF2_INFORMATION_FRONTIERS_OUT%\information_frontiers_runtime.exe" "%BF2_INFORMATION_FRONTIERS_OUT%\actual.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\manager.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\IPIUnit.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\IPICover.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\IPIMobile.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\PlanePolygon.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\Vec3.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\WeaponInfoManager.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\CustomCurve.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\SCurve.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\Debug.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\StringUtil.obj" "%BF2_INFORMATION_FRONTIERS_OUT%\fixture.obj" >"%BF2_INFORMATION_FRONTIERS_OUT%\link.log" 2>&1 if errorlevel 1 goto failed python -I "%~dp0information_frontiers_runtime.py" run "%BF2_INFORMATION_FRONTIERS_OUT%\information_frontiers_runtime.exe" exit /b %errorlevel% diff --git a/Code/Tests/aidll/information_frontiers_runtime.cpp b/Code/Tests/aidll/information_frontiers_runtime.cpp index 9a2e17bdb..653bd9c1e 100644 --- a/Code/Tests/aidll/information_frontiers_runtime.cpp +++ b/Code/Tests/aidll/information_frontiers_runtime.cpp @@ -4,14 +4,14 @@ // belonging to engine TUs outside this focused link. CoverObserver uses the real IPICover // constructor/destructor against a chosen empty engine cover; no IPICover body is shadowed. #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIArmament.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIControlInfo.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPICover.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/WeaponInfoManager.h" +#include "../../BF2/AI/AIDLL/AI/AIUtils/WeaponInfoManager.h" #include "../../BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h" #include "../../BF2/AI/AIDLL/AI/Main/CommonSingletonServer.h" #include "../../BF2/AI/AIDLL/AI/Main/IAIPathfinding.h" diff --git a/Code/Tests/aidll/information_frontiers_runtime.py b/Code/Tests/aidll/information_frontiers_runtime.py index 04db1371b..e55121b4e 100644 --- a/Code/Tests/aidll/information_frontiers_runtime.py +++ b/Code/Tests/aidll/information_frontiers_runtime.py @@ -79,8 +79,8 @@ class _Helpers: AI + 'AIKnowledge/IPIMobile.cpp', AI + 'AIKnowledge/IPIMobile.h', 'AI/AIInterface/BFKnowledge/PlanePolygon.cpp', 'AI/AIInterface/BFKnowledge/PlanePolygon.h', 'Math/Vec3.cpp', - AI + 'AIKnowledge/WeaponInfoManager.cpp', - AI + 'AIBotBehaviour/CustomCurve.cpp', + AI + 'AIUtils/WeaponInfoManager.cpp', + AI + 'AIUtils/CustomCurve.cpp', AI + 'AIUtils/SCurve.cpp', AI + 'Main/AISettingsInterfaces.h', AI + 'Main/IAIPathfinding.h', 'AI/AIInterface/BFKnowledge/BFTimer.h', diff --git a/Code/Tests/aidll/information_prefix_runtime.cpp b/Code/Tests/aidll/information_prefix_runtime.cpp index 734512feb..e1d02a97d 100644 --- a/Code/Tests/aidll/information_prefix_runtime.cpp +++ b/Code/Tests/aidll/information_prefix_runtime.cpp @@ -51,7 +51,7 @@ struct LegacyInformationLayout namespace dice { namespace hfe { namespace ai { Information::Information(IAIObject* object, double time) : m_objectTypeFlags(0), m_strength(0.0f), m_time(time), m_object(object), - m_booked(false), m_bookingPlayerId(-1), m_armament(nullptr), m_controlInfo(nullptr), + m_isBooked(false), m_bookingPlayerId(-1), m_armament(nullptr), m_controlInfo(nullptr), m_cover(nullptr), m_mobile(nullptr), m_physical(nullptr), m_unit(nullptr) { static_assert(sizeof(void*) == 4, "MSVC x86 only"); @@ -61,7 +61,7 @@ Information::Information(IAIObject* object, double time) static_assert(offsetof(Information, m_strength) == offsetof(LegacyInformationLayout, unwritten) + 12, "float split"); static_assert(offsetof(Information, m_time) == offsetof(LegacyInformationLayout, time), "time offset preserved"); static_assert(offsetof(Information, m_object) == offsetof(LegacyInformationLayout, object), "object offset preserved"); - static_assert(offsetof(Information, m_booked) == offsetof(LegacyInformationLayout, bool24), "bool offset preserved"); + static_assert(offsetof(Information, m_isBooked) == offsetof(LegacyInformationLayout, bool24), "bool offset preserved"); static_assert(offsetof(Information, m_bookingPlayerId) == offsetof(LegacyInformationLayout, int28), "integer offset preserved"); static_assert(offsetof(Information, m_armament) == offsetof(LegacyInformationLayout, plugIn4), "plugin4 offset preserved"); static_assert(offsetof(Information, m_controlInfo) == offsetof(LegacyInformationLayout, plugIn5), "plugin5 offset preserved"); diff --git a/Code/Tests/aidll/information_query_runtime.h b/Code/Tests/aidll/information_query_runtime.h index 14cf64fff..d53325076 100644 --- a/Code/Tests/aidll/information_query_runtime.h +++ b/Code/Tests/aidll/information_query_runtime.h @@ -3,4 +3,4 @@ #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" diff --git a/Code/Tests/aidll/ipicover_runtime.cpp b/Code/Tests/aidll/ipicover_runtime.cpp index 3325e1c87..1d8b1851d 100644 --- a/Code/Tests/aidll/ipicover_runtime.cpp +++ b/Code/Tests/aidll/ipicover_runtime.cpp @@ -61,7 +61,7 @@ namespace dice { namespace hfe { namespace ai { // focused link. No production IPICover/PlanePolygon definition is supplied by the fixture. Information::Information(IAIObject* object, double time) : m_objectTypeFlags(0), m_allowedTimeDiff(0), m_strength(0), m_basicTemp(0), m_time(time), - m_object(object), m_booked(false), m_bookingPlayerId(-1), m_armament(nullptr), + m_object(object), m_isBooked(false), m_bookingPlayerId(-1), m_armament(nullptr), m_controlInfo(nullptr), m_cover(nullptr), m_mobile(nullptr), m_physical(nullptr), m_unit(nullptr) {} Information::~Information() {} int Information::getInformationSort() { unexpected("Information::getInformationSort"); } diff --git a/Code/Tests/aidll/map_polygon_runtime.cpp b/Code/Tests/aidll/map_polygon_runtime.cpp index 0ca196ff8..19102f44a 100644 --- a/Code/Tests/aidll/map_polygon_runtime.cpp +++ b/Code/Tests/aidll/map_polygon_runtime.cpp @@ -61,8 +61,8 @@ static void query(Map* map,MaterialManager* materials,Vec3 p,bool expected,unsig CHECK(actualIsland==(expected?island:invalid)); } static void append(Map* destination,Map* from) { - destination->m_quadTreeManager->m_islands.push_back(from->m_quadTreeManager->m_islands[0]); - from->m_quadTreeManager->m_islands.clear(); + destination->m_quadTreeManager->m_quadTrees.push_back(from->m_quadTreeManager->m_quadTrees[0]); + from->m_quadTreeManager->m_quadTrees.clear(); } int main(int argc,char** argv) { SetErrorMode(SEM_NOGPFAULTERRORBOX|SEM_FAILCRITICALERRORS); @@ -83,7 +83,7 @@ int main(int argc,char** argv) { Map* map; if(mode=="empty_tree") { map=new Map("never-loaded",0); - map->m_quadTreeManager->m_islands.push_back(std::make_pair(new QuadTree(0),static_cast(nullptr))); + map->m_quadTreeManager->m_quadTrees.push_back(std::make_pair(new QuadTree(0),static_cast(nullptr))); } else map=load("empty_leaf"); query(map,nullptr,{0,0,0},false); } else if(mode=="leaf_success") { diff --git a/Code/Tests/aidll/map_polygon_runtime.py b/Code/Tests/aidll/map_polygon_runtime.py index 0b5f50980..8c54c4897 100644 --- a/Code/Tests/aidll/map_polygon_runtime.py +++ b/Code/Tests/aidll/map_polygon_runtime.py @@ -143,7 +143,7 @@ def generate(out): node=AI+'AIPathFinding/NavMesh/QuadTreeNode.cpp' if (BF2/node).exists(): whole.append(node) whole += [AI+'AIPathFinding/Cluster/ClusterGraph.cpp',AI+'AIPathFinding/Material/MaterialManager.cpp', - AI+'Main/IAIPathfinding.cpp','Math/Mat4Inverse.cpp','Math/Plane3.cpp','Math/Vec3.cpp', + AI+'Main/IAIPathfinding.cpp',AI+'Main/IAIPathfindingSetup.cpp','Math/Mat4Inverse.cpp','Math/Plane3.cpp','Math/Vec3.cpp', 'Core/Debug.cpp','Core/StringUtil.cpp'] headers=[AI+'Main/AIPathfinding.h',AI+'Main/IAIPathfinding.h',AI+'Main/AISettingsInterfaces.h', AI+'AIPathFinding/NavMesh/QuadTree.h',AI+'AIPathFinding/NavMesh/QuadTreeNode.h', diff --git a/Code/Tests/aidll/material_query_runtime.cpp b/Code/Tests/aidll/material_query_runtime.cpp index a015e04f7..52bcc602f 100644 --- a/Code/Tests/aidll/material_query_runtime.cpp +++ b/Code/Tests/aidll/material_query_runtime.cpp @@ -31,10 +31,10 @@ struct Vec3 // record only; it is not a production-header or retail ABI assertion. struct Polygon { - unsigned char m_numberOfVertices; + unsigned char vertexCount; unsigned char m_material; - unsigned short m_cluster; - unsigned int m_firstIndex; + unsigned short cluster; + unsigned int vertexOffset; Vec3 m_normal; }; @@ -51,7 +51,7 @@ class QuadTreeManager { public: QuadTree* getIsland(unsigned int island) const; - std::vector > m_islands; + std::vector > m_quadTrees; }; class AIPathfinding @@ -105,12 +105,12 @@ static int runNormal() CHECK(tree.getMaterialOfPolygon(2) == 0xE6); QuadTreeManager manager; - manager.m_islands.push_back(std::make_pair(&tree, static_cast(0))); + manager.m_quadTrees.push_back(std::make_pair(&tree, static_cast(0))); dice::hfe::ai::Polygon secondPolygon = {}; secondPolygon.m_material = 0xFF; QuadTree secondTree; secondTree.m_polygons = &secondPolygon; - manager.m_islands.push_back(std::make_pair(&secondTree, static_cast(0))); + manager.m_quadTrees.push_back(std::make_pair(&secondTree, static_cast(0))); AIPathfinding::MapContainer map; map.m_quadTreeManager = &manager; @@ -161,7 +161,7 @@ static int runBadIsland() QuadTree tree; tree.m_polygons = &polygon; QuadTreeManager manager; - manager.m_islands.push_back(std::make_pair(&tree, static_cast(0))); + manager.m_quadTrees.push_back(std::make_pair(&tree, static_cast(0))); AIPathfinding::MapContainer map; map.m_quadTreeManager = &manager; unsigned char material = 0xA5; @@ -179,7 +179,7 @@ static int runNullPolygonStorage() QuadTree tree; tree.m_polygons = reinterpret_cast(zero); QuadTreeManager manager; - manager.m_islands.push_back(std::make_pair(&tree, static_cast(0))); + manager.m_quadTrees.push_back(std::make_pair(&tree, static_cast(0))); AIPathfinding::MapContainer map; map.m_quadTreeManager = &manager; unsigned char material = 0xA5; diff --git a/Code/Tests/aidll/material_query_runtime.py b/Code/Tests/aidll/material_query_runtime.py index dc8699ed2..51a47cf0f 100644 --- a/Code/Tests/aidll/material_query_runtime.py +++ b/Code/Tests/aidll/material_query_runtime.py @@ -87,7 +87,7 @@ def preflight(output): for token in (".size()", ".at(", "getNumberOfIslands", "m_numberOfPolygons", "nullptr") ), "island_accessor_is_unchecked_subscript": ( - "return m_islands[island].first;" in manager + "return m_quadTrees[island].first;" in manager and ".size()" not in manager and ".at(" not in manager ), diff --git a/Code/Tests/aidll/member_formation_runtime.cpp b/Code/Tests/aidll/member_formation_runtime.cpp index 096353c3d..51042f4d5 100644 --- a/Code/Tests/aidll/member_formation_runtime.cpp +++ b/Code/Tests/aidll/member_formation_runtime.cpp @@ -49,14 +49,14 @@ namespace dice { namespace hfe { namespace ai { // claim retail construction. Every touched scalar and all native containers live. SquadCoordinator::SquadCoordinator(int side, int index) : m_squadIndex(index), m_side(side), m_strategicAreaAssignment(nullptr), m_i40(4), - m_i44(0), m_formation(nullptr), m_i120(0), m_d124(-999.0) {} + m_i44(0), m_formation(nullptr), m_missionStatus(0), m_d124(-999.0) {} SquadMember::SquadMember(SquadCoordinator* squad, IAIPlayer* player, int squadIndex, int side, int index) : m_squadIndex(squadIndex), m_memberIndex(index), m_player(player), m_bot(nullptr), m_squad(squad), m_side(side), m_havePath(true), m_request(nullptr), m_position{}, m_positionValid(false), m_flag49(true), m_flag4A(false), m_flag4B(true) {} SquadMember::~SquadMember() {} SquadFormation::SquadFormation(SquadCoordinator* coordinator) - : m_coordinator(coordinator), m_maxSquadMembers(0) {} + : m_coordinator(coordinator), m_numberOfSlots(0) {} IAIPlayer::~IAIPlayer() {} IAIMain* IAIMain::m_instance = nullptr; bool SAI::isPlayerCommander() { unexpected("unselected mission commander"); } diff --git a/Code/Tests/aidll/member_update_runtime.cmd b/Code/Tests/aidll/member_update_runtime.cmd index 9d17b0c81..a93c2f4f8 100644 --- a/Code/Tests/aidll/member_update_runtime.cmd +++ b/Code/Tests/aidll/member_update_runtime.cmd @@ -9,7 +9,7 @@ if not exist "%BF2_MEMBER_UPDATE_OUT%" mkdir "%BF2_MEMBER_UPDATE_OUT%" python -I "%~dp0member_update_runtime.py" generate "%BF2_MEMBER_UPDATE_OUT%" if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_MEMBER_UPDATE_OUT%\manager.obj" >"%BF2_MEMBER_UPDATE_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_MEMBER_UPDATE_OUT%\manager.obj" >"%BF2_MEMBER_UPDATE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%BF2_MEMBER_UPDATE_OUT%\actual.cpp" /Fo"%BF2_MEMBER_UPDATE_OUT%\actual.obj" >>"%BF2_MEMBER_UPDATE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed diff --git a/Code/Tests/aidll/member_update_runtime.cpp b/Code/Tests/aidll/member_update_runtime.cpp index 35228e7cb..2e32f47b7 100644 --- a/Code/Tests/aidll/member_update_runtime.cpp +++ b/Code/Tests/aidll/member_update_runtime.cpp @@ -51,7 +51,7 @@ SquadMember::SquadMember(SquadCoordinator* squad,IAIPlayer* player,int squadInde m_time24(0.0),m_havePath(true),m_request(nullptr),m_int38(777),m_position{1,2,3},m_positionValid(false), m_flag49(true),m_flag4A(false),m_flag4B(true),m_moved(true),m_vector54{},m_vector60{} {} SquadMember::~SquadMember() {} -SquadFormation::SquadFormation(SquadCoordinator* squad):m_coordinator(squad),m_maxSquadMembers(0) {} +SquadFormation::SquadFormation(SquadCoordinator* squad):m_coordinator(squad),m_numberOfSlots(0) {} IAIPlayer::~IAIPlayer() {} Bot::~Bot() {} int Bot::getBotType() const { unexpected("Bot::getBotType"); } diff --git a/Code/Tests/aidll/member_update_runtime.h b/Code/Tests/aidll/member_update_runtime.h index a22d2bcae..b34a0538a 100644 --- a/Code/Tests/aidll/member_update_runtime.h +++ b/Code/Tests/aidll/member_update_runtime.h @@ -6,5 +6,5 @@ #include "../../BF2/AI/AIDLL/AI/AIBot/BotMain.h" #include "../../BF2/AI/AIInterface/BFKnowledge/AIPlayer.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/Main/AIDllFrontier.h" diff --git a/Code/Tests/aidll/member_update_runtime.py b/Code/Tests/aidll/member_update_runtime.py index f113a652b..0343ac931 100644 --- a/Code/Tests/aidll/member_update_runtime.py +++ b/Code/Tests/aidll/member_update_runtime.py @@ -89,7 +89,7 @@ def generate(out): paths.append(Path(__file__).with_name('sai_states_runtime.py')) (out/'fixture_sources.json').write_text(json.dumps({p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},indent=2),encoding='utf-8') paths = [CODE/'BF2'/p for p in ( - AI+'AIKnowledge/InformationManager.cpp', AI+'AIKnowledge/InformationManager.h', 'Core/SpHandlePool.h', + AI+'Main/InformationManager.cpp', AI+'Main/InformationManager.h', 'Core/SpHandlePool.h', AI+'AIKnowledge/Information.h', AI+'AIBot/SquadMember.h', AI+'AIBot/SquadCoordinator.h', AI+'AIBot/SquadFormation.h', AI+'AIBot/BotMain.h', 'AI/AIInterface/BFKnowledge/AIPlayer.h')] (out/'whole_sources.json').write_text(json.dumps({p.as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},indent=2),encoding='utf-8') diff --git a/Code/Tests/aidll/mobile_courier_runtime.cmd b/Code/Tests/aidll/mobile_courier_runtime.cmd index b192b716d..df8858e8e 100644 --- a/Code/Tests/aidll/mobile_courier_runtime.cmd +++ b/Code/Tests/aidll/mobile_courier_runtime.cmd @@ -16,8 +16,10 @@ for %%F in (InformationFactory BFInformationCourier Information InformationReal if errorlevel 1 goto failed ) cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\IAIPathfinding.cpp" /Fo"%BF2_MOBILE_COURIER_OUT%\IAIPathfinding.obj" >>"%BF2_MOBILE_COURIER_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\IAIPathfindingSetup.cpp" /Fo"%BF2_MOBILE_COURIER_OUT%\IAIPathfindingSetup.obj" >>"%BF2_MOBILE_COURIER_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" /Fo"%BF2_MOBILE_COURIER_OUT%\CustomCurve.obj" >>"%BF2_MOBILE_COURIER_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\CustomCurve.cpp" /Fo"%BF2_MOBILE_COURIER_OUT%\CustomCurve.obj" >>"%BF2_MOBILE_COURIER_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" /Fo"%BF2_MOBILE_COURIER_OUT%\SCurve.obj" >>"%BF2_MOBILE_COURIER_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Core\%%F.cpp" /Fo"%BF2_MOBILE_COURIER_OUT%\%%F.obj" >>"%BF2_MOBILE_COURIER_OUT%\compile.log" 2>&1 @@ -26,7 +28,7 @@ for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /I"%BF2_MOBILE_COURIER_OUT%" /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%~dp0mobile_courier_runtime.cpp" /Fo"%BF2_MOBILE_COURIER_OUT%\fixture.obj" >>"%BF2_MOBILE_COURIER_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed set "O=%BF2_MOBILE_COURIER_OUT%" -link /nologo /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%O%\mobile_courier_runtime.exe" "%O%\InformationFactory.obj" "%O%\BFInformationCourier.obj" "%O%\Information.obj" "%O%\InformationReal.obj" "%O%\IPIPhysicalReal.obj" "%O%\IPIArmament.obj" "%O%\IPIArmamentReal.obj" "%O%\IPIUnit.obj" "%O%\IPIMobile.obj" "%O%\IPIMobileReal.obj" "%O%\IPIMobileKnown.obj" "%O%\InformationManager.obj" "%O%\WeaponInfo.obj" "%O%\WeaponInfoReal.obj" "%O%\WeaponInfoManager.obj" "%O%\IAIPathfinding.obj" "%O%\CustomCurve.obj" "%O%\Debug.obj" "%O%\StringUtil.obj" "%O%\fixture.obj" >"%O%\link.log" 2>&1 +link /nologo /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%O%\mobile_courier_runtime.exe" "%O%\InformationFactory.obj" "%O%\BFInformationCourier.obj" "%O%\Information.obj" "%O%\InformationReal.obj" "%O%\IPIPhysicalReal.obj" "%O%\IPIArmament.obj" "%O%\IPIArmamentReal.obj" "%O%\IPIUnit.obj" "%O%\IPIMobile.obj" "%O%\IPIMobileReal.obj" "%O%\IPIMobileKnown.obj" "%O%\InformationManager.obj" "%O%\WeaponInfo.obj" "%O%\WeaponInfoReal.obj" "%O%\WeaponInfoManager.obj" "%O%\IAIPathfinding.obj" "%O%\IAIPathfindingSetup.obj" "%O%\CustomCurve.obj" "%O%\SCurve.obj" "%O%\Debug.obj" "%O%\StringUtil.obj" "%O%\fixture.obj" >"%O%\link.log" 2>&1 if errorlevel 1 goto failed python -I "%~dp0mobile_courier_runtime.py" run "%O%\mobile_courier_runtime.exe" exit /b %errorlevel% diff --git a/Code/Tests/aidll/mobile_courier_runtime.cpp b/Code/Tests/aidll/mobile_courier_runtime.cpp index 8a41614e3..2d7cdd88f 100644 --- a/Code/Tests/aidll/mobile_courier_runtime.cpp +++ b/Code/Tests/aidll/mobile_courier_runtime.cpp @@ -4,12 +4,12 @@ #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationCourier.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationFactory.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationReal.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.h" -#include "../../BF2/AI/AIDLL/AI/AIStrategicMap/AerialHeightMap.h" +#include "../../BF2/AI/AIDLL/AI/AIPathFinding/AerialHeightMap/AerialHeightMap.h" #include "../../BF2/AI/AIDLL/AI/Main/AISettingsInterfaces.h" #include "../../BF2/AI/AIDLL/AI/Main/CommonSingletonServer.h" #include "../../BF2/AI/AIDLL/AI/Main/IAIPathfinding.h" @@ -37,7 +37,7 @@ using namespace dice::hfe::ai; static_assert(sizeof(void*) == 4, "x86 only"); static_assert(sizeof(IPIMobile::ValidPos) == 20, "retail ValidPos stride"); static_assert(offsetof(IPIMobile::ValidPos, polygon) == 0, "polygon is the first path output"); -static_assert(offsetof(IPIMobile::ValidPos, quadTree) == 4, "quadTree is the second path output"); +static_assert(offsetof(IPIMobile::ValidPos, island) == 4, "quadTree is the second path output"); static_assert(offsetof(IPIMobile::ValidPos, position) == 8, "position follows the two indices"); static_assert(sizeof(IPIMobile) == 72, "retail x86 IPIMobile layout"); static_assert(sizeof(IPIMobileReal) == 72, "retail x86 IPIMobileReal layout"); @@ -105,7 +105,7 @@ static IPIMobile::ValidPos valid(unsigned int polygon, unsigned int quadTree, { IPIMobile::ValidPos result; result.polygon = polygon; - result.quadTree = quadTree; + result.island = quadTree; result.position.x = x; result.position.y = y; result.position.z = z; @@ -114,7 +114,7 @@ static IPIMobile::ValidPos valid(unsigned int polygon, unsigned int quadTree, static bool equalPos(const IPIMobile::ValidPos& a, const IPIMobile::ValidPos& b) { - return a.polygon == b.polygon && a.quadTree == b.quadTree + return a.polygon == b.polygon && a.island == b.island && equalVec(a.position, b.position); } @@ -496,7 +496,7 @@ static void modeBaseMaterial() expectRawRecords(mobile, infantry, material3, material3, true, "material 3"); check(materialCalls.size() == 1, "material 3 issues one material query"); check(materialCalls[0].map == 1, "material map is bool(traceMap == 0)"); - check(materialCalls[0].firstIndex == material3.quadTree + check(materialCalls[0].firstIndex == material3.island && materialCalls[0].secondIndex == material3.polygon, "material query receives quadTree then polygon"); diff --git a/Code/Tests/aidll/mobile_courier_runtime.py b/Code/Tests/aidll/mobile_courier_runtime.py index da4131fea..d1a3a7d83 100644 --- a/Code/Tests/aidll/mobile_courier_runtime.py +++ b/Code/Tests/aidll/mobile_courier_runtime.py @@ -56,7 +56,7 @@ 'InformationReal.h', 'InformationManager.cpp', 'InformationManager.h', 'IPIMobile.cpp', 'IPIMobile.h', 'IPIMobileReal.cpp', 'IPIMobileReal.h', 'IPIMobileKnown.cpp', 'IPIMobileKnown.h')] -SOURCES += [AI + 'Main/IAIPathfinding.cpp', AI + 'Main/IAIPathfinding.h', +SOURCES += [AI + 'Main/IAIPathfinding.cpp', AI + 'Main/IAIPathfindingSetup.cpp', AI + 'Main/IAIPathfinding.h', AI + 'Main/AISettingsInterfaces.h', BFK + 'IAIObject.h', BFK + 'IAIObjectPlugIn.h', BFK + 'BFTimer.h'] FIXTURE_FILES = [ diff --git a/Code/Tests/aidll/movement_runtime.cpp b/Code/Tests/aidll/movement_runtime.cpp index fd1b2efd1..a004a1698 100644 --- a/Code/Tests/aidll/movement_runtime.cpp +++ b/Code/Tests/aidll/movement_runtime.cpp @@ -54,7 +54,7 @@ SquadMember::~SquadMember() {} SquadCoordinator::SquadCoordinator(int side, int index) : m_squadIndex(index), m_side(side), m_v28{21.0f, 22.0f, 23.0f}, m_formation(nullptr) {} SquadFormation::SquadFormation(SquadCoordinator* squad) - : m_coordinator(squad), m_maxSquadMembers(0) {} + : m_coordinator(squad), m_numberOfSlots(0) {} IAIPlayer::~IAIPlayer() {} #if defined(MOVEMENT_OBSERVERS) diff --git a/Code/Tests/aidll/plan_executor_runtime.cmd b/Code/Tests/aidll/plan_executor_runtime.cmd index c18b8f769..c699dadc2 100644 --- a/Code/Tests/aidll/plan_executor_runtime.cmd +++ b/Code/Tests/aidll/plan_executor_runtime.cmd @@ -10,7 +10,7 @@ python -I "%~dp0plan_executor_runtime.py" generate "%BF2_PLAN_EXECUTOR_OUT%" if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" set "TASK_FI=/FI"%TASK_CODE%\BF2\Core\BuildConfig.h"" -cl %TASK_FLAGS% %TASK_FI% "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_PLAN_EXECUTOR_OUT%\manager.obj" >"%BF2_PLAN_EXECUTOR_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% %TASK_FI% "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_PLAN_EXECUTOR_OUT%\manager.obj" >"%BF2_PLAN_EXECUTOR_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed cl %TASK_FLAGS% %TASK_FI% "%TASK_CODE%\BF2\IO\Input\PlayerInput.cpp" /Fo"%BF2_PLAN_EXECUTOR_OUT%\input.obj" >>"%BF2_PLAN_EXECUTOR_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed diff --git a/Code/Tests/aidll/plan_executor_runtime.cpp b/Code/Tests/aidll/plan_executor_runtime.cpp index 4c577dcf6..44eb7f076 100644 --- a/Code/Tests/aidll/plan_executor_runtime.cpp +++ b/Code/Tests/aidll/plan_executor_runtime.cpp @@ -238,7 +238,7 @@ IBotManager::~IBotManager() {} IBotManagerModifier::IBotManagerModifier() {} IBotManagerModifier::~IBotManagerModifier() {} Information::Information(IAIObject* object, double time) - : m_objectTypeFlags(0), m_strength(0.0f), m_time(time), m_object(object), m_booked(false), m_bookingPlayerId(-1), + : m_objectTypeFlags(0), m_strength(0.0f), m_time(time), m_object(object), m_isBooked(false), m_bookingPlayerId(-1), m_armament(nullptr), m_controlInfo(nullptr), m_cover(nullptr), m_mobile(nullptr), m_physical(nullptr), m_unit(nullptr) { @@ -285,7 +285,7 @@ BotManager::BotInfo::BotInfo(Bot* bot) { } BotManager::BotManager() - : m_queuePriorityA(new BotQueue), m_queuePriorityB(new BotQueue), m_queueSensing(new SensingQueue), + : m_planned(new BotQueue), m_unplanned(new BotQueue), m_sensingQueue(new SensingQueue), m_lodLevelFullPriority(fullPriority), m_plannedDecisionMakingThresholdFull(plannedThreshold), m_unplannedDecisionMakingThresholdFull(unplannedThreshold), m_planExecutionsThisTick(7), m_tickCount180(8), m_tickCount184(9), m_planHalfToggle(initialToggle), m_planCursor(initialCursor) @@ -303,10 +303,10 @@ BotManager::BotManager() view.occupiedObjects = &m_occupiedObjects; view.pathCursor = &m_pathfindingCursor; view.hearingResume = &m_hearingResumeId; - view.infos = &m_botInfos; - view.queueA = m_queuePriorityA; - view.queueB = m_queuePriorityB; - view.sensing = m_queueSensing; + view.infos = &m_bots; + view.queueA = m_planned; + view.queueB = m_unplanned; + view.sensing = m_sensingQueue; view.cursor = &m_planCursor; view.toggle = &m_planHalfToggle; view.executions = &m_planExecutionsThisTick; @@ -315,9 +315,9 @@ BotManager::BotManager() } BotManager::~BotManager() { - delete m_queuePriorityA; - delete m_queuePriorityB; - delete m_queueSensing; + delete m_planned; + delete m_unplanned; + delete m_sensingQueue; } BotMain::BotMain(IAIPlayer*, unsigned int, float*, float, int, BotOrder*, BotMemory*, PlanInterpreter*, int, UrgencyGenerator*, UrgencyGenerator**) diff --git a/Code/Tests/aidll/plan_executor_runtime.h b/Code/Tests/aidll/plan_executor_runtime.h index ccf71b608..293a63987 100644 --- a/Code/Tests/aidll/plan_executor_runtime.h +++ b/Code/Tests/aidll/plan_executor_runtime.h @@ -13,7 +13,7 @@ #include "../../BF2/AI/AIDLL/AI/AIBot/BotMain.h" #include "../../BF2/AI/AIDLL/AI/AIBot/BotNavigation.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIMobile.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h" #include "../../BF2/AI/AIInterface/BFKnowledge/AIPlayer.h" diff --git a/Code/Tests/aidll/plan_executor_runtime.py b/Code/Tests/aidll/plan_executor_runtime.py index 0307de438..f9de37823 100644 --- a/Code/Tests/aidll/plan_executor_runtime.py +++ b/Code/Tests/aidll/plan_executor_runtime.py @@ -178,7 +178,7 @@ def generate(out): paths.append(Path(__file__).with_name('spawn_metadata_runtime.py')) (out / 'fixture_sources.json').write_text( json.dumps({p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}, indent=2), encoding='utf-8') - whole = [CODE / 'BF2' / p for p in (AI + 'AIKnowledge/InformationManager.cpp', 'Core/SpHandlePool.h', + whole = [CODE / 'BF2' / p for p in (AI + 'Main/InformationManager.cpp', 'Core/SpHandlePool.h', 'IO/Input/PlayerInput.cpp', 'IO/Input/Input.h', 'Core/Debug.cpp')] (out / 'whole_sources.json').write_text( json.dumps({p.as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in whole}, indent=2), diff --git a/Code/Tests/aidll/random_kit_runtime.cmd b/Code/Tests/aidll/random_kit_runtime.cmd index aa1933f52..2dd6512af 100644 --- a/Code/Tests/aidll/random_kit_runtime.cmd +++ b/Code/Tests/aidll/random_kit_runtime.cmd @@ -13,7 +13,7 @@ cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%BF2_RANDOM_KIT_OUT%\ra if errorlevel 1 goto failed cl %TASK_FLAGS% /I"%BF2_RANDOM_KIT_OUT%" /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%~dp0random_kit_runtime.cpp" /Fo"%BF2_RANDOM_KIT_OUT%\fixture.obj" >>"%BF2_RANDOM_KIT_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_RANDOM_KIT_OUT%\pool.obj" >>"%BF2_RANDOM_KIT_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_RANDOM_KIT_OUT%\pool.obj" >>"%BF2_RANDOM_KIT_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed link /nologo /OPT:REF /INCREMENTAL:NO /SUBSYSTEM:CONSOLE /OUT:"%BF2_RANDOM_KIT_OUT%\random_kit_runtime.exe" "%BF2_RANDOM_KIT_OUT%\actual.obj" "%BF2_RANDOM_KIT_OUT%\fixture.obj" "%BF2_RANDOM_KIT_OUT%\pool.obj" >"%BF2_RANDOM_KIT_OUT%\link.log" 2>&1 if errorlevel 1 goto failed diff --git a/Code/Tests/aidll/random_kit_runtime.h b/Code/Tests/aidll/random_kit_runtime.h index 3e4ca7e2c..2c8fa4677 100644 --- a/Code/Tests/aidll/random_kit_runtime.h +++ b/Code/Tests/aidll/random_kit_runtime.h @@ -8,7 +8,7 @@ #include "../../BF2/AI/AIDLL/AI/AIStrategicEntity/AIStrategicArea.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h" #include "../../BF2/AI/AIDLL/AI/AIStrategic/SAI.h" #include "../../BF2/AI/AIDLL/AI/Main/AIMain.h" diff --git a/Code/Tests/aidll/random_kit_runtime.py b/Code/Tests/aidll/random_kit_runtime.py index 6d56d0ed6..1fe9b20c9 100644 --- a/Code/Tests/aidll/random_kit_runtime.py +++ b/Code/Tests/aidll/random_kit_runtime.py @@ -89,8 +89,8 @@ def generate(out): actual += ['}',found[0],'} }'] (out/'random_kit_actual.cpp').write_text('\n\n'.join(actual), encoding='utf-8') (out/'source.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8') - whole_paths=['BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.cpp', - 'BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h','BF2/Core/SpHandlePool.h'] + whole_paths=['BF2/AI/AIDLL/AI/Main/InformationManager.cpp', + 'BF2/AI/AIDLL/AI/Main/InformationManager.h','BF2/Core/SpHandlePool.h'] (out/'whole_sources.json').write_text(json.dumps([ dict(source=(CODE/relative).as_posix(),sha256=hashlib.sha256((CODE/relative).read_bytes()).hexdigest()) for relative in whole_paths],indent=2),encoding='utf-8') diff --git a/Code/Tests/aidll/rectangle_query_runtime.h b/Code/Tests/aidll/rectangle_query_runtime.h index efd3ee1ea..0f408adbd 100644 --- a/Code/Tests/aidll/rectangle_query_runtime.h +++ b/Code/Tests/aidll/rectangle_query_runtime.h @@ -4,5 +4,5 @@ #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #endif diff --git a/Code/Tests/aidll/sai_prepare_runtime.cmd b/Code/Tests/aidll/sai_prepare_runtime.cmd index dfb6bb7cd..0b71a2b62 100644 --- a/Code/Tests/aidll/sai_prepare_runtime.cmd +++ b/Code/Tests/aidll/sai_prepare_runtime.cmd @@ -11,7 +11,7 @@ if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%BF2_SAI_PREPARE_OUT%\sai_prepare_actual.cpp" /Fo"%BF2_SAI_PREPARE_OUT%\actual.obj" >"%BF2_SAI_PREPARE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_SAI_PREPARE_OUT%\manager.obj" >>"%BF2_SAI_PREPARE_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_SAI_PREPARE_OUT%\manager.obj" >>"%BF2_SAI_PREPARE_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Core\%%F.cpp" /Fo"%BF2_SAI_PREPARE_OUT%\%%F.obj" >>"%BF2_SAI_PREPARE_OUT%\compile.log" 2>&1 diff --git a/Code/Tests/aidll/sai_prepare_runtime.cpp b/Code/Tests/aidll/sai_prepare_runtime.cpp index e373c2f84..a963f4b62 100644 --- a/Code/Tests/aidll/sai_prepare_runtime.cpp +++ b/Code/Tests/aidll/sai_prepare_runtime.cpp @@ -75,8 +75,8 @@ void operator delete(void* pointer, std::size_t) noexcept { ::operator delete(po static void checkCtor(SAI::BotInfo* info, Bot* bot) { - require(info && info->m_bot == bot && info->m_int04 == -1 && info->m_int08 == -1 && - info->m_int0C == -1 && info->m_float10 == 0.0f && info->m_double14 == 0.0, + require(info && info->m_bot == bot && info->m_currentlyOrderedSquare == -1 && info->m_lastOrderedSquare == -1 && + info->m_currentlyOccupiedSquare == -1 && info->m_float10 == 0.0f && info->m_double14 == 0.0, "actual BotInfo constructor fields precede next callback"); remember(info); } @@ -162,12 +162,12 @@ namespace dice { namespace hfe { namespace ai { ISAI::~ISAI() {} SAI::SAI(int side, int, int, Vec2, Vec2) : m_side(side) { - slots = &m_botInfo; pending = &m_vector94; removing = &m_vectorA0; + slots = &m_bots; pending = &m_vector94; removing = &m_vectorA0; spawnRequests = &m_map5C; spawnCounts = &m_map1D8; teleports = &m_list110; - unchangedSet = &m_setFC; + unchangedSet = &m_assignedBots; totals[0] = m_enemyStrengths; totals[1] = m_enemyCounts; totals[2] = m_friendlyStrengths; totals[3] = m_friendlyCounts; - m_botInfo.resize(10, nullptr); m_vector94.reserve(10); m_vectorA0.reserve(10); + m_bots.resize(10, nullptr); m_vector94.reserve(10); m_vectorA0.reserve(10); for (int a = 0; a < 4; ++a) for (int i = 0; i < 6; ++i) totals[a][i] = float(100 * (a + 1) + i); } SAI::~SAI() {} diff --git a/Code/Tests/aidll/sai_prepare_runtime.h b/Code/Tests/aidll/sai_prepare_runtime.h index d8118b455..1c933cf96 100644 --- a/Code/Tests/aidll/sai_prepare_runtime.h +++ b/Code/Tests/aidll/sai_prepare_runtime.h @@ -3,7 +3,7 @@ #include "../../BF2/AI/AIDLL/AI/AIStrategic/SAI.h" #include "../../BF2/AI/AIDLL/AI/AIBot/BotMain.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" #include "../../BF2/AI/AIDLL/AI/AIStrategicMap/BotSpawner.h" diff --git a/Code/Tests/aidll/sai_strengths_runtime.cmd b/Code/Tests/aidll/sai_strengths_runtime.cmd index 016eb6cf4..975ecf7ec 100644 --- a/Code/Tests/aidll/sai_strengths_runtime.cmd +++ b/Code/Tests/aidll/sai_strengths_runtime.cmd @@ -11,7 +11,7 @@ if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%BF2_SAI_STRENGTHS_OUT%\sai_strengths_actual.cpp" /Fo"%BF2_SAI_STRENGTHS_OUT%\actual.obj" >"%BF2_SAI_STRENGTHS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_SAI_STRENGTHS_OUT%\manager.obj" >>"%BF2_SAI_STRENGTHS_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_SAI_STRENGTHS_OUT%\manager.obj" >>"%BF2_SAI_STRENGTHS_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed for %%F in (Debug StringUtil) do ( cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\Core\%%F.cpp" /Fo"%BF2_SAI_STRENGTHS_OUT%\%%F.obj" >>"%BF2_SAI_STRENGTHS_OUT%\compile.log" 2>&1 diff --git a/Code/Tests/aidll/sai_strengths_runtime.h b/Code/Tests/aidll/sai_strengths_runtime.h index 4d897384e..060248d5a 100644 --- a/Code/Tests/aidll/sai_strengths_runtime.h +++ b/Code/Tests/aidll/sai_strengths_runtime.h @@ -4,7 +4,7 @@ #include "../../BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/AIInformationGrid.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIPhysical.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/UnitPredicate.h" diff --git a/Code/Tests/aidll/sai_update_runtime.cpp b/Code/Tests/aidll/sai_update_runtime.cpp index 0a6e11193..9137b9737 100644 --- a/Code/Tests/aidll/sai_update_runtime.cpp +++ b/Code/Tests/aidll/sai_update_runtime.cpp @@ -96,11 +96,11 @@ SAI::SAI(int side, int, int, Vec2, Vec2) m_stateC(stateArrays[2]), m_stateD(stateArrays[3]), m_int1F4(initialBuffer) { state = &m_int18C; buffer = &m_int1F4; timestamp = &m_float190; - suppression = &m_flag1D1; bots = &m_botInfo; + suppression = &m_flag1D1; bots = &m_bots; } SAI::~SAI() {} SAI::BotInfo::BotInfo(Bot* bot) - : m_bot(bot), m_int04(-1), m_int08(-1), m_int0C(-1), m_float10(0.0f), m_double14(0.0) {} + : m_bot(bot), m_currentlyOrderedSquare(-1), m_lastOrderedSquare(-1), m_currentlyOccupiedSquare(-1), m_float10(0.0f), m_double14(0.0) {} IBFTimer::IBFTimer() {} IBFTimer::~IBFTimer() {} IAISettings::IAISettings() {} diff --git a/Code/Tests/aidll/seeded_polygon_runtime.cpp b/Code/Tests/aidll/seeded_polygon_runtime.cpp index 3830204fd..83c6613fd 100644 --- a/Code/Tests/aidll/seeded_polygon_runtime.cpp +++ b/Code/Tests/aidll/seeded_polygon_runtime.cpp @@ -78,9 +78,9 @@ static Map* load(const char* name) static void appendIsland(Map* destination, Map* source) { - destination->m_quadTreeManager->m_islands.push_back( - source->m_quadTreeManager->m_islands[0]); - source->m_quadTreeManager->m_islands.clear(); + destination->m_quadTreeManager->m_quadTrees.push_back( + source->m_quadTreeManager->m_quadTrees[0]); + source->m_quadTreeManager->m_quadTrees.clear(); } static AIPathfinding* pathWith(Map* map) diff --git a/Code/Tests/aidll/squad_assignment_runtime.cpp b/Code/Tests/aidll/squad_assignment_runtime.cpp index 7a517357e..3e2a1f314 100644 --- a/Code/Tests/aidll/squad_assignment_runtime.cpp +++ b/Code/Tests/aidll/squad_assignment_runtime.cpp @@ -38,7 +38,7 @@ namespace dice { namespace hfe { namespace ai { // [CHOSEN, not recovered] Native lifetime setup solely for the queried fields. SquadCoordinator::SquadCoordinator(int side, int squadIndex) : m_squadIndex(squadIndex), m_side(side), m_strategicAreaAssignment(nullptr), - m_i40(4), m_i44(0), m_i60(0), m_i96(-1), m_formation(nullptr), m_i120(0) {} + m_i40(4), m_i44(0), m_i60(0), m_squadLeaderIndex(-1), m_formation(nullptr), m_missionStatus(0) {} AIStrategicObject::AIStrategicObject(float, float) {} AIStrategicObject::~AIStrategicObject() {} AIStrategicArea::AIStrategicArea(const std::string& name, unsigned int, float radius) @@ -57,10 +57,10 @@ int main(int argc, char** argv) AIStrategicArea a("first", 1, 0.0f), b("second", 2, 0.0f); if (mode == "null") { - first.m_i40 = 123; first.m_i44 = -3; first.m_i60 = 10; first.m_i120 = 4; + first.m_i40 = 123; first.m_i44 = -3; first.m_i60 = 10; first.m_missionStatus = 4; require(!first.isSquadAssignedToAnyArea(), "null assignment false despite nonzero neighboring state"); require(first.getSquadStrategicAreaAssignment() == nullptr, "stored null returned"); - require(first.m_i40 == 123 && first.m_i44 == -3 && first.m_i60 == 10 && first.m_i120 == 4, + require(first.m_i40 == 123 && first.m_i44 == -3 && first.m_i60 == 10 && first.m_missionStatus == 4, "queries leave neighboring state untouched"); require(destroyedAreas == 0, "no area lifetime effects"); } @@ -83,14 +83,14 @@ int main(int argc, char** argv) else if (mode == "unassign") { first.m_strategicAreaAssignment = &a; second.m_strategicAreaAssignment = &b; - first.m_i40 = -9; first.m_i44 = 51; first.m_i120 = 123; + first.m_i40 = -9; first.m_i44 = 51; first.m_missionStatus = 123; first.m_i60 = 777; first.m_side = 13; first.m_squadIndex = -29; first.m_v28 = {1,2,3}; first.m_v64 = {4,5,6}; require(first.isSquadAssignedToAnyArea(), "assigned before real unassignment"); first.unAssignSquad(); require(!first.isSquadAssignedToAnyArea(), "real unassignment makes query false"); require(first.getSquadStrategicAreaAssignment() == nullptr, "real unassignment clears pointer"); - require(first.m_i40 == 4 && first.m_i44 == 0 && first.m_i120 == 0, "actual three other stores preserved"); + require(first.m_i40 == 4 && first.m_i44 == 0 && first.m_missionStatus == 0, "actual three other stores preserved"); require(first.m_i60 == 777 && first.m_side == 13 && first.m_squadIndex == -29, "unrelated scalar fields preserved"); require(first.m_v28.x == 1 && first.m_v28.y == 2 && first.m_v28.z == 3 && first.m_v64.x == 4 && first.m_v64.y == 5 && first.m_v64.z == 6, "neighbor vectors preserved"); diff --git a/Code/Tests/aidll/squad_kit_runtime.cpp b/Code/Tests/aidll/squad_kit_runtime.cpp index 0494eb90b..d48b75c20 100644 --- a/Code/Tests/aidll/squad_kit_runtime.cpp +++ b/Code/Tests/aidll/squad_kit_runtime.cpp @@ -48,9 +48,9 @@ static int observeKit(int identity, int value) namespace dice { namespace hfe { namespace ai { // [CHOSEN, not recovered] Fixture-only lifetimes and collaborator. Each native STL // member constructs/destructs normally; unrelated engine/formation work is omitted. -SquadManager::SquadManager() { sideVectors = m_coordinators; } +SquadManager::SquadManager() { sideVectors = m_Squads; } SquadCoordinator::SquadCoordinator(int side, int squadIndex) - : m_squadIndex(squadIndex), m_side(side), m_i96(-1), m_formation(nullptr) {} + : m_squadIndex(squadIndex), m_side(side), m_squadLeaderIndex(-1), m_formation(nullptr) {} SquadMember::SquadMember(SquadCoordinator* squad, IAIPlayer* player, int squadIndex, int side, int memberIndex) : m_squadIndex(squadIndex), m_memberIndex(memberIndex), m_isSquadLeader(false), diff --git a/Code/Tests/aidll/squad_maneuver_runtime.cmd b/Code/Tests/aidll/squad_maneuver_runtime.cmd index f857d094a..aee51421b 100644 --- a/Code/Tests/aidll/squad_maneuver_runtime.cmd +++ b/Code/Tests/aidll/squad_maneuver_runtime.cmd @@ -9,7 +9,7 @@ if not exist "%BF2_SQUAD_MANEUVER_OUT%" mkdir "%BF2_SQUAD_MANEUVER_OUT%" python -I "%~dp0squad_maneuver_runtime.py" generate "%BF2_SQUAD_MANEUVER_OUT%" if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_SQUAD_MANEUVER_OUT%\manager.obj" >"%BF2_SQUAD_MANEUVER_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_SQUAD_MANEUVER_OUT%\manager.obj" >"%BF2_SQUAD_MANEUVER_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%BF2_SQUAD_MANEUVER_OUT%\actual.cpp" /Fo"%BF2_SQUAD_MANEUVER_OUT%\actual.obj" >>"%BF2_SQUAD_MANEUVER_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed diff --git a/Code/Tests/aidll/squad_maneuver_runtime.cpp b/Code/Tests/aidll/squad_maneuver_runtime.cpp index 24c6d31a6..e1b435c46 100644 --- a/Code/Tests/aidll/squad_maneuver_runtime.cpp +++ b/Code/Tests/aidll/squad_maneuver_runtime.cpp @@ -44,7 +44,7 @@ static bool* firingField; #include "mocks.inl" namespace dice {namespace hfe {namespace ai { // [CHOSEN, not recovered] Native scoped lifetimes; no retail publication/deep construction. -SquadCoordinator::SquadCoordinator(int side,int index):m_squadIndex(index),m_side(side),m_i120(0),m_i148(77), +SquadCoordinator::SquadCoordinator(int side,int index):m_squadIndex(index),m_side(side),m_missionStatus(0),m_i148(77), m_b156(true),m_b157(true),m_v28{},m_v108{} {} SquadMember::SquadMember(SquadCoordinator* squad,IAIPlayer* player,int squadIndex,int side,int index) :m_squadIndex(squadIndex),m_memberIndex(index),m_player(player),m_bot(nullptr),m_squad(squad),m_side(side), @@ -181,10 +181,10 @@ int main(int argc,char** argv) } else if(mode=="fresh_position") {a.m_position={900,0,0};botCallback=[&](int id,int op)->unsigned{if(op&&id==0){a.m_position={1,0,0};squad.m_v108={2,0,0};}return op?1:handle;};} - else if(mode=="mission_full_width"){squad.m_squadMembers.clear();squad.m_i120=0x102;expected=0;expectedTrace="";} + else if(mode=="mission_full_width"){squad.m_squadMembers.clear();squad.m_missionStatus=0x102;expected=0;expectedTrace="";} else if(mode=="mission_stop"||mode=="mission_after_scan") { - squad.m_i120=2;expected=0; + squad.m_missionStatus=2;expected=0; if(mode=="mission_stop"){squad.m_squadMembers.clear();expectedTrace="";} else {alive[0]=alive[1]=false;expectedTrace="p0,p1";} stoppingSquad=&squad;expectedStopTrace=expectedTrace; diff --git a/Code/Tests/aidll/squad_maneuver_runtime.h b/Code/Tests/aidll/squad_maneuver_runtime.h index 81438ea65..d664369ef 100644 --- a/Code/Tests/aidll/squad_maneuver_runtime.h +++ b/Code/Tests/aidll/squad_maneuver_runtime.h @@ -5,5 +5,5 @@ #include "../../BF2/AI/AIDLL/AI/AIBot/BotMain.h" #include "../../BF2/AI/AIInterface/BFKnowledge/AIPlayer.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/Main/AIDllFrontier.h" diff --git a/Code/Tests/aidll/squad_maneuver_runtime.py b/Code/Tests/aidll/squad_maneuver_runtime.py index 9e840596f..920d24503 100644 --- a/Code/Tests/aidll/squad_maneuver_runtime.py +++ b/Code/Tests/aidll/squad_maneuver_runtime.py @@ -69,7 +69,7 @@ def generate(out): mocks.append('} } }');(out/'mocks.inl').write_text('\n'.join(mocks),encoding='utf-8') paths=[Path(__file__).with_suffix(s) for s in ('.h','.cpp','.py','.cmd')]+[Path(__file__).with_name('spawn_metadata_runtime.py')] (out/'fixture_sources.json').write_text(json.dumps({p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},indent=2),encoding='utf-8') - paths=[CODE/'BF2'/p for p in (AI+'AIKnowledge/InformationManager.cpp',AI+'AIKnowledge/InformationManager.h','Core/SpHandlePool.h',AI+'AIKnowledge/Information.h',AI+'AIBot/SquadCoordinator.h',AI+'AIBot/SquadMember.h',AI+'AIBot/BotMain.h','AI/AIInterface/BFKnowledge/AIPlayer.h')] + paths=[CODE/'BF2'/p for p in (AI+'Main/InformationManager.cpp',AI+'Main/InformationManager.h','Core/SpHandlePool.h',AI+'AIKnowledge/Information.h',AI+'AIBot/SquadCoordinator.h',AI+'AIBot/SquadMember.h',AI+'AIBot/BotMain.h','AI/AIInterface/BFKnowledge/AIPlayer.h')] (out/'whole_sources.json').write_text(json.dumps({p.as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in paths},indent=2),encoding='utf-8') def run(out): diff --git a/Code/Tests/aidll/squad_queries_runtime.cpp b/Code/Tests/aidll/squad_queries_runtime.cpp index 3a9d78258..55b5ee716 100644 --- a/Code/Tests/aidll/squad_queries_runtime.cpp +++ b/Code/Tests/aidll/squad_queries_runtime.cpp @@ -17,7 +17,7 @@ using namespace dice::hfe::ai; static_assert(sizeof(void*) == 4, "MSVC x86 fixture only"); static_assert(sizeof(Vec3) == 12, "three float coordinates"); static_assert(std::is_same::value, "squad pointer type"); -static_assert(std::is_same::value, "signed leader index"); +static_assert(std::is_same::value, "signed leader index"); static_assert(std::is_same>::value, "native pointer vector"); static_assert(std::is_same::value, "position type"); static_assert(std::is_same::value, "non-const pointer query"); @@ -26,7 +26,7 @@ static_assert(std::is_same), sizeof(std::list)); return 0; } @@ -89,22 +89,22 @@ int main(int argc, char** argv) else if (mode == "leader") { first.m_squadMembers = {&member, nullptr, &another}; - first.m_i96 = 0; + first.m_squadLeaderIndex = 0; require(first.getSquadLeader() == &member, "first leader index"); - first.m_i96 = 2; + first.m_squadLeaderIndex = 2; require(first.getSquadLeader() == &another, "last leader index"); first.m_squadMembers[2] = &member; require(first.getSquadLeader() == &member, "fresh indexed entry"); first.m_squadMembers.reserve(first.m_squadMembers.capacity() + 17); first.m_squadMembers[2] = &another; require(first.getSquadLeader() == &another, "native vector relocation uses current storage"); - first.m_i96 = 1; + first.m_squadLeaderIndex = 1; require(first.getSquadLeader() == nullptr, "in-bounds null entry returned unchanged"); - require(first.m_squadMembers.size() == 3 && first.m_i96 == 1, "no roster or leader mutation"); + require(first.m_squadMembers.size() == 3 && first.m_squadLeaderIndex == 1, "no roster or leader mutation"); } else if (mode == "chain") { - first.m_squadMembers = {&another, &member}; first.m_i96 = 0; + first.m_squadMembers = {&another, &member}; first.m_squadLeaderIndex = 0; second.m_v108 = {4,5,6}; Vec3 output = {}; member.getSquad()->getSquadLeader()->getSquad()->getSquadPosition(output); diff --git a/Code/Tests/aidll/squad_runtime.cpp b/Code/Tests/aidll/squad_runtime.cpp index c4044475c..914c50335 100644 --- a/Code/Tests/aidll/squad_runtime.cpp +++ b/Code/Tests/aidll/squad_runtime.cpp @@ -225,7 +225,7 @@ int main(int argc, char** argv) { SquadFormation formation(&coordinator); expectCalls("side,size"); - require(formation.m_slots.size() == 3 && formation.m_slotTargets.size() == 3, + require(formation.m_slots.size() == 3 && formation.m_trailingPositions.size() == 3, "three parallel formation slots"); require(formation.m_side == 1 && formation.getFormationMaxSpeed() == 5.0f, "formation side and empty speed"); @@ -233,7 +233,7 @@ int main(int argc, char** argv) if (mode == "formation_constructor") { for (int i = 0; i < 3; ++i) - require(!formation.m_slots[i]->m_occupied && !formation.m_slotTargets[i].first, + require(!formation.m_slots[i]->hasSquadMemberAssigned && !formation.m_trailingPositions[i].first, "formation starts empty"); require(same(formation.m_direction, Vec3{1, 0, 0}) && same(formation.m_slots[0]->m_offset, Vec3{0, 0, 0}) && @@ -242,7 +242,7 @@ int main(int argc, char** argv) } else if (mode.compare(0, 5, "join_") == 0) { - formation.m_slots[0]->m_occupied = true; + formation.m_slots[0]->hasSquadMemberAssigned = true; formation.m_slots[0]->m_memberIndex = mode == "join_duplicate" ? 1 : 0; formation.m_v72 = {4, 5, 6}; formation.m_v60 = {7, 8, 9}; formation.m_b56 = true; @@ -251,7 +251,7 @@ int main(int argc, char** argv) slot->m_i20 = 88; slot->m_b24 = true; slot->m_i28 = 99; slot->m_offset = {2, 4, 6}; slot->m_referenceSlot = 77; if (mode == "join_full") - for (auto* s : formation.m_slots) { s->m_occupied = true; s->m_memberIndex = 9; } + for (auto* s : formation.m_slots) { s->hasSquadMemberAssigned = true; s->m_memberIndex = 9; } formation.joinFormation(1); expectCalls("time,member"); require(formation.m_b56 && std::fabs(formation.m_d92 - 10.2) < 1e-12 && @@ -264,8 +264,8 @@ int main(int argc, char** argv) } else { - require(slot->m_occupied && slot->m_memberIndex == 1 && slot->m_i20 == -1 && - !slot->m_b24 && slot->m_i28 == 0 && !formation.m_slots[2]->m_occupied, + require(slot->hasSquadMemberAssigned && slot->m_memberIndex == 1 && slot->m_i20 == -1 && + !slot->m_b24 && slot->m_i28 == 0 && !formation.m_slots[2]->hasSquadMemberAssigned, "first free slot admission"); require(same(slot->m_offset, Vec3{2, 4, 6}) && slot->m_referenceSlot == 77, "admission preserves slot geometry"); @@ -277,7 +277,7 @@ int main(int argc, char** argv) { formation.m_b56 = true; formation.m_d92 = 9.0; formation.m_v60 = {0, 0, 0}; formation.m_v72 = {3, 0, 0}; - formation.m_slots[0]->m_occupied = mode != "movement_empty"; + formation.m_slots[0]->hasSquadMemberAssigned = mode != "movement_empty"; if (mode == "movement_distance_boundary") formation.m_v72.x = 2; if (mode == "movement_deadline_boundary") timer.now = 9; if (mode == "movement_nan_distance") formation.m_v72.x = std::numeric_limits::quiet_NaN(); @@ -303,12 +303,12 @@ int main(int argc, char** argv) } else if (mode.compare(0, 6, "reset_") == 0) { - formation.m_slots[0]->m_occupied = mode != "reset_empty"; + formation.m_slots[0]->hasSquadMemberAssigned = mode != "reset_empty"; coordinatorHasPosition = mode == "reset_frontier"; formation.m_v72 = {11, 12, 13}; for (unsigned i = 0; i != 3; ++i) { - formation.m_slotTargets[i] = std::make_pair(true, Vec3{4, 5, 6}); + formation.m_trailingPositions[i] = std::make_pair(true, Vec3{4, 5, 6}); formation.m_slots[i]->m_i20 = 42; formation.m_slots[i]->m_memberIndex = 20 + i; formation.m_slots[i]->m_b24 = true; @@ -318,10 +318,10 @@ int main(int argc, char** argv) expectCalls(mode == "reset_empty" ? "" : "position"); require(same(formation.m_trailingPosition, Vec3{11, 12, 13}), "trailing anchor copy"); for (unsigned i = 0; i != 3; ++i) - require(!formation.m_slotTargets[i].first && same(formation.m_slotTargets[i].second, Vec3{4, 5, 6}) && + require(!formation.m_trailingPositions[i].first && same(formation.m_trailingPositions[i].second, Vec3{4, 5, 6}) && formation.m_slots[i]->m_i20 == -1 && formation.m_slots[i]->m_memberIndex == 20 + i && formation.m_slots[i]->m_b24, "trailing reset clears only validity and slot target index"); - require(formation.m_slots[0]->m_occupied == (mode != "reset_empty"), "reset preserves occupancy"); + require(formation.m_slots[0]->hasSquadMemberAssigned == (mode != "reset_empty"), "reset preserves occupancy"); } else return 2; observedFormation = nullptr; diff --git a/Code/Tests/aidll/squad_strength_runtime.cpp b/Code/Tests/aidll/squad_strength_runtime.cpp index 91026e05c..d6835534f 100644 --- a/Code/Tests/aidll/squad_strength_runtime.cpp +++ b/Code/Tests/aidll/squad_strength_runtime.cpp @@ -46,10 +46,10 @@ namespace dice { namespace hfe { namespace ai { // [CHOSEN, not recovered] Only a genuine nonnull identity for the stop test. This // fixture-only completion has no interface or layout claim and is never dereferenced. class IAIObject {}; -SquadManager::SquadManager() { sides = m_coordinators; } +SquadManager::SquadManager() { sides = m_Squads; } SquadCoordinator::SquadCoordinator(int side, int squadIndex) : m_squadIndex(squadIndex), m_side(side), m_strategicAreaAssignment(nullptr), - m_i96(-1), m_formation(nullptr), m_i120(0) {} + m_squadLeaderIndex(-1), m_formation(nullptr), m_missionStatus(0) {} SquadMember::SquadMember(SquadCoordinator* squad, IAIPlayer* player, int squadIndex, int side, int memberIndex) : m_squadIndex(squadIndex), m_memberIndex(memberIndex), m_isSquadLeader(false), m_playerId(-1), m_player(player), m_bot(nullptr), m_squad(squad), m_side(side), m_request(nullptr) {} @@ -152,16 +152,16 @@ int main(int argc, char** argv) a.m_squadMembers = {&m1}; if (mode == "leaves") { - a.m_i120 = (std::numeric_limits::min)(); + a.m_missionStatus = (std::numeric_limits::min)(); require(a.getMissionStatus() == (std::numeric_limits::min)(), "full-width status field"); - a.m_i120 = 258; require(a.getMissionStatus() == 258, "fresh status read"); + a.m_missionStatus = 258; require(a.getMissionStatus() == 258, "fresh status read"); require(!a.isSquadAssignedToArea(-123), "null assignment false"); a.m_strategicAreaAssignment = &area; require(a.isSquadAssignedToArea(-123), "signed area index match"); require(!a.isSquadAssignedToArea(0), "area mismatch"); area.m_index = (std::numeric_limits::max)(); require(a.isSquadAssignedToArea(area.m_index), "fresh full-width area index"); - require(a.m_i120 == 258 && trace.empty(), "leaf getters do not call players or mutate status"); + require(a.m_missionStatus == 258 && trace.empty(), "leaf getters do not call players or mutate status"); } else if (mode == "empty") { @@ -174,14 +174,14 @@ int main(int argc, char** argv) else if (mode == "filter") { sides[0] = {&a,&b,&c}; sides[1] = {&d}; - a.m_i120 = 258; a.m_strategicAreaAssignment = &area; - b.m_i120 = 2; b.m_strategicAreaAssignment = nullptr; - c.m_i120 = 2; c.m_strategicAreaAssignment = &area; c.m_squadMembers = {&m3}; + a.m_missionStatus = 258; a.m_strategicAreaAssignment = &area; + b.m_missionStatus = 2; b.m_strategicAreaAssignment = nullptr; + c.m_missionStatus = 2; c.m_strategicAreaAssignment = &area; c.m_squadMembers = {&m3}; require(manager.getSquadStrengths(1,123,kind) == 0, "mission, null and nonmatching area filters"); require(trace.empty(), "filtered squads never query player"); require(manager.getSquadStrengths(1,-123,kind) == 0, "matching dead squad contributes zero"); require(trace == std::vector({31}), "only matching mission-2 squad queried"); - trace.clear(); d.m_i120=2; d.m_strategicAreaAssignment=&area; d.m_squadMembers={&m2}; + trace.clear(); d.m_missionStatus=2; d.m_strategicAreaAssignment=&area; d.m_squadMembers={&m2}; require(manager.getSquadStrengths(2,-123,kind) == 0, "side two selected"); require(trace == std::vector({21}), "other side independent"); } @@ -214,7 +214,7 @@ int main(int argc, char** argv) } else if (mode == "outer_append" || mode == "outer_shrink") { - a.m_i120=b.m_i120=2; a.m_strategicAreaAssignment=b.m_strategicAreaAssignment=&area; + a.m_missionStatus=b.m_missionStatus=2; a.m_strategicAreaAssignment=b.m_strategicAreaAssignment=&area; b.m_squadMembers={&m2}; sides[0]={&a}; if(mode=="outer_shrink") sides[0].push_back(&b); callback = [&](int id,int call) { @@ -228,7 +228,7 @@ int main(int argc, char** argv) IAIObject identity; p1.alive=true; p1.vehicle=&identity; printTrace=true; if(mode=="manager_frontier") { - a.m_i120=2; a.m_strategicAreaAssignment=&area; sides[0]={&a}; + a.m_missionStatus=2; a.m_strategicAreaAssignment=&area; sides[0]={&a}; manager.getSquadStrengths(1,-123,kind); } else a.getStrategicStrength(kind); diff --git a/Code/Tests/aidll/squad_update_runtime.cpp b/Code/Tests/aidll/squad_update_runtime.cpp index 2e6e58630..c7865e9e7 100644 --- a/Code/Tests/aidll/squad_update_runtime.cpp +++ b/Code/Tests/aidll/squad_update_runtime.cpp @@ -36,11 +36,11 @@ using Rosters=std::vector[2]; using PositionMap=std::map; using Messages=std::list; #define MEMBER_ACCESS(Tag,Type,Member) struct Tag { using type=Type SquadManager::*; friend type nativeMember(Tag); }; template struct NativeAccess; -MEMBER_ACCESS(RostersTag,Rosters,m_coordinators) +MEMBER_ACCESS(RostersTag,Rosters,m_Squads) MEMBER_ACCESS(SquadCursorTag,int,m_squadCursor) MEMBER_ACCESS(SideCursorTag,int,m_sideCursor) -MEMBER_ACCESS(FirstBlockTag,SquadManager::SideBlock,m_sideBlock0) -MEMBER_ACCESS(SecondBlockTag,SquadManager::SideBlock,m_sideBlock1) +using Blocks=SquadManager::SideBlock[2]; +MEMBER_ACCESS(BlocksTag,Blocks,m_artillery) MEMBER_ACCESS(DurationTag,double,m_double156) MEMBER_ACCESS(FloatTag,float,m_float152) MEMBER_ACCESS(PositionsTag,PositionMap,m_playerValidPositions) @@ -50,7 +50,7 @@ static SquadManager* tested; static Rosters& sides() { return tested->*nativeMember(RostersTag{}); } static int& squadCursor() { return tested->*nativeMember(SquadCursorTag{}); } static int& sideCursor() { return tested->*nativeMember(SideCursorTag{}); } -static SquadManager::SideBlock& block(int side) { return side?tested->*nativeMember(SecondBlockTag{}):tested->*nativeMember(FirstBlockTag{}); } +static SquadManager::SideBlock& block(int side) { return (tested->*nativeMember(BlocksTag{}))[side?1:0]; } static double& duration() { return tested->*nativeMember(DurationTag{}); } static std::string mode,calls; static int maximumSquads=1,maxQueries,pathCalls,humanCalls; @@ -98,7 +98,7 @@ int main(int argc,char** argv) { require(squadCursor()==0 && sideCursor()==1 && duration()==25.0 && manager->*nativeMember(FloatTag{})==40.0f,"real constructor scalar stores"); require(sides()[0].empty() && sides()[1].empty() && (manager->*nativeMember(PositionsTag{})).empty() && (manager->*nativeMember(MessagesTag{})).empty(),"real native containers empty"); for(int side=0;side<2;++side) { - require(!block(side).m_b0,"side active flag initialized"); + require(!block(side).incomingArtillery,"side active flag initialized"); const Vec3 positions[]={block(side).m_artilleryPosition,block(side).m_fleePos0,block(side).m_fleePos1}; for(const Vec3& p:positions) require(p.x==0 && p.y==0 && p.z==0,"three real Vec3 values zero initialized"); byteValue(&block(side).m_artilleryStartTime,sizeof(double),0xa5,"timestamp representation remains unwritten"); @@ -119,14 +119,14 @@ int main(int argc,char** argv) { block(0).m_artilleryStartTime=block(1).m_artilleryStartTime=10.0; const std::string pathPass="p0:0,p0:1,p1:0,p1:1"; if(mode.compare(0,4,"art_")==0) { - block(0).m_b0=true; + block(0).incomingArtillery=true; std::string wanted=pathPass; bool active0=false,active1=false; - if(mode=="art_inactive") { block(0).m_b0=false; wanted=""; } + if(mode=="art_inactive") { block(0).incomingArtillery=false; wanted=""; } else if(mode=="art_equal" || mode=="art_future") { expectedTime=mode=="art_equal"?35.0:34.0; wanted=""; active0=true; } else if(mode=="art_first") {} else if(mode=="art_just_after") expectedTime=std::nextafter(35.0,36.0); - else if(mode=="art_second") { block(0).m_b0=false; block(1).m_b0=true; } - else if(mode=="art_both") { block(1).m_b0=true; wanted+=","+pathPass; } + else if(mode=="art_second") { block(0).incomingArtillery=false; block(1).incomingArtillery=true; } + else if(mode=="art_both") { block(1).incomingArtillery=true; wanted+=","+pathPass; } else if(mode=="art_time_nan" || mode=="art_duration_nan" || mode=="art_start_nan") { if(mode=="art_time_nan") expectedTime=std::numeric_limits::quiet_NaN(); else if(mode=="art_duration_nan") duration()=std::numeric_limits::quiet_NaN(); @@ -134,13 +134,13 @@ int main(int argc,char** argv) { wanted=""; active0=true; } else if(mode=="art_enable_second") { - onPath=[&](SquadCoordinator*) { if(pathCalls==1) block(1).m_b0=true; }; wanted+=","+pathPass; + onPath=[&](SquadCoordinator*) { if(pathCalls==1) block(1).incomingArtillery=true; }; wanted+=","+pathPass; } else if(mode=="art_disable_second") { - block(1).m_b0=true; onPath=[&](SquadCoordinator*) { if(pathCalls==1) block(1).m_b0=false; }; + block(1).incomingArtillery=true; onPath=[&](SquadCoordinator*) { if(pathCalls==1) block(1).incomingArtillery=false; }; } else if(mode=="art_duration_change") { - block(1).m_b0=true; active1=true; onPath=[&](SquadCoordinator*) { if(pathCalls==1) duration()=100; }; + block(1).incomingArtillery=true; active1=true; onPath=[&](SquadCoordinator*) { if(pathCalls==1) duration()=100; }; } else if(mode=="art_grow") { onPath=[&](SquadCoordinator*) { if(pathCalls==1) { sides()[0].reserve(sides()[0].capacity()+7); sides()[0].push_back(&e); } }; @@ -151,16 +151,16 @@ int main(int argc,char** argv) { onPath=[&](SquadCoordinator*) { if(pathCalls==1) { sides()[0].reserve(sides()[0].capacity()+7); sides()[0][1]=&e; } }; wanted="p0:0,p0:2,p1:0,p1:1"; } - else if(mode=="art_rearm_first") { onPath=[&](SquadCoordinator*) { if(pathCalls==1) block(0).m_b0=true; }; active0=true; } + else if(mode=="art_rearm_first") { onPath=[&](SquadCoordinator*) { if(pathCalls==1) block(0).incomingArtillery=true; }; active0=true; } else unexpected("unknown artillery mode"); const auto mutation=onPath; onPath=[&](SquadCoordinator* coordinator) { - if(mode=="art_both") require(block(0).m_b0==false && block(1).m_b0==(pathCalls<=4),"side clear precedes each full traversal"); - else if(pathCalls==1) require(mode=="art_second"?!block(1).m_b0:!block(0).m_b0,"expired flag cleared before callback"); + if(mode=="art_both") require(block(0).incomingArtillery==false && block(1).incomingArtillery==(pathCalls<=4),"side clear precedes each full traversal"); + else if(pathCalls==1) require(mode=="art_second"?!block(1).incomingArtillery:!block(0).incomingArtillery,"expired flag cleared before callback"); if(mutation) mutation(coordinator); }; manager.updateArtilleryStatus(expectedTime); expect(wanted); - require(block(0).m_b0==active0 && block(1).m_b0==active1,"final artillery flags"); + require(block(0).incomingArtillery==active0 && block(1).incomingArtillery==active1,"final artillery flags"); } else { std::string wanted="messages,u0:0"; int wantedSide=0,wantedCursor=0; if(mode=="tick_cycle") { @@ -189,7 +189,7 @@ int main(int argc,char** argv) { sideCursor()=0; wanted="messages,u1:0"; wantedSide=1; wantedCursor=4; onUpdate=[](SquadCoordinator*) { sides()[0].clear(); squadCursor()=3; }; } - else if(mode=="tick_artillery_order") { block(0).m_b0=true; wanted=pathPass+",messages,u0:0"; } + else if(mode=="tick_artillery_order") { block(0).incomingArtillery=true; wanted=pathPass+",messages,u0:0"; } else if(mode=="tick_message_mutation") { wanted="messages,u0:2,humans"; wantedSide=1; onMessages=[&]() { sideCursor()=0; squadCursor()=1; sides()[1].reserve(sides()[1].capacity()+7); sides()[1][1]=&e; }; diff --git a/Code/Tests/aidll/user_order_runtime.cmd b/Code/Tests/aidll/user_order_runtime.cmd index 2eac620d0..bfd36d3a2 100644 --- a/Code/Tests/aidll/user_order_runtime.cmd +++ b/Code/Tests/aidll/user_order_runtime.cmd @@ -7,7 +7,7 @@ set "TASK_CODE=%~dp0..\.." if not defined BF2_USER_ORDER_OUT set "BF2_USER_ORDER_OUT=%TASK_CODE%\Build\ai_user_order_validation_20260927" if not exist "%BF2_USER_ORDER_OUT%" mkdir "%BF2_USER_ORDER_OUT%" set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\UserOrderManager.cpp" /Fo"%BF2_USER_ORDER_OUT%\UserOrderManager.obj" +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIStrategicEntity\UserOrders\UserOrderManager.cpp" /Fo"%BF2_USER_ORDER_OUT%\UserOrderManager.obj" if errorlevel 1 exit /b 1 cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%~dp0user_order_runtime.cpp" /Fo"%BF2_USER_ORDER_OUT%\fixture.obj" if errorlevel 1 exit /b 1 diff --git a/Code/Tests/aidll/user_order_runtime.cpp b/Code/Tests/aidll/user_order_runtime.cpp index bfad3c0f8..d2d5522fb 100644 --- a/Code/Tests/aidll/user_order_runtime.cpp +++ b/Code/Tests/aidll/user_order_runtime.cpp @@ -13,7 +13,7 @@ #include #include #define private public -#include "../../BF2/AI/AIDLL/AI/Main/UserOrderManager.h" +#include "../../BF2/AI/AIDLL/AI/AIStrategicEntity/UserOrders/UserOrderManager.h" #include "../../BF2/AI/AIDLL/AI/AIStrategicEntity/GuardPosition.h" #include "../../BF2/AI/AIDLL/AI/AIStrategicEntity/PatrolPath.h" #undef private diff --git a/Code/Tests/aidll/vehicle_occupancy_runtime.cmd b/Code/Tests/aidll/vehicle_occupancy_runtime.cmd index 097f353fa..45f5c400e 100644 --- a/Code/Tests/aidll/vehicle_occupancy_runtime.cmd +++ b/Code/Tests/aidll/vehicle_occupancy_runtime.cmd @@ -11,7 +11,7 @@ if errorlevel 1 exit /b 1 set "TASK_FLAGS=/nologo /c /O2 /MD /std:c++14 /permissive /EHsc /W3 /Gy /DDEDICATED=1 /DBF2_IMAGE_AIDLL" cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" /FAs /Fa"%BF2_VEHICLE_OCCUPANCY_OUT%\actual.asm" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIUtils\VehicleOccupancy.cpp" /Fo"%BF2_VEHICLE_OCCUPANCY_OUT%\actual.obj" >"%BF2_VEHICLE_OCCUPANCY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed -cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" /Fo"%BF2_VEHICLE_OCCUPANCY_OUT%\manager.obj" >>"%BF2_VEHICLE_OCCUPANCY_OUT%\compile.log" 2>&1 +cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%TASK_CODE%\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" /Fo"%BF2_VEHICLE_OCCUPANCY_OUT%\manager.obj" >>"%BF2_VEHICLE_OCCUPANCY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed cl %TASK_FLAGS% /FI"%TASK_CODE%\BF2\Core\BuildConfig.h" "%~dp0vehicle_occupancy_runtime.cpp" /Fo"%BF2_VEHICLE_OCCUPANCY_OUT%\fixture.obj" >>"%BF2_VEHICLE_OCCUPANCY_OUT%\compile.log" 2>&1 if errorlevel 1 goto failed diff --git a/Code/Tests/aidll/vehicle_occupancy_runtime.cpp b/Code/Tests/aidll/vehicle_occupancy_runtime.cpp index 2498e648d..d5d5d3ef1 100644 --- a/Code/Tests/aidll/vehicle_occupancy_runtime.cpp +++ b/Code/Tests/aidll/vehicle_occupancy_runtime.cpp @@ -3,7 +3,7 @@ // for this caller fixture. They do not establish the unrecovered engine forwarding ABI. #include "../../BF2/AI/AIDLL/AI/AIUtils/VehicleOccupancy.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/Information.h" -#include "../../BF2/AI/AIDLL/AI/AIKnowledge/InformationManager.h" +#include "../../BF2/AI/AIDLL/AI/Main/InformationManager.h" #include "../../BF2/AI/AIDLL/AI/AIKnowledge/IPIUnit.h" #include #include @@ -47,7 +47,7 @@ namespace dice { namespace hfe { namespace ai { // [TEMP] Chosen genuine native storage, no raw objects or header rewriting. A constructor // may access its actual private fields; the captured typed field pointer permits mutations. Information::Information(IAIObject* object, double time) - : m_objectTypeFlags(0), m_strength(0), m_time(time), m_object(object), m_booked(false), + : m_objectTypeFlags(0), m_strength(0), m_time(time), m_object(object), m_isBooked(false), m_bookingPlayerId(-1), m_armament(nullptr), m_controlInfo(nullptr), m_cover(nullptr), m_mobile(nullptr), m_physical(nullptr), m_unit(constructingUnit) { unitSlots[this] = &m_unit; } diff --git a/Code/Tests/aidll/vehicle_occupancy_runtime.py b/Code/Tests/aidll/vehicle_occupancy_runtime.py index 263172ab8..dedb83fbe 100644 --- a/Code/Tests/aidll/vehicle_occupancy_runtime.py +++ b/Code/Tests/aidll/vehicle_occupancy_runtime.py @@ -18,8 +18,8 @@ def record(out): out.mkdir(parents=True, exist_ok=True) paths = ('AI/AIDLL/AI/AIUtils/VehicleOccupancy.cpp', 'AI/AIDLL/AI/AIUtils/VehicleOccupancy.h', - 'AI/AIDLL/AI/AIKnowledge/InformationManager.cpp', - 'AI/AIDLL/AI/AIKnowledge/InformationManager.h', + 'AI/AIDLL/AI/Main/InformationManager.cpp', + 'AI/AIDLL/AI/Main/InformationManager.h', 'AI/AIDLL/AI/AIKnowledge/Information.h', 'AI/AIDLL/AI/AIKnowledge/IPIUnit.h', 'Core/SpHandlePool.h') evidence = [] diff --git a/Code/Tests/syntaxcheck.cmd b/Code/Tests/syntaxcheck.cmd index 65efcdf75..693bbc64b 100644 --- a/Code/Tests/syntaxcheck.cmd +++ b/Code/Tests/syntaxcheck.cmd @@ -1517,7 +1517,7 @@ cl %FLAGS0% "%~dp0..\BF2\Game\Objects\Visual\LightSourceTemplate.cpp" if errorlevel 1 set /a RC+=1 @rem AI manifests: every engine AI TU and every AIDLL-only TU. -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\Aimer.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotActionPlan\Aimer.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\BotMain.cpp" if errorlevel 1 set /a RC+=1 @@ -1541,7 +1541,10 @@ cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensedObject.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgent.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgentPatterns.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgentMouseFreeLookPattern.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgentNullPattern.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgentSoldierPattern.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SensingAgentTurretPattern.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\SquadCoordinator.cpp" if errorlevel 1 set /a RC+=1 @@ -1885,11 +1888,12 @@ cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BBTrigger if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\BotBehaviour.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\CustomCurve.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\CustomCurve.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\SCurve.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\UrgeCurve.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\UrgencyMerger.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBot\UrgencyMerger.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIBotBehaviour\VehicleUrgencyCalculator.cpp" if errorlevel 1 set /a RC+=1 @@ -2017,7 +2021,7 @@ cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationF if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationKnown.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationManager.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\InformationManager.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\InformationReal.cpp" if errorlevel 1 set /a RC+=1 @@ -2025,7 +2029,7 @@ cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfo.c if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoKnown.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoManager.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIUtils\WeaponInfoManager.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\WeaponInfoReal.cpp" if errorlevel 1 set /a RC+=1 @@ -2195,7 +2199,7 @@ cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategic\StrategyPrer if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AILandingZone.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AILandingZoneManager.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AILandingZoneManager.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\AIStrategicArea.cpp" if errorlevel 1 set /a RC+=1 @@ -2231,7 +2235,7 @@ cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\SAWayP if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\AICamera.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\AerialHeightMap.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIPathFinding\AerialHeightMap\AerialHeightMap.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicMap\BFStrategicEnvironment.cpp" if errorlevel 1 set /a RC+=1 @@ -2308,8 +2312,9 @@ if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AILODManager.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIMain.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\IAIMain.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIMineManager.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIKnowledge\AIMineManager.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\AIModule.cpp" if errorlevel 1 set /a RC+=1 @@ -2342,12 +2347,14 @@ if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\CommunicationHub.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\IAIPathfinding.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\IAIPathfindingSetup.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\IBotManager.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\IBotManagerModifier.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\StrategyManager.cpp" if errorlevel 1 set /a RC+=1 -cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\Main\UserOrderManager.cpp" +cl %FLAGS% /DBF2_IMAGE_AIDLL=1 "%~dp0..\BF2\AI\AIDLL\AI\AIStrategicEntity\UserOrders\UserOrderManager.cpp" if errorlevel 1 set /a RC+=1 cl %FLAGS% "%~dp0..\BF2\AI\AIInterface\BFKnowledge\AIObject.cpp" if errorlevel 1 set /a RC+=1 From b840398e18fcba0f8b1ec348b90201a391e40993 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Fri, 6 Nov 2026 06:55:46 +0100 Subject: [PATCH 09/71] Memory: recover Memory.dll (111/111 functions, differential-tested against retail) Recovers the retail Memory.dll (Ver 1.01, 2005/01/10 "Final") into Code/BF2/Memory as its own image, bf2_memory. Every function cites its PE address; placement follows the shipped function and data order. The Final build is mostly stubs: only the chunk pools, the sanity limit, getStatus and the resource counters do work; the counters, trace and histogram exports return constants, as in retail. - Platform seams behind #if, [CHOSEN, not recovered]: constructor/destructor instead of DllMain on POSIX, stderr instead of the message box, pthreads, and a 16-byte header slot on 64-bit. - BF2_MEMORY_PASSTHROUGH (AUTO/ON/OFF) forwards to malloc/free under AddressSanitizer. - Built on request only (EXCLUDE_FROM_ALL) and linked into no game image: the game keeps allocating through the shared CRT (issue #7). Code/BF2/Memory is skipped by the engine source discovery in CMakeLists.txt and Code/Build/build.cmd. - Windows: Code/Build/memory.cmd. Tests: Code/Tests/memory (unit tests, internal tests, and memory_diff, which runs one allocation script against the retail and the rebuilt DLL; the outputs were identical with MSVC x86). Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 10 +- Code/BF2/Memory/AllocInfo.cpp | 298 +++++++++++++++++ Code/BF2/Memory/CMakeLists.txt | 90 +++++ Code/BF2/Memory/Callstack.cpp | 55 +++ Code/BF2/Memory/ChunkPools.cpp | 264 +++++++++++++++ Code/BF2/Memory/Histogram.cpp | 161 +++++++++ Code/BF2/Memory/Memory.cpp | 459 ++++++++++++++++++++++++++ Code/BF2/Memory/Memory.h | 91 +++++ Code/BF2/Memory/MemoryInternal.h | 385 +++++++++++++++++++++ Code/BF2/Memory/MemoryTrace.cpp | 332 +++++++++++++++++++ Code/BF2/Memory/Threading.cpp | 249 ++++++++++++++ Code/Build/build.cmd | 4 + Code/Build/memory.cmd | 53 +++ Code/Tests/memory/CMakeLists.txt | 41 +++ Code/Tests/memory/memory_diff.cmd | 55 +++ Code/Tests/memory/memory_diff.cpp | 278 ++++++++++++++++ Code/Tests/memory/memory_internal.cpp | 298 +++++++++++++++++ Code/Tests/memory/memory_unit.cpp | 393 ++++++++++++++++++++++ 18 files changed, 3515 insertions(+), 1 deletion(-) create mode 100644 Code/BF2/Memory/AllocInfo.cpp create mode 100644 Code/BF2/Memory/CMakeLists.txt create mode 100644 Code/BF2/Memory/Callstack.cpp create mode 100644 Code/BF2/Memory/ChunkPools.cpp create mode 100644 Code/BF2/Memory/Histogram.cpp create mode 100644 Code/BF2/Memory/Memory.cpp create mode 100644 Code/BF2/Memory/Memory.h create mode 100644 Code/BF2/Memory/MemoryInternal.h create mode 100644 Code/BF2/Memory/MemoryTrace.cpp create mode 100644 Code/BF2/Memory/Threading.cpp create mode 100644 Code/Build/memory.cmd create mode 100644 Code/Tests/memory/CMakeLists.txt create mode 100644 Code/Tests/memory/memory_diff.cmd create mode 100644 Code/Tests/memory/memory_diff.cpp create mode 100644 Code/Tests/memory/memory_internal.cpp create mode 100644 Code/Tests/memory/memory_unit.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ced401078..9d147a502 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -113,7 +113,10 @@ set(bf2_engine_sources) set(bf2_engine_headers) foreach(component_path IN LISTS bf2_component_paths) get_filename_component(component_name "${component_path}" NAME) - if(IS_DIRECTORY "${component_path}" AND NOT component_name STREQUAL "External") + # Memory is the recovered Memory.dll, its own image (bf2_memory, Code/BF2/Memory/CMakeLists.txt); + # the engine keeps its own memory:: stubs, so its units must not join the engine source list. + if(IS_DIRECTORY "${component_path}" AND NOT component_name STREQUAL "External" + AND NOT component_name STREQUAL "Memory") file(GLOB_RECURSE component_sources CONFIGURE_DEPENDS "${component_path}/*.cpp" @@ -1636,6 +1639,11 @@ set_property(TARGET bf2_syntaxcheck PROPERTY FOLDER "Diagnostics") endif() include(CTest) + +# bf2_memory - the rebuilt Memory.dll (Code/BF2/Memory). Built on request only (EXCLUDE_FROM_ALL) +# and linked into no game image (issue #7). Its tests join CTest when BF2_MEMORY_TESTS is ON. +add_subdirectory(Code/BF2/Memory) + # The focused checks mirror Code/Tests/*.cmd, which are MSVC x86 gates; they are not part of the # Linux port (its checks are the dice_py runtime check and the production run). if(BUILD_TESTING AND MSVC) diff --git a/Code/BF2/Memory/AllocInfo.cpp b/Code/BF2/Memory/AllocInfo.cpp new file mode 100644 index 000000000..bf0bf165c --- /dev/null +++ b/Code/BF2/Memory/AllocInfo.cpp @@ -0,0 +1,298 @@ +// Allocation records keyed by call stack, and the leak report written from them. +// +// In the shipped configuration nothing creates records: the call-stack capture is compiled out +// (Callstack.cpp) and the only caller, the DLL detach path, dumps an empty table without a file. +// The bodies are kept as shipped. Placement [INFERRED]. + +#include +#include +#include + +#include "MemoryInternal.h" + +namespace dice { +namespace hfe { +namespace memory { + +namespace { + +int s_hashSize; +AllocInfo** s_hashTable; + +} // namespace + +// PE 0x10001010. Rotating XOR over the return addresses. +unsigned int hashCallstack(const unsigned int* frames, int numFrames) +{ + unsigned int hash = 0x719fdae9; + for (int i = numFrames; i > 0; --i) { + hash ^= *frames++; + hash = (hash << 8) | (hash >> 24); + } + return hash; +} + +// PE 0x10001040. +void initAllocInfoHash(int hashSize) +{ + s_hashSize = hashSize; + s_hashTable = static_cast(std::malloc(hashSize * sizeof(AllocInfo*))); + std::memset(s_hashTable, 0, hashSize * sizeof(AllocInfo*)); +} + +// PE 0x10001080. Clears the counters of every record that belongs to a trace identifier, identifier +// by identifier. +void resetTraceAllocInfo() +{ + for (int traceId = 0; traceId < g_traceIdentifierCount; ++traceId) { + for (int i = 0; i < s_hashSize; ++i) { + for (AllocInfo* info = s_hashTable[i]; info; info = info->next) { + if (info->traceId != traceId) + continue; + info->currentNumAllocs = 0; + info->currentTotalSize = 0; + info->peakSize = 0; + info->peakNumAllocs = 0; + info->visualFrameAllocs = 0; + info->physicsFrameAllocs = 0; + info->peakVisualFrameAllocs = 0; + info->peakPhysicsFrameAllocs = 0; + } + } + } +} + +// PE 0x100010F0. +const char* allocInfoNotActive() +{ + return "not active in final build"; +} + +// PE 0x10001100. Writes the leak report to `fileName` (when given) for the records of `traceId` +// (-1 for all), listing only records with live allocations unless `includeAll`. `release` frees +// each listed record and then the table; the records' frame arrays are not freed. +// The report header is written without checking that the file opened. +void dumpAllocInfo(const char* fileName, bool includeAll, bool release, int traceId) +{ + FILE* file = 0; + if (fileName) { + file = std::fopen(fileName, BF2_MEMORY_TEXT_WRITE); + std::fprintf(file, "# Leak report format v1.10\n"); + } + + int populated = 0; + int longestChain = 0; + if (file) { + std::fprintf(file, "\n# Module dump\n"); + std::fprintf(file, "\n# Allocation history (%s)\n", includeAll ? "all allocations" : "leaks only"); + } + + int totalElements = 0; + for (int bucket = 0; bucket < s_hashSize; ++bucket) { + AllocInfo* info = s_hashTable[bucket]; + if (info) + ++populated; + int chain = 0; + if (!info) + continue; + for (;;) { + AllocInfo* next = info->next; + if (traceId != -1 && info->traceId != traceId) { + // A non-matching record ends the bucket's walk without updating the longest chain + // when it is the last one. + info = next; + if (!info) + break; + continue; + } + if (file && (info->currentNumAllocs != 0 || includeAll)) { + std::fprintf(file, + "alloc depth=%d peakSize=%d peakNumAllocs=%d currentNumAllocs=%d " + "currentTotalSize=%d minAllocSize=%d maxAllocSize=%d ", + info->numFrames, info->peakSize, info->peakNumAllocs, + info->currentNumAllocs, info->currentTotalSize, info->minAllocSize, + info->maxAllocSize); + for (int i = 0; i < info->numFrames; ++i) + std::fprintf(file, "0x%08x%s", info->frames[i], i + 1 < info->numFrames ? "<-" : ""); + std::fprintf(file, "\n"); + } + ++totalElements; + if (release) + std::free(info); + ++chain; + info = next; + if (!info) { + if (chain > longestChain) + longestChain = chain; + break; + } + } + } + + if (file) { + std::fprintf(file, "\n# AllocInfo hash table summary:\n"); + std::fprintf(file, "# hash size: %d\n", s_hashSize); + // x87: the int product with 100.0f is divided by the int size at extended precision and + // stored as a double. + std::fprintf(file, "# populated bucket indices: %d (%5.2g%%)\n", populated, + static_cast(populated) * 100.0 / static_cast(s_hashSize)); + std::fprintf(file, "# total elements: %d\n", totalElements); + std::fprintf(file, "# longest chain: %d\n", longestChain); + std::fclose(file); + } + if (release) + std::free(s_hashTable); +} + +// PE 0x10001310. Clears the live counters of every record. The longest chain is counted and then +// discarded. +void clearCurrentAllocInfo() +{ + int longestChain = 0; + for (int bucket = 0; bucket < s_hashSize; ++bucket) { + int chain = 0; + AllocInfo* info = s_hashTable[bucket]; + if (!info) + continue; + do { + info->currentNumAllocs = 0; + info->currentTotalSize = 0; + info = info->next; + ++chain; + } while (info); + if (chain > longestChain) + longestChain = chain; + } + (void)longestChain; +} + +// PE 0x10001360. Returns the record of the caller's call stack (at most 128 frames, skipping 3), +// creating it at the end of its bucket. A found record moves to the front of its bucket. Returns +// null when the capture fails. +AllocInfo* findAllocInfo(int depth) +{ + unsigned int frames[128]; + if (depth > 128) + depth = 128; + const int numFrames = captureCallstack(frames, depth, 3); + if (numFrames == -1) + return 0; + + const unsigned int hash = hashCallstack(frames, numFrames); + const unsigned int bucket = hash % static_cast(s_hashSize); + AllocInfo* prev = 0; + AllocInfo* const head = s_hashTable[bucket]; + for (AllocInfo* info = head; info; info = info->next) { + if (info->hash == hash && info->numFrames == numFrames && + std::memcmp(info->frames, frames, numFrames * sizeof(unsigned int)) == 0) { + if (head != info) { + AllocInfo* const next = info->next; + s_hashTable[bucket] = info; + info->next = head; + if (prev) + prev->next = next; + } + return info; + } + prev = info; + } + + AllocInfo* info = static_cast(std::malloc(sizeof(AllocInfo))); + std::memset(info, 0, sizeof(AllocInfo)); + info->hash = hash; + info->frames = static_cast(std::malloc(numFrames * sizeof(unsigned int))); + std::memcpy(info->frames, frames, numFrames * sizeof(unsigned int)); + info->numFrames = numFrames; + if (prev) + prev->next = info; + else + s_hashTable[hash % static_cast(s_hashSize)] = info; + return info; +} + +// PE 0x100014C0. Empty in the shipped configuration. +void allocInfoNoOp() +{ +} + +// PE 0x100014D0. Records an allocation of `size` bytes (a negative size records a free of -size). +// An allocation is attributed to the innermost trace scope opened on the calling thread, and its +// per-frame count restarts when the visual or physics frame advanced. +void AllocInfo::update(int size) +{ + if (!(size >= 0)) { + currentNumAllocs += -1; + currentTotalSize -= -size; + return; + } + + traceId = -1; + if (g_traceStackTop != -1) { + const TraceStackEntry& entry = g_traceStack[g_traceStackTop]; + if (entry.thread == currentThreadId()) + traceId = entry.id; + } + + visualFrameAllocs += 1; + if (visualFrameAllocs > peakVisualFrameAllocs) + peakVisualFrameAllocs = visualFrameAllocs; + if (lastVisualFrame != g_visualFrame) { + visualFrameAllocs = 0; + lastVisualFrame = g_visualFrame; + } + physicsFrameAllocs += 1; + if (physicsFrameAllocs > peakPhysicsFrameAllocs) + peakPhysicsFrameAllocs = physicsFrameAllocs; + if (lastPhysicsFrame != g_physicsFrame) { + physicsFrameAllocs = 0; + lastPhysicsFrame = g_physicsFrame; + } + + currentNumAllocs += 1; + currentTotalSize += size; + if (peakSize == 0) { + minAllocSize = size; + maxAllocSize = size; + } else { + if (minAllocSize > size) + minAllocSize = size; + if (maxAllocSize < size) + maxAllocSize = size; + } + if (peakSize < currentTotalSize) + peakSize = currentTotalSize; + if (peakNumAllocs < currentNumAllocs) + peakNumAllocs = currentNumAllocs; +} + +// PE 0x100015C0. Writes the leak report and releases the records. +void dumpLeaks(const char* fileName, bool includeAll) +{ + dumpAllocInfo(fileName, includeAll, true, -1); +} + +// PE 0x100015E0. +void dumpAllAllocInfo(const char* fileName) +{ + dumpAllocInfo(fileName, false, false, -1); +} + +// PE 0x10001600. A negative identifier lists every record of the identifier, live or not. +void dumpTraceAllocInfo(const char* fileName, int traceId) +{ + dumpAllocInfo(fileName, traceId < 0, false, traceId); +} + +// PE 0x10001630. +void writeAllocInfoNotActive(const char* fileName) +{ + FILE* file = std::fopen(fileName, BF2_MEMORY_TEXT_WRITE); + if (file) { + std::fprintf(file, "%s", "not active in final build"); + std::fclose(file); + } +} + +} // namespace memory +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Memory/CMakeLists.txt b/Code/BF2/Memory/CMakeLists.txt new file mode 100644 index 000000000..24405ac79 --- /dev/null +++ b/Code/BF2/Memory/CMakeLists.txt @@ -0,0 +1,90 @@ +# bf2_memory - the rebuilt Memory.dll. +# +# Builds on its own (cmake -S Code/BF2/Memory) or from the top-level tree, where it is +# EXCLUDE_FROM_ALL. No game image links it: the game allocates through the shared CRT +# (https://github.com/B2BF/OpenBF2/issues/7). Output name Memory (Memory.dll, Memory.dylib, +# Memory.so). + +cmake_minimum_required(VERSION 3.16) + +set(BF2_MEMORY_STANDALONE OFF) +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + project(BF2Memory LANGUAGES CXX) + set(BF2_MEMORY_STANDALONE ON) +endif() + +# [CHOSEN, not recovered] AUTO enables pass-through (no chunk pools) when the compiler reports +# AddressSanitizer; ON and OFF force it. +set(BF2_MEMORY_PASSTHROUGH "AUTO" CACHE STRING "Memory.dll pass-through to the CRT heap: AUTO, ON or OFF") +set_property(CACHE BF2_MEMORY_PASSTHROUGH PROPERTY STRINGS AUTO ON OFF) +option(BF2_MEMORY_ASAN "Build bf2_memory and its tests with AddressSanitizer (Clang/GCC)" OFF) + +set(BF2_MEMORY_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/AllocInfo.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Callstack.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/ChunkPools.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Memory.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Histogram.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Threading.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/MemoryTrace.cpp" +) + +function(bf2_memory_configure target) + target_compile_features(${target} PRIVATE cxx_std_14) + target_include_directories(${target} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}") + target_compile_definitions(${target} PRIVATE BF2_MEMORY_BUILD) + if(BF2_MEMORY_PASSTHROUGH STREQUAL "ON") + target_compile_definitions(${target} PRIVATE BF2_MEMORY_PASSTHROUGH=1) + elseif(BF2_MEMORY_PASSTHROUGH STREQUAL "OFF") + target_compile_definitions(${target} PRIVATE BF2_MEMORY_PASSTHROUGH=0) + endif() + if(MSVC) + target_compile_definitions(${target} PRIVATE _CRT_SECURE_NO_WARNINGS) + # The shipped DLL uses the dynamic CRT (MSVCR71/MSVCP71). + set_property(TARGET ${target} PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") + else() + # The shipped code formats with sprintf; keep it and silence the SDK deprecation. + target_compile_options(${target} PRIVATE -Wall -Wno-deprecated-declarations) + if(BF2_MEMORY_ASAN) + target_compile_options(${target} PRIVATE -fsanitize=address -fno-omit-frame-pointer) + target_link_options(${target} PRIVATE -fsanitize=address) + endif() + endif() +endfunction() + +if(BF2_MEMORY_STANDALONE) + add_library(bf2_memory SHARED ${BF2_MEMORY_SOURCES}) +else() + add_library(bf2_memory SHARED EXCLUDE_FROM_ALL ${BF2_MEMORY_SOURCES}) +endif() +bf2_memory_configure(bf2_memory) +set_target_properties(bf2_memory PROPERTIES + OUTPUT_NAME Memory + PREFIX "" + CXX_VISIBILITY_PRESET hidden + FOLDER "BF2" +) +if(WIN32) + target_link_libraries(bf2_memory PRIVATE kernel32 user32) +else() + find_package(Threads REQUIRED) + target_link_libraries(bf2_memory PRIVATE Threads::Threads) +endif() + +# The same sources as a static object set, for the white-box tests of the internal report formats. +add_library(bf2_memory_internal STATIC EXCLUDE_FROM_ALL ${BF2_MEMORY_SOURCES}) +bf2_memory_configure(bf2_memory_internal) +if(WIN32) + target_link_libraries(bf2_memory_internal PUBLIC kernel32 user32) +else() + find_package(Threads REQUIRED) + target_link_libraries(bf2_memory_internal PUBLIC Threads::Threads) +endif() + +option(BF2_MEMORY_TESTS "Build the bf2_memory tests" ${BF2_MEMORY_STANDALONE}) +if(BF2_MEMORY_TESTS) + if(BF2_MEMORY_STANDALONE) + enable_testing() + endif() + add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../../Tests/memory" "${CMAKE_CURRENT_BINARY_DIR}/tests") +endif() diff --git a/Code/BF2/Memory/Callstack.cpp b/Code/BF2/Memory/Callstack.cpp new file mode 100644 index 000000000..476c61399 --- /dev/null +++ b/Code/BF2/Memory/Callstack.cpp @@ -0,0 +1,55 @@ +// Call-stack capture for the allocation records. Compiled out in the shipped configuration: the +// capture reports zero frames and nothing ever activates it. The lock is constructed and destroyed +// with the DLL but never taken. +// +// Names follow the matching functions of the 2006 Memory_r.dll, which implements them +// (OutputDebugString notice, frame-pointer walk); [INFERRED]. Placement [INFERRED]. + +#include "MemoryInternal.h" + +namespace dice { +namespace hfe { +namespace memory { + +namespace { + +bool s_callstackActive; +Mutex s_callstackLock; + +} // namespace + +// PE 0x10001670. +bool isCallstackActive() +{ + return s_callstackActive; +} + +// PE 0x10001680. +void initCallstack() +{ +} + +// PE 0x10001690. +void shutdownCallstack() +{ +} + +// PE 0x100016A0. Returns the number of frames stored. +int captureCallstack(unsigned int* frames, int maxFrames, int skipFrames) +{ + (void)frames; + (void)maxFrames; + (void)skipFrames; + return 0; +} + +// PE 0x100016B0. [UNRESOLVED] Identity unknown; the 2006 build's counterpart also returns 0. No +// caller, so the parameter list is not attested; declared without parameters. +int callstackModuleCount() +{ + return 0; +} + +} // namespace memory +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Memory/ChunkPools.cpp b/Code/BF2/Memory/ChunkPools.cpp new file mode 100644 index 000000000..a9007c864 --- /dev/null +++ b/Code/BF2/Memory/ChunkPools.cpp @@ -0,0 +1,264 @@ +// Fixed-size element pools for small blocks of the main thread. +// +// Seventeen size classes (the table below) each own a chain of 1 MiB slabs taken from the CRT heap +// on first use. A block of n bytes (header included) is served by the smallest class of at least +// n bytes; larger blocks and blocks of other threads go to the CRT directly (Memory.cpp). +// Placement [INFERRED]; class names follow the DLL's error strings ("ChunkPools::free", +// "MemoryPool error" in the 2006 build). + +#include +#include +#include + +#include "MemoryInternal.h" + +namespace dice { +namespace hfe { +namespace memory { + +namespace { + +// Size classes in bytes, header included; -1 ends the table. 58 is not a multiple of four, so that +// class's elements round up to 60. +const int kPoolSizes[] = {4, 8, 12, 16, 20, 24, 28, 32, 48, 58, 64, 68, 72, 76, 80, 84, 88, -1}; + +const int kPoolChunkSize = 0x100000; + +unsigned int s_maxPoolSize; +int s_numPools; +ChunkPool* s_pools; +ChunkPool** s_poolBySize; + +int roundToPoolAlignment(int size) +{ + return (size & ~(kPoolAlignment - 1)) + ((size & (kPoolAlignment - 1)) != 0 ? kPoolAlignment : 0); +} + +} // namespace + +// PE 0x100016C0. +ChunkPool::ChunkPool() + : m_freeHead(0) +{ +} + +// PE 0x100016D0. +void ChunkPool::addToFreeList(MemoryPool* pool) +{ + if (!pool->m_inFreeList) { + pool->m_inFreeList = true; + pool->m_nextFree = m_freeHead; + m_freeHead = pool; + } +} + +// PE 0x100016F0. +void ChunkPool::updateFreeList() +{ + MemoryPool* const head = m_freeHead; + if (!head) + return; + if (head->m_numUsed + 1 >= head->m_capacity) { + head->m_inFreeList = false; + m_freeHead = head->m_nextFree; + } +} + +// PE 0x10001710. +bool ChunkPools::isActive() +{ + return s_numPools > 0; +} + +// PE 0x10001720. +MemoryPool::MemoryPool() + : m_numAllocs(0) + , m_next(0) + , m_prev(0) + , m_memory(0) + , m_freeList(0) + , m_chainIndex(0) + , m_inFreeList(false) + , m_nextFree(0) +{ +} + +// PE 0x10001740. Releases the rest of the chain, then this slab's memory. +MemoryPool::~MemoryPool() +{ + if (m_next) { + m_next->~MemoryPool(); + std::free(m_next); + } + if (m_memory) + std::free(m_memory); +} + +// PE 0x10001770. +void MemoryPool::init(int elementSize, int chunkSize) +{ + m_numUsed = 0; + m_memory = 0; + m_freeList = 0; + m_chunkSize = chunkSize; + m_elementSize = roundToPoolAlignment(elementSize); + m_capacity = chunkSize / m_elementSize; +} + +// PE 0x100017B0. +void MemoryPool::free(void* element) +{ + *static_cast(element) = m_freeList; + --m_numUsed; + m_freeList = element; +} + +// PE 0x100017D0. Releases the lookup table, every chain and the class table. The lookup table +// pointer is left dangling. +void ChunkPools::shutdown() +{ + std::free(s_poolBySize); + for (int i = 0; i < s_numPools; ++i) { + MemoryPool* const first = s_pools[i].m_first; + first->~MemoryPool(); + std::free(s_pools[i].m_first); + } + // Allocated with new[] in init and released with the CRT free, as shipped. + std::free(s_pools); + s_numPools = 0; +} + +// PE 0x10001870. +char* ChunkPools::getStatus(char* buffer) +{ + if (s_numPools <= 0) + return buffer + std::sprintf(buffer, "ChunkPools not activated\n"); + + buffer += std::sprintf(buffer, "ChunkPools\n"); + for (int i = 0; i < s_numPools; ++i) + buffer += std::sprintf(buffer, "%-*d", 16, kPoolSizes[i]); + buffer += std::sprintf(buffer, "\n"); + for (int i = 0; i < s_numPools; ++i) + buffer += std::sprintf(buffer, "%-*u", 16, static_cast(s_pools[i].m_first->m_numAllocs)); + buffer += std::sprintf(buffer, "\n"); + return buffer; +} + +// PE 0x10001940. Returns `block` to slab `chainIndex` of the class serving `size`. +bool ChunkPools::free(void* block, int size, int chainIndex) +{ + ChunkPool* const pool = s_poolBySize[size]; + if (pool && chainIndex >= 0 && chainIndex < ChunkPool::kMaxChains) { + MemoryPool* const slab = pool->m_chains[chainIndex]; + if (slab) { + slab->free(block); + --s_poolBySize[size]->m_first->m_numAllocs; + s_poolBySize[size]->addToFreeList(slab); + return true; + } + } + memoryError(false, "memory.dll: chunkPools::free fails, should not come here!"); + return false; +} + +// PE 0x100019C0. Registers a new slab at its chain position and offers it for allocation. +void ChunkPools::setInternalPoolByIndex(int size, int chainIndex, MemoryPool* slab) +{ + ChunkPool* const pool = s_poolBySize[size]; + if (chainIndex >= 0 && chainIndex < ChunkPool::kMaxChains) { + pool->m_chains[chainIndex] = slab; + pool->addToFreeList(slab); + return; + } + memoryError(false, "memory.dll: setInternalPoolByIndex() fails, should not come here"); +} + +// PE 0x10001A10. +void* MemoryPool::alloc(unsigned int size, int* chainIndex) +{ + m_chainIndex = *chainIndex; + if (m_numUsed < m_capacity) { + if (!m_memory) { + m_memory = static_cast(std::malloc(m_elementSize * m_capacity)); + for (int i = 0; i < m_capacity - 1; ++i) + *reinterpret_cast(m_memory + i * m_elementSize) = m_memory + (i + 1) * m_elementSize; + *reinterpret_cast(m_memory + (m_capacity - 1) * m_elementSize) = 0; + m_freeList = m_memory; + } + ++m_numUsed; + void* const element = m_freeList; + m_freeList = *static_cast(element); + return element; + } + + ++*chainIndex; + if (!m_next) { + m_next = new (std::malloc(sizeof(MemoryPool))) MemoryPool(); + m_next->init(m_elementSize, m_chunkSize); + m_next->m_prev = this; + ChunkPools::setInternalPoolByIndex(size, *chainIndex, m_next); + } + return m_next->alloc(size, chainIndex); +} + +// PE 0x10001B40. Builds the classes and the size-to-class lookup (sizes 0..largest class). +void ChunkPools::init() +{ + s_maxPoolSize = 0; + int count = 0; + for (; kPoolSizes[count] != -1; ++count) { + if (static_cast(kPoolSizes[count]) > s_maxPoolSize) + s_maxPoolSize = kPoolSizes[count]; + } + s_numPools = count; + + s_poolBySize = static_cast(std::malloc((s_maxPoolSize + 1) * sizeof(ChunkPool*))); + for (unsigned int i = 0; i <= s_maxPoolSize; ++i) + s_poolBySize[i] = 0; + + s_pools = new ChunkPool[s_numPools]; + + int nextSize = 0; + for (int i = 0; i < s_numPools; ++i) { + const int size = kPoolSizes[i]; + ChunkPool* const pool = &s_pools[i]; + pool->m_first = new (std::malloc(sizeof(MemoryPool))) MemoryPool(); + pool->m_first->init(size, kPoolChunkSize); + for (; nextSize <= size; ++nextSize) + s_poolBySize[nextSize] = pool; + + ChunkPool* const owner = s_poolBySize[size]; + MemoryPool* const first = pool->m_first; + owner->m_chains[0] = first; + owner->addToFreeList(first); + } +} + +// PE 0x10001D00. +void* ChunkPools::alloc(unsigned int size, int* chainIndex) +{ + if (size == 0 || size > s_maxPoolSize) + return 0; + ChunkPool* const pool = s_poolBySize[size]; + if (!pool) + return 0; + + void* element; + MemoryPool* const slab = pool->m_freeHead; + if (slab) { + pool->updateFreeList(); + *chainIndex = slab->m_chainIndex; + element = slab->alloc(size, chainIndex); + } else { + *chainIndex = 0; + element = pool->m_first->alloc(size, chainIndex); + } + if (!element) + return 0; + ++pool->m_first->m_numAllocs; + return element; +} + +} // namespace memory +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Memory/Histogram.cpp b/Code/BF2/Memory/Histogram.cpp new file mode 100644 index 000000000..95b54464f --- /dev/null +++ b/Code/BF2/Memory/Histogram.cpp @@ -0,0 +1,161 @@ +// Allocation-size histogram: live and peak block counts for each size below 10000 bytes, one +// bucket for larger blocks, and the live and peak byte totals. +// +// In the shipped configuration nothing calls histogramAlloc or histogramFree, so the histogram +// never activates: the queries read zero and the dump writes no file. Placement [INFERRED]. + +#include +#include + +#include "MemoryInternal.h" + +namespace dice { +namespace hfe { +namespace memory { + +namespace { + +const unsigned int kHistogramSizes = 10000; + +struct HistogramEntry +{ + unsigned int peak; + unsigned int current; +}; + +HistogramEntry s_entries[kHistogramSizes]; +bool s_active; +unsigned int s_peakLarge; +unsigned int s_currentLarge; +unsigned int s_peakTotal; +unsigned int s_currentTotal; +Mutex s_lock; + +} // namespace + +// PE 0x10002300. +unsigned int histogramCurrentTotal() +{ + s_lock.lock(); + const unsigned int total = s_currentTotal; + s_lock.unlock(); + return total; +} + +// PE 0x10002320. +unsigned int histogramPeakTotal() +{ + s_lock.lock(); + const unsigned int total = s_peakTotal; + s_lock.unlock(); + return total; +} + +// PE 0x10002340. Writes the histogram to `fileName`; nothing happens before the first allocation. +void histogramDump(const char* fileName) +{ + s_lock.lock(); + if (!s_active) { + s_lock.unlock(); + return; + } + FILE* file = std::fopen(fileName, BF2_MEMORY_TEXT_WRITE); + if (!file) { + s_lock.unlock(); + return; + } + std::fprintf(file, "Allocations greater than %u bytes\n", kHistogramSizes); + std::fprintf(file, "Current:%u Peak:%u\n", s_currentLarge, s_peakLarge); + std::fprintf(file, "Total bytes allocated. Current:%u Peak:%u\n\n", s_currentTotal, s_peakTotal); + for (unsigned int size = 0; size < kHistogramSizes; ++size) { + if (s_entries[size].current > 0) + std::fprintf(file, "Size:%u Current:%u Peak:%u\n", size, s_entries[size].current, s_entries[size].peak); + } + std::fprintf(file, "\nBlocks where current is zero\n\n"); + for (unsigned int size = 0; size < kHistogramSizes; ++size) { + if (s_entries[size].current == 0 && s_entries[size].peak > 0) + std::fprintf(file, "Size:%u Peak:%u\n", size, s_entries[size].peak); + } + std::fclose(file); + s_lock.unlock(); +} + +// PE 0x10002460. Clears the per-size peaks; the totals keep theirs. +void histogramResetPeaks() +{ + s_lock.lock(); + for (unsigned int size = 0; size < kHistogramSizes; ++size) + s_entries[size].peak = 0; + s_lock.unlock(); +} + +// PE 0x10002490. +void histogramPeaksToCurrent() +{ + s_lock.lock(); + for (unsigned int size = 0; size < kHistogramSizes; ++size) + s_entries[size].peak = s_entries[size].current; + s_lock.unlock(); +} + +// PE 0x100024C0. +void histogramResetCurrent() +{ + s_lock.lock(); + for (unsigned int size = 0; size < kHistogramSizes; ++size) + s_entries[size].current = 0; + s_lock.unlock(); +} + +// PE 0x100024F0. +void histogramResetAll() +{ + s_lock.lock(); + if (s_active) + std::memset(s_entries, 0, sizeof(s_entries)); + s_lock.unlock(); +} + +// PE 0x10002530. The first allocation clears the table and activates the histogram. +void histogramAlloc(unsigned int size) +{ + s_lock.lock(); + if (!s_active) { + std::memset(s_entries, 0, sizeof(s_entries)); + s_active = true; + } + s_currentTotal += size; + if (s_currentTotal > s_peakTotal) + s_peakTotal = s_currentTotal; + if (size >= kHistogramSizes) { + ++s_currentLarge; + if (s_currentLarge > s_peakLarge) + s_peakLarge = s_currentLarge; + } else { + ++s_entries[size].current; + if (s_entries[size].current > s_entries[size].peak) + s_entries[size].peak = s_entries[size].current; + } + s_lock.unlock(); +} + +// PE 0x100025E0. Counts never drop below zero; the byte total is not clamped. +void histogramFree(unsigned int size) +{ + s_lock.lock(); + if (s_active) { + s_currentTotal -= size; + if (size >= kHistogramSizes) { + if (s_currentLarge != 0) + --s_currentLarge; + } else { + if (s_entries[size].current > 0) + --s_entries[size].current; + } + } + s_lock.unlock(); +} + +} // namespace memory +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Memory/Memory.cpp b/Code/BF2/Memory/Memory.cpp new file mode 100644 index 000000000..af37035e7 --- /dev/null +++ b/Code/BF2/Memory/Memory.cpp @@ -0,0 +1,459 @@ +// Memory.dll entry point, error handling and the 32 exports. +// +// The shipped "Final" configuration: bf_malloc serves main-thread blocks of up to 88 bytes (header +// included) from ChunkPools and everything else from the CRT heap, behind a one-word header. +// Header bits: 0 always clear, 1 set for a pooled block, 2-16 the block size and 17-31 the slab's +// chain position for a pooled block, 2-31 the block size otherwise. +// Placement [INFERRED]. + +#include +#include +#include + +#include "MemoryInternal.h" + +#if !defined(_WIN32) +# if defined(__APPLE__) +# include +# else +# include +# include +# endif +#endif + +namespace dice { +namespace hfe { +namespace memory { + +namespace { + +// The shipped block header. The shipped code builds it field by field in an uninitialised local +// whose bit 0 it clears first; every other bit is then overwritten, so starting from zero gives the +// same word. +union BlockHeader +{ + struct + { + unsigned int reserved : 1; + unsigned int pooled : 1; + unsigned int size : 15; + unsigned int chainIndex : 15; + } pool; + struct + { + unsigned int reserved : 1; + unsigned int pooled : 1; + unsigned int size : 30; + } heap; + unsigned int raw; +}; + +void defaultErrorCallback(bool continuable, const char* message); + +const char* s_notActive = "no active in final build"; +char* s_status = const_cast("Memory.dll Ver:1.01 Date:2005/01/10 - Final"); +unsigned int s_maxAllocSize = 0x1000000; + +// The handler pointer sits in read-only data: register_err_callback cannot replace it. +void (*const s_errorCallback)(bool, const char*) = defaultErrorCallback; + +ThreadId s_mainThreadId; +bool s_disabled; +MemoryNameStats s_memoryNames[16]; +Mutex s_memoryLock; // constructed and destroyed with the DLL, never taken + +} // namespace + +#if !defined(_WIN32) +// [CHOSEN, not recovered] POSIX thread identity. +ThreadId currentThreadId() +{ +# if defined(__APPLE__) + unsigned long long id = 0; + pthread_threadid_np(0, &id); + return id; +# else + return static_cast(syscall(SYS_gettid)); +# endif +} +#endif + +// PE 0x10001DB0. [INFERRED] An out-of-line copy of the thread-id helper; nothing calls it. +ThreadId memoryCurrentThreadId() +{ + return currentThreadId(); +} + +namespace { + +// PE 0x10001DC0. Shows the message; a non-continuable error then stops the process with a write +// through a null pointer. +void defaultErrorCallback(bool continuable, const char* message) +{ +#if defined(_WIN32) + MessageBoxA(0, message, "BF2 Memory Error", MB_CANCELTRYCONTINUE | MB_ICONHAND); +#else + // [CHOSEN, not recovered] No message box on the POSIX ports: the message goes to stderr. + std::fprintf(stderr, "BF2 Memory Error: %s\n", message); + std::fflush(stderr); +#endif + if (!continuable) + *static_cast(0) = 0x7306b; +} + +} // namespace + +// PE 0x10001DF0 (Windows). Attach builds the pools and records the main thread; detach releases the +// pools and, when call stacks were active, the allocation records. +#if defined(_WIN32) +} // namespace memory +} // namespace hfe +} // namespace dice + +BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) +{ + using namespace dice::hfe::memory; + switch (reason) { + case DLL_PROCESS_ATTACH: + ChunkPools::init(); + s_mainThreadId = currentThreadId(); + return TRUE; + case DLL_PROCESS_DETACH: + ChunkPools::shutdown(); + if (isCallstackActive()) { + shutdownCallstack(); + dumpLeaks(0, false); + } + break; + } + return TRUE; +} + +namespace dice { +namespace hfe { +namespace memory { +#else +namespace { + +// [CHOSEN, not recovered] The POSIX ports run the DllMain attach and detach bodies from the shared +// library's constructor and destructor. +__attribute__((constructor)) void memoryLibraryLoad() +{ + ChunkPools::init(); + s_mainThreadId = currentThreadId(); +} + +__attribute__((destructor)) void memoryLibraryUnload() +{ + ChunkPools::shutdown(); + if (isCallstackActive()) { + shutdownCallstack(); + dumpLeaks(0, false); + } +} + +} // namespace +#endif + +// PE 0x10001E50. +MemoryNameStats::MemoryNameStats() +{ + std::memset(this, 0, sizeof(*this)); +} + +// PE 0x10001E70. Only positive sizes update the byte counters and the peaks. +void MemoryNameStats::alloc(int size) +{ + ++numAllocs; + if (size <= 0) + return; + bytes += size; + if (size < minBlock || peakBytes == 0) + minBlock = size; + if (size > maxBlock) + maxBlock = size; + if (numAllocs > peakNumAllocs) + peakNumAllocs = numAllocs; + if (bytes > peakBytes) + peakBytes = bytes; +} + +// PE 0x10001EC0. +void MemoryNameStats::free(int size) +{ + --numAllocs; + bytes -= size; +} + +// PE 0x10001EE0. +void memoryError(bool continuable, const char* message) +{ + if (!continuable) + s_disabled = true; + s_errorCallback(continuable, message); +} + +// PE 0x10001F10. After a fatal error every request goes to the CRT without a header. +void* bf_malloc(unsigned int size, int unused) +{ + (void)unused; + if (s_disabled) + return std::malloc(size); + + char message[128]; + if (!(size > 0)) + ++size; + if (size > s_maxAllocSize) { + std::sprintf(message, "memory.dll: sanity check: block size %d (%5.2f MB) doesn't seem sane", + size, static_cast(size) * (1.0 / 1048576.0)); + memoryError(true, message); + } + + BlockHeader header; + header.raw = 0; + header.pool.reserved = 0; + const unsigned int blockSize = size + kHeaderSize; + void* block; + if (!BF2_MEMORY_PASSTHROUGH && currentThreadId() == s_mainThreadId) { + int chainIndex = 0; // left unset by a rejected size; the heap path overwrites the bits + block = ChunkPools::alloc(blockSize, &chainIndex); + header.pool.chainIndex = chainIndex; + header.pool.size = blockSize & 0x7fff; + header.pool.pooled = 1; + if (block) + goto store; + } + header.heap.pooled = 0; + header.heap.size = blockSize; + block = std::malloc(blockSize); + if (!block) { + std::sprintf(message, "memory.dll: all alloc attempts failed for size %d", size); + memoryError(false, message); + return 0; + } + +store: + char* const user = static_cast(block) + kHeaderSize; + *reinterpret_cast(user - 4) = header.raw; + return user; +} + +// PE 0x10002030. +int getSizeOfAllocation(void* p) +{ + if (!p) + return 0; + BlockHeader header; + header.raw = *reinterpret_cast(static_cast(p) - 4); + if (header.pool.pooled) + return static_cast(header.pool.size) - static_cast(kHeaderSize); + return static_cast(header.heap.size) - static_cast(kHeaderSize); +} + +// PE 0x10002060. Nothing is released after a fatal error. A pooled block the pools reject is +// reported and then handed to the CRT free. +void bf_free(void* p) +{ + if (s_disabled || !p) + return; + + char* const block = static_cast(p) - kHeaderSize; + BlockHeader header; + header.raw = *reinterpret_cast(static_cast(p) - 4); + if (header.pool.pooled) { + char message[128]; + if (currentThreadId() != s_mainThreadId) { + std::sprintf(message, "memory.dll: thread %d is deallocating main thread memory", + static_cast(currentThreadId())); + memoryError(false, message); + } + if (ChunkPools::free(block, header.pool.size, header.pool.chainIndex)) + return; + std::sprintf(message, "memory.dll: ChunkPools::free fails at memory 0x%lx", + static_cast(reinterpret_cast(block))); + memoryError(false, message); + } + std::free(block); +} + +// PE 0x10002120. +unsigned int histogramCurrentUsedMemory() +{ + return histogramCurrentTotal(); +} + +// PE 0x10002130. +unsigned int histogramPeakUsedMemory() +{ + return histogramPeakTotal(); +} + +// PE 0x10002140. +void histogramDumpToFile(const char* fileName) +{ + histogramDump(fileName); +} + +// PE 0x10002150. +void histogramClearPeaks() +{ + histogramResetPeaks(); +} + +// PE 0x10002160. +void histogramClearCurrent() +{ + histogramResetCurrent(); +} + +// PE 0x10002170. +char* getStatus(const char* unused) +{ + (void)unused; + return s_status; +} + +// PE 0x10002180. +void memory_update_modules(const char* unused) +{ + (void)unused; +} + +// PE 0x10002190. +void set_all_allocations_to_zero() +{ +} + +// PE 0x100021A0. +const char* dump_allocations_to_file(const char* fileName, int includeAll) +{ + (void)fileName; + (void)includeAll; + return s_notActive; +} + +// PE 0x100021B0. +const char* dump_active_allocations_to_file(const char* fileName) +{ + (void)fileName; + return s_notActive; +} + +// PE 0x100021C0. +const char* memoryTraceReport() +{ + return "use_traceIdentifiers not enabled"; +} + +// PE 0x100021D0. +void memoryTraceReportToFile(const char* fileName) +{ + (void)fileName; +} + +// PE 0x100021E0. +void startMemoryTrace(int& id, const char* name) +{ + (void)id; + (void)name; +} + +// PE 0x100021F0. +void endMemoryTrace(int id) +{ + (void)id; +} + +// PE 0x10002200. +void memoryTraceReset() +{ +} + +// PE 0x10002210. +void nextVisualFrame() +{ +} + +// PE 0x10002220. +void nextPhysicFrame() +{ +} + +// PE 0x10002230. +int addMemoryName(const char* name) +{ + (void)name; + return 0; +} + +// PE 0x10002240. +void resourceTraceAllocate(int& id, const char* name, int size) +{ + resourceAllocate(id, name, size); +} + +// PE 0x10002250. +void resourceTraceFree(int& id, const char* name, int size) +{ + resourceFree(id, name, size); +} + +// PE 0x10002260. Copies the fixed notice; the size and depth are ignored. +void get_callstack_debug_str(char* buffer, int size, int depth) +{ + (void)size; + (void)depth; + std::strcpy(buffer, "Only available in DEBUG builds"); +} + +// PE 0x10002280. Ignored in the shipped configuration. +void register_err_callback(void (*callback)(bool, const char*)) +{ + (void)callback; +} + +// PE 0x10002290. +void set_max_alloc_size(unsigned int size) +{ + s_maxAllocSize = size; +} + +// PE 0x100022A0. +unsigned int get_max_alloc_size() +{ + return s_maxAllocSize; +} + +// PE 0x100022B0. +void reset_max_alloc_size() +{ + s_maxAllocSize = 0x1000000; +} + +// PE 0x100022C0. +int get_total_bytes_allocated() +{ + return 0; +} + +// PE 0x100022D0. +long long get_accumulated_bytes_allocated() +{ + return 0; +} + +// PE 0x100022E0. +int get_total_allocation_call_count() +{ + return 0; +} + +// PE 0x100022F0. +int get_accumulated_allocation_call_count() +{ + return 0; +} + +} // namespace memory +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Memory/Memory.h b/Code/BF2/Memory/Memory.h new file mode 100644 index 000000000..107999db9 --- /dev/null +++ b/Code/BF2/Memory/Memory.h @@ -0,0 +1,91 @@ +// Public interface of Memory.dll, the engine heap the shipped Battlefield 2 1.50 images import. +// +// The 32 declarations below are the DLL's whole export table. Their parameter and return types come +// from the decorated names (`?bf_malloc@memory@hfe@dice@@YAPAXIH@Z` and so on); an MSVC x86 build +// of this header mangles to the same strings, so a retail importer binds to the rebuilt DLL by name. +// +// The shipped DLL is the "Final" configuration (version string "Memory.dll Ver:1.01 +// Date:2005/01/10 - Final"): only the allocator, the max-allocation sanity limit, the status string +// and the resource counters do work. The tracing, histogram, leak-dump and counter exports are +// compiled-out stubs in that configuration, and this reconstruction keeps them so. +// +// Not linked into any game image: the game allocates through the shared CRT (issue #7). + +#ifndef BF2_MEMORY_MEMORY_H +#define BF2_MEMORY_MEMORY_H + +#if defined(_WIN32) +# if defined(BF2_MEMORY_BUILD) +# define BF2_MEMORY_API __declspec(dllexport) +# else +# define BF2_MEMORY_API __declspec(dllimport) +# endif +#else +// [CHOSEN, not recovered] POSIX shared-library visibility for the native ports. +# define BF2_MEMORY_API __attribute__((visibility("default"))) +#endif + +namespace dice { +namespace hfe { +namespace memory { + +// Allocator. +// Returns a block of at least `size` bytes (a zero size is treated as one byte). The second +// argument is accepted and ignored by the shipped DLL. Returns null only when every allocation +// attempt failed, after the error handler ran. +BF2_MEMORY_API void* bf_malloc(unsigned int size, int unused); +// Releases a block from bf_malloc. Null is ignored. Blocks from the main thread's pools must be +// freed on that thread; anything else is a fatal memory error. +BF2_MEMORY_API void bf_free(void* p); +// Returns the size requested from bf_malloc for `p` (one for a zero-size request), or 0 for null. +BF2_MEMORY_API int getSizeOfAllocation(void* p); + +// Sanity limit: a request above it reports a continuable error and is still allocated. +BF2_MEMORY_API void set_max_alloc_size(unsigned int size); +BF2_MEMORY_API unsigned int get_max_alloc_size(); +// Restores the default limit of 16 MiB. +BF2_MEMORY_API void reset_max_alloc_size(); + +// Error reporting. The shipped DLL ignores the registration and keeps its built-in handler. +BF2_MEMORY_API void register_err_callback(void (*callback)(bool continuable, const char* message)); + +// Status and counters. The counters always read zero in the shipped configuration. +BF2_MEMORY_API char* getStatus(const char* unused); +BF2_MEMORY_API int get_total_bytes_allocated(); +BF2_MEMORY_API long long get_accumulated_bytes_allocated(); +BF2_MEMORY_API int get_total_allocation_call_count(); +BF2_MEMORY_API int get_accumulated_allocation_call_count(); +BF2_MEMORY_API void get_callstack_debug_str(char* buffer, int size, int depth); + +// Size histogram. Nothing feeds it in the shipped configuration, so the queries read zero and the +// dump writes no file. +BF2_MEMORY_API unsigned int histogramCurrentUsedMemory(); +BF2_MEMORY_API unsigned int histogramPeakUsedMemory(); +BF2_MEMORY_API void histogramDumpToFile(const char* fileName); +BF2_MEMORY_API void histogramClearPeaks(); +BF2_MEMORY_API void histogramClearCurrent(); + +// Allocation tracing and leak dumps; inactive in the shipped configuration. +BF2_MEMORY_API int addMemoryName(const char* name); +BF2_MEMORY_API void startMemoryTrace(int& id, const char* name); +BF2_MEMORY_API void endMemoryTrace(int id); +BF2_MEMORY_API void memoryTraceReset(); +BF2_MEMORY_API const char* memoryTraceReport(); +BF2_MEMORY_API void memoryTraceReportToFile(const char* fileName); +BF2_MEMORY_API void nextVisualFrame(); +BF2_MEMORY_API void nextPhysicFrame(); +BF2_MEMORY_API const char* dump_allocations_to_file(const char* fileName, int includeAll); +BF2_MEMORY_API const char* dump_active_allocations_to_file(const char* fileName); +BF2_MEMORY_API void memory_update_modules(const char* unused); +BF2_MEMORY_API void set_all_allocations_to_zero(); + +// Named resource counters. `id` starts at -1; the first call resolves `name` (case-insensitive) +// to a slot and stores it. +BF2_MEMORY_API void resourceTraceAllocate(int& id, const char* name, int size); +BF2_MEMORY_API void resourceTraceFree(int& id, const char* name, int size); + +} // namespace memory +} // namespace hfe +} // namespace dice + +#endif // BF2_MEMORY_MEMORY_H diff --git a/Code/BF2/Memory/MemoryInternal.h b/Code/BF2/Memory/MemoryInternal.h new file mode 100644 index 000000000..de12010fe --- /dev/null +++ b/Code/BF2/Memory/MemoryInternal.h @@ -0,0 +1,385 @@ +// Internal declarations shared by the Memory.dll translation units. +// +// Placement and the names of internal types, functions and globals are [INFERRED]: the shipped DLL +// carries no symbols or source paths beyond its 32 exports. The split into translation units +// follows the shipped function and data order, seven contiguous groups: +// AllocInfo.cpp 0x10001010-0x10001630 call-stack keyed allocation records, leak report v1.10 +// Callstack.cpp 0x10001670-0x100016B0 compiled-out capture, its unused lock +// ChunkPools.cpp 0x100016C0-0x10001D80 MemoryPool slabs, ChunkPool classes, ChunkPools +// Memory.cpp 0x10001DB0-0x100022F0 DllMain, error handler, MemoryNameStats, 32 exports +// Histogram.cpp 0x10002300-0x100025E0 size histogram (never fed in Final) +// Threading.cpp 0x10002650-0x100029D0 Mutex, Event, Thread +// MemoryTrace.cpp 0x100029E0-0x10003270 trace/resource identifiers, report builder +// Internal names follow the DLL's own strings (ChunkPools::free, MemoryPool, AllocInfo) and, for the +// call-stack functions, the 2006 Memory_r.dll debug build; the rest are [INFERRED]. + +#ifndef BF2_MEMORY_MEMORYINTERNAL_H +#define BF2_MEMORY_MEMORYINTERNAL_H + +#include + +#if defined(_WIN32) +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +#else +# include +#endif + +#include "Memory.h" + +// [CHOSEN, not recovered] Pass-through switch for sanitizer builds. When on, bf_malloc never uses the +// chunk pools, so every block is its own CRT allocation that AddressSanitizer can see. The block +// header, getSizeOfAllocation, the resource counters and every other export behave as without it. +// Defaults to on when the compiler reports AddressSanitizer, off otherwise. +#ifndef BF2_MEMORY_PASSTHROUGH +# if defined(__SANITIZE_ADDRESS__) +# define BF2_MEMORY_PASSTHROUGH 1 +# elif defined(__has_feature) +# if __has_feature(address_sanitizer) +# define BF2_MEMORY_PASSTHROUGH 1 +# endif +# endif +#endif +#ifndef BF2_MEMORY_PASSTHROUGH +# define BF2_MEMORY_PASSTHROUGH 0 +#endif + +namespace dice { +namespace hfe { +namespace memory { + +// ------------------------------------------------------------------------------------------------ +// Platform seam. The MSVC x86 values are the shipped ones. +// ------------------------------------------------------------------------------------------------ + +#if defined(_M_IX86) || defined(__i386__) +// The block header is one 32-bit word in front of the user pointer. +const unsigned int kHeaderSize = 4; +// Pool element sizes are rounded up to a multiple of four. +const int kPoolAlignment = 4; +#else +// [CHOSEN, not recovered] 64-bit ports keep the 32-bit header word directly in front of the user +// pointer but reserve 16 bytes for it and round pool elements to 16, so blocks keep the platform +// malloc alignment. Every size class therefore pools 12 fewer user bytes than on x86. +const unsigned int kHeaderSize = 16; +const int kPoolAlignment = 16; +#endif + +#if defined(_WIN32) +typedef DWORD ThreadId; +inline ThreadId currentThreadId() { return GetCurrentThreadId(); } +#else +// [CHOSEN, not recovered] POSIX thread identity for the main-thread checks. +typedef unsigned long long ThreadId; +ThreadId currentThreadId(); +#endif + +// fopen mode of every text file the DLL writes. +#if defined(_WIN32) +# define BF2_MEMORY_TEXT_WRITE "wt" +#else +// [CHOSEN, not recovered] POSIX has no text mode; "w" is the same file. +# define BF2_MEMORY_TEXT_WRITE "w" +#endif + +// ------------------------------------------------------------------------------------------------ +// Threading primitives (Threading.cpp). Only Mutex has users, and those only lock the histogram. +// ------------------------------------------------------------------------------------------------ + +class Mutex +{ +public: + Mutex(); + ~Mutex(); + void lock(); + void unlock(); + +private: +#if defined(_WIN32) + CRITICAL_SECTION* m_section; +#else + pthread_mutex_t* m_section; +#endif +}; + +// A manual-reset event, initially clear. +class Event +{ +public: + Event(); + ~Event(); + void signal(); + // Waits up to `milliseconds` (0 waits forever); returns whether the event was signalled. + bool wait(unsigned int milliseconds); + +private: +#if defined(_WIN32) + HANDLE* m_handle; +#else + struct Impl; + Impl* m_handle; +#endif +}; + +class Thread +{ +public: + // Thread priorities accepted by start(). + enum Priority + { + PriorityIdle, + PriorityBelowNormal, + PriorityNormal, + PriorityAboveNormal, + PriorityTimeCritical + }; + + Thread(); + virtual ~Thread(); + // Body run on the new thread. + virtual void run() = 0; + + // Creates the thread and applies `priority`. The first argument is ignored. + bool start(int unused, int priority); + // Waits for the thread to finish and releases its handle. + bool join(); + +private: + struct Data + { +#if defined(_WIN32) + HANDLE handle; + DWORD id; +#else + pthread_t handle; + unsigned long id; +#endif + bool running; + }; + +#if defined(_WIN32) + static DWORD WINAPI threadProc(void* thread); +#else + static void* threadProc(void* thread); +#endif + + Data* m_data; +}; + +// [INFERRED] Out-of-line thread-id helpers of the threading and main units; nothing calls them. +ThreadId threadingCurrentThreadId(); +ThreadId memoryCurrentThreadId(); + +// ------------------------------------------------------------------------------------------------ +// Errors (Memory.cpp). +// ------------------------------------------------------------------------------------------------ + +// Reports `message` through the error handler. A non-continuable error first switches the DLL to +// plain CRT allocation; the built-in handler then stops the process. +void memoryError(bool continuable, const char* message); + +// ------------------------------------------------------------------------------------------------ +// Chunk pools (ChunkPools.cpp). +// ------------------------------------------------------------------------------------------------ + +// One 1 MiB slab of equal-size elements with an intrusive free list. Slabs of a size class form a +// chain; the first slab also counts the live elements of the whole class. +class MemoryPool +{ +public: + MemoryPool(); + ~MemoryPool(); + + void init(int elementSize, int chunkSize); + // Takes an element, walking to (and creating) later slabs of the chain when this one is full. + // `chainIndex` holds this slab's position on entry and the serving slab's on return. + void* alloc(unsigned int size, int* chainIndex); + void free(void* element); + + int m_numAllocs; // live elements of the size class; first slab only + int m_elementSize; + int m_chunkSize; + MemoryPool* m_next; // next slab of the chain + MemoryPool* m_prev; + char* m_memory; // the slab, allocated on first use + void* m_freeList; + int m_numUsed; + int m_capacity; + int m_chainIndex; + bool m_inFreeList; + MemoryPool* m_nextFree; // ChunkPool free-list link +}; + +// One size class: its first slab, the list of slabs with room, and the slabs by chain position. +struct ChunkPool +{ + enum { kMaxChains = 512 }; + + ChunkPool(); + void addToFreeList(MemoryPool* pool); + // Drops the head slab from the free list when the next allocation fills it. + void updateFreeList(); + + MemoryPool* m_first; + MemoryPool* m_freeHead; + MemoryPool* m_chains[kMaxChains]; +}; + +class ChunkPools +{ +public: + static void init(); + static void shutdown(); + static bool isActive(); + // Returns an element for a block of `size` bytes (header included) and its chain position, or + // null when the size has no pool. + static void* alloc(unsigned int size, int* chainIndex); + static bool free(void* block, int size, int chainIndex); + static void setInternalPoolByIndex(int size, int chainIndex, MemoryPool* pool); + // Appends the per-class table to `buffer`; returns the new end. + static char* getStatus(char* buffer); +}; + +// ------------------------------------------------------------------------------------------------ +// Allocation records and leak report (AllocInfo.cpp), call stacks (Callstack.cpp). +// ------------------------------------------------------------------------------------------------ + +// Statistics of all allocations made from one call stack. +struct AllocInfo +{ + void update(int size); + + int numFrames; + unsigned int* frames; + unsigned int hash; + int traceId; + int peakSize; + int peakNumAllocs; + int currentNumAllocs; + int currentTotalSize; + int minAllocSize; + int maxAllocSize; + int visualFrameAllocs; + int peakVisualFrameAllocs; + int lastVisualFrame; + int physicsFrameAllocs; + int peakPhysicsFrameAllocs; + int lastPhysicsFrame; + AllocInfo* next; +}; + +unsigned int hashCallstack(const unsigned int* frames, int numFrames); +void initAllocInfoHash(int hashSize); +void resetTraceAllocInfo(); +const char* allocInfoNotActive(); +void dumpAllocInfo(const char* fileName, bool includeAll, bool release, int traceId); +void clearCurrentAllocInfo(); +AllocInfo* findAllocInfo(int depth); +void allocInfoNoOp(); +void dumpLeaks(const char* fileName, bool includeAll); +void dumpAllAllocInfo(const char* fileName); +void dumpTraceAllocInfo(const char* fileName, int traceId); +void writeAllocInfoNotActive(const char* fileName); + +bool isCallstackActive(); +void initCallstack(); +void shutdownCallstack(); +int captureCallstack(unsigned int* frames, int maxFrames, int skipFrames); +int callstackModuleCount(); + +// ------------------------------------------------------------------------------------------------ +// Size histogram (Histogram.cpp). +// ------------------------------------------------------------------------------------------------ + +unsigned int histogramCurrentTotal(); +unsigned int histogramPeakTotal(); +void histogramDump(const char* fileName); +void histogramResetPeaks(); +void histogramPeaksToCurrent(); +void histogramResetCurrent(); +void histogramResetAll(); +void histogramAlloc(unsigned int size); +void histogramFree(unsigned int size); + +// ------------------------------------------------------------------------------------------------ +// Trace identifiers and resource counters (MemoryTrace.cpp). +// ------------------------------------------------------------------------------------------------ + +// Named counter. The resource and trace tables hold up to 2048 of them. +struct TraceIdentifier +{ + TraceIdentifier(); + + char name[256]; + int unused; // [UNRESOLVED] zeroed by the constructor, never read or written + int peakBytes; + int peakNumAllocs; + int numAllocs; + int bytes; + int minBlock; + int maxBlock; +}; + +// One open trace scope of the per-process trace stack. +struct TraceStackEntry +{ + TraceStackEntry(); + + int id; + ThreadId thread; +}; + +enum +{ + kMaxTraceIdentifiers = 0x800, + kMaxTraceDepth = 0x80 +}; + +extern TraceIdentifier* g_traceIdentifiers[kMaxTraceIdentifiers]; +extern int g_traceIdentifierCount; +extern int g_visualFrame; +extern int g_physicsFrame; +extern TraceStackEntry g_traceStack[kMaxTraceDepth + 1]; +extern int g_traceStackTop; + +const char* formatNumber(int value, bool restart); +int findTraceIdentifier(const char* name, TraceIdentifier** table, int* count); +void pushMemoryTrace(int& id, const char* name); +void popMemoryTrace(int id); +int traceAlloc(int size); +void traceFree(int idPlusOne, int size); +int compareTraceBytes(const void* a, const void* b); +void resourceAllocate(int& id, const char* name, int size); +void resourceFree(int& id, const char* name, int size); +char* buildTraceReport(TraceIdentifier** table, int count); +const char* traceReport(); +const char* resourceReport(); +void traceReportToFile(const char* fileName); + +// ------------------------------------------------------------------------------------------------ +// Per-name statistics (Memory.cpp). +// ------------------------------------------------------------------------------------------------ + +struct MemoryNameStats +{ + MemoryNameStats(); + void alloc(int size); + void free(int size); + + char name[64]; + int unused; // [UNRESOLVED] zeroed by the constructor, never read or written + int peakBytes; + int peakNumAllocs; + int numAllocs; + int bytes; + int minBlock; + int maxBlock; +}; + +} // namespace memory +} // namespace hfe +} // namespace dice + +#endif // BF2_MEMORY_MEMORYINTERNAL_H diff --git a/Code/BF2/Memory/MemoryTrace.cpp b/Code/BF2/Memory/MemoryTrace.cpp new file mode 100644 index 000000000..c44962829 --- /dev/null +++ b/Code/BF2/Memory/MemoryTrace.cpp @@ -0,0 +1,332 @@ +// Named allocation counters: trace identifiers (scoped with a per-process trace stack) and resource +// identifiers, with a text report. +// +// In the shipped configuration only the resource counters are reachable (resourceTraceAllocate and +// resourceTraceFree); the trace exports are stubs and no export returns a report. Placement +// [INFERRED]. + +#include +#include +#include +#include +#include +#include + +#include "MemoryInternal.h" + +#if defined(_WIN32) +# define bf2MemoryStricmp _stricmp +#else +# include +// [CHOSEN, not recovered] POSIX spelling of the CRT's case-insensitive compare. +# define bf2MemoryStricmp strcasecmp +#endif + +namespace dice { +namespace hfe { +namespace memory { + +TraceIdentifier* g_traceIdentifiers[kMaxTraceIdentifiers]; +int g_traceIdentifierCount; +int g_visualFrame; +int g_physicsFrame; +TraceStackEntry g_traceStack[kMaxTraceDepth + 1]; +int g_traceStackTop = -1; + +namespace { + +const char* s_unnamed = "nameNOTset"; + +char s_report[0x100000]; +TraceIdentifier* s_resourceIdentifiers[kMaxTraceIdentifiers]; +int s_resourceIdentifierCount; +char s_numberBuffer[0x400]; +char* s_numberCursor; + +struct SortedTrace +{ + unsigned int bytes; + int index; +}; + +// Records `size` against `entry`: counts, bytes, block range and peaks. +inline void recordAllocation(TraceIdentifier* entry, int size) +{ + ++entry->numAllocs; + entry->bytes += size; + if (size >= 0) { + if (size < entry->minBlock || entry->peakBytes == 0) + entry->minBlock = size; + if (size > entry->maxBlock) + entry->maxBlock = size; + } + if (entry->numAllocs > entry->peakNumAllocs) + entry->peakNumAllocs = entry->numAllocs; + if (entry->bytes > entry->peakBytes) + entry->peakBytes = entry->bytes; +} + +} // namespace + +// PE 0x100029E0. Formats `value` with '.' between groups of three digits into a shared buffer and +// returns it. Strings of one report line follow each other in the buffer; `restart` begins again +// at its start. +const char* formatNumber(int value, bool restart) +{ + char* out = (!restart && s_numberCursor) ? s_numberCursor : s_numberBuffer; + char* const start = out; + bool negative = false; + if (value < 0) { + *out++ = '-'; + negative = true; + value = static_cast(0u - static_cast(value)); + } + int digits = 0; + do { + if (digits == 3) { + digits = 0; + *out++ = '.'; + } + *out++ = static_cast('0' + value % 10); + ++digits; + value /= 10; + } while (value != 0); + + char* low = negative ? start + 1 : start; + char* high = out - 1; + while (low < high) { + const char c = *high; + *high = *low; + *low = c; + ++low; + --high; + } + *out++ = 0; + s_numberCursor = out; + return start; +} + +// PE 0x10002A80. +TraceStackEntry::TraceStackEntry() + : id(-1) +{ +} + +// PE 0x10002A90. +TraceIdentifier::TraceIdentifier() +{ + std::memset(this, 0, sizeof(*this)); + std::strcpy(name, s_unnamed); +} + +// PE 0x10002AC0. Returns the slot of `name` (case-insensitive), adding it when new. A full table +// renames slot 0 to an error marker and returns 0. +int findTraceIdentifier(const char* name, TraceIdentifier** table, int* count) +{ + for (int i = 0; i < *count; ++i) { + if (bf2MemoryStricmp(name, table[i]->name) == 0) + return i; + } + if (*count == kMaxTraceIdentifiers) { + std::strncpy(table[0]->name, "ERROR. TOO MANY IDENTIFIERS", 0x100); + return 0; + } + table[*count] = new TraceIdentifier; + std::strncpy(table[*count]->name, name, 0x100); + return (*count)++; +} + +// PE 0x10002B90. Opens a trace scope on the calling thread, resolving `id` from `name` first. +void pushMemoryTrace(int& id, const char* name) +{ + if (g_traceStackTop >= kMaxTraceDepth) + return; + if (id == -1) + id = findTraceIdentifier(name, g_traceIdentifiers, &g_traceIdentifierCount); + if (id < 0 || id >= kMaxTraceIdentifiers) + return; + ++g_traceStackTop; + g_traceStack[g_traceStackTop].id = id; + g_traceStack[g_traceStackTop].thread = currentThreadId(); +} + +// PE 0x10002C00. Closes the innermost scope when it is `id`'s on the calling thread. An empty stack +// is reset to depth 0. +void popMemoryTrace(int id) +{ + if (g_traceStackTop < 0) { + g_traceStackTop = 0; + return; + } + if (g_traceStack[g_traceStackTop].id == id && g_traceStack[g_traceStackTop].thread == currentThreadId()) { + g_traceStack[g_traceStackTop].id = -1; + --g_traceStackTop; + } +} + +// PE 0x10002C50. Records an allocation against the innermost scope; returns its identifier plus +// one, or 0 when no scope is open. +int traceAlloc(int size) +{ + if (g_traceStackTop < 0) + return 0; + const int id = g_traceStack[g_traceStackTop].id; + if (id < 0) + return 0; + recordAllocation(g_traceIdentifiers[id], size); + return id + 1; +} + +// PE 0x10002CF0. +void traceFree(int idPlusOne, int size) +{ + if (idPlusOne < 1) + return; + TraceIdentifier* const entry = g_traceIdentifiers[idPlusOne - 1]; + --entry->numAllocs; + entry->bytes -= size; +} + +// PE 0x10002D20. qsort order: descending bytes. +int compareTraceBytes(const void* a, const void* b) +{ + const unsigned int left = static_cast(a)->bytes; + const unsigned int right = static_cast(b)->bytes; + if (left == right) + return 0; + return left < right ? 1 : -1; +} + +std::string traceFileName(const std::string& path); + +// PE 0x10002D40. [INFERRED] File-name part of `path`; nothing calls it. Both separators must occur +// for the cut to happen: the larger find wins and a missing separator reads as npos. +std::string traceFileName(const std::string& path) +{ + std::string::size_type cut = path.rfind("\\", std::string::npos, 1); + const std::string::size_type slash = path.rfind("/", std::string::npos, 1); + if (slash > cut) + cut = slash; + if (cut == std::string::npos) + return path; + return path.substr(cut + 1, std::string::npos); +} + +// PE 0x10002DC0. Resolves `id` from `name` on first use and records the allocation. +void resourceAllocate(int& id, const char* name, int size) +{ + if (id == -1) { + id = findTraceIdentifier(name, s_resourceIdentifiers, &s_resourceIdentifierCount); + if (id < 0) + return; + } + recordAllocation(s_resourceIdentifiers[id], size); +} + +// PE 0x10002E60. +void resourceFree(int& id, const char* name, int size) +{ + if (id == -1) { + id = findTraceIdentifier(name, s_resourceIdentifiers, &s_resourceIdentifierCount); + if (id < 0) + return; + } + TraceIdentifier* const entry = s_resourceIdentifiers[id]; + --entry->numAllocs; + entry->bytes -= size; +} + +// PE 0x10002EB0. Builds the report of `table` in the shared report buffer: the byte total, then one +// line per identifier with live allocations, largest first. Returns null for an empty table. +// The per-directory totals of '/'- or '\\'-separated names are collected and then discarded, as +// shipped; they never reach the report. +char* buildTraceReport(TraceIdentifier** table, int count) +{ + SortedTrace sorted[kMaxTraceIdentifiers]; + char prefix[0x400]; + if (count <= 0) + return 0; + + unsigned int totalBytes = 0; + for (int i = 0; i < count; ++i) { + sorted[i].bytes = table[i]->bytes; + sorted[i].index = i; + totalBytes += table[i]->bytes; + } + std::qsort(sorted, count, sizeof(SortedTrace), compareTraceBytes); + + std::map groups; + std::sprintf(s_report, "Total bytes allocated:%u\n", totalBytes); + char* out = s_report + std::strlen(s_report); + for (int k = 0; k < count; ++k) { + const int index = sorted[k].index; + TraceIdentifier* const entry = table[index]; + if (entry->numAllocs == 0 || entry->bytes == 0) + continue; + + int level = 0; + for (int pos = 0; entry->name[pos]; ++pos) { + const char c = entry->name[pos]; + if (c != '/' && c != '\\') + continue; + std::strncpy(prefix, entry->name, pos); + prefix[pos] = 0; + std::string key(prefix); + std::map::iterator group = groups.find(key); + if (group == groups.end()) { + TraceIdentifier total; + total.numAllocs += entry->numAllocs; + total.bytes += entry->bytes; + total.minBlock = level; + groups.insert(std::make_pair(key, total)); + } else { + group->second.bytes += entry->bytes; + group->second.numAllocs += entry->numAllocs; + } + ++level; + } + + const char* const bytes = formatNumber(entry->bytes, true); + const char* const peakNumAllocs = formatNumber(entry->peakNumAllocs, false); + const char* const numAllocs = formatNumber(entry->numAllocs, false); + const char* const maxBlock = formatNumber(entry->maxBlock, false); + const char* const minBlock = formatNumber(entry->minBlock, false); + const char* const peakBytes = formatNumber(entry->peakBytes, false); + std::sprintf(out, "Bytes:%s(%s) MinBlock:%s MaxBlock:%s NumAllocs:%s(%s) %s [%d]\n", bytes, + peakBytes, minBlock, maxBlock, numAllocs, peakNumAllocs, entry->name, index); + out += std::strlen(out); + } + *out = 0; + return s_report; +} + +// PE 0x10003230. +const char* traceReport() +{ + const char* report = buildTraceReport(g_traceIdentifiers, g_traceIdentifierCount); + return report ? report : "no traces found"; +} + +// PE 0x10003250. +const char* resourceReport() +{ + const char* report = buildTraceReport(s_resourceIdentifiers, s_resourceIdentifierCount); + return report ? report : "no resources found"; +} + +// PE 0x10003270. +void traceReportToFile(const char* fileName) +{ + const char* report = buildTraceReport(g_traceIdentifiers, g_traceIdentifierCount); + if (!report) + report = "no traces found"; + FILE* file = std::fopen(fileName, BF2_MEMORY_TEXT_WRITE); + if (file) { + std::fprintf(file, "%s", report); + std::fclose(file); + } +} + +} // namespace memory +} // namespace hfe +} // namespace dice diff --git a/Code/BF2/Memory/Threading.cpp b/Code/BF2/Memory/Threading.cpp new file mode 100644 index 000000000..190cf9443 --- /dev/null +++ b/Code/BF2/Memory/Threading.cpp @@ -0,0 +1,249 @@ +// Mutex, event and thread wrappers linked into Memory.dll. Only the mutex has users (the histogram +// lock and two locks nothing takes); the event and thread classes have no callers in the DLL. +// Placement [INFERRED]. +// +// The Windows bodies are the shipped ones. [CHOSEN, not recovered] The POSIX bodies map them onto +// pthreads: a recursive mutex for the critical section, a mutex and condition variable for the +// manual-reset event, pthread_join for the exit-code poll, and no priority change. + +#include + +#include "MemoryInternal.h" + +namespace dice { +namespace hfe { +namespace memory { + +#if !defined(_WIN32) +struct Event::Impl +{ + pthread_mutex_t mutex; + pthread_cond_t cond; + bool signalled; +}; +#endif + +// PE 0x10002650. +Mutex::Mutex() +{ +#if defined(_WIN32) + m_section = static_cast(std::malloc(sizeof(CRITICAL_SECTION))); + if (m_section) + InitializeCriticalSection(m_section); +#else + m_section = static_cast(std::malloc(sizeof(pthread_mutex_t))); + if (m_section) { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(m_section, &attr); + pthread_mutexattr_destroy(&attr); + } +#endif +} + +// PE 0x10002670. +void Mutex::lock() +{ +#if defined(_WIN32) + EnterCriticalSection(m_section); +#else + pthread_mutex_lock(m_section); +#endif +} + +// PE 0x10002680. +void Mutex::unlock() +{ +#if defined(_WIN32) + LeaveCriticalSection(m_section); +#else + pthread_mutex_unlock(m_section); +#endif +} + +// PE 0x10002690. Manual reset, initially clear. +Event::Event() +{ +#if defined(_WIN32) + m_handle = static_cast(std::malloc(sizeof(HANDLE))); + if (m_handle) + *m_handle = CreateEventA(0, TRUE, FALSE, 0); +#else + m_handle = static_cast(std::malloc(sizeof(Impl))); + if (m_handle) { + pthread_mutex_init(&m_handle->mutex, 0); + pthread_cond_init(&m_handle->cond, 0); + m_handle->signalled = false; + } +#endif +} + +// PE 0x100026C0. +void Event::signal() +{ +#if defined(_WIN32) + SetEvent(*m_handle); +#else + pthread_mutex_lock(&m_handle->mutex); + m_handle->signalled = true; + pthread_cond_broadcast(&m_handle->cond); + pthread_mutex_unlock(&m_handle->mutex); +#endif +} + +// PE 0x100026D0. +bool Event::wait(unsigned int milliseconds) +{ +#if defined(_WIN32) + if (milliseconds == 0) + milliseconds = INFINITE; + return WaitForSingleObject(*m_handle, milliseconds) == WAIT_OBJECT_0; +#else + pthread_mutex_lock(&m_handle->mutex); + if (milliseconds == 0) { + while (!m_handle->signalled) + pthread_cond_wait(&m_handle->cond, &m_handle->mutex); + } else { + struct timespec deadline; + clock_gettime(CLOCK_REALTIME, &deadline); + deadline.tv_sec += milliseconds / 1000; + deadline.tv_nsec += static_cast(milliseconds % 1000) * 1000000L; + if (deadline.tv_nsec >= 1000000000L) { + ++deadline.tv_sec; + deadline.tv_nsec -= 1000000000L; + } + while (!m_handle->signalled) { + if (pthread_cond_timedwait(&m_handle->cond, &m_handle->mutex, &deadline) != 0) + break; + } + } + const bool signalled = m_handle->signalled; + pthread_mutex_unlock(&m_handle->mutex); + return signalled; +#endif +} + +// PE 0x10002700. Runs the thread body; the exit code is always 0. +#if defined(_WIN32) +DWORD WINAPI Thread::threadProc(void* thread) +{ + static_cast(thread)->run(); + return 0; +} +#else +void* Thread::threadProc(void* thread) +{ + static_cast(thread)->run(); + return 0; +} +#endif + +// PE 0x10002720. +Thread::Thread() +{ + m_data = new Data; + m_data->handle = 0; + m_data->id = 0; + m_data->running = false; +} + +// PE 0x10002760; the deleting form is PE 0x100028F0. +Thread::~Thread() +{ + delete m_data; +} + +// PE 0x10002780. +bool Thread::start(int unused, int priority) +{ + (void)unused; +#if defined(_WIN32) + m_data->handle = CreateThread(0, 0, threadProc, this, 0, &m_data->id); + if (!m_data->handle) { + m_data->running = false; + return false; + } + m_data->running = true; + if (priority == PriorityNormal) + return true; + int level = THREAD_PRIORITY_NORMAL; + switch (priority) { + case PriorityIdle: + level = THREAD_PRIORITY_IDLE; + break; + case PriorityBelowNormal: + level = THREAD_PRIORITY_BELOW_NORMAL; + break; + case PriorityAboveNormal: + level = THREAD_PRIORITY_ABOVE_NORMAL; + break; + case PriorityTimeCritical: + level = THREAD_PRIORITY_TIME_CRITICAL; + break; + } + SetThreadPriority(m_data->handle, level); + return true; +#else + (void)priority; + if (pthread_create(&m_data->handle, 0, threadProc, this) != 0) { + m_data->running = false; + return false; + } + m_data->running = true; + return true; +#endif +} + +// PE 0x10002850. The shipped body polls the exit code until the thread is no longer active. +bool Thread::join() +{ + if (m_data->running) { +#if defined(_WIN32) + DWORD exitCode = STILL_ACTIVE; + do { + if (!GetExitCodeThread(m_data->handle, &exitCode)) + break; + } while (exitCode == STILL_ACTIVE); + CloseHandle(m_data->handle); +#else + pthread_join(m_data->handle, 0); +#endif + m_data->handle = 0; + m_data->running = false; + } + return true; +} + +// PE 0x100028B0. +Mutex::~Mutex() +{ +#if defined(_WIN32) + DeleteCriticalSection(m_section); +#else + pthread_mutex_destroy(m_section); +#endif + std::free(m_section); +} + +// PE 0x100028D0. +Event::~Event() +{ +#if defined(_WIN32) + CloseHandle(*m_handle); +#else + pthread_cond_destroy(&m_handle->cond); + pthread_mutex_destroy(&m_handle->mutex); +#endif + std::free(m_handle); +} + +// PE 0x100029D0. +ThreadId threadingCurrentThreadId() +{ + return currentThreadId(); +} + +} // namespace memory +} // namespace hfe +} // namespace dice diff --git a/Code/Build/build.cmd b/Code/Build/build.cmd index f1a75aad6..0dc91b370 100644 --- a/Code/Build/build.cmd +++ b/Code/Build/build.cmd @@ -118,6 +118,10 @@ for /r "%ROOT%" %%F in (*.cpp) do ( rem directory is excluded here; CMakeLists.txt mirrors this with bf2_voipserver_only_sources. echo %%F | find /i "\BF2\VoipServer\" >nul if not errorlevel 1 set "ENGINE_OBJECT=0" + rem Code\BF2\Memory is the recovered Memory.dll, its own image (Code\Build\memory.cmd); the + rem engine keeps its own memory:: stubs. CMakeLists.txt skips the directory the same way. + echo %%F | find /i "\BF2\Memory\" >nul + if not errorlevel 1 set "ENGINE_OBJECT=0" if /i "%%~fF"=="%ROOT%\Core\DllModule.cpp" set "ENGINE_OBJECT=0" rem The side-DLL image owns its globals translation unit. rem It defines the nineteen names initDll fills, zero-initialised; Core\Globals.cpp is diff --git a/Code/Build/memory.cmd b/Code/Build/memory.cmd new file mode 100644 index 000000000..a23cb31d2 --- /dev/null +++ b/Code/Build/memory.cmd @@ -0,0 +1,53 @@ +@echo off +setlocal EnableDelayedExpansion +rem =========================================================================== +rem SCAFFOLDING - NOT RECOVERED SOURCE. Builds the REPLACEMENT Memory.dll from +rem Code\BF2\Memory. +rem +rem No game image links or loads it: the game allocates through the shared CRT +rem (https://github.com/B2BF/OpenBF2/issues/7). The DLL exists for the +rem differential test against the retail Memory.dll +rem (Code\Tests\memory\memory_diff.cmd) and for a later decision on using it. +rem IT NEVER WRITES INTO THE GAME DIRECTORY. +rem +rem usage: memory.cmd [native] x86, the retail-fidelity build +rem memory.cmd x64 native x64 ([CHOSEN, not recovered] 16-byte header) +rem Output: Code\Build\bin_memory_native\Memory.dll (bin_memory_x64 for x64). +rem BF2_MEMORY_OUT and BF2_MEMORY_BIN override the object and DLL directories. +rem Set BF2_MEMORY_PASSTHROUGH=1 to build the pass-through variant. +rem =========================================================================== +set "ARCH=x86" +if /i "%~1"=="x64" set "ARCH=x64" +if not "%~1"=="" if /i not "%~1"=="native" if /i not "%~1"=="x64" ( + echo usage: memory.cmd [native^|x64] + exit /b 2 +) +call "%~dp0vsdevcmd.cmd" %ARCH% +if errorlevel 1 exit /b 1 + +for %%I in ("%~dp0..") do set "CODE=%%~fI" +set "SRC=%CODE%\BF2\Memory" +set "OUT=%~dp0obj_memory_native" +set "BIN=%~dp0bin_memory_native" +if "%ARCH%"=="x64" set "OUT=%~dp0obj_memory_x64" +if "%ARCH%"=="x64" set "BIN=%~dp0bin_memory_x64" +if defined BF2_MEMORY_OUT set "OUT=%BF2_MEMORY_OUT%" +if defined BF2_MEMORY_BIN set "BIN=%BF2_MEMORY_BIN%" +set "PT=" +if defined BF2_MEMORY_PASSTHROUGH set "PT=/DBF2_MEMORY_PASSTHROUGH=%BF2_MEMORY_PASSTHROUGH%" +if not exist "%OUT%" mkdir "%OUT%" +if not exist "%BIN%" mkdir "%BIN%" + +rem /MD - the shipped DLL uses the dynamic CRT (MSVCR71/MSVCP71). +set "CFLAGS=/nologo /c /O2 /MD /EHsc /W3 /GS- /DBF2_MEMORY_BUILD /D_CRT_SECURE_NO_WARNINGS %PT% /I"%SRC%"" +set "OBJS=" +for %%F in (AllocInfo Callstack ChunkPools Memory Histogram Threading MemoryTrace) do ( + cl %CFLAGS% "%SRC%\%%F.cpp" /Fo"%OUT%\%%F.obj" + if errorlevel 1 exit /b 1 + set "OBJS=!OBJS! "%OUT%\%%F.obj"" +) +rem /BASE - the shipped image's preferred base; cosmetic under ASLR. +link /nologo /DLL /OUT:"%BIN%\Memory.dll" /IMPLIB:"%OUT%\Memory.lib" /BASE:0x10000000 %OBJS% kernel32.lib user32.lib +if errorlevel 1 exit /b 1 +echo [memory] built %BIN%\Memory.dll +exit /b 0 diff --git a/Code/Tests/memory/CMakeLists.txt b/Code/Tests/memory/CMakeLists.txt new file mode 100644 index 000000000..ea46d1d8c --- /dev/null +++ b/Code/Tests/memory/CMakeLists.txt @@ -0,0 +1,41 @@ +# [TEMP] Test scaffolding for bf2_memory. +# +# memory_unit black-box checks through the 32 exports of the shared library +# memory_internal white-box checks of the internal report formats (static object set) +# memory_diff Windows only: the differential harness run against the retail Memory.dll and +# the rebuilt MSVC x86 DLL (memory_diff.cmd) + +add_executable(memory_unit memory_unit.cpp) +target_compile_features(memory_unit PRIVATE cxx_std_14) +target_link_libraries(memory_unit PRIVATE bf2_memory) +target_include_directories(memory_unit PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../BF2/Memory") + +add_executable(memory_internal memory_internal.cpp) +target_compile_features(memory_internal PRIVATE cxx_std_14) +target_link_libraries(memory_internal PRIVATE bf2_memory_internal) +target_compile_definitions(memory_internal PRIVATE BF2_MEMORY_BUILD) + +foreach(test_target memory_unit memory_internal) + if(BF2_MEMORY_PASSTHROUGH STREQUAL "ON") + target_compile_definitions(${test_target} PRIVATE BF2_MEMORY_PASSTHROUGH=1) + elseif(BF2_MEMORY_PASSTHROUGH STREQUAL "OFF") + target_compile_definitions(${test_target} PRIVATE BF2_MEMORY_PASSTHROUGH=0) + endif() + if(MSVC) + target_compile_definitions(${test_target} PRIVATE _CRT_SECURE_NO_WARNINGS) + set_property(TARGET ${test_target} PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") + elseif(BF2_MEMORY_ASAN) + target_compile_options(${test_target} PRIVATE -fsanitize=address -fno-omit-frame-pointer) + target_link_options(${test_target} PRIVATE -fsanitize=address) + endif() + if(NOT WIN32) + find_package(Threads REQUIRED) + target_link_libraries(${test_target} PRIVATE Threads::Threads) + endif() + add_test(NAME ${test_target} COMMAND ${test_target} WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") +endforeach() + +if(WIN32) + add_executable(memory_diff memory_diff.cpp) + target_compile_definitions(memory_diff PRIVATE _CRT_SECURE_NO_WARNINGS) +endif() diff --git a/Code/Tests/memory/memory_diff.cmd b/Code/Tests/memory/memory_diff.cmd new file mode 100644 index 000000000..ca0190df2 --- /dev/null +++ b/Code/Tests/memory/memory_diff.cmd @@ -0,0 +1,55 @@ +@echo off +setlocal +rem =========================================================================== +rem [TEMP] SCAFFOLDING. Differential test of Memory.dll: runs memory_diff.exe +rem against the retail Memory.dll and against the rebuilt MSVC x86 DLL and +rem compares the two outputs. +rem +rem usage: memory_diff.cmd +rem holds the retail Memory.dll with its msvcr71.dll and +rem msvcp71.dll; they are copied into the work directory, never modified. +rem BF2_MEMORY_DIFF_OUT overrides the work directory +rem (default Code\Tests\memory\obj_memory_diff). +rem =========================================================================== +if "%~1"=="" ( + echo usage: memory_diff.cmd ^ + exit /b 2 +) +set "RETAIL=%~1" +set "WORK=%~dp0obj_memory_diff" +if defined BF2_MEMORY_DIFF_OUT set "WORK=%BF2_MEMORY_DIFF_OUT%" +if not exist "%WORK%\retail" mkdir "%WORK%\retail" +if not exist "%WORK%\rebuilt" mkdir "%WORK%\rebuilt" + +set "BF2_MEMORY_OUT=%WORK%\obj" +set "BF2_MEMORY_BIN=%WORK%\rebuilt" +call "%~dp0..\..\Build\memory.cmd" native +if errorlevel 1 exit /b 1 + +rem memory.cmd keeps its developer environment local; load it again for the harness. +call "%~dp0..\..\Build\vsdevcmd.cmd" x86 +if errorlevel 1 exit /b 1 + +copy /y "%RETAIL%\Memory.dll" "%WORK%\retail\Memory.dll" >nul || exit /b 1 +copy /y "%RETAIL%\msvcr71.dll" "%WORK%\retail\msvcr71.dll" >nul || exit /b 1 +copy /y "%RETAIL%\msvcp71.dll" "%WORK%\retail\msvcp71.dll" >nul || exit /b 1 + +cl /nologo /O2 /MD /EHsc /W3 /D_CRT_SECURE_NO_WARNINGS "%~dp0memory_diff.cpp" /Fo"%WORK%\memory_diff.obj" /Fe"%WORK%\memory_diff.exe" +if errorlevel 1 exit /b 1 + +pushd "%WORK%\retail" +"%WORK%\memory_diff.exe" "%WORK%\retail\Memory.dll" > "%WORK%\retail.txt" +set "RC_RETAIL=%errorlevel%" +popd +pushd "%WORK%\rebuilt" +"%WORK%\memory_diff.exe" "%WORK%\rebuilt\Memory.dll" > "%WORK%\rebuilt.txt" +set "RC_REBUILT=%errorlevel%" +popd +echo [memory_diff] exit codes: retail %RC_RETAIL%, rebuilt %RC_REBUILT% +fc /n "%WORK%\retail.txt" "%WORK%\rebuilt.txt" +if errorlevel 1 ( + echo [memory_diff] OUTPUTS DIFFER + exit /b 1 +) +echo [memory_diff] outputs identical +exit /b 0 diff --git a/Code/Tests/memory/memory_diff.cpp b/Code/Tests/memory/memory_diff.cpp new file mode 100644 index 000000000..be899593f --- /dev/null +++ b/Code/Tests/memory/memory_diff.cpp @@ -0,0 +1,278 @@ +// [TEMP] Test scaffolding, not recovered source: differential harness for Memory.dll. +// +// memory_diff.exe +// +// Loads the given DLL (the retail one or the rebuilt MSVC x86 build), resolves the 32 exports by +// their decorated names, runs one deterministic script and prints everything the API makes +// observable: return values, block headers, element strides and reuse inside the pools, chain +// positions, resource ids and which files get written. Absolute addresses are never printed. Run +// it once per DLL and compare the two outputs (memory_diff.cmd). +// +// The script avoids the paths that open the DLL's message box (sanity limit exceeded, fatal +// errors), because the box would block the run. + +#include + +#include +#include +#include + +namespace { + +typedef void* (__cdecl* BfMalloc)(unsigned int, int); +typedef void (__cdecl* BfFree)(void*); +typedef int (__cdecl* GetSize)(void*); +typedef void (__cdecl* SetUInt)(unsigned int); +typedef unsigned int (__cdecl* GetUInt)(); +typedef void (__cdecl* Void)(); +typedef int (__cdecl* GetInt)(); +typedef long long (__cdecl* GetInt64)(); +typedef char* (__cdecl* GetStatus)(const char*); +typedef void (__cdecl* CallstackStr)(char*, int, int); +typedef void (__cdecl* FileFn)(const char*); +typedef int (__cdecl* AddName)(const char*); +typedef void (__cdecl* StartTrace)(int&, const char*); +typedef void (__cdecl* EndTrace)(int); +typedef const char* (__cdecl* Report)(); +typedef const char* (__cdecl* DumpAll)(const char*, int); +typedef const char* (__cdecl* DumpActive)(const char*); +typedef void (__cdecl* ResourceFn)(int&, const char*, int); +typedef void (__cdecl* ErrCallback)(bool, const char*); +typedef void (__cdecl* RegisterCb)(ErrCallback); + +HMODULE g_dll; +int g_missing; + +FARPROC resolve(const char* name) +{ + FARPROC p = GetProcAddress(g_dll, name); + if (!p) { + std::printf("missing export %s\n", name); + ++g_missing; + } + return p; +} + +#define RESOLVE(type, var, name) type var = reinterpret_cast(resolve(name)) + +unsigned int headerOf(void* p) +{ + return *reinterpret_cast(static_cast(p) - 4); +} + +bool fileExists(const char* path) +{ + return GetFileAttributesA(path) != INVALID_FILE_ATTRIBUTES; +} + +BfMalloc g_malloc; +BfFree g_free; +GetSize g_size; + +struct ThreadResult +{ + unsigned int header; + int size; +}; + +DWORD WINAPI otherThread(void* param) +{ + ThreadResult* result = static_cast(param); + void* p = g_malloc(24, 0); + result->header = headerOf(p); + result->size = g_size(p); + g_free(p); + return 0; +} + +void __cdecl ignoredCallback(bool, const char*) +{ + std::printf("callback ran\n"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) { + std::fprintf(stderr, "usage: memory_diff \n"); + return 2; + } + g_dll = LoadLibraryA(argv[1]); + if (!g_dll) { + std::fprintf(stderr, "LoadLibrary failed: %lu\n", GetLastError()); + return 2; + } + + RESOLVE(BfMalloc, bfMalloc, "?bf_malloc@memory@hfe@dice@@YAPAXIH@Z"); + RESOLVE(BfFree, bfFree, "?bf_free@memory@hfe@dice@@YAXPAX@Z"); + RESOLVE(GetSize, getSize, "?getSizeOfAllocation@memory@hfe@dice@@YAHPAX@Z"); + RESOLVE(SetUInt, setMax, "?set_max_alloc_size@memory@hfe@dice@@YAXI@Z"); + RESOLVE(GetUInt, getMax, "?get_max_alloc_size@memory@hfe@dice@@YAIXZ"); + RESOLVE(Void, resetMax, "?reset_max_alloc_size@memory@hfe@dice@@YAXXZ"); + RESOLVE(RegisterCb, registerCb, "?register_err_callback@memory@hfe@dice@@YAXP6AX_NPBD@Z@Z"); + RESOLVE(GetStatus, getStatus, "?getStatus@memory@hfe@dice@@YAPADPBD@Z"); + RESOLVE(GetInt, totalBytes, "?get_total_bytes_allocated@memory@hfe@dice@@YAHXZ"); + RESOLVE(GetInt64, accBytes, "?get_accumulated_bytes_allocated@memory@hfe@dice@@YA_JXZ"); + RESOLVE(GetInt, totalCalls, "?get_total_allocation_call_count@memory@hfe@dice@@YAHXZ"); + RESOLVE(GetInt, accCalls, "?get_accumulated_allocation_call_count@memory@hfe@dice@@YAHXZ"); + RESOLVE(CallstackStr, callstackStr, "?get_callstack_debug_str@memory@hfe@dice@@YAXPADHH@Z"); + RESOLVE(GetUInt, histCurrent, "?histogramCurrentUsedMemory@memory@hfe@dice@@YAIXZ"); + RESOLVE(GetUInt, histPeak, "?histogramPeakUsedMemory@memory@hfe@dice@@YAIXZ"); + RESOLVE(FileFn, histDump, "?histogramDumpToFile@memory@hfe@dice@@YAXPBD@Z"); + RESOLVE(Void, histClearPeaks, "?histogramClearPeaks@memory@hfe@dice@@YAXXZ"); + RESOLVE(Void, histClearCurrent, "?histogramClearCurrent@memory@hfe@dice@@YAXXZ"); + RESOLVE(AddName, addName, "?addMemoryName@memory@hfe@dice@@YAHPBD@Z"); + RESOLVE(StartTrace, startTrace, "?startMemoryTrace@memory@hfe@dice@@YAXAAHPBD@Z"); + RESOLVE(EndTrace, endTrace, "?endMemoryTrace@memory@hfe@dice@@YAXH@Z"); + RESOLVE(Void, traceReset, "?memoryTraceReset@memory@hfe@dice@@YAXXZ"); + RESOLVE(Report, traceReport, "?memoryTraceReport@memory@hfe@dice@@YAPBDXZ"); + RESOLVE(FileFn, traceReportFile, "?memoryTraceReportToFile@memory@hfe@dice@@YAXPBD@Z"); + RESOLVE(Void, nextVisual, "?nextVisualFrame@memory@hfe@dice@@YAXXZ"); + RESOLVE(Void, nextPhysic, "?nextPhysicFrame@memory@hfe@dice@@YAXXZ"); + RESOLVE(DumpAll, dumpAll, "?dump_allocations_to_file@memory@hfe@dice@@YAPBDPBDH@Z"); + RESOLVE(DumpActive, dumpActive, "?dump_active_allocations_to_file@memory@hfe@dice@@YAPBDPBD@Z"); + RESOLVE(FileFn, updateModules, "?memory_update_modules@memory@hfe@dice@@YAXPBD@Z"); + RESOLVE(Void, allToZero, "?set_all_allocations_to_zero@memory@hfe@dice@@YAXXZ"); + RESOLVE(ResourceFn, resAlloc, "?resourceTraceAllocate@memory@hfe@dice@@YAXAAHPBDH@Z"); + RESOLVE(ResourceFn, resFree, "?resourceTraceFree@memory@hfe@dice@@YAXAAHPBDH@Z"); + if (g_missing) + return 3; + g_malloc = bfMalloc; + g_free = bfFree; + g_size = getSize; + + // 1. Fresh slabs: three elements per block size, strides and headers. + for (unsigned int size = 0; size <= 90; ++size) { + void* a = bfMalloc(size, 0); + void* b = bfMalloc(size, 0); + void* c = bfMalloc(size, 0); + const bool pooled = (headerOf(a) & 2) != 0; + std::printf("fresh size=%u hdr=%08x %08x %08x getSize=%d stride=%d,%d align4=%d\n", size, + headerOf(a), headerOf(b), headerOf(c), getSize(a), + pooled ? static_cast(static_cast(b) - static_cast(a)) : 0, + pooled ? static_cast(static_cast(c) - static_cast(b)) : 0, + static_cast(reinterpret_cast(a) & 3)); + bfFree(c); + bfFree(b); + bfFree(a); + } + + // 2. Sizes and headers across the range, and LIFO reuse. + for (unsigned int size = 0; size <= 4200; size += (size < 120 ? 1 : 97)) { + void* a = bfMalloc(size, 0); + std::memset(a, 0x5A, size ? size : 1); + const unsigned int header = headerOf(a); + const int got = getSize(a); + bfFree(a); + void* b = bfMalloc(size, 0); + std::printf("size=%u hdr=%08x getSize=%d reuse=%d\n", size, header, got, + (header & 2) ? (a == b ? 1 : 0) : -1); + bfFree(b); + } + void* big = bfMalloc(3u << 20, 0); + std::printf("big hdr=%08x getSize=%d\n", headerOf(big), getSize(big)); + bfFree(big); + std::printf("null getSize=%d\n", getSize(0)); + bfFree(0); + + // 3. Chain overflow of the class serving 1-byte requests. + { + std::vector blocks; + int perChain[3] = {0, 0, 0}; + for (int i = 0; i < 131072 * 2 + 5; ++i) { + void* p = bfMalloc(1, 0); + const unsigned int chain = headerOf(p) >> 17; + if (chain < 3) + ++perChain[chain]; + blocks.push_back(p); + } + std::printf("chain counts %d %d %d last=%u\n", perChain[0], perChain[1], perChain[2], + headerOf(blocks.back()) >> 17); + void* victim0 = blocks[7]; + void* victim1 = blocks[131072 + 9]; + bfFree(victim0); + bfFree(victim1); + void* r1 = bfMalloc(1, 0); + void* r2 = bfMalloc(1, 0); + void* r3 = bfMalloc(1, 0); + std::printf("reuse r1=%s chain=%u r2=%s chain=%u r3chain=%u\n", + r1 == victim1 ? "victim1" : (r1 == victim0 ? "victim0" : "other"), headerOf(r1) >> 17, + r2 == victim1 ? "victim1" : (r2 == victim0 ? "victim0" : "other"), headerOf(r2) >> 17, + headerOf(r3) >> 17); + blocks[7] = 0; + blocks[131072 + 9] = 0; + bfFree(r1); + bfFree(r2); + bfFree(r3); + for (size_t i = 0; i < blocks.size(); ++i) + bfFree(blocks[i]); + void* after = bfMalloc(1, 0); + std::printf("after release chain=%u\n", headerOf(after) >> 17); + bfFree(after); + } + + // 4. Another thread allocates from the CRT heap. + { + ThreadResult result = {0, 0}; + HANDLE thread = CreateThread(0, 0, otherThread, &result, 0, 0); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + std::printf("thread hdr=%08x getSize=%d\n", result.header, result.size); + } + + // 5. Limits, status and stubs. + std::printf("max=%u\n", getMax()); + setMax(12345); + std::printf("max=%u\n", getMax()); + void* under = bfMalloc(12345, 0); + std::printf("at limit hdr=%08x\n", headerOf(under)); + bfFree(under); + resetMax(); + std::printf("max=%u\n", getMax()); + registerCb(ignoredCallback); + std::printf("status=%s\n", getStatus("x")); + std::printf("counters %d %lld %d %d\n", totalBytes(), accBytes(), totalCalls(), accCalls()); + char buffer[64]; + std::memset(buffer, '#', sizeof(buffer)); + callstackStr(buffer, 8, 4); + buffer[63] = 0; + std::printf("callstack=%s\n", buffer); + std::printf("hist %u %u\n", histCurrent(), histPeak()); + histClearPeaks(); + histClearCurrent(); + DeleteFileA("memdiff_hist.txt"); + histDump("memdiff_hist.txt"); + std::printf("hist file=%d\n", fileExists("memdiff_hist.txt") ? 1 : 0); + std::printf("addMemoryName=%d\n", addName("Name")); + int traceId = -1; + startTrace(traceId, "Trace"); + std::printf("trace id=%d\n", traceId); + endTrace(traceId); + traceReset(); + nextVisual(); + nextPhysic(); + std::printf("trace report=%s\n", traceReport()); + DeleteFileA("memdiff_trace.txt"); + traceReportFile("memdiff_trace.txt"); + std::printf("trace file=%d\n", fileExists("memdiff_trace.txt") ? 1 : 0); + DeleteFileA("memdiff_dump.txt"); + std::printf("dump=%s\n", dumpAll("memdiff_dump.txt", 1)); + std::printf("dump active=%s\n", dumpActive("memdiff_dump.txt")); + std::printf("dump file=%d\n", fileExists("memdiff_dump.txt") ? 1 : 0); + updateModules("x"); + allToZero(); + + // 6. Resource ids. + int r[6] = {-1, -1, -1, -1, -1, 1}; + resAlloc(r[0], "Textures", 100); + resAlloc(r[1], "Meshes", 10); + resAlloc(r[2], "textures", 5); + resFree(r[3], "MESHES", 10); + resAlloc(r[4], "Sounds", 1); + resAlloc(r[5], "Ignored", 1); + std::printf("resource ids %d %d %d %d %d %d\n", r[0], r[1], r[2], r[3], r[4], r[5]); + + std::printf("done\n"); + return 0; +} diff --git a/Code/Tests/memory/memory_internal.cpp b/Code/Tests/memory/memory_internal.cpp new file mode 100644 index 000000000..533166e19 --- /dev/null +++ b/Code/Tests/memory/memory_internal.cpp @@ -0,0 +1,298 @@ +// [TEMP] Test scaffolding, not recovered source: white-box checks of the rebuilt Memory library's +// internal functions, linked from the static object set. The shipped configuration never writes +// the leak report, the histogram or the trace report, so their formats are checked here directly. + +#include +#include +#include +#include + +#include "MemoryInternal.h" + +using namespace dice::hfe::memory; + +namespace { + +int g_failures; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +#define CHECK_EQ_STR(actual, expected) \ + do { \ + const std::string a_ = (actual); \ + const std::string e_ = (expected); \ + if (a_ != e_) { \ + std::fprintf(stderr, "FAIL %s:%d:\n--- got\n%s\n--- expected\n%s\n", __FILE__, \ + __LINE__, a_.c_str(), e_.c_str()); \ + ++g_failures; \ + } \ + } while (0) + +std::string readFile(const char* path) +{ + std::string text; + FILE* f = std::fopen(path, "rb"); + if (!f) + return ""; + char buf[4096]; + size_t n; + while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0) + text.append(buf, n); + std::fclose(f); + return text; +} + +void testFormatNumber() +{ + CHECK_EQ_STR(formatNumber(0, true), "0"); + CHECK_EQ_STR(formatNumber(999, false), "999"); + CHECK_EQ_STR(formatNumber(1000, false), "1.000"); + CHECK_EQ_STR(formatNumber(1234567, false), "1.234.567"); + CHECK_EQ_STR(formatNumber(-1234, false), "-1.234"); + const char* first = formatNumber(5, true); + const char* second = formatNumber(6, false); + CHECK(second == first + 2); // strings of one line follow each other +} + +void testHash() +{ + const unsigned int frames[] = {1, 2}; + CHECK(hashCallstack(frames, 2) == 0xdae8739fu); + CHECK(hashCallstack(frames, 0) == 0x719fdae9u); +} + +void testReports() +{ + CHECK_EQ_STR(traceReport(), "no traces found"); + CHECK_EQ_STR(resourceReport(), "no resources found"); + traceReportToFile("bf2mem_internal_trace.txt"); + CHECK_EQ_STR(readFile("bf2mem_internal_trace.txt"), "no traces found"); + + // Trace scopes: allocations go to the innermost scope of this thread. + int outer = -1, inner = -1; + pushMemoryTrace(outer, "Game/Objects"); + CHECK(outer == 0); + CHECK(traceAlloc(300) == 1); + pushMemoryTrace(inner, "Game\\Sound"); + CHECK(inner == 1); + CHECK(traceAlloc(2000) == 2); + CHECK(traceAlloc(4000) == 2); + popMemoryTrace(inner); + CHECK(traceAlloc(100) == 1); + traceFree(2, 2000); + popMemoryTrace(outer); + CHECK(g_traceStackTop == -1); + CHECK(traceAlloc(5) == 0); + popMemoryTrace(outer); // an empty stack resets to depth 0 + CHECK(g_traceStackTop == 0); + g_traceStackTop = -1; + + CHECK_EQ_STR(traceReport(), + "Total bytes allocated:4400\n" + "Bytes:4.000(6.000) MinBlock:2.000 MaxBlock:4.000 NumAllocs:1(2) Game\\Sound [1]\n" + "Bytes:400(400) MinBlock:100 MaxBlock:300 NumAllocs:2(2) Game/Objects [0]\n"); + + int unused = -1; + pushMemoryTrace(unused, "Empty"); + popMemoryTrace(unused); + // A zero-byte identifier stays out of the lines but not out of the total. + CHECK_EQ_STR(std::string(traceReport()).substr(0, 27), "Total bytes allocated:4400\n"); + + int res = -1; + resourceAllocate(res, "Textures", 1234567); + CHECK(res == 0); + resourceAllocate(res, "ignored", 1); + int res2 = -1; + resourceAllocate(res2, "textures", 1); // case-insensitive: same slot + CHECK(res2 == 0); + CHECK_EQ_STR(resourceReport(), + "Total bytes allocated:1234569\n" + "Bytes:1.234.569(1.234.569) MinBlock:1 MaxBlock:1.234.567 NumAllocs:3(3) Textures [0]\n"); + resourceFree(res, "Textures", 1234569); + resourceFree(res, "Textures", 0); + resourceFree(res, "Textures", 0); + CHECK_EQ_STR(resourceReport(), "Total bytes allocated:0\n"); +} + +void testHistogram() +{ + CHECK(histogramCurrentTotal() == 0); + std::remove("bf2mem_internal_hist.txt"); + histogramDump("bf2mem_internal_hist.txt"); + CHECK_EQ_STR(readFile("bf2mem_internal_hist.txt"), ""); // inactive: no file + + histogramAlloc(16); + histogramAlloc(16); + histogramAlloc(40); + histogramAlloc(20000); + histogramFree(40); + CHECK(histogramCurrentTotal() == 20032); + CHECK(histogramPeakTotal() == 20072); + histogramDump("bf2mem_internal_hist.txt"); + CHECK_EQ_STR(readFile("bf2mem_internal_hist.txt"), + "Allocations greater than 10000 bytes\n" + "Current:1 Peak:1\n" + "Total bytes allocated. Current:20032 Peak:20072\n\n" + "Size:16 Current:2 Peak:2\n" + "\nBlocks where current is zero\n\n" + "Size:40 Peak:1\n"); + + histogramFree(20000); + histogramFree(20000); // the large count stays at zero + histogramResetPeaks(); + histogramDump("bf2mem_internal_hist.txt"); + CHECK_EQ_STR(readFile("bf2mem_internal_hist.txt"), + "Allocations greater than 10000 bytes\n" + "Current:0 Peak:1\n" + "Total bytes allocated. Current:4294947328 Peak:20072\n\n" + "Size:16 Current:2 Peak:0\n" + "\nBlocks where current is zero\n\n"); + histogramPeaksToCurrent(); + histogramResetCurrent(); + histogramDump("bf2mem_internal_hist.txt"); + CHECK(readFile("bf2mem_internal_hist.txt").find("\nBlocks where current is zero\n\nSize:16 Peak:2\n") != + std::string::npos); + histogramResetAll(); + std::remove("bf2mem_internal_hist.txt"); +} + +void testAllocInfo() +{ + initAllocInfoHash(3); + AllocInfo* a = findAllocInfo(64); + CHECK(a != 0); + CHECK(a->numFrames == 0); // the capture is compiled out + CHECK(findAllocInfo(64) == a); + a->update(100); + a->update(50); + a->update(-50); + CHECK(a->traceId == -1); + dumpAllocInfo("bf2mem_internal_leaks.txt", false, false, -1); + CHECK_EQ_STR(readFile("bf2mem_internal_leaks.txt"), + "# Leak report format v1.10\n" + "\n# Module dump\n" + "\n# Allocation history (leaks only)\n" + "alloc depth=0 peakSize=150 peakNumAllocs=2 currentNumAllocs=1 currentTotalSize=100 " + "minAllocSize=50 maxAllocSize=100 \n" + "\n# AllocInfo hash table summary:\n" + "# hash size: 3\n" + "# populated bucket indices: 1 ( 33%)\n" + "# total elements: 1\n" + "# longest chain: 1\n"); + + dumpTraceAllocInfo("bf2mem_internal_leaks.txt", 5); // no record of identifier 5 + CHECK(readFile("bf2mem_internal_leaks.txt").find("alloc depth") == std::string::npos); + CHECK(readFile("bf2mem_internal_leaks.txt").find("# longest chain: 0\n") != std::string::npos); + + clearCurrentAllocInfo(); + CHECK(a->currentNumAllocs == 0 && a->peakSize == 150); + dumpAllAllocInfo("bf2mem_internal_leaks.txt"); + CHECK(readFile("bf2mem_internal_leaks.txt").find("alloc depth") == std::string::npos); + dumpLeaks("bf2mem_internal_leaks.txt", true); // all records listed, then released + CHECK(readFile("bf2mem_internal_leaks.txt").find("(all allocations)\nalloc depth=0 peakSize=150") != + std::string::npos); + + writeAllocInfoNotActive("bf2mem_internal_leaks.txt"); + CHECK_EQ_STR(readFile("bf2mem_internal_leaks.txt"), "not active in final build"); + CHECK_EQ_STR(allocInfoNotActive(), "not active in final build"); + std::remove("bf2mem_internal_leaks.txt"); + std::remove("bf2mem_internal_trace.txt"); +} + +void testChunkPoolStatus() +{ + char status[1024]; + std::string expectedSizes, expectedCounts; + const int sizes[] = {4, 8, 12, 16, 20, 24, 28, 32, 48, 58, 64, 68, 72, 76, 80, 84, 88}; + char cell[32]; + for (int i = 0; i < 17; ++i) { + std::snprintf(cell, sizeof(cell), "%-16d", sizes[i]); + expectedSizes += cell; + } + void* p = 0; + if (!BF2_MEMORY_PASSTHROUGH) + p = bf_malloc(88 - kHeaderSize, 0); + for (int i = 0; i < 17; ++i) { + std::snprintf(cell, sizeof(cell), "%-16u", (i == 16 && p) ? 1u : 0u); + expectedCounts += cell; + } + char* end = ChunkPools::getStatus(status); + CHECK(ChunkPools::isActive()); + CHECK_EQ_STR(std::string(status, end), "ChunkPools\n" + expectedSizes + "\n" + expectedCounts + "\n"); + bf_free(p); +} + +void testNameStats() +{ + MemoryNameStats stats; + CHECK(stats.numAllocs == 0 && stats.name[0] == 0); + stats.alloc(0); // counts, but touches nothing else + CHECK(stats.numAllocs == 1 && stats.peakNumAllocs == 0 && stats.bytes == 0); + stats.alloc(30); + stats.alloc(10); + CHECK(stats.bytes == 40 && stats.minBlock == 10 && stats.maxBlock == 30); + CHECK(stats.peakNumAllocs == 3 && stats.peakBytes == 40); + stats.free(30); + CHECK(stats.numAllocs == 2 && stats.bytes == 10); +} + +struct CountingThread : Thread +{ + Event* done; + int ran; + void run() override + { + ++ran; + done->signal(); + } +}; + +void testThreading() +{ + Mutex mutex; + mutex.lock(); + mutex.lock(); // recursive, as a critical section + mutex.unlock(); + mutex.unlock(); + + Event event; + CHECK(!event.wait(10)); + CountingThread thread; + thread.done = &event; + thread.ran = 0; + CHECK(thread.start(0, Thread::PriorityNormal)); + CHECK(event.wait(0)); + CHECK(thread.join()); + CHECK(thread.ran == 1); + CHECK(threadingCurrentThreadId() == currentThreadId()); + CHECK(memoryCurrentThreadId() == currentThreadId()); +} + +} // namespace + +int main() +{ +#if defined(_WIN32) + ChunkPools::init(); // DllMain does this in the DLL; this executable links the objects +#endif + testFormatNumber(); + testHash(); + testReports(); + testHistogram(); + testAllocInfo(); + testChunkPoolStatus(); + testNameStats(); + testThreading(); + if (g_failures) { + std::fprintf(stderr, "memory_internal: %d failure(s)\n", g_failures); + return 1; + } + std::printf("memory_internal: all checks passed\n"); + return 0; +} diff --git a/Code/Tests/memory/memory_unit.cpp b/Code/Tests/memory/memory_unit.cpp new file mode 100644 index 000000000..06f363769 --- /dev/null +++ b/Code/Tests/memory/memory_unit.cpp @@ -0,0 +1,393 @@ +// [TEMP] Test scaffolding, not recovered source: black-box checks of the rebuilt Memory library +// through its 32 exports. Links the shared library, so the library's +// load hook runs on this process's main thread, as DllMain attach does for the game. + +#include +#include +#include +#include +#include +#include + +#if !defined(_WIN32) +# include +# include +# include +#endif + +#include "Memory.h" + +// Mirrors the library's pass-through default (MemoryInternal.h); CMake passes an explicit value +// when BF2_MEMORY_PASSTHROUGH is ON or OFF. +#ifndef BF2_MEMORY_PASSTHROUGH +# if defined(__SANITIZE_ADDRESS__) +# define BF2_MEMORY_PASSTHROUGH 1 +# elif defined(__has_feature) +# if __has_feature(address_sanitizer) +# define BF2_MEMORY_PASSTHROUGH 1 +# endif +# endif +#endif +#ifndef BF2_MEMORY_PASSTHROUGH +# define BF2_MEMORY_PASSTHROUGH 0 +#endif + +using namespace dice::hfe::memory; + +namespace { + +int g_failures; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + ++g_failures; \ + } \ + } while (0) + +// The platform constants of MemoryInternal.h, restated for an independent model. +#if defined(_M_IX86) || defined(__i386__) +const unsigned int kHeader = 4; +const unsigned int kAlign = 4; +#else +const unsigned int kHeader = 16; +const unsigned int kAlign = 16; +#endif +const int kClassSizes[] = {4, 8, 12, 16, 20, 24, 28, 32, 48, 58, 64, 68, 72, 76, 80, 84, 88}; +const int kNumClasses = sizeof(kClassSizes) / sizeof(kClassSizes[0]); +const unsigned int kMaxPooled = 88; + +unsigned int headerOf(void* p) +{ + unsigned int word; + std::memcpy(&word, static_cast(p) - 4, 4); + return word; +} + +bool isPooled(void* p) { return (headerOf(p) & 2) != 0; } +unsigned int chainOf(void* p) { return headerOf(p) >> 17; } + +// Smallest class serving a block of `blockSize` bytes, or -1. +int classFor(unsigned int blockSize) +{ + for (int i = 0; i < kNumClasses; ++i) + if (blockSize <= static_cast(kClassSizes[i])) + return i; + return -1; +} + +unsigned int strideOf(int cls) +{ + const unsigned int size = kClassSizes[cls]; + return (size + kAlign - 1) / kAlign * kAlign; +} + +// Captures what `fn` writes to stderr. +template std::string captureStderr(Fn fn) +{ +#if defined(_WIN32) + fn(); + return std::string(); +#else + std::fflush(stderr); + char path[] = "/tmp/bf2mem_stderr_XXXXXX"; + const int fd = mkstemp(path); + const int saved = dup(2); + dup2(fd, 2); + fn(); + std::fflush(stderr); + dup2(saved, 2); + close(saved); + std::string text; + FILE* f = std::fopen(path, "r"); + if (f) { + char buf[512]; + size_t n; + while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0) + text.append(buf, n); + std::fclose(f); + } + close(fd); + unlink(path); + return text; +#endif +} + +bool fileExists(const char* path) +{ + FILE* f = std::fopen(path, "r"); + if (!f) + return false; + std::fclose(f); + return true; +} + +// Must run first: every class's first slab is still untouched, so its elements come out in +// address order, one stride apart. +void testFreshSlabStrides() +{ + for (int cls = 0; cls < kNumClasses; ++cls) { + const unsigned int block = kClassSizes[cls]; + if (block <= kHeader) + continue; // no user size reaches this class + const unsigned int user = block - kHeader; + CHECK(classFor(user + kHeader) == cls); + void* a = bf_malloc(user, 0); + void* b = bf_malloc(user, 0); + void* c = bf_malloc(user, 0); + CHECK(isPooled(a) && isPooled(b) && isPooled(c)); + CHECK(static_cast(b) - static_cast(a) == static_cast(strideOf(cls))); + CHECK(static_cast(c) - static_cast(b) == static_cast(strideOf(cls))); + CHECK(chainOf(a) == 0); + CHECK(reinterpret_cast(static_cast(a) - kHeader) % kAlign == 0); + bf_free(c); + bf_free(b); + bf_free(a); + } +} + +void testSizesAndHeaders() +{ + for (unsigned int size = 0; size <= 300; ++size) { + void* p = bf_malloc(size, 0); + CHECK(p != 0); + const unsigned int effective = size == 0 ? 1 : size; + CHECK(getSizeOfAllocation(p) == static_cast(effective)); + const unsigned int block = effective + kHeader; + const bool pooled = !BF2_MEMORY_PASSTHROUGH && block <= kMaxPooled; + CHECK(isPooled(p) == pooled); + CHECK((headerOf(p) & 1) == 0); + if (pooled) + CHECK(((headerOf(p) >> 2) & 0x7fff) == block); + else + CHECK((headerOf(p) >> 2) == block); + std::memset(p, 0xA5, effective); + bf_free(p); + } + CHECK(getSizeOfAllocation(0) == 0); + bf_free(0); + + void* big = bf_malloc(1u << 20, 0); + CHECK(!isPooled(big)); + CHECK(getSizeOfAllocation(big) == (1 << 20)); + CHECK((headerOf(big) >> 2) == (1u << 20) + kHeader); + std::memset(big, 1, 1u << 20); + bf_free(big); +} + +void testLifoReuse() +{ + for (unsigned int user = 1; user + kHeader <= kMaxPooled; ++user) { + void* a = bf_malloc(user, 0); + bf_free(a); + void* b = bf_malloc(user, 0); + CHECK(a == b); + bf_free(b); + } +} + +// Fills the first slab of one class so the next element comes from chain position 1, then shows +// that a freed chain-0 element is served next (the freed slab heads the free list). +void testChainOverflow() +{ + const unsigned int user = 1; + const int cls = classFor(user + kHeader); + const unsigned int capacity = 0x100000 / strideOf(cls); + std::vector blocks; + blocks.reserve(capacity + 2); + void* firstChain1 = 0; + for (unsigned int i = 0; i < capacity + 1; ++i) { + void* p = bf_malloc(user, 0); + if (!firstChain1 && chainOf(p) == 1) + firstChain1 = p; + blocks.push_back(p); + } + CHECK(firstChain1 != 0); + CHECK(chainOf(blocks.back()) == 1); + int chain0 = 0; + for (size_t i = 0; i < blocks.size(); ++i) + if (chainOf(blocks[i]) == 0) + ++chain0; + CHECK(chain0 == static_cast(capacity)); + + void* victim = blocks[10]; + CHECK(chainOf(victim) == 0); + bf_free(victim); + void* again = bf_malloc(user, 0); + CHECK(again == victim); + CHECK(chainOf(again) == 0); + blocks[10] = again; + for (size_t i = 0; i < blocks.size(); ++i) + bf_free(blocks[i]); +} + +void testOtherThread() +{ + void* fromThread = 0; + int sizeSeen = 0; + bool pooled = true; + std::thread worker([&] { + fromThread = bf_malloc(16, 0); + sizeSeen = getSizeOfAllocation(fromThread); + pooled = isPooled(fromThread); + bf_free(fromThread); + }); + worker.join(); + CHECK(fromThread != 0); + CHECK(sizeSeen == 16); + CHECK(!pooled); +} + +void testMaxAllocAndCallback() +{ + CHECK(get_max_alloc_size() == 0x1000000u); + set_max_alloc_size(1000); + CHECK(get_max_alloc_size() == 1000u); + + static bool s_callbackRan; + s_callbackRan = false; + register_err_callback([](bool, const char*) { s_callbackRan = true; }); + + void* p = 0; + const std::string text = captureStderr([&] { p = bf_malloc(2000, 0); }); + CHECK(p != 0); + CHECK(getSizeOfAllocation(p) == 2000); + bf_free(p); +#if !defined(_WIN32) + CHECK(text.find("BF2 Memory Error: memory.dll: sanity check: block size 2000 (") != std::string::npos); +#endif + // The shipped DLL ignores the registration. + CHECK(!s_callbackRan); + + void* q = 0; + const std::string quiet = captureStderr([&] { q = bf_malloc(1000, 0); }); + CHECK(quiet.empty()); + bf_free(q); + + reset_max_alloc_size(); + CHECK(get_max_alloc_size() == 0x1000000u); +} + +void testStubs() +{ + CHECK(std::strcmp(getStatus("x"), "Memory.dll Ver:1.01 Date:2005/01/10 - Final") == 0); + CHECK(get_total_bytes_allocated() == 0); + CHECK(get_accumulated_bytes_allocated() == 0); + CHECK(get_total_allocation_call_count() == 0); + CHECK(get_accumulated_allocation_call_count() == 0); + + char buffer[64]; + get_callstack_debug_str(buffer, sizeof(buffer), 8); + CHECK(std::strcmp(buffer, "Only available in DEBUG builds") == 0); + + CHECK(histogramCurrentUsedMemory() == 0); + CHECK(histogramPeakUsedMemory() == 0); + histogramClearPeaks(); + histogramClearCurrent(); + std::remove("bf2mem_hist.txt"); + histogramDumpToFile("bf2mem_hist.txt"); + CHECK(!fileExists("bf2mem_hist.txt")); + + CHECK(addMemoryName("Textures") == 0); + int traceId = -1; + startMemoryTrace(traceId, "Scope"); + CHECK(traceId == -1); + endMemoryTrace(traceId); + memoryTraceReset(); + nextVisualFrame(); + nextPhysicFrame(); + CHECK(std::strcmp(memoryTraceReport(), "use_traceIdentifiers not enabled") == 0); + std::remove("bf2mem_trace.txt"); + memoryTraceReportToFile("bf2mem_trace.txt"); + CHECK(!fileExists("bf2mem_trace.txt")); + + std::remove("bf2mem_dump.txt"); + CHECK(std::strcmp(dump_allocations_to_file("bf2mem_dump.txt", 1), "no active in final build") == 0); + CHECK(std::strcmp(dump_active_allocations_to_file("bf2mem_dump.txt"), "no active in final build") == 0); + CHECK(!fileExists("bf2mem_dump.txt")); + memory_update_modules("x"); + set_all_allocations_to_zero(); +} + +void testResourceIds() +{ + int textures = -1, meshes = -1, again = -1, freed = -1; + resourceTraceAllocate(textures, "Textures", 100); + resourceTraceAllocate(meshes, "Meshes", 50); + resourceTraceAllocate(again, "TEXTURES", 10); + resourceTraceFree(freed, "meshes", 50); + CHECK(textures == 0); + CHECK(meshes == 1); + CHECK(again == 0); + CHECK(freed == 1); + // A resolved id is used as is; the name is not looked at again. + int fixed = 1; + resourceTraceAllocate(fixed, "Textures", 1); + CHECK(fixed == 1); +} + +#if !defined(_WIN32) +// A pooled block freed on another thread is a non-continuable error: the built-in handler reports +// it and stops the process. +void testFatalCrossThreadFree() +{ + void* pooled = bf_malloc(8, 0); + CHECK(isPooled(pooled)); + int pipeFd[2]; + CHECK(pipe(pipeFd) == 0); + const pid_t child = fork(); + if (child == 0) { + dup2(pipeFd[1], 2); + close(pipeFd[0]); + std::thread worker([&] { bf_free(pooled); }); + worker.join(); + _exit(0); // not reached + } + close(pipeFd[1]); + std::string text; + char buf[256]; + ssize_t n; + while ((n = read(pipeFd[0], buf, sizeof(buf))) > 0) + text.append(buf, static_cast(n)); + close(pipeFd[0]); + int status = 0; + waitpid(child, &status, 0); + CHECK(WIFSIGNALED(status)); + CHECK(text.find("is deallocating main thread memory") != std::string::npos); + bf_free(pooled); +} +#endif + +} // namespace + +int main() +{ + if (!BF2_MEMORY_PASSTHROUGH) { + testFreshSlabStrides(); + } else { + void* p = bf_malloc(8, 0); + CHECK(!isPooled(p)); + bf_free(p); + } + testSizesAndHeaders(); + if (!BF2_MEMORY_PASSTHROUGH) { + testLifoReuse(); + testChainOverflow(); + } + testOtherThread(); + testMaxAllocAndCallback(); + testStubs(); + testResourceIds(); +#if !defined(_WIN32) + if (!BF2_MEMORY_PASSTHROUGH) + testFatalCrossThreadFree(); +#endif + std::printf("memory_unit: pass-through %s\n", BF2_MEMORY_PASSTHROUGH ? "on" : "off"); + if (g_failures) { + std::fprintf(stderr, "memory_unit: %d failure(s)\n", g_failures); + return 1; + } + std::printf("memory_unit: all checks passed\n"); + return 0; +} From d6d0ba7137593094e0c6ba913fd7ceb313460c22 Mon Sep 17 00:00:00 2001 From: Markus Kraus Date: Sat, 7 Nov 2026 16:02:06 +0100 Subject: [PATCH 10/71] Engine, game, AI and client UI updates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Branch: `mac/pr1-engine` → `main`. First of three stacked PRs: (1) this, (2) `mac/pr2-renderer`, (3) `mac/pr3-macos`. Diff: 583 files, +23,580 / −3,585. Code and build files only. Contents - Engine and game recoveries and fixes in Core, IO, Game, Scene, Sound, Physics, Animation, Math and VoIP. Examples: - the scene object lifecycle and ObjectManager queries, recovered against the PE; - the GameServer radio messages in self-hosted games; - zoom hides the crosshair; - the input and window message paths. - Menu, HUD and client UI: SwiffPlayer natives, gameswf and BFMeme recoveries and fixes. - AI: updates to the AI library since #1/#2. - Platform-neutral helpers the later stages build on: - scripted input (`Platform/InputScript`); - the x87 arithmetic policy (`X87Compat`, `ExtendedFloat` for arm64). - Shared interfaces from the renderer tree. Engine code here uses three headers from it: `GeomMisc/DebugCircleDrawer.h`, `GeomMisc/DebugLineDrawer.h` and `Geom/ParticleSystem/ParticleSystemManager.h`. - Tests: - `runtime_pair` fixtures for the recovered `Object` manager and destructor contracts (PE 0x0071E3D0, 0x007200D0); - POSIX registry, network and thread checks. - Build files: `CMakeLists.txt`, `CMakePresets.json`, `Code/Build` scripts and `package_release.py`. - These are one file each for all three stages, so they already define the renderer and macOS targets. - The macOS parts only take effect on macOS (PR 3). The detailed history of every change, with the PE/ELF evidence, is on `mac-metal`. This PR carries the final state of its files. Validation (this stage on its own) - Windows (MSVC 14.44, the CI steps): - x86: `build_python.cmd`, configure, `bf2_run_checks` and `bf2_editor_run_checks`, `bf2_w32ded`, `bf2_aidll`. - x64: `build_python.cmd`, configure, `bf2_w64ded`. - All pass. - Linux (Ubuntu 26.04, `linux-x64`): `bf2` and `dice_py_check_run` pass. - Not built at this stage: the Windows client and editor. Their renderer is still `main`'s and needs PR 2; hosted CI skips both anyway (no April 2005 DirectX SDK). The per-change history with the PE/ELF evidence is on mac-metal. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 738 ++- CMakePresets.json | 49 + Code/AidllAbi/aidll-macos.exports | 3 + Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp | 2 - Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h | 14 +- Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp | 6 - Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h | 3 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp | 6 - Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h | 10 +- Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h | 2 +- Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h | 2 +- .../AI/AIDLL/AI/AIBot/SquadCoordinator.cpp | 36 + Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h | 2 - Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp | 59 + Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h | 3 +- Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp | 24 + Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h | 8 +- .../AI/AIBotActionPlan/BAPActionInline.h | 11 +- .../AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp | 7 - .../AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h | 5 - .../AIKnowledge/BFInformationEnvironment.cpp | 6 - .../AI/AIKnowledge/BFInformationEnvironment.h | 2 +- .../AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp | 22 + .../AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp | 19 + Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h | 12 +- Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h | 3 +- Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp | 9 + .../BF2/AI/AIDLL/AI/Main/InformationManager.h | 4 +- .../AIInterface/BFKnowledge/AIAdapterTypes.h | 3 +- .../AI/AIInterface/BFKnowledge/AIFrontier.h | 4 +- .../BF2/AI/AIInterface/BFKnowledge/BFGame.cpp | 6 +- .../BFKnowledge/BFGraphCreator.cpp | 154 +- .../BFKnowledge/BFObjectEnvironment.cpp | 1 - .../AI/AIInterface/BFKnowledge/BFSquad.cpp | 6 - .../AIInterface/BFKnowledge/DebugRenderer.cpp | 113 +- .../AIInterface/BFKnowledge/DebugRenderer.h | 12 +- .../Animation/BoneAnimation/BoneAnimation.cpp | 7 +- .../BoneAnimation/RagDollTemplate.cpp | 6 + Code/BF2/Animation/BoneAnimation/Trigger.cpp | 7 +- Code/BF2/Core/ClassFactoryInstantiations.cpp | 1 - Code/BF2/Core/ConsoleObjectBase.cpp | 18 +- Code/BF2/Core/ConsoleObjectMacro.h | 68 +- Code/BF2/Core/ConsoleObjects.cpp | 18 +- Code/BF2/Core/Debug.cpp | 9 +- Code/BF2/Core/Hash.h | 23 + Code/BF2/Core/LoadStat.cpp | 13 +- Code/BF2/Core/ModuleRegistry.cpp | 25 + Code/BF2/Core/MsvcCrtCompat.h | 288 ++ Code/BF2/Core/PlatformCompat.h | 24 + Code/BF2/Core/PluginDll.cpp | 63 +- Code/BF2/Core/PluginDll.h | 4 +- Code/BF2/Core/PosixRegistry.h | 20 + Code/BF2/Core/Registry.cpp | 119 + Code/BF2/Core/StringTokenizer.h | 66 + Code/BF2/Core/StringUtil.cpp | 57 +- Code/BF2/Core/StringUtil.h | 3 + Code/BF2/Core/System.cpp | 6 + Code/BF2/Core/WeakPtr.h | 1 + Code/BF2/External/BFMeme/Action.cpp | 2 + Code/BF2/External/BFMeme/ActionListAction.cpp | 2 + Code/BF2/External/BFMeme/ActionNode.cpp | 4 + Code/BF2/External/BFMeme/AlphaFadeEffect.cpp | 40 +- Code/BF2/External/BFMeme/AlphaFadeEffect.h | 4 +- Code/BF2/External/BFMeme/AndData.cpp | 2 + Code/BF2/External/BFMeme/BlendFuncEffect.cpp | 6 +- Code/BF2/External/BFMeme/BlendFuncEffect.h | 4 +- Code/BF2/External/BFMeme/BoolData.cpp | 2 + .../External/BFMeme/CallFunctionAction.cpp | 2 + Code/BF2/External/BFMeme/ClassIStream.cpp | 14 +- Code/BF2/External/BFMeme/ClassIStream.h | 11 +- Code/BF2/External/BFMeme/ClassOStream.cpp | 6 +- Code/BF2/External/BFMeme/ClassOStream.h | 4 +- Code/BF2/External/BFMeme/ColorEffect.cpp | 6 +- Code/BF2/External/BFMeme/ColorEffect.h | 4 +- Code/BF2/External/BFMeme/CullNode.cpp | 39 + .../BFMeme/CullVariableActionNode.cpp | 4 + Code/BF2/External/BFMeme/Data.cpp | 77 + .../External/BFMeme/DynamicIndexPointer.cpp | 2 + Code/BF2/External/BFMeme/Effect.cpp | 10 +- Code/BF2/External/BFMeme/Effect.h | 8 +- Code/BF2/External/BFMeme/EffectNode.cpp | 4 + Code/BF2/External/BFMeme/EqualData.cpp | 2 + Code/BF2/External/BFMeme/Event.cpp | 2 + Code/BF2/External/BFMeme/EventQueue.cpp | 2 + Code/BF2/External/BFMeme/FileIStream.cpp | 2 + Code/BF2/External/BFMeme/FileOStream.cpp | 2 + Code/BF2/External/BFMeme/FloatData.cpp | 2 + Code/BF2/External/BFMeme/Function.cpp | 2 + Code/BF2/External/BFMeme/IStream.cpp | 54 +- Code/BF2/External/BFMeme/IStream.h | 8 +- .../BF2/External/BFMeme/InputNodeVisitors.cpp | 2 + Code/BF2/External/BFMeme/IntData.cpp | 9 + Code/BF2/External/BFMeme/LogicalData.cpp | 2 + Code/BF2/External/BFMeme/MoveEffect.cpp | 6 +- Code/BF2/External/BFMeme/MoveEffect.h | 4 +- Code/BF2/External/BFMeme/MovePointer.cpp | 49 +- Code/BF2/External/BFMeme/MovePointer.h | 7 +- Code/BF2/External/BFMeme/NameNode.cpp | 2 + Code/BF2/External/BFMeme/NamedInputStream.cpp | 2 + .../External/BFMeme/NamedObjectRegistry.cpp | 6 +- .../BF2/External/BFMeme/NativeSavedDispatch.h | 89 + Code/BF2/External/BFMeme/Node.cpp | 23 +- Code/BF2/External/BFMeme/NodeState.cpp | 2 + Code/BF2/External/BFMeme/NotData.cpp | 2 + Code/BF2/External/BFMeme/OStream.cpp | 32 +- Code/BF2/External/BFMeme/OStream.h | 8 +- Code/BF2/External/BFMeme/Object.cpp | 2 + Code/BF2/External/BFMeme/Object.h | 14 + Code/BF2/External/BFMeme/ObjectCollection.cpp | 2 + Code/BF2/External/BFMeme/ObjectList.cpp | 4 + Code/BF2/External/BFMeme/OrData.cpp | 2 + Code/BF2/External/BFMeme/PictureNode.cpp | 4 +- Code/BF2/External/BFMeme/PictureNode.h | 6 +- Code/BF2/External/BFMeme/Pointer.cpp | 2 + Code/BF2/External/BFMeme/Quad.cpp | 152 + Code/BF2/External/BFMeme/Quad.h | 13 +- .../BF2/External/BFMeme/SetVariableAction.cpp | 21 + .../External/BFMeme/SetVariableSineAction.cpp | 42 + .../External/BFMeme/SetVariableSoftAction.cpp | 30 + Code/BF2/External/BFMeme/ShowEffectNode.cpp | 2 + Code/BF2/External/BFMeme/SliderNode.h | 2 + Code/BF2/External/BFMeme/SplitNode.cpp | 2 + Code/BF2/External/BFMeme/Stream.cpp | 20 +- Code/BF2/External/BFMeme/Stream.h | 6 +- Code/BF2/External/BFMeme/Style.cpp | 4 +- Code/BF2/External/BFMeme/Style.h | 6 +- Code/BF2/External/BFMeme/System.cpp | 32 +- Code/BF2/External/BFMeme/System.h | 28 +- Code/BF2/External/BFMeme/TextNode.cpp | 2 + Code/BF2/External/BFMeme/TextNode.h | 2 + Code/BF2/External/BFMeme/ToggleData.cpp | 2 + Code/BF2/External/BFMeme/TransformNode.cpp | 38 + Code/BF2/External/BFMeme/TypeDescriptor.cpp | 2 + .../External/BFMeme/VariableColorEffect.cpp | 6 +- .../BF2/External/BFMeme/VariableColorEffect.h | 6 +- Code/BF2/External/GameSpy/LOCAL_CHANGES.md | 10 + Code/BF2/External/GameSpy/common/gsCore.c | 63 + .../GameSpy/common/gsPlatformSocket.h | 4 +- .../GameSpy/common/linux/gsThreadLinux.c | 7 +- .../GameSpy/common/macosx/gsThreadMacOSX.c | 7 +- Code/BF2/External/GameSpy/natneg/natneg.c | 7 + Code/BF2/External/NovintHFX/NovintHFX.h | 4 + Code/BF2/External/README.md | 6 +- Code/BF2/External/base/container.cpp | 8 +- Code/BF2/External/base/container.h | 12 +- Code/BF2/External/base/tu_math.h | 5 +- Code/BF2/External/base/tu_types.h | 4 +- Code/BF2/External/base/utility.cpp | 4 + Code/BF2/External/base/utility.h | 27 +- .../External/gameswf/GAMESWF_DIVERGENCES.md | 6 +- .../gameswf/SwiffPlayer/SwiffCrashLog.cpp | 38 +- .../SwiffPlayer/SwiffNativesRecovered.inl | 4421 +++++++++++++++++ .../gameswf/SwiffPlayer/SwiffPlayer.cpp | 1325 +++-- .../gameswf/SwiffPlayer/SwiffPlayer.h | 71 +- .../gameswf/SwiffPlayer/SwiffPlayerModule.cpp | 32 +- .../gameswf/SwiffPlayer/SwiffPlayerModule.h | 16 + Code/BF2/External/gameswf/gameswf.h | 22 +- Code/BF2/External/gameswf/gameswf_action.cpp | 120 +- Code/BF2/External/gameswf/gameswf_action.h | 98 +- Code/BF2/External/gameswf/gameswf_button.cpp | 26 + Code/BF2/External/gameswf/gameswf_dlist.cpp | 54 +- Code/BF2/External/gameswf/gameswf_dlist.h | 5 + Code/BF2/External/gameswf/gameswf_impl.cpp | 175 +- Code/BF2/External/gameswf/gameswf_impl.h | 33 + Code/BF2/External/gameswf/gameswf_log.cpp | 51 + Code/BF2/External/gameswf/gameswf_log.h | 13 + Code/BF2/External/gameswf/gameswf_render.cpp | 8 +- Code/BF2/External/gameswf/gameswf_render.h | 5 +- Code/BF2/External/gameswf/gameswf_string.cpp | 17 +- Code/BF2/External/gameswf/gameswf_text.cpp | 70 +- .../External/gameswf/gameswf_textformat.cpp | 8 + Code/BF2/External/gameswf/gameswf_types.cpp | 10 +- .../python-embedded/linux/CMakeLists.txt | 63 +- .../External/python-embedded/linux/README.md | 9 +- .../External/python-embedded/macos/README.md | 66 + .../External/python-embedded/macos/pyconfig.h | 974 ++++ .../py-src-2.3.4/Modules/socketmodule.c | 5 + .../py-src-2.3.4/Objects/longobject.c | 9 + .../py-src-2.3.4/Objects/obmalloc.c | 7 + .../py-src-2.3.4/Python/ceval.c | 32 + Code/BF2/Game/AudioSettings.cpp | 34 + Code/BF2/Game/Common/ClientConnection.cpp | 3 +- Code/BF2/Game/Common/GhostManager.cpp | 22 +- Code/BF2/Game/Common/PlayerActionManager.cpp | 3 + Code/BF2/Game/Common/ServerConnection.cpp | 16 +- Code/BF2/Game/ControlSettings.cpp | 4 +- Code/BF2/Game/ControlSettings.h | 4 +- Code/BF2/Game/DemoRecorder/DemoLibrary.cpp | 73 +- Code/BF2/Game/DemoRecorder/DemoLibrary.h | 25 +- Code/BF2/Game/GameClient/GameClient.cpp | 19 +- Code/BF2/Game/GameLogic/GameLogic.cpp | 4 +- .../BF2/Game/GameLogic/GameLogicExplosion.cpp | 3 +- Code/BF2/Game/GameLogic/Player.cpp | 18 +- Code/BF2/Game/GameLogic/ServerGameLogic.cpp | 83 +- .../Game/GameLogic/SpawnSystem/SpawnGroup.cpp | 26 +- Code/BF2/Game/GameLogic/VoiceMessages.cpp | 3 +- Code/BF2/Game/GameServer/AutoRecorder.h | 8 + Code/BF2/Game/GameServer/GameServer.cpp | 197 +- .../Game/GameServer/VoipServerConnection.cpp | 9 +- Code/BF2/Game/GeneralSettings.cpp | 1 + Code/BF2/Game/HudInformationLayer.cpp | 11 +- Code/BF2/Game/LocalProfileManager.h | 13 +- .../Game/LocalProfileManagerOperations.cpp | 28 +- Code/BF2/Game/LocalProfileManagerSuffix.cpp | 12 + Code/BF2/Game/Main/BF2.cpp | 314 +- Code/BF2/Game/Main/BF2.h | 10 +- Code/BF2/Game/Main/BF2ClientFrontiers.cpp | 13 - Code/BF2/Game/Main/BF2ClientSeams.h | 10 +- Code/BF2/Game/Main/BF2Engine.cpp | 419 +- Code/BF2/Game/Main/BF2Engine.h | 5 +- Code/BF2/Game/Main/BF2Render.cpp | 104 +- Code/BF2/Game/Main/BF2Window.cpp | 10 +- Code/BF2/Game/Main/BF2Window.h | 11 + Code/BF2/Game/Main/IVideoOptions.h | 3 +- Code/BF2/Game/Main/OpenBF2Console.cpp | 15 +- .../Game/MatchMaking/Client/CdKeyStore.cpp | 47 +- .../MatchMaking/Server/MatchMakingServer.cpp | 3 +- Code/BF2/Game/Objects/Base/Bundle.cpp | 9 +- Code/BF2/Game/Objects/Base/Camera.cpp | 21 +- .../Objects/Base/ModuleWorldObjTemplBase.cpp | 105 +- Code/BF2/Game/Objects/Base/SimpleObject.cpp | 26 +- .../Objects/Base/SimpleObjectTemplate.cpp | 4 +- .../Game/Objects/Fx/EffectBundleTemplate.cpp | 8 +- .../Game/Objects/Fx/EffectBundleTemplate.h | 2 +- .../Objects/Fx/ExplosionEffectFlashBang.cpp | 7 + Code/BF2/Game/Objects/Fx/Particle.cpp | 20 + Code/BF2/Game/Objects/Game/AnimatedBundle.cpp | 11 +- Code/BF2/Game/Objects/Game/AntennaObject.cpp | 8 +- Code/BF2/Game/Objects/Game/AreaObject.cpp | 8 +- .../Objects/Game/CommanderToolsManager.cpp | 5 +- .../Objects/Game/DestroyableWindowsBundle.cpp | 12 +- Code/BF2/Game/Objects/Game/EngineBase.h | 1 + Code/BF2/Game/Objects/Game/ForceObject.cpp | 8 + Code/BF2/Game/Objects/Game/Kit.cpp | 26 +- Code/BF2/Game/Objects/Game/MaskObject.cpp | 12 +- Code/BF2/Game/Objects/Game/ObjectSpawner.cpp | 12 +- .../Game/PlayerControlObjectHelpers.cpp | 30 + Code/BF2/Game/Objects/Game/Rotor.cpp | 10 +- Code/BF2/Game/Objects/Game/Soldier.cpp | 47 +- .../Game/Objects/Game/SoldierAnimation.cpp | 42 +- Code/BF2/Game/Objects/Game/SupplyDepot.cpp | 9 +- .../Objects/GameLogicComp/ArmorGLComp.cpp | 17 +- Code/BF2/Game/Objects/GeometryPartAccess.h | 90 +- Code/BF2/Game/Objects/IStrategicObjectComp.h | 14 +- Code/BF2/Game/Objects/IVehicleHudComp.h | 6 +- .../Objects/Projectiles/GenericProjectile.cpp | 21 +- .../Projectiles/GenericProjectileTemplate.cpp | 4 +- .../Objects/RemoteControlledObjectTemplate.h | 2 + Code/BF2/Game/Objects/StrategicObjectComp.cpp | 4 +- Code/BF2/Game/Objects/StrategicObjectComp.h | 4 +- .../Objects/StrategicObjectCompTemplate.cpp | 7 +- .../Objects/StrategicObjectCompTemplate.h | 10 +- Code/BF2/Game/Objects/TemplateLeaves.cpp | 35 +- .../Game/Objects/VehicleHudCompTemplate.cpp | 14 +- Code/BF2/Game/Objects/VehicleHudIcons.h | 20 +- Code/BF2/Game/Objects/Visual/LightSource.cpp | 5 +- .../Game/Objects/WeaponHudCompTemplate.cpp | 5 +- .../SoldierDeviationComp.cpp | 16 +- .../Weapons/FireComponents/SingleFireComp.cpp | 18 +- .../Game/Objects/Weapons/GenericFireArm.cpp | 9 +- .../Weapons/TargetComponents/TargetComp.cpp | 14 +- .../ZoomComponents/DefaultZoomComp.cpp | 46 +- .../Weapons/ZoomComponents/DefaultZoomComp.h | 2 +- Code/BF2/Game/PasswordCodec.cpp | 51 + Code/BF2/Game/ProfileManager.cpp | 144 +- .../ParticleSystem/ParticleSystemManager.h | 56 +- Code/BF2/GeomMisc/DebugCircleDrawer.h | 31 + Code/BF2/GeomMisc/DebugLineDrawer.h | 54 + Code/BF2/IO/BitStream.cpp | 51 + Code/BF2/IO/Console/Console.cpp | 70 +- Code/BF2/IO/File/File.cpp | 16 + Code/BF2/IO/File/FileChangeManager.h | 12 +- Code/BF2/IO/File/FileManager.cpp | 62 +- Code/BF2/IO/File/FileManager.h | 6 + Code/BF2/IO/File/FileManagerConsole.cpp | 102 + Code/BF2/IO/File/IFileSystem.h | 2 + Code/BF2/IO/File/UnixFileStream.cpp | 8 + Code/BF2/IO/File/UnixFileSystem.cpp | 73 +- Code/BF2/IO/Input/ControlMap.cpp | 146 +- Code/BF2/IO/Input/ControlMap.h | 2 +- Code/BF2/IO/Input/ControlMapManager.cpp | 208 +- Code/BF2/IO/Input/ControlMapManager.h | 9 +- Code/BF2/IO/Input/FalconDevice.cpp | 40 +- Code/BF2/IO/Input/FalconDevice.h | 11 + Code/BF2/IO/Input/GameControllerDevice.cpp | 6 + Code/BF2/IO/Input/Input.h | 16 +- Code/BF2/IO/Input/KeyboardDevice.cpp | 17 +- Code/BF2/IO/Input/MouseDevice.cpp | 25 +- Code/BF2/IO/Localization/ExcelLexicon.cpp | 22 +- .../Network/NetworkLayer/Socket/UDPSocket.cpp | 10 +- Code/BF2/IO/Network/NetworkStats.cpp | 26 + .../IO/Network/ProtocolLayer/NetClient.cpp | 97 +- Code/BF2/IO/Network/ProtocolLayer/NetClient.h | 13 + .../IO/Network/ProtocolLayer/NetServer.cpp | 28 +- Code/BF2/IO/Network/ProtocolLayer/NetServer.h | 8 + .../IO/Network/ProtocolLayer/SWConnection.cpp | 32 +- Code/BF2/IO/Stream/BoundingBox.cpp | 7 +- Code/BF2/IO/Tokenizer.cpp | 86 +- Code/BF2/IO/Tokenizer.h | 12 +- Code/BF2/Math/Frustum.cpp | 25 +- Code/BF2/Math/Frustum.h | 4 +- Code/BF2/Math/Intersect.cpp | 13 +- Code/BF2/Math/LocalBoundingBox.cpp | 22 +- Code/BF2/Math/LocalBoundingBox.h | 6 +- Code/BF2/Math/Mat4Inverse.cpp | 75 +- Code/BF2/Math/PortableX87.h | 9 +- Code/BF2/Math/Vec3.cpp | 3 + Code/BF2/Math/Vec3.h | 32 + Code/BF2/Menu/BF2HudManager.cpp | 52 +- Code/BF2/Menu/BF2HudManager.h | 20 +- Code/BF2/Menu/BF2HudManagerAbilities.cpp | 67 + Code/BF2/Menu/BF2HudManagerChatInput.cpp | 22 + Code/BF2/Menu/BF2HudManagerHudEvents.cpp | 8 + Code/BF2/Menu/BF2HudManagerInit.cpp | 2 +- Code/BF2/Menu/BF2HudManagerInput.cpp | 63 + Code/BF2/Menu/BF2HudManagerPointer.cpp | 32 +- Code/BF2/Menu/BF2HudManagerProjection.cpp | 57 + Code/BF2/Menu/BF2HudManagerSpotted.cpp | 21 +- Code/BF2/Menu/BF2HudManagerSpottedTarget.cpp | 79 + Code/BF2/Menu/BF2HudManagerUpdate.cpp | 89 + Code/BF2/Menu/BetweenRoundsLogic.cpp | 41 + Code/BF2/Menu/Bf2ActionListAction.cpp | 2 + Code/BF2/Menu/Bf2BarNode.cpp | 4 +- Code/BF2/Menu/Bf2BarNode.h | 4 +- Code/BF2/Menu/Bf2BlendFuncEffect.cpp | 2 + Code/BF2/Menu/Bf2BlendFuncEffect.h | 2 + Code/BF2/Menu/Bf2ButtonNode.cpp | 2 +- Code/BF2/Menu/Bf2ButtonNode.h | 12 +- Code/BF2/Menu/Bf2CallFunctionAction.cpp | 2 + Code/BF2/Menu/Bf2ColorEffect.cpp | 6 +- Code/BF2/Menu/Bf2ColorEffect.h | 6 +- Code/BF2/Menu/Bf2CompassNode.cpp | 6 +- Code/BF2/Menu/Bf2CompassNode.h | 8 +- Code/BF2/Menu/Bf2CullNode.cpp | 35 + Code/BF2/Menu/Bf2EditNode.cpp | 2 +- Code/BF2/Menu/Bf2EditNode.h | 4 +- Code/BF2/Menu/Bf2EffectNode.cpp | 2 + Code/BF2/Menu/Bf2EffectNode.h | 2 + Code/BF2/Menu/Bf2FixedSliderNode.h | 2 + Code/BF2/Menu/Bf2HoverNode.cpp | 30 + Code/BF2/Menu/Bf2HoverNode.h | 2 + Code/BF2/Menu/Bf2HudBuilder.cpp | 20 +- Code/BF2/Menu/Bf2HudBuilder.h | 6 +- Code/BF2/Menu/Bf2MenuMapNode.cpp | 85 +- Code/BF2/Menu/Bf2MenuMapNode.h | 87 +- Code/BF2/Menu/Bf2MiniMenuMapNode.cpp | 12 +- Code/BF2/Menu/Bf2MiniMenuMapNode.h | 10 +- Code/BF2/Menu/Bf2MoveEffect.cpp | 2 + Code/BF2/Menu/Bf2MoveEffect.h | 2 + Code/BF2/Menu/Bf2NewListBoxNode.cpp | 2 +- Code/BF2/Menu/Bf2NewListBoxNode.h | 4 +- Code/BF2/Menu/Bf2ObjectMarkerNode.cpp | 8 +- Code/BF2/Menu/Bf2ObjectMarkerNode.h | 12 +- Code/BF2/Menu/Bf2ObjectSelectionNode.cpp | 2 + Code/BF2/Menu/Bf2ObjectSelectionNode.h | 2 + Code/BF2/Menu/Bf2PictureNode.cpp | 8 +- Code/BF2/Menu/Bf2PictureNode.h | 10 +- Code/BF2/Menu/Bf2SplitNode.cpp | 2 + Code/BF2/Menu/Bf2Style.cpp | 24 +- Code/BF2/Menu/Bf2Style.h | 16 +- Code/BF2/Menu/Bf2TextNode.cpp | 2 + Code/BF2/Menu/Bf2TextNode.h | 2 + Code/BF2/Menu/Bf2TransformListNode.cpp | 51 + Code/BF2/Menu/Bf2TransformListNode.h | 5 +- Code/BF2/Menu/Bf2TransformNode.cpp | 36 + Code/BF2/Menu/BfEditNode.cpp | 251 +- Code/BF2/Menu/BfEditNode.h | 7 +- Code/BF2/Menu/BfFixedSliderNode.h | 2 + Code/BF2/Menu/BfListBoxData.cpp | 102 +- Code/BF2/Menu/BfListBoxData.h | 10 +- Code/BF2/Menu/BfNewListBoxNode.cpp | 66 +- Code/BF2/Menu/BfNewListBoxNode.h | 6 +- Code/BF2/Menu/BfOccupiedVehicleData.cpp | 2 +- Code/BF2/Menu/BfOccupiedVehicleData.h | 14 +- Code/BF2/Menu/BfOccupiedVehicleNode.cpp | 4 +- Code/BF2/Menu/BfOccupiedVehicleNode.h | 2 + Code/BF2/Menu/BfTransformNode.cpp | 52 + Code/BF2/Menu/DifFontMetadata.cpp | 2 + Code/BF2/Menu/Font.cpp | 2 + Code/BF2/Menu/HudAmmo.cpp | 46 +- Code/BF2/Menu/HudArtillerySeams.h | 4 +- Code/BF2/Menu/HudBlinker.h | 6 + Code/BF2/Menu/HudChat.cpp | 10 +- Code/BF2/Menu/HudCommander.cpp | 29 +- Code/BF2/Menu/HudCommander.h | 3 +- Code/BF2/Menu/HudConsoleBindings.cpp | 16 + Code/BF2/Menu/HudInformationAdapter.cpp | 8 + Code/BF2/Menu/HudQuestionManager.cpp | 33 + Code/BF2/Menu/HudScoreboard.cpp | 8 +- Code/BF2/Menu/HudScoreboard.h | 2 +- Code/BF2/Menu/HudSquad.cpp | 16 +- Code/BF2/Menu/HudSquad.h | 4 +- Code/BF2/Menu/HudVehicleFrontiers.cpp | 7 + Code/BF2/Menu/HudVehicleInformation.cpp | 41 + Code/BF2/Menu/HudVoip.cpp | 2 +- Code/BF2/Menu/HudVoip.h | 11 +- Code/BF2/Menu/ISwiffHost.h | 14 +- Code/BF2/Menu/ISwiffPlayer.h | 12 +- Code/BF2/Menu/ISwiffRender.h | 24 +- Code/BF2/Menu/MainMenuLogic.cpp | 51 + Code/BF2/Menu/Ref2System.cpp | 33 +- Code/BF2/Menu/Ref2System.h | 25 +- Code/BF2/Menu/SwiffHost.cpp | 128 +- Code/BF2/Menu/SwiffHost.h | 8 +- Code/BF2/Physics/CollisionManager.cpp | 39 +- Code/BF2/Physics/CollisionMeshTemplate.cpp | 25 +- Code/BF2/Physics/SoldierResponse.h | 7 + Code/BF2/Platform/ExtendedFloat.h | 244 + Code/BF2/Platform/InputScript.cpp | 638 +++ Code/BF2/Platform/InputScript.h | 147 + Code/BF2/Platform/MsvcRand.h | 42 + Code/BF2/Platform/Utf16.h | 40 + Code/BF2/Platform/Windows/WinInputScript.cpp | 424 ++ Code/BF2/Platform/Windows/WinInputScript.h | 56 + Code/BF2/Platform/X87Compat.h | 34 +- Code/BF2/Scene/Object/BinTreeCuller.cpp | 84 +- Code/BF2/Scene/Object/BinTreeCuller.h | 29 +- Code/BF2/Scene/Object/Object.cpp | 151 +- Code/BF2/Scene/Object/ObjectCache.cpp | 1 + Code/BF2/Scene/Object/ObjectManager.cpp | 517 +- Code/BF2/Scene/Object/ObjectManager.h | 17 +- .../BF2/Scene/Object/ObjectManagerConsole.cpp | 12 +- Code/BF2/Scene/Object/ObjectPredicator.cpp | 15 + Code/BF2/Scene/Object/ObjectPredicator.h | 3 + .../Scene/Object/ObjectPriorityCalculator.cpp | 37 +- Code/BF2/Scene/Object/PlayerManager.cpp | 44 +- Code/BF2/Scene/Object/PlayerScoreData.cpp | 1 - Code/BF2/Scene/Object/PlayerScoreData.h | 4 +- Code/BF2/Scene/Object/QuadTreeCuller.cpp | 99 +- Code/BF2/Scene/Object/QuadTreeCuller.h | 14 +- .../WorldObjTemplPortal/IPortalPassing.h | 23 + .../Object/WorldObjTemplPortal/ISector.h | 23 + .../WorldObjTemplPortal/PortalEvent.cpp | 16 +- .../Object/WorldObjTemplPortal/PortalEvent.h | 2 +- .../WorldObjTemplPortal/PortalManager.cpp | 438 +- .../WorldObjTemplPortal/PortalManager.h | 21 +- .../WorldObjTemplPortal/PortalPassing.cpp | 84 + .../WorldObjTemplPortal/PortalPassing.h | 36 + .../Object/WorldObjTemplPortal/Sector.cpp | 87 + .../Scene/Object/WorldObjTemplPortal/Sector.h | 35 + Code/BF2/Sound/BfSound.cpp | 6 +- Code/BF2/Sound/BfSound/MusicPlayer.cpp | 6 + Code/BF2/Sound/BfSound/MusicPlayer.h | 3 + Code/BF2/Sound/ObjectSoundNode.cpp | 2 +- Code/BF2/Sound/SoundEngine/BfSoundEngine.cpp | 3 +- Code/BF2/Sound/SoundEngine/Music.cpp | 16 + Code/BF2/Sound/SoundEngine/OpenALSample.cpp | 73 + Code/BF2/Sound/SoundEngine/Sound.cpp | 3 +- Code/BF2/Sound/SoundEngine/SoundEvaluator.cpp | 3 +- Code/BF2/Sound/SoundEngine/SoundFile.cpp | 8 + Code/BF2/Sound/SoundEngine/Win32System.cpp | 159 +- Code/BF2/Sound/SoundEngine/Win32System.h | 14 + Code/BF2/VoipServer/VoipServerInstance.cpp | 5 +- Code/Build/bf2audio.cmd | 23 +- Code/Build/dxsdk.cmd | 125 + Code/Build/package_release.py | 46 +- Code/Build/ship.ps1 | 4 +- Code/Build/swiffplayer.cmd | 24 +- Code/Build/textureatlasbuilder.cmd | 101 +- Code/StaticPlugins/StaticPlugins.cpp | 177 + Code/StaticPlugins/StaticPlugins.h | 42 + .../bf2audio-private-symbols.txt | 12 + Code/StaticPlugins/image-private-symbols.txt | 28 + Code/SwiffPlayerAbi/NativeRenderCalls.h | 72 + Code/Tests/README.md | 7 +- Code/Tests/SwiffHostStandIn.h | 8 +- Code/Tests/buffer_manager_collect_runtime.cmd | 4 +- Code/Tests/buffer_manager_collect_runtime.cpp | 31 +- Code/Tests/bundled_height_runtime.cmd | 2 + Code/Tests/bundled_height_runtime.cpp | 4 +- Code/Tests/bundled_mesh_draw_runtime.cmd | 7 +- Code/Tests/bundled_mesh_draw_runtime.cpp | 72 +- Code/Tests/bundled_mesh_state_runtime.cmd | 7 +- Code/Tests/bundled_mesh_state_runtime.cpp | 15 +- Code/Tests/client_startup_runtime.cpp | 8 +- Code/Tests/control_settings_runtime.cpp | 6 +- Code/Tests/demo_library_runtime.cmd | 2 +- Code/Tests/demo_library_runtime.cpp | 6 + Code/Tests/effect_parameter_cache_runtime.cmd | 14 +- Code/Tests/effect_parameter_cache_runtime.cpp | 24 +- Code/Tests/effect_stock_d3d_runtime.cmd | 4 +- Code/Tests/effect_stock_d3d_runtime.cpp | 28 +- Code/Tests/env_map_runtime.cmd | 7 +- Code/Tests/env_map_runtime.cpp | 45 +- Code/Tests/envmap_bind_runtime.cpp | 6 +- Code/Tests/envmap_object_runtime.cmd | 9 +- Code/Tests/envmap_object_runtime.cpp | 6 +- Code/Tests/font_runtime_support.h | 2 +- Code/Tests/fsmovie_d3d_runtime.cmd | 10 +- Code/Tests/fsmovie_d3d_runtime.cpp | 17 +- Code/Tests/fsmovie_runtime.cmd | 6 +- Code/Tests/fsmovie_runtime.cpp | 2 +- .../geometry_template_lifecycle_runtime.cmd | 6 +- .../geometry_template_lifecycle_runtime.cpp | 14 +- Code/Tests/hud_atlas_snapshot_runtime.cmd | 6 +- Code/Tests/hud_commander_apply_runtime.cpp | 2 +- Code/Tests/hud_edit_node_runtime.cmd | 4 - Code/Tests/hud_edit_node_runtime.cpp | 66 +- Code/Tests/hud_input_keys_runtime.cpp | 4 +- Code/Tests/hud_projection_runtime.cpp | 38 +- Code/Tests/hud_spotted_runtime.cpp | 2 +- Code/Tests/light_manager_runtime.cpp | 20 +- Code/Tests/local_profile_lifetime_runtime.cpp | 14 +- Code/Tests/menu_interact_runtime.cpp | 351 ++ Code/Tests/menu_interact_runtime.sh | 25 + Code/Tests/mouse_device_runtime.cpp | 2 +- Code/Tests/movies/bink_harness.cmd | 48 + Code/Tests/movies/bink_harness.cpp | 822 +++ Code/Tests/n1_posix_net/build.py | 54 + Code/Tests/n1_posix_net/loopback.cpp | 136 + Code/Tests/n1_posix_net/run.sh | 10 + .../Tests/object_drawer_occlusion_runtime.cmd | 2 + .../Tests/object_drawer_occlusion_runtime.cpp | 140 +- Code/Tests/overgrowth_runtime.cmd | 3 +- Code/Tests/overgrowth_runtime.cpp | 73 +- Code/Tests/particle_active_draw_fixture.inl | 6 +- Code/Tests/particle_draw_runtime.cmd | 4 +- Code/Tests/particle_draw_runtime.cpp | 67 +- .../Tests/particle_instance_type0_runtime.cmd | 4 +- .../Tests/particle_instance_type0_runtime.cpp | 7 +- .../Tests/particle_instance_type1_runtime.cmd | 4 +- .../Tests/particle_instance_type1_runtime.cpp | 4 +- .../Tests/particle_instance_type2_runtime.cmd | 4 +- .../Tests/particle_instance_type2_runtime.cpp | 5 +- .../Tests/particle_instance_type3_runtime.cmd | 4 +- .../Tests/particle_instance_type3_runtime.cpp | 8 +- .../Tests/particle_instance_type4_runtime.cmd | 4 +- .../Tests/particle_instance_type4_runtime.cpp | 7 +- Code/Tests/particle_nsa_draw_fixture.inl | 6 +- Code/Tests/particle_preload_runtime.cmd | 4 +- Code/Tests/particle_preload_runtime.cpp | 7 +- .../Tests/particle_renderer_fixture_support.h | 11 +- Code/Tests/particle_system_manager_abi.cmd | 2 + Code/Tests/particle_system_manager_abi.cpp | 9 +- Code/Tests/particle_trail_draw_fixture.inl | 4 +- Code/Tests/particle_update_runtime.cmd | 4 +- Code/Tests/particle_update_runtime.cpp | 64 +- Code/Tests/portable_x87.cpp | 289 ++ Code/Tests/portable_x87_check.py | 72 + Code/Tests/posix_registry/build.sh | 29 + Code/Tests/posix_registry/registry_check.cpp | 101 + Code/Tests/quad_drawer_states_runtime.cmd | 6 +- Code/Tests/quad_drawer_states_runtime.cpp | 44 +- Code/Tests/renddx9_detail_helpers_runtime.cmd | 6 +- Code/Tests/renddx9_detail_helpers_runtime.cpp | 67 +- Code/Tests/renddx9_host/RendDX9Host.cpp | 288 +- Code/Tests/render_view_runtime.cmd | 6 +- Code/Tests/render_view_runtime.cpp | 4 - .../Tests/renderer_accessor_fixture_support.h | 27 + .../resource_manager_lifecycle_runtime.cmd | 4 +- .../resource_manager_lifecycle_runtime.cpp | 20 +- Code/Tests/road_objects_runtime.cmd | 6 +- Code/Tests/road_objects_runtime.cpp | 78 +- Code/Tests/runtime_pair.cmd | 3 + Code/Tests/runtime_pair.cpp | 16 + Code/Tests/s2_10_threads/audio_worker.cpp | 47 + Code/Tests/s2_10_threads/boundaries.cpp | 208 + Code/Tests/s2_10_threads/build.py | 56 + Code/Tests/s2_10_threads/prepare-tsan.py | 51 + Code/Tests/s2_10_threads/retail.py | 29 + Code/Tests/s2_10_threads/run-tsan.sh | 46 + Code/Tests/s2_10_threads/smoke.tcl | 47 + Code/Tests/skinnedmesh_selection_runtime.cmd | 8 +- Code/Tests/skinnedmesh_selection_runtime.cpp | 98 +- .../Tests/soldier_weapon_geometry_runtime.cpp | 8 +- Code/Tests/static_mesh_occluders_runtime.cmd | 6 +- Code/Tests/static_mesh_occluders_runtime.cpp | 81 +- Code/Tests/swiff_disconnect_runtime.cmd | 6 +- Code/Tests/swiff_disconnect_runtime.cpp | 6 +- Code/Tests/swiff_font_header_runtime.cmd | 11 +- Code/Tests/swiff_font_header_runtime.cpp | 6 +- .../swiffplayer_host/SwiffPlayerHost.cpp | 88 +- Code/Tests/syntaxcheck.cmd | 123 + Code/Tests/test_ai_ledger.py | 117 + Code/Tests/test_ai_static_init.py | 231 + Code/Tests/vc71_set_runtime.cmd | 25 - Code/Tests/vc71_set_runtime.cpp | 336 -- Code/Tests/video_bink_d3d_runtime.cmd | 6 +- Code/Tools/BF2Editor/App/EngineHost.cpp | 14 +- .../BF2Editor/App/TerrainLayerRecords.cpp | 8 +- Code/Tools/BF2Editor/CMakeLists.txt | 40 +- Code/Tools/BF2Editor/Framework/EditorConfig.h | 7 +- Code/Tools/BF2Editor/renddx9_for_editor.cmd | 7 +- 583 files changed, 23580 insertions(+), 3585 deletions(-) create mode 100644 Code/AidllAbi/aidll-macos.exports create mode 100644 Code/BF2/Core/MsvcCrtCompat.h create mode 100644 Code/BF2/Core/PosixRegistry.h create mode 100644 Code/BF2/Core/StringTokenizer.h create mode 100644 Code/BF2/External/BFMeme/NativeSavedDispatch.h create mode 100644 Code/BF2/External/gameswf/SwiffPlayer/SwiffNativesRecovered.inl create mode 100644 Code/BF2/External/python-embedded/macos/README.md create mode 100644 Code/BF2/External/python-embedded/macos/pyconfig.h create mode 100644 Code/BF2/GeomMisc/DebugCircleDrawer.h create mode 100644 Code/BF2/GeomMisc/DebugLineDrawer.h create mode 100644 Code/BF2/Platform/ExtendedFloat.h create mode 100644 Code/BF2/Platform/InputScript.cpp create mode 100644 Code/BF2/Platform/InputScript.h create mode 100644 Code/BF2/Platform/MsvcRand.h create mode 100644 Code/BF2/Platform/Utf16.h create mode 100644 Code/BF2/Platform/Windows/WinInputScript.cpp create mode 100644 Code/BF2/Platform/Windows/WinInputScript.h create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/IPortalPassing.h create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/ISector.h create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/PortalPassing.cpp create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/PortalPassing.h create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/Sector.cpp create mode 100644 Code/BF2/Scene/Object/WorldObjTemplPortal/Sector.h create mode 100644 Code/Build/dxsdk.cmd create mode 100644 Code/StaticPlugins/StaticPlugins.cpp create mode 100644 Code/StaticPlugins/StaticPlugins.h create mode 100644 Code/StaticPlugins/bf2audio-private-symbols.txt create mode 100644 Code/StaticPlugins/image-private-symbols.txt create mode 100644 Code/SwiffPlayerAbi/NativeRenderCalls.h create mode 100644 Code/Tests/menu_interact_runtime.cpp create mode 100755 Code/Tests/menu_interact_runtime.sh create mode 100644 Code/Tests/movies/bink_harness.cmd create mode 100644 Code/Tests/movies/bink_harness.cpp create mode 100644 Code/Tests/n1_posix_net/build.py create mode 100644 Code/Tests/n1_posix_net/loopback.cpp create mode 100644 Code/Tests/n1_posix_net/run.sh create mode 100644 Code/Tests/portable_x87.cpp create mode 100644 Code/Tests/portable_x87_check.py create mode 100644 Code/Tests/posix_registry/build.sh create mode 100644 Code/Tests/posix_registry/registry_check.cpp create mode 100644 Code/Tests/renderer_accessor_fixture_support.h create mode 100644 Code/Tests/s2_10_threads/audio_worker.cpp create mode 100644 Code/Tests/s2_10_threads/boundaries.cpp create mode 100644 Code/Tests/s2_10_threads/build.py create mode 100644 Code/Tests/s2_10_threads/prepare-tsan.py create mode 100644 Code/Tests/s2_10_threads/retail.py create mode 100644 Code/Tests/s2_10_threads/run-tsan.sh create mode 100644 Code/Tests/s2_10_threads/smoke.tcl create mode 100644 Code/Tests/test_ai_ledger.py create mode 100644 Code/Tests/test_ai_static_init.py delete mode 100644 Code/Tests/vc71_set_runtime.cmd delete mode 100644 Code/Tests/vc71_set_runtime.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9d147a502..d8d0f7043 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,6 +8,12 @@ if(POLICY CMP0141) endif() project(BF2Rebuilt LANGUAGES C CXX) +# [CHOSEN, not recovered] Header-selection preparation for the G2w forwarding backend. +option(BF2_GFX_SEAM "Compile the renderer against the D3D9/D3DX subset headers" OFF) +if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + # [CHOSEN, not recovered] The macOS client's Cocoa host is Objective-C++ (docs/macos-s2-4.md). + enable_language(OBJCXX) +endif() # ================================================================================================= # TOOLCHAINS (2026-09-29). Three configurations, one source tree: @@ -16,23 +22,35 @@ project(BF2Rebuilt LANGUAGES C CXX) # * GCC/Clang, Linux - the native Linux dedicated port: `bf2` + `libdice_py.so`. It is the x64 # x86-64 port's pointer-bearing layouts compiled by the platform family the ELF # oracle was built for. -# Everything Linux-specific in this file sits under BF2_BUILD_LINUX; the MSVC configurations are -# untouched by it. The Linux build is a native port (`[CHOSEN, not recovered]` layouts, like x64), -# not a reproduction of the shipped 32-bit ELF's object layouts. +# * AppleClang, macOS - the native macOS dedicated port: `bf2` + `libdice_py.dylib`, the Linux +# port's sources and layouts built for Darwin (docs/macos-port.md). +# Linux and macOS form the POSIX family (BF2_BUILD_POSIX); what they share sits under that switch, +# and only what genuinely differs sits under BF2_BUILD_LINUX or BF2_BUILD_MACOS. The MSVC +# configurations are untouched by any of them. Both POSIX builds are native ports +# (`[CHOSEN, not recovered]` layouts, like x64), not reproductions of the shipped 32-bit ELF's +# object layouts. The macOS configuration is an intentional port change requested by the project +# owner, `[CHOSEN, not recovered]` throughout. # ================================================================================================= set(BF2_BUILD_LINUX OFF) +set(BF2_BUILD_MACOS OFF) +set(BF2_BUILD_POSIX OFF) if(MSVC) # The two Windows configurations, selected by pointer width below. elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") set(BF2_BUILD_LINUX ON) + set(BF2_BUILD_POSIX ON) +elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") + # [CHOSEN, not recovered] AppleClang (or upstream Clang) on macOS: the macos-x64 preset. + set(BF2_BUILD_MACOS ON) + set(BF2_BUILD_POSIX ON) else() message(FATAL_ERROR - "BF2Rebuilt builds with MSVC on Windows (msvc-x86 / msvc-x64 presets) or with GCC/Clang on " - "Linux x86-64 (linux-x64 preset). This toolchain is ${CMAKE_CXX_COMPILER_ID} on " - "${CMAKE_SYSTEM_NAME}.") + "BF2Rebuilt builds with MSVC on Windows (msvc-x86 / msvc-x64 presets), with GCC/Clang on " + "Linux x86-64 (linux-x64 preset) or with Clang on macOS (macos-x64 preset). This " + "toolchain is ${CMAKE_CXX_COMPILER_ID} on ${CMAKE_SYSTEM_NAME}.") endif() -if(CMAKE_SIZEOF_VOID_P EQUAL 4 AND NOT BF2_BUILD_LINUX) +if(CMAKE_SIZEOF_VOID_P EQUAL 4 AND NOT BF2_BUILD_POSIX) set(BF2_BUILD_X64 OFF) set(BF2_NATIVE_ARCH "x86") elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) @@ -45,6 +63,11 @@ elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) message(STATUS "Configuring the native Linux x86-64 dedicated-server port (bf2 + libdice_py.so). " "See docs/building.md for toolchain and runtime setup.") + elseif(BF2_BUILD_MACOS) + set(BF2_NATIVE_ARCH "macos-${CMAKE_SYSTEM_PROCESSOR}") + message(STATUS + "Configuring the native macOS ${CMAKE_SYSTEM_PROCESSOR} dedicated-server port " + "(bf2 + libdice_py.dylib). See docs/building.md and docs/macos-port.md.") else() set(BF2_NATIVE_ARCH "x64") message(STATUS @@ -54,7 +77,7 @@ elseif(CMAKE_SIZEOF_VOID_P EQUAL 8) else() message(FATAL_ERROR "BF2Rebuilt supports only MSVC x86 (retail-fidelity), MSVC x64 (native dedicated port) " - "and Linux x86-64 (native dedicated port) configurations; " + "and 64-bit Linux/macOS (native dedicated port) configurations; " "CMAKE_SIZEOF_VOID_P=${CMAKE_SIZEOF_VOID_P}.") endif() @@ -132,6 +155,17 @@ foreach(component_path IN LISTS bf2_component_paths) endif() endforeach() list(SORT bf2_engine_sources) +# [CHOSEN, not recovered] The CPU effect library has its own image and source manifest. +list(REMOVE_ITEM bf2_engine_sources + "${BF2_ROOT}/Platform/Gfx/Effect/Cache.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/Runtime.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/D3DAsm.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/FxBuild.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/FxParser.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/FxStates.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/Native.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/NativeMojo.cpp" + "${BF2_ROOT}/Platform/Gfx/Effect/NativeVkd3d.cpp") list(SORT bf2_engine_headers) # These translation units belong to AIDLL_w32ded.dll, not bf2_w32ded.exe. The source tree is @@ -357,12 +391,13 @@ endif() # Game/Main/StatusMonitorImpl_win32.cpp and IO/File/Win32FileSystem.cpp, the ELF attests # IO/File/UnixFileSystem.cpp and StatusMonitorImpl_posix. The POSIX pair already compiles to an empty # TU under MSVC by its own guards; the Win32 pair is whole-file Win32 API with no guard, so it leaves -# the manifest on Linux instead. Same discipline as the AIDLL and client lists above. +# the manifest on Linux instead. Same discipline as the AIDLL and client lists above. macOS takes +# the POSIX pair as well ([CHOSEN, not recovered]: there was no retail macOS server). set(bf2_win32_only_sources "${BF2_ROOT}/IO/File/Win32FileSystem.cpp" "${BF2_ROOT}/Game/Main/StatusMonitorImpl_win32.cpp" ) -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) list(REMOVE_ITEM bf2_engine_sources ${bf2_win32_only_sources}) endif() @@ -484,6 +519,9 @@ function(bf2_configure_c_target target) ) if(BF2_BUILD_LINUX) target_compile_definitions("${target}" PRIVATE _LINUX _GNU_SOURCE) + elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The SDK's own Darwin branch ("MacOSX: _MACOSX + _UNIX"). + target_compile_definitions("${target}" PRIVATE _MACOSX) endif() endif() bf2_add_compile_debug_info("${target}") @@ -516,12 +554,18 @@ endfunction() # The embedded CPython's headers: Include/ plus the platform pyconfig.h directory. Windows uses the # vendored PC/pyconfig.h; Linux uses the configure-generated pyconfig.h vendored under -# External/python-embedded/linux/ (a chosen path - see that directory's README). +# External/python-embedded/linux/ (a chosen path - see that directory's README); macOS uses the +# Darwin configure output vendored under External/python-embedded/macos/ ([CHOSEN, not recovered]). if(BF2_BUILD_LINUX) set(BF2_PYTHON_INCLUDE_DIRS "${BF2_EXTERNAL_ROOT}/python-embedded/linux" "${BF2_EXTERNAL_ROOT}/python-embedded/py-src-2.3.4/Include" ) +elseif(BF2_BUILD_MACOS) + set(BF2_PYTHON_INCLUDE_DIRS + "${BF2_EXTERNAL_ROOT}/python-embedded/macos" + "${BF2_EXTERNAL_ROOT}/python-embedded/py-src-2.3.4/Include" + ) else() set(BF2_PYTHON_INCLUDE_DIRS "${BF2_EXTERNAL_ROOT}/python-embedded/py-src-2.3.4/Include" @@ -541,6 +585,12 @@ if(BF2_BUILD_LINUX) set(CURSES_NEED_NCURSES TRUE) set(CURSES_NEED_WIDE TRUE) find_package(Curses REQUIRED) +elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS SDK's system ncurses (libncurses.tbd) carries the same + # entry points; the SDK has no separate libncursesw, so the wide variant is not requested. + find_package(Threads REQUIRED) + set(CURSES_NEED_NCURSES TRUE) + find_package(Curses REQUIRED) endif() add_library(bf2_engine_objects OBJECT @@ -555,12 +605,19 @@ if(BF2_BUILD_X64 AND MSVC) # build failure. Explicit fixed-width wire conversions remain reviewable in source. target_compile_options(bf2_engine_objects PRIVATE /Gy /we4244 /we4267 /we4311 /we4312) endif() -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) target_include_directories(bf2_engine_objects PRIVATE ${CURSES_INCLUDE_DIRS}) # The engine's own GameSpy-facing TUs (persistence, match-making, HTTP) include the SDK headers, - # whose platform switch is _LINUX (gsPlatform.h) - the same define bf2_configure_c_target gives - # the SDK's C objects. - target_compile_definitions(bf2_engine_objects PRIVATE _LINUX) + # whose platform switch is _LINUX or _MACOSX (gsPlatform.h) - the same define + # bf2_configure_c_target gives the SDK's C objects. BF2_PLATFORM_POSIX selects the engine's + # POSIX implementations (UnixFileSystem, the ncurses status monitor) on every POSIX family + # member, including macOS, whose compilers do not define __unix__. + target_compile_definitions(bf2_engine_objects PRIVATE BF2_PLATFORM_POSIX) + if(BF2_BUILD_LINUX) + target_compile_definitions(bf2_engine_objects PRIVATE _LINUX) + else() + target_compile_definitions(bf2_engine_objects PRIVATE _MACOSX) + endif() endif() # The client is a second compilation of the shared engine sources, not a relink of @@ -573,6 +630,17 @@ set(bf2_client_sources ) list(REMOVE_DUPLICATES bf2_client_sources) list(SORT bf2_client_sources) +if(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS client replaces the DirectInput 8 devices with + # MacInputDeviceManager and the Mac*Device TUs (docs/macos-s2-4.md). The Novint Falcon stays + # disabled: FalconDevice.cpp is kept, and outside _WIN32 it defines only the menu's + # g_falconMouseMode (docs/macos-port.md, S2.8). The Linux and MSVC client manifests are unchanged. + list(REMOVE_ITEM bf2_client_sources + "${BF2_ROOT}/IO/Input/DX8InputDeviceManager.cpp" + "${BF2_ROOT}/IO/Input/KeyboardDevice.cpp" + "${BF2_ROOT}/IO/Input/MouseDevice.cpp" + "${BF2_ROOT}/IO/Input/GameControllerDevice.cpp") +endif() add_library(bf2_client_objects OBJECT EXCLUDE_FROM_ALL ${bf2_client_sources} ${bf2_engine_headers} @@ -584,14 +652,30 @@ bf2_set_platform_compat(bf2_client_objects) # same MSVC STL layout even when this CMake tree is configured as Debug; iterator debugging changes # container layout and cannot cross the image boundary. PluginAbi.h enforces the matching contract. target_compile_definitions(bf2_client_objects PRIVATE - BF2_PLUGIN_ABI_NATIVE=1 _ITERATOR_DEBUG_LEVEL=0 ) +# [CHOSEN, not recovered] The native x64 client (https://github.com/B2BF/OpenBF2/issues/7): a pointer +# truncated into a 32-bit integer fails the build, as in the plugin scripts' x64 mode. The editor's +# own objects and its second compilation of shared TUs take the same list. +set(BF2_CLIENT_X64_COMPILE_OPTIONS) +if(BF2_BUILD_X64 AND MSVC) + set(BF2_CLIENT_X64_COMPILE_OPTIONS /Gy /we4311 /we4312) +endif() +target_compile_options(bf2_client_objects PRIVATE ${BF2_CLIENT_X64_COMPILE_OPTIONS}) target_include_directories(bf2_client_objects PRIVATE ${BF2_PYTHON_INCLUDE_DIRS} "${BF2_EXTERNAL_ROOT}/zlib-1.2.3" "${BF2_EXTERNAL_ROOT}/zlib-1.2.3/contrib/minizip" ) +if(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS client (docs/macos-port.md, "Client triage") compiles the + # shared engine sources with the platform switches the macOS server objects use: + # BF2_PLATFORM_POSIX selects the POSIX file system and status monitor, _MACOSX the GameSpy + # SDK's Darwin branch, BF2_STATIC_PLUGINS the statically linked plugin images + # (Code/StaticPlugins). The Linux and MSVC client objects are unchanged. + target_include_directories(bf2_client_objects PRIVATE ${CURSES_INCLUDE_DIRS}) + target_compile_definitions(bf2_client_objects PRIVATE BF2_PLATFORM_POSIX _MACOSX BF2_STATIC_PLUGINS=1) +endif() source_group(TREE "${BF2_ROOT}" PREFIX "BF2" FILES ${bf2_client_sources} ${bf2_engine_headers} @@ -860,6 +944,14 @@ if(BF2_BUILD_LINUX) set(BF2_DEDICATED_DEFAULT_OUTPUT_DIR "${CMAKE_BINARY_DIR}/bin_linux") set(BF2_DICE_PY_DEFAULT_DIR "") set(BF2_DICE_PY_BUILD_HINT "libdice_py.so is a CMake target (dice_py) on Linux") +elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS port keeps the Linux names: `bf2` beside libdice_py.dylib, + # found through an @loader_path rpath. + set(BF2_DEDICATED_TARGET "bf2") + set(BF2_DEDICATED_OUTPUT_NAME "bf2") + set(BF2_DEDICATED_DEFAULT_OUTPUT_DIR "${CMAKE_BINARY_DIR}/bin_macos") + set(BF2_DICE_PY_DEFAULT_DIR "") + set(BF2_DICE_PY_BUILD_HINT "libdice_py.dylib is a CMake target (dice_py) on macOS") elseif(BF2_BUILD_X64) set(BF2_DEDICATED_TARGET "bf2_w64ded") set(BF2_DEDICATED_OUTPUT_NAME "bf2_w64ded") @@ -880,8 +972,9 @@ else() endif() set(BF2_DEDICATED_OUTPUT_DIR "${BF2_DEDICATED_DEFAULT_OUTPUT_DIR}" CACHE PATH "Where ${BF2_DEDICATED_OUTPUT_NAME}.exe is written (never the retail game directory)") -if(BF2_BUILD_LINUX) - # libdice_py.so - the embedded CPython 2.3.4 as a shared library, built beside `bf2`. +if(BF2_BUILD_POSIX) + # libdice_py.so/.dylib - the embedded CPython 2.3.4 as a shared library, built beside `bf2`. + # One build description serves both POSIX ports; it selects the platform's pyconfig.h itself. set(BF2_DICE_PY_OUTPUT_DIR "${BF2_DEDICATED_OUTPUT_DIR}") if(EXISTS "${BF2_EXTERNAL_ROOT}/python-embedded/linux/CMakeLists.txt") add_subdirectory("${BF2_EXTERNAL_ROOT}/python-embedded/linux" "${CMAKE_BINARY_DIR}/dice_py") @@ -919,7 +1012,7 @@ set_target_properties("${BF2_DEDICATED_TARGET}" PROPERTIES PDB_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}" FOLDER "BF2" ) -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) if(TARGET dice_py) target_link_libraries("${BF2_DEDICATED_TARGET}" PRIVATE dice_py) endif() @@ -955,7 +1048,7 @@ endif() # copy_if_different so a rebuild does not touch the file when nothing changed. # NOTE: the guard is evaluated at CONFIGURE time, exactly like the .lib check below it. If the DLL # is built later by Code/Build/python/build_python.cmd, re-run CMake once so this rule appears. -if(BF2_BUILD_LINUX) +if(BF2_BUILD_POSIX) # Nothing to stage: the dice_py target writes libdice_py.so into BF2_DEDICATED_OUTPUT_DIR, and # the executable carries an $ORIGIN rpath (below) so the pair can be copied anywhere together. elseif(EXISTS "${BF2_DICE_PY_DLL}") @@ -994,6 +1087,22 @@ if(BF2_BUILD_LINUX) -pthread "-Wl,-Map=${BF2_DEDICATED_OUTPUT_DIR}/${BF2_DEDICATED_OUTPUT_NAME}.map" ) +elseif(BF2_BUILD_MACOS) + # [CHOSEN, not recovered] The macOS counterparts of the Linux link contract above: libSystem + # supplies pthreads, dl and libm; ncurses comes from the SDK. libdice_py.dylib is resolved + # beside the executable through @loader_path, the Mach-O spelling of $ORIGIN. ld64 rejects + # undefined symbols by default, so this link is strict like the Linux one. There is no + # static-runtime option: libc++ is part of the OS on macOS. + target_link_libraries("${BF2_DEDICATED_TARGET}" PRIVATE + Threads::Threads ${CMAKE_DL_LIBS} ${CURSES_LIBRARIES}) + set_target_properties("${BF2_DEDICATED_TARGET}" PROPERTIES + BUILD_RPATH "@loader_path" + INSTALL_RPATH "@loader_path" + BUILD_WITH_INSTALL_RPATH TRUE + ) + target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE + "-Wl,-map,${BF2_DEDICATED_OUTPUT_DIR}/${BF2_DEDICATED_OUTPUT_NAME}.map" + ) else() target_link_libraries("${BF2_DEDICATED_TARGET}" PRIVATE advapi32 user32 shell32 dbghelp ws2_32) target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE @@ -1013,12 +1122,13 @@ if(NOT BF2_BUILD_X64) else() target_link_options("${BF2_DEDICATED_TARGET}" PRIVATE /OPT:REF /OPT:ICF /INCREMENTAL:NO) endif() -endif() # BF2_BUILD_LINUX / MSVC link contracts +endif() # BF2_BUILD_LINUX / BF2_BUILD_MACOS / MSVC link contracts # ================================================================================================= # bf2_aidll - THE BOT-AI SIDE-DLL IMAGE. -# Windows x64 remains dedicated-only; Linux builds its own native libaidll.so. -if(NOT BF2_BUILD_X64 OR BF2_BUILD_LINUX) +# The native Windows x64 profile remains dedicated-only. POSIX ports build their own AI image +# below with native headers; they cannot use the shipped x86 library. +if(NOT BF2_BUILD_X64 OR BF2_BUILD_POSIX) # # AIDLL_w32ded.dll is a THIRD server-side image built from this same tree: bf2_w32ded.exe loads it # through ai::AIConnection::init -> LoadLibraryBf -> the exported initDll, and reaches it afterwards @@ -1056,9 +1166,10 @@ foreach(bf2_aidll_line IN LISTS bf2_aidll_manifest_lines) endif() endforeach() add_library(bf2_aidll SHARED EXCLUDE_FROM_ALL ${bf2_aidll_sources}) -if(BF2_BUILD_LINUX) - # [CHOSEN, not recovered] Native Linux AI image (a native-port design, not retail); same host toolchain - # and STL ABI as bf2. Never substitute the retail 32-bit libaidll.so. +if(BF2_BUILD_POSIX) + # [CHOSEN, not recovered] Native POSIX AI image (Linux libaidll.so, macOS libaidll.dylib; a + # native-port design, not retail); same host toolchain and STL ABI as bf2. Never substitute the + # retail 32-bit libaidll.so (docs/macos-s2-6-aidll.md). bf2_configure_cpp_target(bf2_aidll) bf2_set_image(bf2_aidll 1) bf2_set_platform_compat(bf2_aidll) @@ -1071,11 +1182,18 @@ if(BF2_BUILD_LINUX) FOLDER "BF2") # Keep module globals private, including names also defined by the engine. The only # cross-image entry points are the existing ClassManager handshake exports. - target_link_options(bf2_aidll PRIVATE - -Wl,--no-undefined - "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") - set_property(TARGET bf2_aidll APPEND PROPERTY LINK_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") + if(BF2_BUILD_MACOS) + target_link_options(bf2_aidll PRIVATE + "-Wl,-exported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-macos.exports") + set_property(TARGET bf2_aidll APPEND PROPERTY LINK_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-macos.exports") + else() + target_link_options(bf2_aidll PRIVATE + -Wl,--no-undefined + "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") + set_property(TARGET bf2_aidll APPEND PROPERTY LINK_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/Code/AidllAbi/aidll-posix.map") + endif() add_dependencies("${BF2_DEDICATED_TARGET}" bf2_aidll) # [CHOSEN, not recovered] Engine-free check of the real loader and export lookup. @@ -1088,9 +1206,12 @@ if(BF2_BUILD_LINUX) target_link_libraries(bf2_aidll_loader_check PRIVATE ${CMAKE_DL_LIBS}) set_target_properties(bf2_aidll_loader_check PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}") - set_target_properties(bf2_aidll_loader_check PROPERTIES BUILD_RPATH "\$ORIGIN") + if(BF2_BUILD_MACOS) + set_target_properties(bf2_aidll_loader_check PROPERTIES BUILD_RPATH "@loader_path") + else() + set_target_properties(bf2_aidll_loader_check PROPERTIES BUILD_RPATH "\$ORIGIN") + endif() add_dependencies(bf2_aidll_loader_check bf2_aidll) - else() set_target_properties(bf2_aidll PROPERTIES LINKER_LANGUAGE CXX @@ -1125,8 +1246,8 @@ target_link_options(bf2_aidll PRIVATE /IGNORE:4006,4088,4098 ) -endif() # Linux / Windows AIDLL -endif() # x86 Windows or Linux AIDLL +endif() # POSIX / Windows AIDLL +endif() # x86 Windows or POSIX AIDLL if(NOT BF2_BUILD_X64) @@ -1255,6 +1376,14 @@ set_target_properties(bf2_voipserver_standalone PROPERTIES bf2_configure_cpp_target(bf2_voipserver_standalone) bf2_set_image(bf2_voipserver_standalone 1) target_link_libraries(bf2_voipserver_standalone PRIVATE bf2_voipserver kernel32 user32 advapi32 ws2_32) +endif() # Windows x86 voice images + + +# The client and the editor build in both Windows configurations: x86, and the native x64 client +# ([CHOSEN, not recovered], https://github.com/B2BF/OpenBF2/issues/7). The x64 images keep the +# shipped file names (BF2.exe and its plugin DLLs, which BF2.exe loads by name) and are written only +# inside the x64 build tree. +if(NOT BF2_BUILD_POSIX) # ================================================================================================= # bf2_client - THE CLIENT LINK-REACH IMAGE (2026-09-03). @@ -1300,7 +1429,7 @@ set_target_properties(bf2_client PROPERTIES ) bf2_configure_cpp_target(bf2_client) bf2_set_image(bf2_client 0) -target_compile_definitions(bf2_client PRIVATE BF2_PLUGIN_ABI_NATIVE=1 _ITERATOR_DEBUG_LEVEL=0) +target_compile_definitions(bf2_client PRIVATE _ITERATOR_DEBUG_LEVEL=0) set_target_properties(bf2_client PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${BF2_GAME_DIR}" VS_DEBUGGER_COMMAND_ARGUMENTS "+modPath mods/bf2 +fullscreen 0 +multi 1" @@ -1338,6 +1467,9 @@ endif() # The bounded Novint SDK surface contains no cross-compiler STL objects. Import # names and the 32-byte ApplicationData carrier are read from the original client; # the matching DLL supplies third-party bodies. +# [CHOSEN, not recovered] x86 only: NovintHFX.dll is a 32-bit DLL, so the x64 client imports nothing +# from it and IO/Input/FalconDevice.cpp reports the device as not connected (issue #7). +if(NOT BF2_BUILD_X64) set(BF2_NOVINT_IMPORT_LIB "${CMAKE_BINARY_DIR}/novint_hfx/NovintHFX.lib") add_custom_command(OUTPUT "${BF2_NOVINT_IMPORT_LIB}" COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_BINARY_DIR}/novint_hfx" @@ -1358,6 +1490,7 @@ if(EXISTS "${BF2_GAME_DIR}/NovintHFX.dll") VERBATIM ) endif() +endif() # NOT BF2_BUILD_X64 (Novint) # [CHOSEN, not recovered] Build and stage one native client/plugin set: # https://github.com/B2BF/OpenBF2/issues/7. These DLLs target the rebuilt host only; @@ -1395,6 +1528,16 @@ endif() # # Rebuild and stage plugins on every client build. Their scripts do not emit full include # dependencies, so a glob over plugin sources would miss changes in shared engine headers. +# +# Each script takes the architecture as its flavour argument: `native` builds the x86 DLL into +# Code/Build/bin__native, `x64` the native x64 DLL into Code/Build/bin__x64. The x64 +# RendDX9.dll has no Bink import: it links the FFmpeg-based Bink stand-in (renddx9.cmd x64, +# docs/macos-c-bink.md); the x86 DLL imports binkw32.dll. +if(BF2_BUILD_X64) + set(BF2_PLUGIN_FLAVOUR x64) +else() + set(BF2_PLUGIN_FLAVOUR native) +endif() if(TRUE) # ⚠ EACH SCRIPT IS NAMED BY ITS FULL NATIVE PATH, not bare beside WORKING_DIRECTORY. cmd.exe # finds a bare script name only by searching the current directory, and that search is OFF @@ -1411,24 +1554,32 @@ if(TRUE) file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/swiffplayer.cmd" BF2_SWIFFPLAYER_SCRIPT) file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/textureatlasbuilder.cmd" BF2_TEXTUREATLAS_SCRIPT) add_custom_target(bf2_textureatlas_native - COMMAND cmd.exe /d /c "${BF2_TEXTUREATLAS_SCRIPT}" native + COMMAND cmd.exe /d /c "${BF2_TEXTUREATLAS_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native TextureAtlasBuilder.dll (Code/Build/textureatlasbuilder.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} TextureAtlasBuilder.dll (Code/Build/textureatlasbuilder.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_textureatlas_native PROPERTY FOLDER "BF2") + # [CHOSEN, not recovered] G2w: BF2_GFX_SEAM=ON makes renddx9.cmd compile the renderer against the subset + # headers plus the generated forwarding backend (Platform/Gfx/D3D9Forward, docs/macos-c-g2w-forward.md). + set(BF2_RENDDX9_SEAM_ENV) + if(BF2_GFX_SEAM) + set(BF2_RENDDX9_SEAM_ENV "${CMAKE_COMMAND}" -E env BF2_GFX_SEAM=ON) + endif() add_custom_target(bf2_renddx9_native - COMMAND cmd.exe /d /c "${BF2_RENDDX9_SCRIPT}" native + COMMAND ${BF2_RENDDX9_SEAM_ENV} cmd.exe /d /c "${BF2_RENDDX9_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native RendDX9.dll (Code/Build/renddx9.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} RendDX9.dll (Code/Build/renddx9.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_renddx9_native PROPERTY FOLDER "BF2") - add_dependencies(bf2_renddx9_native bf2_textureatlas_native) + if(NOT BF2_GFX_SEAM) + add_dependencies(bf2_renddx9_native bf2_textureatlas_native) + endif() add_custom_target(bf2_swiffplayer_native - COMMAND cmd.exe /d /c "${BF2_SWIFFPLAYER_SCRIPT}" native + COMMAND cmd.exe /d /c "${BF2_SWIFFPLAYER_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native SwiffPlayer.dll (Code/Build/swiffplayer.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} SwiffPlayer.dll (Code/Build/swiffplayer.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_swiffplayer_native PROPERTY FOLDER "BF2") @@ -1442,9 +1593,9 @@ if(TRUE) # ordering rule as the two above: after SwiffPlayer, never concurrently. file(TO_NATIVE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bf2audio.cmd" BF2_BF2AUDIO_SCRIPT) add_custom_target(bf2_bf2audio_native - COMMAND cmd.exe /d /c "${BF2_BF2AUDIO_SCRIPT}" native + COMMAND cmd.exe /d /c "${BF2_BF2AUDIO_SCRIPT}" ${BF2_PLUGIN_FLAVOUR} WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build" - COMMENT "Building the native BF2Audio.dll (Code/Build/bf2audio.cmd native)" + COMMENT "Building the ${BF2_PLUGIN_FLAVOUR} BF2Audio.dll (Code/Build/bf2audio.cmd ${BF2_PLUGIN_FLAVOUR})" VERBATIM ) set_property(TARGET bf2_bf2audio_native PROPERTY FOLDER "BF2") @@ -1454,26 +1605,26 @@ endif() set(BF2_PLUGIN_STAGE_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/stage_plugin.cmake") add_custom_target(bf2_client_plugins COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_renddx9_native/RendDX9.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_renddx9_${BF2_PLUGIN_FLAVOUR}/RendDX9.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/renddx9.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/renddx9.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_swiffplayer_native/SwiffPlayer.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_swiffplayer_${BF2_PLUGIN_FLAVOUR}/SwiffPlayer.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/swiffplayer.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/swiffplayer.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_bf2audio_native/BF2Audio.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_bf2audio_${BF2_PLUGIN_FLAVOUR}/BF2Audio.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/bf2audio.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/bf2audio.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" COMMAND "${CMAKE_COMMAND}" - "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_textureatlasbuilder_native/TextureAtlasBuilder.dll" + "-DBF2_PLUGIN_SRC=${CMAKE_CURRENT_SOURCE_DIR}/Code/Build/bin_textureatlasbuilder_${BF2_PLUGIN_FLAVOUR}/TextureAtlasBuilder.dll" "-DBF2_PLUGIN_DST_DIR=${BF2_CLIENT_OUTPUT_DIR}" - "-DBF2_PLUGIN_HINT=build it with Code/Build/textureatlasbuilder.cmd native" + "-DBF2_PLUGIN_HINT=build it with Code/Build/textureatlasbuilder.cmd ${BF2_PLUGIN_FLAVOUR}" -P "${BF2_PLUGIN_STAGE_SCRIPT}" - COMMENT "Staging the four native plugins beside the diagnostic BF2.exe" + COMMENT "Staging the four ${BF2_PLUGIN_FLAVOUR} plugins beside the diagnostic BF2.exe" VERBATIM ) # Ordering AND obligation: all four plugin builds complete before anything is copied. This @@ -1482,6 +1633,13 @@ add_custom_target(bf2_client_plugins # point where it hurts, which is a live debugging session. add_dependencies(bf2_client_plugins bf2_textureatlas_native bf2_renddx9_native bf2_swiffplayer_native bf2_bf2audio_native) add_dependencies(bf2_client bf2_client_plugins) +# The subsystem version that keeps the classic (pre-6.0) window frame; see the link options below. +# x64: 5.02, the lowest version link.exe accepts for an x64 image, on the same side of 6.0. +if(BF2_BUILD_X64) + set(BF2_CLIENT_SUBSYSTEM "/SUBSYSTEM:WINDOWS,5.02") +else() + set(BF2_CLIENT_SUBSYSTEM "/SUBSYSTEM:WINDOWS,5.01") +endif() # System imports present in the retail BF2.exe. target_link_libraries(bf2_client PRIVATE advapi32 crypt32 dbghelp dinput8 dsound dxguid gdi32 ole32 psapi shell32 user32 winmm ws2_32 @@ -1491,6 +1649,19 @@ target_link_libraries(bf2_client PRIVATE if(TARGET bf2_voipserver_client) target_link_libraries(bf2_client PRIVATE bf2_voipserver_client) endif() +# [CHOSEN, not recovered] x64 (issue #7): BF2VoipServer.dll is x86-only (its .def pins x86 decorated +# names), so the native x64 client links the voice-server module statically, as the x64 dedicated +# server and the macOS client do. Client image (/DDEDICATED=0), same sources as bf2_voipserver_client. +if(BF2_BUILD_X64) + add_library(bf2_voipserver_client_objects OBJECT EXCLUDE_FROM_ALL ${bf2_voipserver_only_sources}) + bf2_configure_cpp_target(bf2_voipserver_client_objects) + bf2_set_image(bf2_voipserver_client_objects 0) + bf2_set_platform_compat(bf2_voipserver_client_objects) + target_compile_definitions(bf2_voipserver_client_objects PRIVATE _ITERATOR_DEBUG_LEVEL=0) + target_compile_options(bf2_voipserver_client_objects PRIVATE ${BF2_CLIENT_X64_COMPILE_OPTIONS}) + set_property(TARGET bf2_voipserver_client_objects PROPERTY FOLDER "BF2") + target_sources(bf2_client PRIVATE $) +endif() target_link_options(bf2_client PRIVATE /FORCE /INCREMENTAL:NO @@ -1515,7 +1686,7 @@ target_link_options(bf2_client PRIVATE # default subsystem version assumed" and silently falls back to 6.0, which is the bug. 5.01 is # the lowest value it accepts for x86. What governs the frame is the 6.0 boundary, so 5.01 and # retail's 4.0 behave identically here; the field itself still differs from the shipped image. - /SUBSYSTEM:WINDOWS,5.01 + "${BF2_CLIENT_SUBSYSTEM}" /NODEFAULTLIB:python23.lib "/MAP:${BF2_CLIENT_OUTPUT_DIR}/BF2.map" /IGNORE:4006,4088,4098 @@ -1560,8 +1731,16 @@ endif() target_link_libraries(bf2_client_linkcheck PRIVATE advapi32 crypt32 dbghelp dinput8 dsound dxguid gdi32 ole32 psapi shell32 user32 winmm ws2_32 ) -add_dependencies(bf2_client_linkcheck bf2_novint_imports) -target_link_libraries(bf2_client_linkcheck PRIVATE "${BF2_NOVINT_IMPORT_LIB}") +if(TARGET bf2_voipserver_client_objects) + target_sources(bf2_client_linkcheck PRIVATE $) +elseif(TARGET bf2_voipserver_client) + # x86: the CBF2VoipServer members come from BF2VoipServer.dll's import library, as for bf2_client. + target_link_libraries(bf2_client_linkcheck PRIVATE bf2_voipserver_client) +endif() +if(TARGET bf2_novint_imports) + add_dependencies(bf2_client_linkcheck bf2_novint_imports) + target_link_libraries(bf2_client_linkcheck PRIVATE "${BF2_NOVINT_IMPORT_LIB}") +endif() target_link_options(bf2_client_linkcheck PRIVATE /FORCE:MULTIPLE /INCREMENTAL:NO @@ -1570,9 +1749,431 @@ target_link_options(bf2_client_linkcheck PRIVATE /NODEFAULTLIB:python23.lib ) -# The BF2 Editor links the client object -# set above, so it lives in this Windows-x86-only block. Every editor target is EXCLUDE_FROM_ALL. +# The BF2 Editor links the client object set above, so it lives in this Windows client block +# (x86 and native x64). Every editor target is EXCLUDE_FROM_ALL. add_subdirectory(Code/Tools/BF2Editor) +endif() # NOT BF2_BUILD_POSIX (client and editor) + +# ================================================================================================= +# bf2_client on macOS - THE NATIVE macOS CLIENT IMAGE. [CHOSEN, not recovered] +# +# An owner-requested port change (macOSplan.md, package S2.0; docs/macos-port.md, "Client triage"). +# The client objects above are compiled with DEDICATED=0 and the macOS platform switches. The client +# plugin images are not shared libraries here: retail-DLL swapping is retired +# (https://github.com/B2BF/OpenBF2/issues/7), so RendDX9, SwiffPlayer and BF2Audio are static +# libraries, and Code/StaticPlugins/StaticPlugins.cpp answers the engine's LoadLibrary/GetProcAddress +# lookups for the ones linked in (BF2_STATIC_PLUGINS). RendDX9 is not linked by default; see +# BF2_MACOS_LINK_RENDDX9 below. Each library compiles its image's manifest +# from Code/Build/.cmd with that image's define; keep the lists in step with the scripts. +# Left out of every library: the Windows loader entry (RendDX9Abi/DllMain.cpp) and the engine TUs the +# host image already compiles (Math/*, Core/ConsoleObjectBase.cpp), because one image holds one copy. +# The RendDX9Abi kit (heap adapters, vc71 string, frontier log) is compiled once, in +# bf2_plugin_kit_static, for the same reason. The three plugin entry pairs are renamed per image so +# they can coexist in one link. TextureAtlasBuilder is embedded in the native renderer. +# +# The link is strict (ld64 rejects undefined symbols). It does not complete yet: the compile triage +# in docs/macos-port.md lists the blocked translation units by blocker class. +# ================================================================================================= +if(BF2_BUILD_MACOS) + set(BF2_RENDDX9_STATIC_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/CrashReport.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/EngineFile.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/PluginEntry.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/NativeConsoleObjects.cpp" + # [CHOSEN, not recovered] The binkw32 entry points on the vendored FFmpeg Bink decoders + # (bf2_ffmpeg_bink below; docs/macos-c-bink.md) and their AudioQueue sound output. + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkFFmpeg.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkAudioCoreAudio.cpp" + ) + # Code/Build/renddx9.cmd, STEP 2: SOURCES minus the kit, DllMain.cpp and the shared Math TUs, + # then CONSOLE_SOURCES minus Core/ConsoleObjectBase.cpp. + foreach(rel + RendDX9/BF2Render.cpp RendDX9/PostProductionFrameWork.cpp RendDX9/RendDX9Init.cpp + RendDX9/BufferManager.cpp RendDX9/QueryManager.cpp RendDX9/RendDX9Types.cpp + RendDX9/Texture.cpp RendDX9/TextureManager.cpp RendDX9/TextureAtlas/TextureAtlas.cpp + RendDX9/ResourceManager.cpp RendDX9/ResourceTracer.cpp RendDX9/VideoOptions.cpp + RendDX9/Effect.cpp RendDX9/DiceEffect.cpp + RendDX9/FXParameter.cpp RendDX9/ShaderManager.cpp RendDX9/StateManager.cpp + RendDX9/RendDX9Draw.cpp RendDX9/RenderQueues.cpp RendDX9/Ra/EffectManager.cpp + RendDX9/MovieRenderer.cpp + RendDX9/Ra/RaShaderPermutator.cpp RendDX9/Ra/RaShader.cpp RendDX9/Ra/RaVertexStreams.cpp + RendDX9/Ra/RaStreamDataEditable.cpp RendMisc/RendModule.cpp RendMisc/RenderView.cpp + RendMisc/EnvMapSystem/EnvMapManager.cpp RendMisc/EnvMapSystem/EnvMapObject.cpp + IO/Tokenizer.cpp Geom/ModuleGeom.cpp Geom/GeometryTemplateManager.cpp + Geom/MeshTemplate.cpp Geom/StaticMeshTemplate.cpp Geom/SkinnedMeshTemplate.cpp + Geom/SkinnedMesh.cpp Geom/BundledMeshTemplate.cpp Geom/BundledMeshMaterial.cpp + Geom/BundledMeshStateManager.cpp Geom/BundledMesh.cpp Geom/BundledMeshDraw.cpp + Geom/BundledMeshHeight.cpp Geom/StaticMesh.cpp Geom/StaticMeshLightmapGeneration.cpp + Geom/StaticMeshMaterial.cpp Geom/StaticMeshStateManager.cpp Geom/SkyDome.cpp + Geom/UndergrowthSystem.cpp Geom/UndergrowthSystemLoad.cpp + Geom/LightningManager.cpp Geom/WeatherManager.cpp Geom/Rain/RainManager.cpp + Geom/UndergrowthSystemRender.cpp Geom/Terrain.cpp Geom/QuadPatch.cpp + Geom/RaQuadPatchAdapter.cpp + Geom/SurroundingPatch.cpp Geom/TerrainDraw.cpp Geom/TerrainEditable.cpp + Geom/TerrainEditableGetSets.cpp Geom/QuadPatchEditable.cpp + Geom/SurroundingPatchEditable.cpp Geom/TerrainLightSampling.cpp + Geom/LightmapGeneration/LightmapGeneration.cpp + Geom/LightmapGeneration/MeshLightSampling.cpp Geom/ObjectDrawer.cpp + Geom/XpLightManager.cpp Geom/LightMerger.cpp Geom/LightGeometry.cpp Geom/MeshOptimizer.cpp + Geom/BundledMeshOptimizer.cpp Geom/StaticMeshOptimizer.cpp Geom/NametagManager.cpp Geom/NameTagRenderer.cpp + Geom/Overgrowth/OverGrowth.cpp Geom/Overgrowth/OverGrowthLoad.cpp + Geom/Overgrowth/OverGrowthCells.cpp Geom/Overgrowth/OverGrowthCellRender.cpp + Geom/Overgrowth/OverGrowthRender.cpp Geom/RoadCompiledRenderer.cpp + Geom/RoadCompiledTemplate.cpp Geom/RoadCompiled.cpp Geom/RoadTemplate.cpp + Geom/RoadEditableRenderer.cpp Geom/RoadEditable.cpp Geom/DecalSystem/DecalManager.cpp + Geom/DecalSystem/DecalShadowManager.cpp + Geom/DecalSystem/DecalObject.cpp Geom/DecalSystem/DecalTemplate.cpp + Geom/DecalSystem/DecalRenderer.cpp Geom/ParticleSystem/ParticleSystemManager.cpp + Geom/HemiMapManager/HemiMapManager.cpp Geom/ParticleSystem/ParticleSystemTemplate.cpp + Geom/ParticleSystem/ParticleSystemTemplateType1.cpp + Geom/ParticleSystem/MeshParticleMesh/MeshParticleMeshTemplate.cpp + Geom/ParticleSystem/MeshParticleMesh/MeshParticleMesh.cpp + Geom/ParticleSystem/TrailSystemTemplate.cpp + Geom/ParticleSystem/ParticleSystemTemplateType3.cpp + Geom/ParticleSystem/NSAParticleSystemTemplate.cpp Geom/StaticMeshRenderer.cpp + Geom/SkinnedMeshRenderer.cpp Geom/SwiffRender.cpp GeomMisc/ModuleGeomMisc.cpp + GeomMisc/FSQuadDrawer.cpp GeomMisc/DebugTextWriter.cpp GeomMisc/Debug.cpp + GeomMisc/DebugBoxMesh.cpp + GeomMisc/DebugCylinderMesh.cpp + GeomMisc/DebugSphereMesh.cpp + GeomMisc/DebugPlaneMesh.cpp + GeomMisc/DebugPolygonMesh.cpp + GeomMisc/DebugTorusMesh.cpp + GeomMisc/DebugXMesh.cpp + GeomMisc/DebugRenderer.cpp GeomMisc/DebugTextDrawer.cpp + GeomMisc/DebugCircleDrawer.cpp + GeomMisc/DebugLineDrawer.cpp + GeomMisc/FontSystem/FontSystem.cpp GeomMisc/FontSystem/SwiffFont.cpp + GeomMisc/OverlayTexture.cpp GeomMisc/DebugLineGraphD3d.cpp GeomMisc/PerlinNoise.cpp + GeomMisc/DebugBlockGraphD3D.cpp + GeomMisc/LoadingScreen/LoadingScreen.cpp + GeomMisc/SplineControlPoint.cpp GeomMisc/EditorSpline.cpp + GeomMisc/MenuRend/MemeTexture.cpp GeomMisc/MenuRend/FSMoviePlayer.cpp + GeomMisc/MenuRend/Video.cpp GeomMisc/MenuRend/QuadDrawer.cpp + GeomMisc/MenuRend/QuadOutputCache.cpp + Geom/LightManagerConsole.cpp Geom/HemiMapManager/HemiMapManagerConsole.cpp + Geom/SkyDomeConsole.cpp Geom/TerrainConsole.cpp RendDX9/RendererConsole.cpp + Geom/TerrainCullerConsole.cpp + Geom/NametagManagerConsole.cpp Geom/Overgrowth/OverGrowthConsole.cpp + Geom/UndergrowthSystemConsole.cpp Geom/DecalSystem/DecalManagerConsole.cpp + Geom/ObjectGeometryConsole.cpp Geom/LightmapGeneration/LightmapGenerationConsole.cpp + Geom/StaticMeshRendererConsole.cpp Geom/WeatherManagerConsole.cpp + Geom/HeightmapEventNode.cpp) + list(APPEND BF2_RENDDX9_STATIC_SOURCES "${BF2_ROOT}/${rel}") + endforeach() + + # Code/Build/swiffplayer.cmd, STEP 2, minus the kit and DllMain.cpp. + set(BF2_SWIFFPLAYER_STATIC_SOURCES + "${CMAKE_CURRENT_SOURCE_DIR}/Code/SwiffPlayerAbi/PluginEntry.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/SwiffPlayerAbi/SwiffMemory.cpp" + "${BF2_EXTERNAL_ROOT}/gameswf/SwiffPlayer/SwiffPlayer.cpp" + "${BF2_EXTERNAL_ROOT}/gameswf/SwiffPlayer/SwiffCrashLog.cpp" + "${BF2_EXTERNAL_ROOT}/gameswf/SwiffPlayer/SwiffPlayerModule.cpp" + ) + foreach(rel + base/config.cpp base/container.cpp base/file_util.cpp base/image.cpp + base/image_filters.cpp base/jpeg.cpp base/membuf.cpp base/tu_file.cpp base/tu_random.cpp + base/tu_timer.cpp base/tu_types.cpp base/utf8.cpp base/utility.cpp base/zlib_adapter.cpp + gameswf/gameswf_action.cpp gameswf/gameswf_button.cpp gameswf/gameswf_dlist.cpp + gameswf/gameswf_font.cpp gameswf/gameswf_fontlib.cpp gameswf/gameswf_impl.cpp + gameswf/gameswf_log.cpp gameswf/gameswf_morph2.cpp gameswf/gameswf_movie.cpp + gameswf/gameswf_render.cpp gameswf/gameswf_shape.cpp gameswf/gameswf_sound.cpp + gameswf/gameswf_stream.cpp gameswf/gameswf_string.cpp gameswf/gameswf_styles.cpp + gameswf/gameswf_tesselate.cpp gameswf/gameswf_text.cpp gameswf/gameswf_textformat.cpp + gameswf/gameswf_timers.cpp gameswf/gameswf_types.cpp gameswf/gameswf_xml.cpp) + list(APPEND BF2_SWIFFPLAYER_STATIC_SOURCES "${BF2_EXTERNAL_ROOT}/${rel}") + endforeach() + + # Code/Build/bf2audio.cmd, STEP 2, minus the kit. Win32System.cpp is that image's DllMain and + # its LoadLibrary wrappers; it stays in the list so the triage reports it (package S2.5). + set(BF2_BF2AUDIO_STATIC_SOURCES "${BF2_ROOT}/Sound/NullSound.cpp") + foreach(rel + Ambient.cpp BfOpenAL.cpp BfSoundEngine.cpp Music.cpp OpenALProvider.cpp + OpenALSample.cpp Reverb.cpp Sample.cpp Sound.cpp SoundDefaults.cpp SoundEvaluator.cpp + SoundFile.cpp SoundTrigger.cpp WavFileFormat.cpp Win32System.cpp) + list(APPEND BF2_BF2AUDIO_STATIC_SOURCES "${BF2_ROOT}/Sound/SoundEngine/${rel}") + endforeach() + set(BF2_VORBIS_STATIC_SOURCES + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/src/bitwise.c" + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/src/framing.c" + ) + foreach(name + analysis bitrate block codebook envelope floor0 floor1 info lookup lpc lsp mapping0 + mdct psy registry res0 sharedbook smallft synthesis vorbisfile window) + list(APPEND BF2_VORBIS_STATIC_SOURCES "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/lib/${name}.c") + endforeach() + + # The settings every plugin library shares with the client objects. + function(bf2_configure_static_plugin target image_define) + bf2_configure_cpp_target("${target}") + bf2_set_image("${target}" 0) + bf2_set_platform_compat("${target}") + target_compile_definitions("${target}" PRIVATE + _ITERATOR_DEBUG_LEVEL=0 BF2_PLATFORM_POSIX _MACOSX + BF2_STATIC_PLUGINS=1 ${image_define}) + set_property(TARGET "${target}" PROPERTY FOLDER "BF2") + endfunction() + + # [CHOSEN, not recovered] Each statically linked plugin image keeps its own host-service globals + # (dice::hfe::classManager, settings, g_system, game and the rest that its PluginEntry.cpp + # defines and its initDll fills), as the DLL did. The host defines globals of the same names, + # often with other types. The image's static library is therefore prelinked into one + # relocatable object (ld -r) in which the symbols named in Code/StaticPlugins/ + # image-private-symbols.txt are bound to the image's own definitions and then made local; + # everything else keeps its linkage. See docs/macos-port.md, "Plugin globals". + # BF2Audio defines no host-service globals; its own null sound/template pair + # (Sound/SoundEngine/BfSoundEngine.cpp, created by getSoundEngine) is image-private in the + # same way and is listed in Code/StaticPlugins/bf2audio-private-symbols.txt. + set(BF2_STATIC_PLUGIN_PRIVATE_SYMBOLS + "${CMAKE_CURRENT_SOURCE_DIR}/Code/StaticPlugins/image-private-symbols.txt") + function(bf2_prelink_static_plugin consumer library symbols) + set(prelinked "${CMAKE_CURRENT_BINARY_DIR}/StaticPlugins/${library}_prelinked.o") + set(arch_flags "") + foreach(arch IN LISTS CMAKE_OSX_ARCHITECTURES) + list(APPEND arch_flags -arch "${arch}") + endforeach() + add_custom_command(OUTPUT "${prelinked}" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/StaticPlugins" + COMMAND "${CMAKE_CXX_COMPILER}" ${arch_flags} -r -nostdlib -o "${prelinked}" + "-Wl,-force_load,$" + "-Wl,-unexported_symbols_list,${symbols}" + DEPENDS "${library}" "$" "${symbols}" + COMMENT "Prelinking ${library} with image-private host-service globals" + VERBATIM) + target_sources("${consumer}" PRIVATE "${prelinked}") + set_source_files_properties("${prelinked}" PROPERTIES EXTERNAL_OBJECT TRUE GENERATED TRUE) + endfunction() + + add_library(bf2_plugin_kit_static STATIC EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BfMemory.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/Frontier.cpp" + ) + bf2_configure_static_plugin(bf2_plugin_kit_static "") + + add_library(bf2_renddx9_static STATIC EXCLUDE_FROM_ALL ${BF2_RENDDX9_STATIC_SOURCES}) + bf2_configure_static_plugin(bf2_renddx9_static BF2_IMAGE_RENDDX9) + # [CHOSEN, not recovered] Native factories/build/save use the renderer's Metal D3D9 seam. + set(BF2_TEXTURE_ATLAS_NATIVE_SOURCES + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/Packer.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureAtlas.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureAtlasConfiguration.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureAtlasD3D9.cpp" + "${BF2_ROOT}/RendDX9/TextureAtlas/TextureAtlasBuilder/TextureFormat.cpp" + ) + target_sources(bf2_renddx9_static PRIVATE ${BF2_TEXTURE_ATLAS_NATIVE_SOURCES}) + # The host manifests also list these paths; keep their builder image guard inactive. + set_source_files_properties(${BF2_TEXTURE_ATLAS_NATIVE_SOURCES} + PROPERTIES COMPILE_DEFINITIONS + "$<$,bf2_renddx9_static>:BF2_IMAGE_TEXTUREATLASBUILDER=1>") + # [CHOSEN, not recovered] One renderer-only prefix selects the subset without TU switches. + target_include_directories(bf2_renddx9_static BEFORE PRIVATE + "${BF2_ROOT}/Platform/Gfx/MacInclude" "${BF2_ROOT}/Platform/Gfx/Include") + target_sources(bf2_renddx9_static PRIVATE + "${BF2_ROOT}/Platform/Gfx/Metal/Frontiers.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/Effect.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXMath.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXGeometry.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXLine.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXPixels.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXImages.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXTextures.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/D3DXMesh.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/Device.cpp" + "${BF2_ROOT}/Platform/Gfx/Metal/MetalBridge.mm" + # zeux/meshoptimizer v1.3 (MIT, External/meshoptimizer/LICENSE.md): the stripifier behind + # the native D3DXConvertMeshSubsetToSingleStrip in D3DXMesh.cpp. + "${BF2_EXTERNAL_ROOT}/meshoptimizer/stripifier.cpp") + set_source_files_properties("${BF2_ROOT}/Platform/Gfx/Metal/MetalBridge.mm" + PROPERTIES COMPILE_OPTIONS "-fobjc-arc") + target_compile_options(bf2_renddx9_static PRIVATE + "$<$:-include${BF2_ROOT}/Platform/Gfx/MacSupport.h>") + target_compile_definitions(bf2_renddx9_static PRIVATE + initDll=bf2_renddx9_initDll deinitDll=bf2_renddx9_deinitDll) + + add_library(bf2_swiffplayer_static STATIC EXCLUDE_FROM_ALL ${BF2_SWIFFPLAYER_STATIC_SOURCES}) + bf2_configure_static_plugin(bf2_swiffplayer_static BF2_IMAGE_SWIFFPLAYER) + target_compile_definitions(bf2_swiffplayer_static PRIVATE + initDll=bf2_swiffplayer_initDll deinitDll=bf2_swiffplayer_deinitDll) + target_include_directories(bf2_swiffplayer_static PRIVATE + "${BF2_EXTERNAL_ROOT}" "${BF2_EXTERNAL_ROOT}/gameswf") + + add_library(bf2_vorbis_static STATIC EXCLUDE_FROM_ALL ${BF2_VORBIS_STATIC_SOURCES}) + bf2_configure_c_target(bf2_vorbis_static) + target_include_directories(bf2_vorbis_static PRIVATE + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/include" + "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/include" + "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/lib") + set_property(TARGET bf2_vorbis_static PROPERTY FOLDER "BF2") + + # [CHOSEN, not recovered] FFmpeg 7.1.1's Bink video/audio decoders, unmodified, over the + # OpenBF2 shim (Code/BF2/External/ffmpeg-bink/README.md; LGPL-2.1-or-later). This is the macOS + # build; Windows x64 compiles the same files in Code/Build/renddx9.cmd, Windows x86 keeps RAD's + # binkw32.dll. Built optimized in every configuration, as FFmpeg is. + set(BF2_FFMPEG_BINK_DIR "${BF2_EXTERNAL_ROOT}/ffmpeg-bink") + add_library(bf2_ffmpeg_bink STATIC EXCLUDE_FROM_ALL + "${BF2_FFMPEG_BINK_DIR}/libavcodec/bink.c" + "${BF2_FFMPEG_BINK_DIR}/libavcodec/binkdsp.c" + "${BF2_FFMPEG_BINK_DIR}/libavcodec/binkaudio.c" + "${BF2_FFMPEG_BINK_DIR}/libavcodec/wma_freqs.c" + "${BF2_FFMPEG_BINK_DIR}/shim/ffbink_shim.c") + target_include_directories(bf2_ffmpeg_bink PRIVATE "${BF2_FFMPEG_BINK_DIR}/shim") + set_target_properties(bf2_ffmpeg_bink PROPERTIES C_STANDARD 11 C_STANDARD_REQUIRED ON + C_EXTENSIONS ON) + target_compile_options(bf2_ffmpeg_bink PRIVATE -O2 -fno-strict-aliasing -fno-math-errno + -Wno-pointer-sign) + set_property(TARGET bf2_ffmpeg_bink PROPERTY FOLDER "BF2") + # [CHOSEN, not recovered] CPU check of the Bink port against reference frames/samples that + # the local ffmpeg CLI produces from the read-only game content (docs/macos-c-bink.md). + add_executable(bf2_bink_decode_test EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/macos_bink_decode.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkFFmpeg.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkAudioCoreAudio.cpp") + target_compile_features(bf2_bink_decode_test PRIVATE cxx_std_17) + target_link_libraries(bf2_bink_decode_test PRIVATE bf2_ffmpeg_bink "-framework AudioToolbox") + # [TEMP] [CHOSEN, not recovered] The black-box Bink harness, port side: the same source the + # retail build runs against binkw32.dll (Code/Tests/movies, docs/tracks/bink/README.md). + add_executable(bf2_bink_harness EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/movies/bink_harness.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkFFmpeg.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Code/RendDX9Abi/BinkAudioCoreAudio.cpp") + target_compile_features(bf2_bink_harness PRIVATE cxx_std_17) + target_link_libraries(bf2_bink_harness PRIVATE bf2_ffmpeg_bink "-framework AudioToolbox") + + add_library(bf2_bf2audio_static STATIC EXCLUDE_FROM_ALL ${BF2_BF2AUDIO_STATIC_SOURCES}) + bf2_configure_static_plugin(bf2_bf2audio_static "BF2_IMAGE_BF2AUDIO;BF2AUDIO_WITH_VORBIS=1") + target_include_directories(bf2_bf2audio_static PRIVATE + "${BF2_EXTERNAL_ROOT}/libogg-1.3.6/include" + "${BF2_EXTERNAL_ROOT}/libvorbis-1.3.7/include") + + # The client-image half of the macOS voice server, statically linked as the Linux server does. + add_library(bf2_voipserver_client_objects OBJECT EXCLUDE_FROM_ALL ${bf2_voipserver_only_sources}) + bf2_configure_cpp_target(bf2_voipserver_client_objects) + bf2_set_image(bf2_voipserver_client_objects 0) + bf2_set_platform_compat(bf2_voipserver_client_objects) + target_compile_definitions(bf2_voipserver_client_objects PRIVATE BF2_PLATFORM_POSIX _MACOSX) + set_property(TARGET bf2_voipserver_client_objects PROPERTY FOLDER "BF2") + + add_executable(bf2_client EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/StaticPlugins/StaticPlugins.cpp" + $ + $ + $ + $ + $ + $ + $ + $ + ) + bf2_configure_static_plugin(bf2_client "") + # bin_macos already holds the server `bf2`; APFS is case-insensitive, so the client cannot be + # `BF2` beside it. It shares the directory, and the @loader_path rpath, with libdice_py.dylib. + set_target_properties(bf2_client PROPERTIES + LINKER_LANGUAGE CXX + OUTPUT_NAME bf2_client + RUNTIME_OUTPUT_DIRECTORY "${BF2_DEDICATED_OUTPUT_DIR}" + BUILD_RPATH "@loader_path" + INSTALL_RPATH "@loader_path" + BUILD_WITH_INSTALL_RPATH TRUE + ) + if(TARGET dice_py) + target_link_libraries(bf2_client PRIVATE dice_py) + endif() + # [CHOSEN, not recovered] The renderer uses the G2 subset and G3 Metal device; + # unimplemented operations stop (docs/macos-g3-metal-device.md). OFF keeps the + # renderer-free client: StaticPlugins.cpp has no RendDX9 entry and BF2Render::init takes + # its shipped failure return. ON links the image for coordinator device-creation checks. + option(BF2_MACOS_LINK_RENDDX9 "Link the RendDX9 static library into the macOS client" OFF) + if(BF2_MACOS_LINK_RENDDX9) + bf2_prelink_static_plugin(bf2_client bf2_renddx9_static "${BF2_STATIC_PLUGIN_PRIVATE_SYMBOLS}") + target_compile_definitions(bf2_client PRIVATE BF2_STATIC_RENDDX9=1) + # [CHOSEN, not recovered] The renderer's Bink port (BinkFFmpeg.cpp) and its audio output. + target_link_libraries(bf2_client PRIVATE bf2_ffmpeg_bink "-framework AudioToolbox") + # [CHOSEN, not recovered] The G4 effect facade (Metal/Effect.cpp) runs the s2 CPU runtime. + target_link_libraries(bf2_client PRIVATE bf2_fx_runtime) + # [CHOSEN, not recovered] System JPEG decoding in the prelinked renderer image. + target_link_libraries(bf2_client PRIVATE "-framework ImageIO" "-framework CoreGraphics") + endif() + target_compile_definitions(bf2_client PRIVATE BF2_STATIC_SWIFFPLAYER=1 BF2_STATIC_BF2AUDIO=1) + bf2_prelink_static_plugin(bf2_client bf2_swiffplayer_static "${BF2_STATIC_PLUGIN_PRIVATE_SYMBOLS}") + bf2_prelink_static_plugin(bf2_client bf2_bf2audio_static + "${CMAKE_CURRENT_SOURCE_DIR}/Code/StaticPlugins/bf2audio-private-symbols.txt") + target_link_libraries(bf2_client PRIVATE + bf2_vorbis_static bf2_plugin_kit_static + Threads::Threads ${CMAKE_DL_LIBS} ${CURSES_LIBRARIES}) + target_link_options(bf2_client PRIVATE + "-Wl,-map,${BF2_DEDICATED_OUTPUT_DIR}/bf2_client.map") + + # [CHOSEN, not recovered] The Cocoa host and the GCController poller (package S2.4, + # docs/macos-s2-4.md): ARC Objective-C++ with the plain-C++ headers the engine includes. + set(BF2_MACOS_HOST_OBJCXX_SOURCES + "${BF2_ROOT}/Platform/macOS/CocoaHost.mm" + "${BF2_ROOT}/Platform/macOS/MacGamepad.mm" + "${BF2_ROOT}/Platform/macOS/MacRawMouse.mm" + "${BF2_ROOT}/Platform/macOS/MacInputScript.mm") # [TEMP] BF2_INPUT_SCRIPT + target_sources(bf2_client PRIVATE ${BF2_MACOS_HOST_OBJCXX_SOURCES}) + set_source_files_properties(${BF2_MACOS_HOST_OBJCXX_SOURCES} + PROPERTIES COMPILE_OPTIONS "-fobjc-arc") + target_link_libraries(bf2_client PRIVATE + "-framework AppKit" "-framework QuartzCore" "-framework Metal" + "-framework GameController" "-framework Carbon" "-framework IOKit") + # [CHOSEN, not recovered] BF2Audio's POSIX arm (Sound/SoundEngine/Win32System.cpp) queries the + # default output device through CoreAudio; OpenAL.framework itself is loaded at run time with + # dlopen, as the Win32 image loads OpenAL32.dll. MacSystem.cpp's alert uses CoreFoundation. + target_link_libraries(bf2_client PRIVATE "-framework CoreAudio" "-framework CoreFoundation") + + # [CHOSEN, not recovered] Keep all static-image views in native ABI agreement. + # This also runs for renderer-OFF builds. The script caches successful probes + # against real target flags and transitive headers; a warm gate takes seconds. + find_package(Python3 COMPONENTS Interpreter REQUIRED) + set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + add_executable(bf2_native_vtable_check EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/macos_vtable_audit.cpp") + bf2_configure_cpp_target(bf2_native_vtable_check) + bf2_set_image(bf2_native_vtable_check 0) + target_compile_definitions(bf2_native_vtable_check PRIVATE BF2_STATIC_PLUGINS=1) + # [CHOSEN, not recovered] Pin captured BFMeme dispatch to native member encodings. + add_executable(bf2_meme_dispatch_check EXCLUDE_FROM_ALL + "${CMAKE_CURRENT_SOURCE_DIR}/Code/Tests/macos_meme_dispatch.cpp") + bf2_configure_cpp_target(bf2_meme_dispatch_check) + bf2_set_image(bf2_meme_dispatch_check 0) + # A cross build (an arm64-only tree on an Intel Mac) cannot execute the native checks: + # the static audit still gates the build with the target's own flags, and the linked + # checks ship in the M2 bundle (docs/macos-c-arm64-client.md). + set(BF2_VTABLE_CHECK_RUNNABLE ON) + if(CMAKE_OSX_ARCHITECTURES AND NOT CMAKE_HOST_SYSTEM_PROCESSOR IN_LIST CMAKE_OSX_ARCHITECTURES) + set(BF2_VTABLE_CHECK_RUNNABLE OFF) + endif() + if(BF2_VTABLE_CHECK_RUNNABLE) + set(BF2_VTABLE_CHECK_COMMAND COMMAND "$" + COMMAND "$") + else() + set(BF2_VTABLE_CHECK_COMMAND COMMAND "${CMAKE_COMMAND}" -E echo + "bf2_native_vtable_check and bf2_meme_dispatch_check are built for ${CMAKE_OSX_ARCHITECTURES} and run in the M2 bundle") + endif() + add_custom_target(bf2_vtable_audit ALL + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/macos/vtable_audit.py" + --build-dir "${CMAKE_BINARY_DIR}" + # AI behaviour system (S0): native vtable order against libaidll.so's + # (tools/macos/ai_behaviour_vtables.json); clang computes the slots, cached. + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/macos/ai_behaviour_vtables.py" + --build-dir "${CMAKE_BINARY_DIR}" + ${BF2_VTABLE_CHECK_COMMAND} + DEPENDS bf2_native_vtable_check bf2_meme_dispatch_check + COMMENT "Auditing native static-plugin vtables" + VERBATIM) + add_dependencies(bf2_client bf2_vtable_audit) + # [CHOSEN, not recovered] A game hosted from the client menu (the welcome page's instant + # battle, CREATE LOCAL) runs the server inside bf2_client, and BF2Engine names its AI image + # "aidll.dll" (BF2.exe 0x409CBD) - retail ships AIDLL.dll beside BF2.exe. The POSIX loader maps + # that to libaidll.dylib, found through the client's @loader_path rpath in bin_macos, where + # bf2_aidll is written. Without it AIConnection::init aborts (the shipped load-failure defect). + if(TARGET bf2_aidll) + add_dependencies(bf2_client bf2_aidll) + endif() + add_dependencies(bf2 bf2_vtable_audit) + add_dependencies(bf2_renddx9_static bf2_vtable_audit) + add_dependencies(bf2_swiffplayer_static bf2_vtable_audit) + add_dependencies(bf2_bf2audio_static bf2_vtable_audit) endif() # ================================================================================================= @@ -1644,8 +2245,22 @@ include(CTest) # and linked into no game image (issue #7). Its tests join CTest when BF2_MEMORY_TESTS is ON. add_subdirectory(Code/BF2/Memory) +# [CHOSEN, not recovered] CPU-only effect pipeline for the macOS renderer facade. +if(BF2_BUILD_MACOS) + add_subdirectory(Code/BF2/Platform/Gfx/Effect) + add_subdirectory(Code/Tests/macos_gfx_forward) + # [CHOSEN, not recovered] Native effect compilation is mandatory; the effect subdirectory + # rejects missing dependencies at configure time. No developer oracle is invoked here. + if(TARGET bf2_renddx9_static) + target_compile_definitions(bf2_renddx9_static PRIVATE BF2_FX_NATIVE=1) + endif() + if(BF2_MACOS_LINK_RENDDX9 AND TARGET bf2_client AND TARGET bf2_renddx9_static) + target_link_libraries(bf2_client PRIVATE bf2_fx_native_compiler) + target_include_directories(bf2_renddx9_static PRIVATE "${BF2_ROOT}/Platform/Gfx/Effect") + endif() +endif() # The focused checks mirror Code/Tests/*.cmd, which are MSVC x86 gates; they are not part of the -# Linux port (its checks are the dice_py runtime check and the production run). +# Linux and macOS ports (their checks are the dice_py runtime check and the production run). if(BUILD_TESTING AND MSVC) function(bf2_add_check target) add_executable("${target}" EXCLUDE_FROM_ALL ${ARGN}) @@ -1712,6 +2327,9 @@ if(BUILD_TESTING AND MSVC) "${BF2_ROOT}/Game/Objects/Visual/LightSource.cpp" "${BF2_ROOT}/Game/Objects/Visual/LightSourceTemplate.cpp" "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/PortalManager.cpp" + "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/PortalPassing.cpp" + "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/Sector.cpp" + "${BF2_ROOT}/Scene/Object/WorldObjTemplPortal/PortalEvent.cpp" "${BF2_ROOT}/Scene/Object/Object.cpp" "${BF2_ROOT}/Scene/Object/ObjectPredicator.cpp" "${BF2_ROOT}/Scene/Object/ObjectUtil.cpp" diff --git a/CMakePresets.json b/CMakePresets.json index e2b3267df..0a9bde771 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -55,6 +55,36 @@ "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", "BUILD_TESTING": "OFF" } + }, + { + "name": "macos-x64", + "displayName": "BF2 native macOS dedicated port", + "description": "AppleClang on macOS: x86_64 build with Unix Makefiles. Needs the Command Line Tools and cmake.", + "generator": "Unix Makefiles", + "binaryDir": "${sourceDir}/out/build/${presetName}", + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Darwin" + }, + "cacheVariables": { + "CMAKE_OSX_SYSROOT": "macosx", + "CMAKE_OSX_ARCHITECTURES": "x86_64", + "CMAKE_OSX_DEPLOYMENT_TARGET": "11.0", + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "BUILD_TESTING": "OFF" + } + }, + { + "name": "macos-universal", + "inherits": "macos-x64", + "displayName": "BF2 native macOS universal port", + "description": "[CHOSEN, not recovered] AppleClang arm64 and x86_64 slices; arm64 runtime validation requires Apple silicon.", + "binaryDir": "${sourceDir}/out/build/${presetName}", + "cacheVariables": { + "CMAKE_OSX_ARCHITECTURES": "arm64;x86_64" + } } ], "buildPresets": [ @@ -90,6 +120,25 @@ "bf2", "dice_py_check" ] + }, + { + "name": "macos-x64", + "displayName": "Build bf2 and libdice_py.dylib", + "configurePreset": "macos-x64", + "targets": [ + "bf2", + "dice_py_check" + ] + }, + { + "name": "macos-universal", + "displayName": "Build universal server and runtime checks", + "configurePreset": "macos-universal", + "targets": [ + "bf2", + "dice_py_check", + "bf2_aidll_loader_check" + ] } ], "testPresets": [ diff --git a/Code/AidllAbi/aidll-macos.exports b/Code/AidllAbi/aidll-macos.exports new file mode 100644 index 000000000..35046f6f3 --- /dev/null +++ b/Code/AidllAbi/aidll-macos.exports @@ -0,0 +1,3 @@ +# [CHOSEN, not recovered] Native macOS AI image boundary; all other symbols are private. +_initDll +_deinitDll diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp index d77e151da..ed47ec6c1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.cpp @@ -244,8 +244,6 @@ unsigned char BotMain::mu8NBehaviours = 0; // ELF .bss 0x4CDFEC. Set by prepareBehaviourPool, not per bot. float* BotMain::maBasicWeights = 0; -// [FRONTIER] Remaining bot lifecycle operations stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the corresponding BotMain operation. // ELF 0x187A50 (D2). In order: the waypoint list (+124, deleting dtor), the behaviour and urgency // arrays (delete[]), the memory (+76; the constructor's argument, deleted here), the death and // spawn callbacks (deleting dtors), the BAP context, the player (IAIPlayer +0x78 diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h index 8c75df2c7..c565c90d1 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotMain.h @@ -75,8 +75,8 @@ class Bot virtual void setLodLevel(BotLodLevel level) = 0; // +0x008 virtual BotLodLevel getLodLevel() const = 0; // +0x00C - virtual void planExecution(const double& slice) = 0; // +0x010 partial [FRONTIER] - virtual int decisionMaking(const double& slice) = 0; // +0x014 partial [FRONTIER] + virtual void planExecution(const double& slice) = 0; // +0x010 + virtual int decisionMaking(const double& slice) = 0; // +0x014 virtual void cheatExecution() = 0; // +0x018 virtual void see(const double& dt) = 0; // +0x01C virtual void updateSensing(const double& dt) = 0; // +0x020 @@ -102,11 +102,11 @@ class Bot virtual bool isTakingOrders() = 0; // +0x070 virtual bool isOrderedBehaviour(unsigned char behaviour) = 0; // +0x074 virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b) = 0; // +0x078 - virtual void setFiringTarget(unsigned int handle) = 0; // +0x07C [FRONTIER] + virtual void setFiringTarget(unsigned int handle) = 0; // +0x07C virtual unsigned int getFiringTarget() const = 0; // +0x080 virtual double getFiringTargetTime() const = 0; // +0x084 virtual SensingAgent* getSensingAgent() = 0; // +0x088 - virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c) = 0; // +0x08C [FRONTIER] + virtual void insertBehaviourInformation(float f, const Vec3& v, unsigned char c) = 0; // +0x08C virtual const std::map& getSensedObjects() const = 0; // +0x090 virtual SensedObject* getSensedObjectFromHandle(unsigned int handle) const = 0; // +0x094 virtual void setUnresolvedCollisionObject(unsigned int handle) = 0; // +0x098 @@ -233,9 +233,9 @@ class BotMain : public Bot // [RETIRE-WHEN: botmain-bases] Remove when the corresponding implementation is complete and validated. virtual void setLodLevel(BotLodLevel level); // +0x008 virtual BotLodLevel getLodLevel() const; // +0x00C - virtual void planExecution(const double& slice); // +0x010 partial [FRONTIER] + virtual void planExecution(const double& slice); // +0x010 ELF 0x188B90 // [INFERRED] Returns an integer work count accumulated by BotManager. - virtual int decisionMaking(const double& slice); // +0x014 partial [FRONTIER] + virtual int decisionMaking(const double& slice); // +0x014 ELF 0x1893D0 virtual void cheatExecution(); // +0x018 virtual void see(const double& dt); // +0x01C virtual void updateSensing(const double& dt); // +0x020 @@ -261,7 +261,7 @@ class BotMain : public Bot virtual bool isTakingOrders(); // +0x070 virtual bool isOrderedBehaviour(unsigned char behaviour); // +0x074 virtual bool isOrderedObject(unsigned int handle, BotBehaviour* b); // +0x078 - virtual void setFiringTarget(unsigned int handle); // +0x07C [FRONTIER] + virtual void setFiringTarget(unsigned int handle); // +0x07C ELF 0x18C5E0 virtual unsigned int getFiringTarget() const; // +0x080 virtual double getFiringTargetTime() const; // +0x084 virtual SensingAgent* getSensingAgent(); // +0x088 diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp index f73385637..99f829c22 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.cpp @@ -1,6 +1,3 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotNavigation operations. - #include "BotNavigation.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF @@ -210,9 +207,6 @@ void BotNavigation::clearProgress() m_zero280[2] = 0; // +288 } -// [FRONTIER] Obstacle updates for living, standing bots are not implemented. -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: aidll-02-skeleton] -// Replace the stop when the corresponding navigation behavior is recovered. namespace { // ELF 0x197560 (vtable 0x4b6c38): a primary object with a mobile plug-in (+0x38), or any diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h index 1e25acba7..debeae782 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotNavigation.h @@ -24,9 +24,8 @@ class BotNavigation { public: explicit BotNavigation(BotMain* owner); - ~BotNavigation(); // [FRONTIER] + ~BotNavigation(); // ELF 0x18FF30 - // [FRONTIER] Navigation methods below remain incomplete unless implemented explicitly. bool update(bool& a, bool* b); void updateOccationally(); // dice's spelling - "Occationally" // ELF 0x192200: the point to walk to; `arrived` at the last point, `direct` when the bot diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp index b0bd80861..8331be476 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.cpp @@ -1,6 +1,3 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BotSenses operations. - #include "BotSenses.h" #include "../AIUtils/checkPointer.h" @@ -113,9 +110,6 @@ BotSenses::~BotSenses() delete m_frustum; } -// [FRONTIER] Remaining sight, hearing and communication operations require implementation. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - // ELF 0x19A040 (172 bytes). Hearing gets a tenth and the fire objects three tenths of the slice; // seeing gets what is left of the deadline (start + slice - now). The ELF reads the update time // (IBFTimer +0x10) three times; the middle read's result is discarded. diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h index 40e94b0c4..894d289a0 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSenses.h @@ -28,20 +28,20 @@ class BotSenses // (`operator new(0x94)` in SensingAgent's constructor). explicit BotSenses(BotMain* owner); ~BotSenses(); - void reset(); // - (two arms frontier) + void reset(); // ELF 0x199D40 // attested: an 11-byte body that returns `this + 112`. const std::map& getSensedObjects() const { return m_sensedObjects; } typedef std::pair FireEntry; - // ELF 0x198420 (6421 bytes) [FRONTIER]. + // ELF 0x198420 (6421 bytes). void see(const double& slice); // ELF 0x19a040: hearing, fire objects, then seeing with the remaining slice. void updateSensing(const double& slice); - void updateHearing(const double& slice); // ELF 0x19be60 [FRONTIER] - void updateFireObjects(const double& slice); // ELF 0x19c460 [FRONTIER] - void updateSeeing(const double& slice); // ELF 0x19a0f0 [FRONTIER] + void updateHearing(const double& slice); // ELF 0x19be60 + void updateFireObjects(const double& slice); // ELF 0x19c460 + void updateSeeing(const double& slice); // ELF 0x19a0f0 // ELF 0x19d8a0: the record for a handle, or null. SensedObject* getSensedObjectFromHandle(unsigned int handle) const; // ELF 0x19C930: the attacker map's fire time for a shooter, else -1000.0. diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h index fe71c56f1..7ed7cedb8 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/BotSquad.h @@ -38,7 +38,7 @@ class BotSquad bool hasMoveOrderOrder(); // dice's name bool hasNoOrder(); - // membership. joinSquad written; remaining methods are [FRONTIER]. + // membership bool joinSquad(int squad); bool createSquad(); void exitSquad(); diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h index 3f7a0dda5..277986c8b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SensingAgent.h @@ -28,7 +28,7 @@ class SensingAgent public: // The second parameter is in the ABI and is never read - see the header block. SensingAgent(BotMain* owner, unsigned char behaviourCount); - ~SensingAgent(); // [FRONTIER] + ~SensingAgent(); // ELF 0x1BBB50 // A focus candidate: one per sensed object (evaluateSensedObjects 0x1BC5B0) or incoming shot // (evaluateFireObjects 0x1BC7E0); 16 bytes, the vector stride (`>> 4`). [INFERRED] member names. diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp index ba9f0a893..15b7dc730 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.cpp @@ -1,6 +1,9 @@ // [INFERRED] Source placement. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadCoordinator operations. +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "SquadCoordinator.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF @@ -90,11 +93,18 @@ static bool maneuverMemberWithinRange(const Vec3& position, const Vec3& squadPos const long double dx = static_cast(static_cast(squadPosition.x) - position.x); const long double dy = static_cast(static_cast(squadPosition.y) - position.y); const long double dz = static_cast(static_cast(squadPosition.z) - position.z); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(squadPosition.x) - position.x; + const bf2x87::Real dy = static_cast(squadPosition.y) - position.y; + const bf2x87::Real dz = static_cast(squadPosition.z) - position.z; #else const long double dx = static_cast(squadPosition.x) - position.x; const long double dy = static_cast(squadPosition.y) - position.y; const long double dz = static_cast(squadPosition.z) - position.z; #endif +#endif #if defined(_WIN32) return (dx * dx + dy * dy) + dz * dz < 8100.0L; #else @@ -142,11 +152,22 @@ static bool shooterMovedAway(const Vec3& firePosition, const Vec3& position) #else #if defined(_WIN32) const long double dx = static_cast(static_cast(firePosition.x) - position.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(firePosition.x) - position.x; #else const long double dx = static_cast(firePosition.x) - position.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(firePosition.y) - position.y; + const bf2x87::Real dz = static_cast(firePosition.z) - position.z; +#else const long double dy = static_cast(firePosition.y) - position.y; const long double dz = static_cast(firePosition.z) - position.z; +#endif #if defined(_WIN32) return (dz * dz + dy * dy) + dx * dx > 25.0L; #else @@ -192,10 +213,17 @@ static float leaderGotoDistanceSq(const Vec3& position, const Vec3& gotoPosition const long double dx = static_cast(static_cast(position.x) - gotoPosition.x); const long double dy = static_cast(static_cast(position.y) - gotoPosition.y); const long double dz = static_cast(static_cast(position.z) - gotoPosition.z); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(gotoPosition.x) - position.x; + const bf2x87::Real dy = static_cast(gotoPosition.y) - position.y; + const bf2x87::Real dz = static_cast(gotoPosition.z) - position.z; #else const long double dx = static_cast(gotoPosition.x) - position.x; const long double dy = static_cast(gotoPosition.y) - position.y; const long double dz = static_cast(gotoPosition.z) - position.z; +#endif #endif return static_cast((dx * dx + dy * dy) + dz * dz); #endif @@ -245,6 +273,13 @@ static bool insideControlPointRadius(const Vec3& controlPoint, const Vec3& posit const long double dy = static_cast(static_cast(controlPoint.y) - position.y); const long double dz = static_cast(static_cast(controlPoint.z) - position.z); return (dx * dx + dy * dy) + dz * dz < static_cast(radiusSq); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(position.x) - controlPoint.x; + const bf2x87::Real dy = static_cast(position.y) - controlPoint.y; + const bf2x87::Real dz = static_cast(position.z) - controlPoint.z; + return (dy * dy + dx * dx) + dz * dz < static_cast(radiusSq); #else const long double dx = static_cast(position.x) - controlPoint.x; const long double dy = static_cast(position.y) - controlPoint.y; @@ -252,6 +287,7 @@ static bool insideControlPointRadius(const Vec3& controlPoint, const Vec3& posit return (dy * dy + dx * dx) + dz * dz < static_cast(radiusSq); #endif #endif +#endif } // [INFERRED] diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h index 7ce3e6bc4..756d9c85b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadCoordinator.h @@ -1,6 +1,4 @@ // Coordinates squad membership, leadership and its owned formation. -// [FRONTIER] Leader-change movement remains incomplete. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. // [INFERRED] Source placement. #ifndef AI_AIDLL_AI_AIBOT_SQUADCOORDINATOR_H // [INFERRED] guard style diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp index fc8cd0484..270aa07a6 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadFormation.cpp @@ -1,4 +1,7 @@ +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "SquadFormation.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF @@ -79,10 +82,17 @@ static bool formationLeaderWithinRange(const Vec3& leader, const Vec3& squad) notWithin: } return within; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real deltaX = static_cast(leader.x) - squad.x; + const bf2x87::Real deltaY = static_cast(leader.y) - squad.y; + const bf2x87::Real deltaZ = static_cast(leader.z) - squad.z; #else const long double deltaX = static_cast(leader.x) - squad.x; const long double deltaY = static_cast(leader.y) - squad.y; const long double deltaZ = static_cast(leader.z) - squad.z; +#endif #if defined(_WIN32) return (deltaZ * deltaZ + deltaY * deltaY) + deltaX * deltaX < 2500.0L; #else @@ -119,16 +129,28 @@ static bool trailPointIsSet(const Vec3& point) notSet: } return set; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real x = point.x; + const bf2x87::Real y = point.y; + const bf2x87::Real z = point.z; #else const long double x = point.x; const long double y = point.y; const long double z = point.z; +#endif #if defined(_WIN32) return (z * z + y * y) + x * x > static_cast(0.001f); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + return (y * y + x * x) + z * z > static_cast(0.001f); #else return (y * y + x * x) + z * z > static_cast(0.001f); #endif #endif +#endif } // [INFERRED] local name. Squared distance between the anchor and the newest crumb, narrowed @@ -170,6 +192,13 @@ static float trailCrumbDistanceSq(const Vec3& anchor, const Vec3& crumb) const long double dy = static_cast(static_cast(anchor.y) - crumb.y); const long double dz = static_cast(static_cast(anchor.z) - crumb.z); return static_cast((dx * dx + dy * dy) + dz * dz); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(crumb.x) - anchor.x; + const bf2x87::Real dy = static_cast(crumb.y) - anchor.y; + const bf2x87::Real dz = static_cast(crumb.z) - anchor.z; + return static_cast((dy * dy + dx * dx) + dz * dz); #else const long double dx = static_cast(crumb.x) - anchor.x; const long double dy = static_cast(crumb.y) - anchor.y; @@ -177,6 +206,7 @@ static float trailCrumbDistanceSq(const Vec3& anchor, const Vec3& crumb) return static_cast((dy * dy + dx * dx) + dz * dz); #endif #endif +#endif } // [INFERRED] local name. A claimed member's squared distance to the anchor, stored as the sort @@ -211,11 +241,22 @@ static float trailMemberDistanceSq(const Vec3& position, const Vec3& anchor) #else #if defined(_WIN32) const long double dx = static_cast(static_cast(position.x) - anchor.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(position.x) - anchor.x; #else const long double dx = static_cast(position.x) - anchor.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(position.y) - anchor.y; + const bf2x87::Real dz = static_cast(position.z) - anchor.z; +#else const long double dy = static_cast(position.y) - anchor.y; const long double dz = static_cast(position.z) - anchor.z; +#endif #if defined(_WIN32) return static_cast((dz * dz + dy * dy) + dx * dx); #else @@ -720,9 +761,26 @@ static bool nearerFormationMember(const Vec3& position, const Vec3& destination, // x64 port has no x87 inline assembly; it is not validated as retail x86 here. #if defined(_WIN32) const long double dx = static_cast(static_cast(position.x) - destination.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(position.x) - destination.x; #else const long double dx = static_cast(position.x) - destination.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(position.y) - destination.y; + const bf2x87::Real dz = static_cast(position.z) - destination.z; + const bf2x87::Real distance = (dy * dy + dx * dx) + dz * dz; + if (distance < minimum) + { + minimum = static_cast(distance); + return true; + } + return false; +#else const long double dy = static_cast(position.y) - destination.y; const long double dz = static_cast(position.z) - destination.z; const long double distance = (dy * dy + dx * dx) + dz * dz; @@ -733,6 +791,7 @@ static bool nearerFormationMember(const Vec3& position, const Vec3& destination, } return false; #endif +#endif } // Captured unsigned slot count, full signed member diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h index 37692a421..aef25b6dd 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadManager.h @@ -72,8 +72,7 @@ class SquadManager void clearPlayerValidPositions(); void unAssignSquads(int side); // ELF 0x1AF800 int unAssignSquads(int areaIndex, int side); // ELF 0x1AF750 - // [FRONTIER] declared by ai-strategic for SAI::checkCommanderUseArtillery; owner ai-bot - // (coord/ai-requests.md). getArtillerySafeDistance is recovered (ELF 0x1AEE60: +0x98). + // Used by SAI::checkCommanderUseArtillery. getArtillerySafeDistance: ELF 0x1AEE60 (+0x98). bool haveCampingHumans(int side, Vec2& position); // ELF 0x1B0610 bool haveHumanPlayerOnOwnSide(int side); // ELF 0x1AE5B0 float getArtillerySafeDistance(); // ELF 0x1AEE60 diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp index 4a2959749..23aabc076 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.cpp @@ -1,6 +1,9 @@ // [INFERRED] Source placement. // [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining SquadMember operations. +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "SquadMember.h" #include #include @@ -57,9 +60,14 @@ static bool memberPathUpdateDue(double previous, double now) notDue: } return due; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + return static_cast(now) > static_cast(previous) + 9.0L; #else return static_cast(now) > static_cast(previous) + 9.0L; #endif +#endif } // [PLATFORM] PE spills only dx, then sums (dz*dz+dx*dx)+dy*dy. ELF retains @@ -102,17 +110,33 @@ static bool memberPathDisplaced(const Vec3& previous, const Vec3& current) #else #if defined(_WIN32) const long double dx = static_cast(static_cast(previous.x) - current.x); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dx = static_cast(previous.x) - current.x; #else const long double dx = static_cast(previous.x) - current.x; #endif +#endif +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real dy = static_cast(previous.y) - current.y; + const bf2x87::Real dz = static_cast(previous.z) - current.z; +#else const long double dy = static_cast(previous.y) - current.y; const long double dz = static_cast(previous.z) - current.z; +#endif #if defined(_WIN32) return (dz * dz + dx * dx) + dy * dy > static_cast(0.01f); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + return (dx * dx + dy * dy) + dz * dz > static_cast(0.01f); #else return (dx * dx + dy * dy) + dz * dz > static_cast(0.01f); #endif #endif +#endif } // Preserve the stores around the two virtual calls: publishing diff --git a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h index 4e92fddff..2222f0d37 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h +++ b/Code/BF2/AI/AIDLL/AI/AIBot/SquadMember.h @@ -54,11 +54,11 @@ class SquadMember void reset(); // ELF 0x1B1930 void removeRequest(); // ELF 0x1B1990 void squadMemberKilled(); // ELF 0x1B1E60 - bool avoidArtillery(Vec3 position, double sinceStart, int side); // ELF 0x1B2840 [FRONTIER] + bool avoidArtillery(Vec3 position, double sinceStart, int side); // ELF 0x1B2840 bool getPosition(Vec3& position); // copies even if invalid - bool isAllowedInFormation(); // nonnull vehicle [FRONTIER] - void updateMemberPos(); // nonnull vehicle [FRONTIER] - bool isMobile(); // owner query [FRONTIER] + bool isAllowedInFormation(); // ELF 0x1B5380 + void updateMemberPos(); // ELF 0x1B1A70 + bool isMobile(); // ELF 0x1B5560 void moveWithFormation(); // ELF 0x1B3AC0 void moveToSlotPos(const Vec3& position, Information* information); // ELF 0x1B3FF0 void moveWithoutFormation(); // ELF 0x1B3E20 diff --git a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h index 8301b5bf9..2cfde386a 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotActionPlan/BAPActionInline.h @@ -8,7 +8,6 @@ #include "../../../../Math/Vec3.h" #include "../../../../IO/Input/PlayerInput.h" #include "../Main/InformationManager.h" -#include "../Main/AIDllFrontier.h" #include "BAPCondition.h" #include "BAPTypes.h" #include "../Main/CommonSingletonServer.h" @@ -108,13 +107,11 @@ inline std::ostream& streamCondition(std::ostream& out, const BAPCondition* cond return out << *condition; } -// [FRONTIER] io::operator<<(std::ostream&, PlayerInputMap) is the engine's (IO/Input/InputMapStream.cpp, -// a bf2 export the shipped libaidll imports through its PLT); that TU is not in the bf2_aidll -// source list (coordinator decision requested), so the debug text stops here. -inline std::ostream& streamInput(std::ostream& out, io::PlayerInputMap) +// io::operator<<(std::ostream&, PlayerInputMap) (ELF 0x48D5A0, IO/Input/InputMapStream.cpp): the +// shipped libaidll.so carries its own copy, and so does bf2_aidll (aidll_sources.txt). +inline std::ostream& streamInput(std::ostream& out, io::PlayerInputMap input) { - BF2_AI_FRONTIER("dice::hfe::io::operator<<(std::ostream&, PlayerInputMap) (engine export, not linked into bf2_aidll)"); - return out; + return io::operator<<(out, input); } // operator<<(std::ostream&, BAPStatementType) (ELF 0x3C7D90) and operator<<(std::ostream&, diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp index 655d2cc40..06122c76e 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.cpp @@ -11,7 +11,6 @@ #include "../AIBotBehaviourPattern/PlanGenerator.h" #include "../AIBotActionPlan/BotScript.h" #include "../AIUtils/checkPointer.h" -#include "../Main/AIDllFrontier.h" namespace dice { namespace hfe { @@ -47,12 +46,6 @@ BotBehaviour::BotBehaviour(float* modifiers, UrgeCurve* urgeCurve) { } -// [TEMP] S0 skeleton default constructor (see the header). -BotBehaviour::BotBehaviour() -{ - BF2_AI_FRONTIER("dice::hfe::ai::BotBehaviour::BotBehaviour (S0 skeleton default constructor: a derived constructor is not recovered)"); -} - // ELF 0x225A70 (D2; D1 0x225B00, D0 0x225B90). The pattern is owned (deleting destructor, slot +4); // the modifier row, the curve and m_targets are not freed here. BotBehaviour::~BotBehaviour() diff --git a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h index 07f9a8adc..133a91324 100644 --- a/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h +++ b/Code/BF2/AI/AIDLL/AI/AIBotBehaviour/BotBehaviour.h @@ -52,11 +52,6 @@ class BotBehaviour : public UrgencyGenerator // [INFERRED] inline reader of +0x20 for BotMemory::modifyBehaviourUrgency (ELF 0x18F2F8 reads it inline). UrgeCurve* getUrgeCurve() const { return m_urgeCurve; } -protected: - // [TEMP] [CHOSEN, not recovered] S0 only: lets the generated derived constructor stubs compile; - // it stops by name. [RETIRE-WHEN: ai-behaviour-skeleton-ctors] every derived constructor is recovered. - BotBehaviour(); - protected: // BotBehaviour(float*, UrgeCurve*, int count) 0x225250: +8 = +0xC = 0, the three arrays of // `count` (checkPointer each), activeUrgency[i] = 1e-5f, targetChanged[i] = true; urgency[] is diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp index 2ede0afff..d42e42c43 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.cpp @@ -1,6 +1,3 @@ -// [FRONTIER] Remaining methods stop by name until implemented. -// [RETIRE-WHEN: aidll-02-skeleton] Complete and validate the remaining BFInformationEnvironment operations. - #include "BFInformationEnvironment.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF @@ -103,9 +100,6 @@ BFInformationEnvironment::BFInformationEnvironment() } } -// [FRONTIER] Unimplemented environment queries and modifiers stop by name. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. - // ELF 0x2E6C30. Deletes every grid of the second vector, then of the first (null slots skipped, // the end re-read after each delete); the vectors free themselves. BFInformationEnvironment::~BFInformationEnvironment() diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h index b6377fd0e..a1427947b 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/BFInformationEnvironment.h @@ -74,7 +74,7 @@ class BFInformationEnvironment : public IAIInformationEnvironment, { public: BFInformationEnvironment(); // - , complete - virtual ~BFInformationEnvironment(); // [FRONTIER] + virtual ~BFInformationEnvironment(); // ELF 0x2E6C30 // IAIInformationEnvironment. All-information, Vec3/Vec2 radius and rectangle wrappers written. virtual void getFriendlyUnits(std::vector&, const Vec3&, Bot*, float) const; diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp index 8a19fac43..df3a5d694 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileKnown.cpp @@ -1,5 +1,8 @@ // so and AIDLL_w32ded.dll . +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "IPIMobileKnown.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF @@ -129,6 +132,24 @@ void IPIMobileKnown::getPositionEstimate(double time, Vec3& position) position.x = scaledX; position.y = scaledY; position.z = scaledZ; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + // [PLATFORM] ELF rounds age before security and retains one x87-wide scale for X/Y/Z. + const float age = static_cast(m_time - time); + const float security = m_information->getSecurity(time); + const bf2x87::Real wideScale = + static_cast(security) * static_cast(age); + const float scaledX = + static_cast(static_cast(m_speed.x) * wideScale); + const float scaledY = + static_cast(static_cast(m_speed.y) * wideScale); + const float scaledZ = + static_cast(static_cast(m_speed.z) * wideScale); + // ELF materializes its temporary Vec3 in Z, X, Y store order. + position.z = scaledZ; + position.x = scaledX; + position.y = scaledY; #else // [PLATFORM] ELF rounds age before security and retains one x87-wide scale for X/Y/Z. const float age = static_cast(m_time - time); @@ -145,6 +166,7 @@ void IPIMobileKnown::getPositionEstimate(double time, Vec3& position) position.z = scaledZ; position.x = scaledX; position.y = scaledY; +#endif #endif const Vec3& knownPosition = m_information->getPosition(); position.x += knownPosition.x; diff --git a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp index 74051148e..efdde7946 100644 --- a/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp +++ b/Code/BF2/AI/AIDLL/AI/AIKnowledge/IPIMobileReal.cpp @@ -1,5 +1,8 @@ // so and AIDLL_w32ded.dll . +#if defined(__APPLE__) +#include "../../../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "IPIMobileReal.h" // 's ios_base::Init object is this TU's static initialisation and teardown (ELF @@ -86,6 +89,21 @@ void IPIMobileReal::getPositionEstimate(double time, Vec3& position) position.x = static_cast(scaledX + static_cast(position.x)); position.y = static_cast(static_cast(scaledY) + position.y); position.z = static_cast(static_cast(scaledZ) + position.z); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + // [PLATFORM] ELF calls the timer first and rounds the delta before calling speed. + const float difference = static_cast( + time - static_cast(CommonSingletonServer::m_iBFTimer)->getGameTime()); + const Vec3& speed = getSpeed(); + const bf2x87::Real scaledX = static_cast(speed.x) * difference; + const float scaledY = + static_cast(static_cast(speed.y) * difference); + const float scaledZ = + static_cast(static_cast(speed.z) * difference); + position.x = static_cast(scaledX + static_cast(position.x)); + position.y = static_cast(static_cast(scaledY) + position.y); + position.z = static_cast(static_cast(scaledZ) + position.z); #else // [PLATFORM] ELF calls the timer first and rounds the delta before calling speed. const float difference = static_cast( @@ -100,6 +118,7 @@ void IPIMobileReal::getPositionEstimate(double time, Vec3& position) position.y = static_cast(static_cast(scaledY) + position.y); position.z = static_cast(static_cast(scaledZ) + position.z); #endif +#endif } unsigned int IPIMobileReal::getSector() const diff --git a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h index 33c039230..aa585d0fb 100644 --- a/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h +++ b/Code/BF2/AI/AIDLL/AI/AIStrategic/SAI.h @@ -76,12 +76,12 @@ class CommanderInterface CommanderInterface(); // - (empty) ~CommanderInterface(); // - (empty) - void giveAttackOrder(const Vec3& position, SquadCoordinator* squad); // [FRONTIER] - void giveMoveOrder(const Vec3& position, SquadCoordinator* squad); // [FRONTIER] - void giveDefendOrder(const Vec3& position, SquadCoordinator* squad); // [FRONTIER] - void giveAttackOrder(const Vec3& position, Bot* bot); // [FRONTIER] - void giveMoveOrder(const Vec3& position, Bot* bot); // [FRONTIER] - void giveDefendOrder(const Vec3& position, Bot* bot); // [FRONTIER] + void giveAttackOrder(const Vec3& position, SquadCoordinator* squad); // ELF 0x323180 + void giveMoveOrder(const Vec3& position, SquadCoordinator* squad); // ELF 0x3231F0 + void giveDefendOrder(const Vec3& position, SquadCoordinator* squad); // ELF 0x323260 + void giveAttackOrder(const Vec3& position, Bot* bot); // ELF 0x3232D0 + void giveMoveOrder(const Vec3& position, Bot* bot); // ELF 0x323340 + void giveDefendOrder(const Vec3& position, Bot* bot); // ELF 0x3233B0 }; // Strategic AI interface, including human-commander ability requests and their rate limits. diff --git a/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h b/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h index 4a72faa85..015ee1906 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h +++ b/Code/BF2/AI/AIDLL/AI/Main/AIDllFrontier.h @@ -1,6 +1,7 @@ // [CHOSEN, not recovered] Reports a missing AI DLL method to stderr, flushes, and aborts. // The argument is its fully qualified name as a string literal. This macro never returns. -// [RETIRE-WHEN: aidll-02-skeleton] Remove when the corresponding implementation is complete and validated. +// The stop mechanism itself, not a stop: since dbg/ai-frontiers no Code/BF2/AI code calls it (the +// header is still included in many files). [RETIRE-WHEN: aidll-02-skeleton] remove with the includes. #ifndef AI_AIDLL_AI_MAIN_AIDLLFRONTIER_H #define AI_AIDLL_AI_MAIN_AIDLLFRONTIER_H diff --git a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp index 0fce9a4f3..2205d88a2 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp +++ b/Code/BF2/AI/AIDLL/AI/Main/BotManager.cpp @@ -54,6 +54,15 @@ int BotManager::s_tabLevel = 0; // ELF 0x3DD580 void BotManager::action(const double& budget) { +#if !defined(_WIN32) + // [TEMP] [CHOSEN, not recovered] BF2_AI_SPAWN_ONLY=1: bots spawn and stay in the game but + // run no per-tick AI (no plans, sensing, decisions), so a round with bots runs while the AI + // reconstruction (branch ai-reconstruct) is incomplete. Off by default. + // [RETIRE-WHEN: ai-reconstruct reaches a full round without stops] + static const bool spawnOnly = std::getenv("BF2_AI_SPAWN_ONLY") != 0; + if (spawnOnly) + return; +#endif IBFTimer* const timer = static_cast(CommonSingletonServer::m_iBFTimer); const double deadline = timer->getUpdateTime() + budget; diff --git a/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h index 99d2870c7..6a940a677 100644 --- a/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h +++ b/Code/BF2/AI/AIDLL/AI/Main/InformationManager.h @@ -11,8 +11,8 @@ namespace dice { namespace hfe { namespace ai { -// [FRONTIER] the pooled type. `Information` is the AI's knowledge record; the pool only ever stores -// `Information*`, so nothing here needs it complete. Chunk 07 owns it. +// The pooled type. `Information` is the AI's knowledge record (AIKnowledge/Information.h); the pool +// only ever stores `Information*`, so nothing here needs it complete. class Information; // sizeof == 4, from `operator new(4u)`: one pointer and nothing else. diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h index a47ed7343..513908481 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIAdapterTypes.h @@ -23,7 +23,8 @@ class IProjectileObject; // `dice::hfe::ChannelMessageType` - BFRadioComm::sendAIRadioMessage's second parameter // (`NS0_18ChannelMessageType`, i.e. hfe scope, not ai). Passed by value; an opaque enum with an -// explicit `int` base gives it the 4-byte slot the call frame shows. [FRONTIER] its enumerators. +// explicit `int` base gives it the 4-byte slot the call frame shows. [CHOSEN] opaque here: the AI +// only passes values through; the enumerators belong to the engine side (Game/IGame.h). enum ChannelMessageType : int; // `dice::hfe::KitType` - KitTemplateManager::getTemplate's parameter (`NS0_7KitType`). diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/AIFrontier.h b/Code/BF2/AI/AIInterface/BFKnowledge/AIFrontier.h index 744e92009..be623fb36 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/AIFrontier.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/AIFrontier.h @@ -1,6 +1,8 @@ // [CHOSEN, not recovered] Reports an unimplemented method to stderr, flushes, and aborts. // The argument must be its fully qualified name as a string literal. This macro never returns. -// [RETIRE-WHEN: aidll-01-adapters] Remove after all adapter bodies are implemented and validated. +// The stop mechanism itself, not a stop: since dbg/ai-frontiers no Code/BF2/AI code calls it. Still +// included by Game/GameLogic/SquadManager/{Squad,SquadManager}.cpp (no call there either) and +// Code/Tests/aidll. [RETIRE-WHEN: aidll-01-adapters] remove with those includes. #ifndef AI_AIINTERFACE_BFKNOWLEDGE_AIFRONTIER_H #define AI_AIINTERFACE_BFKNOWLEDGE_AIFRONTIER_H diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp index e3c8c5f66..e4239a196 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGame.cpp @@ -97,8 +97,10 @@ int BFGame::getAISettingsFromGame(int& a, bool& b, float& c) const { IBase* general = classManager->getSingleton(std::string("GeneralSettings")); #if DEDICATED - // The dedicated images declare no GeneralSettings (Game/GeneralSettings.h is client-only), and - // no dedicated module registers the singleton, so this arm cannot be reached there. + // [FRONTIER] bf2 (ia-32, dedicated) 0x83FED10 has the same menu arm as BF2.exe. It is missing + // here only because IGeneralSettings (Game/GeneralSettings.h) and ILocalProfileManager + // (Game/LocalProfileManager.h) are declared under `#if !DEDICATED` (game track). No dedicated + // module registers "GeneralSettings", so the stop cannot be reached. if (general) { BF2_AI_FRONTIER("dice::hfe::ai::BFGame::getAISettingsFromGame" diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp index 4e56dc3b0..f73ffa275 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFGraphCreator.cpp @@ -1,16 +1,14 @@ -// [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFGraphCreator operations. +// [INFERRED] Source placement. One TU with BFGraph: bf2 (ia-32) lays BFGraph (0x842E050..0x842E3F0) +// directly before BFGraphCreator (0x842E420..0x842E610) under one static initialiser +// (_GLOBAL__I__ZN4dice3hfe2ai7BFGraphC2Ev, 0x842E690). #include "BFGraphCreator.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/AIUtils/DebugRendering/IBFGraph.h" +#include "../../AIDLL/AI/AIUtils/checkPointer.h" #include "../../../Core/ClassManager.h" +#include "../../../Core/Ids.h" // geom::CID_DebugLineGraphD3D, geom::IID_IDebugGraph namespace dice { namespace hfe { @@ -19,6 +17,145 @@ extern ClassManager* classManager; namespace ai { +// geom::IDebugGraph (IID 80039) as BFGraph calls it: the renderer's line graph (geom::DebugLineGraphD3D, +// GeomMisc/DebugLineGraphD3d.cpp, RendDX9 image, PE table 0x1020C7E8). The engine images share no +// header for it, so the slots BFGraph and Core/DebugCounterManager.cpp use are declared here, in +// table order; parameter types are the ones bf2 (ia-32) and BF2.exe pass. [INFERRED] slot names +// (GeomMisc's), [UNRESOLVED] return types where no caller reads them. +class IDebugGraph : public IBase +{ +public: + virtual char setRect(const float* rect) = 0; // +0x10 + virtual void setColour(unsigned int colour) = 0; // +0x14 + virtual void setName(const std::string& name) = 0; // +0x18 + virtual void setBounds(float minimum, float maximum) = 0; // +0x1C + virtual void resetExtrema() = 0; // +0x20 + virtual void draw() = 0; // +0x24 + virtual char setFlag05(char value) = 0; // +0x28 + virtual unsigned char getFlag05() = 0; // +0x2C + virtual void clearLegend() = 0; // +0x30 + virtual void addLegend(const std::string& name, unsigned int colour) = 0; // +0x34 + virtual void setLegendPosition(int x, int y) = 0; // +0x38 + virtual void setHistorySize(int samples) = 0; // +0x3C + virtual void addSample(float sample) = 0; // +0x40 + virtual void setColors(unsigned int a, unsigned int b, unsigned int c) = 0; // +0x44 + virtual void setAutoScale(unsigned char value) = 0; // +0x48 + virtual char setRange(float low, float high) = 0; // +0x4C + virtual char setEnabled(char value) = 0; // +0x50 + virtual bool setByte41(unsigned char value) = 0; // +0x54 + virtual void setDrawValue(unsigned char value) = 0; // +0x58 + virtual unsigned char getDrawValue() = 0; // +0x5C + virtual void setValuePosition(int x, int y) = 0; // +0x60 + virtual void setValueSuffix(const std::string& suffix) = 0; // +0x64 + +protected: + ~IDebugGraph() {} +}; + +// The "DebugLineGraphRenderer" singleton (IID_IDebugGraphRenderer 80040): BFGraph uses +0x10 only. +// [INFERRED] name; Core/DebugCounterManager.cpp calls the same slot to add a graph. +class IDebugGraphRenderer : public IBase +{ +public: + virtual void addGraph(IDebugGraph* graph) = 0; // +0x10 + +protected: + ~IDebugGraphRenderer() {} +}; + +// The AI's debug graph: an IBFGraph over one renderer line graph. sizeof 8 (`operator new(8)` in +// createGraph): the vptr and the line graph. +class BFGraph : public IBFGraph +{ +public: + BFGraph(); + virtual ~BFGraph(); + + virtual void setNumberOfSamples(int samples); + virtual void setDimensions(float x, float y, float width, float height); + virtual void setColours(unsigned int first, unsigned int second, unsigned int third); + virtual void setThresholds(float low, float high); + virtual void setMinMaxY(float minimum, float maximum); + virtual void setCurrentSampleEnding(const std::string& ending); + virtual void setCurrentSampleOffset(int x, int y); + virtual void addSample(float sample); + +private: + IDebugGraph* m_graph; // +0x04 a geom::DebugLineGraphD3D (IID_IDebugGraph) +}; + +// ELF 0x842E110 (C1; C2 0x842E050), PE 0x815AE0. ClassManager +0x34 createInstance( +// CID_DebugLineGraphD3D, IID_IDebugGraph, 0), no null check; the graph's +0x58 (1); then the +// "DebugLineGraphRenderer" singleton, when there is one, takes the graph (+0x10). +BFGraph::BFGraph() +{ + // createInstance answers the IID_IDebugGraph interface pointer. + m_graph = static_cast( + classManager->createInstance(geom::CID_DebugLineGraphD3D, geom::IID_IDebugGraph, 0)); + m_graph->setDrawValue(1); + IDebugGraphRenderer* const renderer = static_cast( + classManager->getSingleton(std::string("DebugLineGraphRenderer"))); + if (renderer) + renderer->addGraph(m_graph); +} + +// ELF 0x842E200 (D1; D2 0x842E1D0, D0 0x842E230), PE 0x815B60. The line graph is freed with plain +// operator delete - not released, and not removed from the graph renderer - in both images. +BFGraph::~BFGraph() +{ + operator delete(m_graph); +} + +// ELF 0x842E270, PE 0x8159D0: the graph's +0x3C. +void BFGraph::setNumberOfSamples(int samples) +{ + m_graph->setHistorySize(samples); +} + +// ELF 0x842E2A0, PE 0x815BA0: the four floats as one rectangle to the graph's +0x10. +void BFGraph::setDimensions(float x, float y, float width, float height) +{ + const float rect[4] = { x, y, width, height }; + m_graph->setRect(rect); +} + +// ELF 0x842E2E0, PE 0x8159E0: the graph's +0x44. +void BFGraph::setColours(unsigned int first, unsigned int second, unsigned int third) +{ + m_graph->setColors(first, second, third); +} + +// ELF 0x842E310, PE 0x8159F0: the graph's +0x4C (low, high), then +0x50 (1). +void BFGraph::setThresholds(float low, float high) +{ + m_graph->setRange(low, high); + m_graph->setEnabled(1); +} + +// ELF 0x842E360, PE 0x826460 (folded): the graph's +0x1C. +void BFGraph::setMinMaxY(float minimum, float maximum) +{ + m_graph->setBounds(minimum, maximum); +} + +// ELF 0x842E390, PE 0x826180 (folded): the graph's +0x64. +void BFGraph::setCurrentSampleEnding(const std::string& ending) +{ + m_graph->setValueSuffix(ending); +} + +// ELF 0x842E3C0, PE 0x815A20: the graph's +0x60. +void BFGraph::setCurrentSampleOffset(int x, int y) +{ + m_graph->setValuePosition(x, y); +} + +// ELF 0x842E3F0, PE 0x815A30: the graph's +0x40. +void BFGraph::addSample(float sample) +{ + m_graph->addSample(sample); +} + // First wins in, exact match out. IBFGraphCreator::IBFGraphCreator() { @@ -40,9 +177,10 @@ BFGraphCreator::~BFGraphCreator() { } +// ELF 0x842E4F0, PE 0x815C00: a new BFGraph through checkPointer. IBFGraph* BFGraphCreator::createGraph() { - BF2_AI_FRONTIER("dice::hfe::ai::BFGraphCreator::createGraph"); + return checkPointer(new BFGraph); } void BFGraphCreator::destroyGraph(IBFGraph* graph) diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp index 9a3e2bc7f..4d94a789d 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFObjectEnvironment.cpp @@ -3,7 +3,6 @@ #include "BFObjectEnvironment.h" -#include "AIFrontier.h" #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../AIDLL/AI/AIUtils/IAimerHelper.h" diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp index 6daf5ed65..b62650c2b 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/BFSquad.cpp @@ -1,14 +1,8 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining BFSquad operations. #include "BFSquad.h" #include "AIPlayer.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../../../Core/ClassManager.h" #include "../../../Game/GameLogic/SquadManager/ISquadManager.h" diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp index 6f5030446..c8a3f81b3 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp +++ b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.cpp @@ -1,16 +1,16 @@ // [INFERRED] Source placement. -// [FRONTIER] Remaining methods stop by name until implemented. -// [TEMP] Temporary implementation boundaries remain. -// [CHOSEN, not recovered] Temporary implementation boundaries remain. -// [RETIRE-WHEN: aidll-01-adapters] Complete and validate the remaining DebugRenderer operations. +// The AI's debug renderer forwards to the engine's debug drawers (RenderSingletonServer, filled by +// its updateStaticMethods). bf2 (ia-32, dedicated) and BF2.exe (client, vtable 0x947AE8) have the +// same bodies: drawAll and reset are empty, the draw calls forward without a null check. #include "DebugRenderer.h" -#include "AIFrontier.h" - #include "../../AIDLL/AI/Main/CommonSingletonServer.h" #include "../SingletonServer.h" // (!) its roster static is BFSingletonServer's, not Common's #include "../../../Core/ClassManager.h" +#include "../../../Core/IBase.h" +#include "../../../GeomMisc/DebugCircleDrawer.h" +#include "../../../GeomMisc/DebugLineDrawer.h" namespace dice { namespace hfe { @@ -19,6 +19,55 @@ extern ClassManager* classManager; namespace ai { +namespace { + +// The line and circle drawers use the GeomMisc interfaces recovered with RendDX9. The text writer's +// slots are declared locally, in table order ([INFERRED] interface name). Slot offsets and +// argument order are BF2.exe's (0x818080..0x818170); the geom::DebugTextWriter slots are the ones +// GeomMisc/DebugTextWriter.cpp implements. bf2 (ia-32) calls the text writer at +0x38/+0x40 +// instead - the Linux engine's writer table is ordered differently - with the same arguments. + +// "DebugTextWriter" (geom::DebugTextWriter, IID_IDebugTextWriter 80043). +class IDebugTextWriter : public IBase +{ +public: + virtual bool setFont(const std::string& path) = 0; // +0x10 + virtual bool isEnabled() const = 0; // +0x14 + virtual void setEnabled(bool enabled) = 0; // +0x18 + virtual unsigned int getColour() const = 0; // +0x1C + virtual void setColour(unsigned int colour) = 0; // +0x20 + virtual void queueWorldGroupColoured(const Vec3& position, unsigned int colour, + const std::vector& text, int spacing, + int alignment, int bottomAligned) = 0; // +0x24 + virtual void queueWorldTextColoured(const Vec3& position, unsigned int colour, + const std::string& text, int alignment) = 0; // +0x28 + virtual void queueGroupColoured(int x, int y, unsigned int colour, + const std::vector& text, int spacing, + int alignment, int bottomAligned) = 0; // +0x2C + +protected: + ~IDebugTextWriter() {} +}; + +// The line drawer's table is recovered with RendDX9 (geom::IDebugLineDrawer, PE 0x1020C758). +inline geom::IDebugLineDrawer* lineDrawer() +{ + return static_cast(RenderSingletonServer::m_debugLineDrawer); +} + +// The circle drawer's table is recovered with RendDX9 (geom::IDebugCircleDrawer, PE 0x1020CB98). +inline geom::IDebugCircleDrawer* circleDrawer() +{ + return static_cast(RenderSingletonServer::m_debugCircleDrawer); +} + +inline IDebugTextWriter* textWriter() +{ + return static_cast(RenderSingletonServer::m_debugTextWriter); +} + +} // namespace + // First wins in, exact match out. IDebugRenderer::IDebugRenderer() { @@ -40,50 +89,68 @@ DebugRenderer::~DebugRenderer() { } -// ELF 0x842E780: shipped dedicated no-op. The client body remains unrecovered. +// ELF 0x842E780, PE 0x83D270 (a shared `ret`): empty in both images. void DebugRenderer::drawAll() { -#if !DEDICATED - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawAll"); -#endif } -// ELF 0x842E790: shipped dedicated no-op. The client body remains unrecovered. +// ELF 0x842E790, PE 0x83D270 (a shared `ret`): empty in both images. void DebugRenderer::reset() { -#if !DEDICATED - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::reset"); -#endif } +// ELF 0x842E7A0, PE 0x818080: the line drawer's +0x20 (drawRibbon) with depth true. Retail hands +// the Vec3 vector to the D3DX-vector slot as it is; both element types are three packed floats. +// [CHOSEN, not recovered] Returns 0: the slot is void (no caller reads the result). int DebugRenderer::drawLine(const std::vector& points, unsigned int colour, float width) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawLine"); + lineDrawer()->drawRibbon(reinterpret_cast&>(points), colour, width, true); + return 0; } -int DebugRenderer::drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool filled, int segments) const +// ELF 0x842E7E0, PE 0x8180A0 (a tail jump): the circle drawer's +0x10, a void slot. The Boolean +// selects terrain heights for the vertices; the count goes through unchanged. +// [CHOSEN, not recovered] Returns 0: the tail jump leaves the drawer's register (no caller reads it). +int DebugRenderer::drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool terrain, int segments) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawCircle"); + circleDrawer()->drawCircle(normal, centre, radius, colour, terrain, static_cast(segments)); + return 0; } +// ELF 0x842E830, PE 0x8180B0: the text writer's queueGroupColoured at the truncated screen +// position; `size` is the line spacing, right alignment is AITextAlignmentX 1, bottom alignment +// any non-zero AITextAlignmentY. +// [CHOSEN, not recovered] Both images return the register the void call leaves; 0 here (no caller +// reads it). int DebugRenderer::drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawScreenText"); + textWriter()->queueGroupColoured(static_cast(position.x), static_cast(position.y), colour, + lines, size, ax == 1, ay != 0); + return 0; } +// ELF 0x842E8A0, PE 0x818120: as drawScreenText, through queueWorldGroupColoured. +// [CHOSEN, not recovered] Returns 0 for the same reason. int DebugRenderer::draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::draw3dText"); + textWriter()->queueWorldGroupColoured(position, colour, lines, size, ax == 1, ay != 0); + return 0; } -int DebugRenderer::drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const +// ELF 0x842E8F0, PE 0x818160 (a tail jump): the line drawer's +0x2C (drawTriangles, per-triangle +// colours). [CHOSEN, not recovered] Returns 0: the slot is void. +int DebugRenderer::drawTriangle(const std::vector& vertices, const std::vector& colours, bool depth) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawTriangle"); + lineDrawer()->drawTriangles(vertices, colours, depth); + return 0; } -int DebugRenderer::drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool filled) const +// ELF 0x842E920, PE 0x818170 (a tail jump): the line drawer's +0x30. [CHOSEN, not recovered] +// Returns 0: the slot is void. +int DebugRenderer::drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool depth) const { - BF2_AI_FRONTIER("dice::hfe::ai::DebugRenderer::drawMesh"); + lineDrawer()->drawMesh(vertices, indices, count, colours, depth); + return 0; } } // namespace ai diff --git a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h index 17fc8ceb1..9167113f0 100644 --- a/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h +++ b/Code/BF2/AI/AIInterface/BFKnowledge/DebugRenderer.h @@ -29,11 +29,11 @@ class IDebugRenderer virtual void drawAll() = 0; virtual void reset() = 0; virtual int drawLine(const std::vector& points, unsigned int colour, float width) const = 0; - virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool filled, int segments) const = 0; + virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool terrain, int segments) const = 0; virtual int drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const = 0; virtual int draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const = 0; - virtual int drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const = 0; - virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool filled) const = 0; + virtual int drawTriangle(const std::vector& vertices, const std::vector& colours, bool depth) const = 0; + virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool depth) const = 0; }; class DebugRenderer : public IDebugRenderer @@ -45,11 +45,11 @@ class DebugRenderer : public IDebugRenderer virtual void drawAll(); virtual void reset(); virtual int drawLine(const std::vector& points, unsigned int colour, float width) const; - virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool filled, int segments) const; + virtual int drawCircle(const Vec3& normal, const Vec3& centre, float radius, unsigned int colour, bool terrain, int segments) const; virtual int drawScreenText(const Vec2& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const; virtual int draw3dText(const Vec3& position, const std::vector& lines, int size, unsigned int colour, AITextAlignmentX ax, AITextAlignmentY ay) const; - virtual int drawTriangle(const std::vector& vertices, const std::vector& indices, bool filled) const; - virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool filled) const; + virtual int drawTriangle(const std::vector& vertices, const std::vector& colours, bool depth) const; + virtual int drawMesh(Vec3* vertices, unsigned int* indices, int count, unsigned int* colours, bool depth) const; }; } // namespace ai diff --git a/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp b/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp index e20269fbb..932f7e13b 100644 --- a/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp +++ b/Code/BF2/Animation/BoneAnimation/BoneAnimation.cpp @@ -14,6 +14,7 @@ #include // rand - getValue's root-bone jitter #include "../../Math/Quat.h" // Quat::slerp #include "../../Math/Vec3.h" +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { @@ -325,12 +326,12 @@ void BoneAnimation::getValue(int bone, float time, hfe::Quat& rotation, hfe::Vec position.z = ta.z; } - if (bone == 0 && m_jitterChance != 0 && rand() % 10 < m_jitterChance) + if (bone == 0 && m_jitterChance != 0 && bf2crt::rand() % 10 < m_jitterChance) { const float amplitudeX = jitter * m_jitterAmplitude; - position.x = amplitudeX * static_cast(rand() % 256 - 128) * 0.00390625f + position.x; + position.x = amplitudeX * static_cast(bf2crt::rand() % 256 - 128) * 0.00390625f + position.x; const float amplitudeY = jitter * m_jitterAmplitude; - position.y = 0.00390625f * (static_cast(rand() % 256 - 128) * amplitudeY) + position.y; + position.y = 0.00390625f * (static_cast(bf2crt::rand() % 256 - 128) * amplitudeY) + position.y; } } diff --git a/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp b/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp index f1eefeb85..ac69f87fb 100644 --- a/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp +++ b/Code/BF2/Animation/BoneAnimation/RagDollTemplate.cpp @@ -47,6 +47,12 @@ inline unsigned long long rdtsc() { #if defined(_WIN32) return __rdtsc(); +#elif defined(__aarch64__) + // [CHOSEN, not recovered] arm64 macOS port (untested): the generic timer's virtual count is + // the constant-rate counter that stands in for the TSC; callers calibrate its frequency. + unsigned long long count; + __asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(count)); + return count; #else unsigned int lo, hi; __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); diff --git a/Code/BF2/Animation/BoneAnimation/Trigger.cpp b/Code/BF2/Animation/BoneAnimation/Trigger.cpp index 331a6a61b..47a89a97b 100644 --- a/Code/BF2/Animation/BoneAnimation/Trigger.cpp +++ b/Code/BF2/Animation/BoneAnimation/Trigger.cpp @@ -12,6 +12,7 @@ #include // rand - Random / Idle triggers #include #include "../../IO/Stream/IStream.h" +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace anim { @@ -267,7 +268,7 @@ void RandomTrigger::applyAnimations(AnimationSystem& system) { if (m_bundles.empty()) return; - const unsigned int pick = static_cast(rand()) % static_cast(m_bundles.size()); + const unsigned int pick = static_cast(bf2crt::rand()) % static_cast(m_bundles.size()); system.playBundle(this, m_bundles[pick], m_prio, -1.0f, 1.0f); } @@ -283,12 +284,12 @@ bool IdleTrigger::update(AnimationSystem& system) if (m_nextIdleTime > system.getIdleTime() || system.getIdleTime() > m_idleTimeMax) return true; - m_nextIdleTime = static_cast(rand() % 100) / 100.0f * (m_idleTimeMax - m_idleTimeMin) + m_nextIdleTime = static_cast(bf2crt::rand() % 100) / 100.0f * (m_idleTimeMax - m_idleTimeMin) + m_idleTimeMin; if (!m_bundles.empty()) { const unsigned int pick = - static_cast(rand()) % static_cast(m_bundles.size()); + static_cast(bf2crt::rand()) % static_cast(m_bundles.size()); system.playBundle(this, m_bundles[pick], m_prio, -1.0f, 1.0f); } return Trigger::update(system); diff --git a/Code/BF2/Core/ClassFactoryInstantiations.cpp b/Code/BF2/Core/ClassFactoryInstantiations.cpp index 300138765..887c42f8e 100644 --- a/Code/BF2/Core/ClassFactoryInstantiations.cpp +++ b/Code/BF2/Core/ClassFactoryInstantiations.cpp @@ -159,4 +159,3 @@ template struct dice::hfe::world::ClassFactory; template struct dice::hfe::world::ClassFactory; template struct dice::hfe::world::ClassFactory; -template struct dice::hfe::world::ClassFactory; diff --git a/Code/BF2/Core/ConsoleObjectBase.cpp b/Code/BF2/Core/ConsoleObjectBase.cpp index 4bca74059..d3868e8ed 100644 --- a/Code/BF2/Core/ConsoleObjectBase.cpp +++ b/Code/BF2/Core/ConsoleObjectBase.cpp @@ -17,6 +17,8 @@ namespace hfe { // Converts typed arguments or stores raw string pointers, executes the binding and formats its result. // setArgFromString uses one-based indices; argument storage belongs to the generated binding. // ELF 0x486320; engine 0x83BE630. Slots +0x68, +0x7C, +0x60, +0x64 are attested in both images. +// RendDX9.dll copy PE 0x1007BFD0 (`retn 0Ch`, hidden result first; the MSVC table's slots +0x64, +// +0x78, +0x5C, +0x60). The trace block below is the [TEMP] harness, not part of the copy. std::string ConsoleObjectBaseImpl::execute(std::string* args, int argCount) { // [TEMP] [CHOSEN, not recovered] BF2_TRACE_CONSOLE logs each invoked binding. @@ -91,21 +93,26 @@ bool ConsoleObjectBaseImpl::isDynamic() const { return m_isDynami // -> +0x50 + index*4. no bounds check in the original - the array is ten wide and the caller is // trusted to stay inside it. execute() iterates its supplied count without clamping; // ordinary console callers perform the command's arity check before dispatch. +// PE 0x10051D60 (the RendDX9.dll copy: mov eax, [ecx + 4*eax + 0x50]; retn 4). const char* ConsoleObjectBaseImpl::getArgType(int index) const { return m_argTypes[index]; } // Range access forwards to the generated object's virtual hooks. // Range endpoints are pointers to mutable members. Preserve hook slot order without swapping the forwarder targets. bool ConsoleObjectBaseImpl::hasRange() const { return objectHasRange(); } +// PE 0x10051DB0 (RendDX9.dll copy: tail call through vtable +0x6C, the result slot passed straight through). std::pair ConsoleObjectBaseImpl::getRange() const { return getObjectRange(); } +// PE 0x10051E80 (RendDX9.dll copy: forwards through vtable +0x74). std::pair ConsoleObjectBaseImpl::getRangeAsString() const { return getObjectRangeAsString(); // sret passed straight through } +// PE 0x10051DD0 (RendDX9.dll copy: forwards through vtable +0x70). std::string ConsoleObjectBaseImpl::getDeltaAsString() const { return getObjectDeltaAsString(); } bool ConsoleObjectBaseImpl::hasBundledType() const { return objectHasBundledType(); } +// PE 0x10051E20 (RendDX9.dll copy: forwards through vtable +0x80). std::string ConsoleObjectBaseImpl::getTypeDescription() const { return getObjectTypeDescription(); } // The eight object-level hooks. Stubs here by design - this is the half the macro overrides, and @@ -116,17 +123,23 @@ void ConsoleObjectBaseImpl::executeObjectMethod() { } std::string ConsoleObjectBaseImpl::getReturnValueAsString() const { return std::string(); } void ConsoleObjectBaseImpl::setArgFromString(int, const std::string&) { } // empty, 5 bytes bool ConsoleObjectBaseImpl::objectHasRange() const { return false; } +// PE 0x100525C0 (RendDX9.dll copy, the vtable +0x6C default of the renderer bindings: stores two zero words +// through its result pointer; retn 4). std::pair ConsoleObjectBaseImpl::getObjectRange() const { return std::pair(0, 0); // zeroes the two pointer out-fields } -std::string ConsoleObjectBaseImpl::getObjectDeltaAsString() const { return std::string(); } +// PE 0x10051E40 (RendDX9.dll copy), BF2.exe 0x410C61 and ELF 0x83BE930 (ConsoleObjectBaseImpl::getObjectDeltaAsString): +// every image's default builds the literal "No Delta" (BF2.exe .rdata 0x881164, ELF .rodata 0x88D0C70); 2703 BF2.exe +// binding vtables point at 0x410C61. The earlier empty-string default was a reconstruction error. +std::string ConsoleObjectBaseImpl::getObjectDeltaAsString() const { return std::string("No Delta"); } std::pair ConsoleObjectBaseImpl::getObjectRangeAsString() const { return std::pair(); // two empty strings into the sret } void ConsoleObjectBaseImpl::checkObjectRange(bool) { } bool ConsoleObjectBaseImpl::objectHasBundledType() const { return false; } +// PE 0x10051E60 (RendDX9.dll copy, vtable +0x80 default: constructs an empty string). std::string ConsoleObjectBaseImpl::getObjectTypeDescription() const { return std::string(); } ConsoleObjectBaseImpl::~ConsoleObjectBaseImpl() { } @@ -136,6 +149,8 @@ ConsoleObject::~ConsoleObject() { } // Defaults for subsequent generated bindings: object name, access and category. // Only the first character of the copied name is lowercased; names must fit the 32-byte allocation. +// The RendDX9 image defines its own copy (Code/RendDX9Abi/NativeConsoleObjects.cpp, PE 0x1007BF60). +#if !defined(BF2_IMAGE_RENDDX9) namespace { const char* g_defaultNameLower = ""; unsigned int g_defaultAccess = 0; @@ -161,6 +176,7 @@ SetConsoleClassDefaults::SetConsoleClassDefaults(const char* objectName, unsigne g_defaultAccess = access; g_defaultCategory = category; } +#endif // !BF2_IMAGE_RENDDX9 // One list per translation-unit tag. Function-local static: the generated constructors run during // static initialisation and this must already exist when the first of them fires. diff --git a/Code/BF2/Core/ConsoleObjectMacro.h b/Code/BF2/Core/ConsoleObjectMacro.h index 0e12bd465..adf77d1bf 100644 --- a/Code/BF2/Core/ConsoleObjectMacro.h +++ b/Code/BF2/Core/ConsoleObjectMacro.h @@ -8,6 +8,7 @@ #include "ConsoleObjects.h" #include #include +#include #include #include @@ -27,6 +28,60 @@ const char* consoleDefaultName(); unsigned int consoleDefaultAccess(); unsigned char consoleDefaultCategory(); +#if defined(BF2_IMAGE_RENDDX9) +// The defaults' object name as passed, before the first character is lowercased (RendDX9 PE +// 0x10247C20; ELF ConsoleObject::mDefaultStaticObjectName). Four RendDX9 binding constructors +// read it. Defined by the RendDX9 image's copy in Code/RendDX9Abi/NativeConsoleObjects.cpp. +const char* consoleDefaultStaticName(); +#endif + +// Where BF2_CC_CONVERT extracts one console argument: its persistent per-type static. Every image extracts straight +// into the static with no stream-state test: RendDX9.dll PE 0x10054B20 (bool), BF2.exe PE 0x00411DD1 +// (bool) and PE 0x00411CEC (float), Linux bf2 ELF 0x08822DE0 (std::string) and ELF 0x087609E0 (int). +// Their libraries (MSVCP71, GCC 3.x libstdc++) leave a scalar target unchanged when the read fails or +// is out of range; C++11 libraries store 0 or the range limit there instead. [PLATFORM] Scalars are +// therefore read through a local that starts as the stored value and stored only when the read +// succeeds, which gives the retail result on every library. Every other type (std::string, the Vec +// types, the template proxies) is extracted in place, partial component writes included, as retail. +template::value> +struct ConsoleArgumentSlot +{ + explicit ConsoleArgumentSlot(T& stored) : m_target(stored) {} + T& target() { return m_target; } + void commit(bool) {} + + T& m_target; +}; + +template +struct ConsoleArgumentSlot +{ + explicit ConsoleArgumentSlot(T& stored) : m_stored(stored), m_value(stored) {} + T& target() { return m_value; } + void commit(bool succeeded) { if (succeeded) m_stored = m_value; } + + T& m_stored; + T m_value; +}; + +#if defined(_WIN32) && !DEDICATED && defined(_MSC_VER) && _MSC_VER > 1310 +// [PLATFORM] [CHOSEN, not recovered] The shipped client calls MSVCP71's operator>>(float&) +// (BF2.exe imports ...QAEAAV01@AAM@Z, not the double overload), which parses through a double +// before narrowing. A modern CRT's direct float extraction can change near-midpoint values and +// reject values that only exceed the float range, so newer toolchains read a double here. The +// VC7.1 matching build keeps the retail float extraction. Preserve failed reads. +template<> +struct ConsoleArgumentSlot +{ + explicit ConsoleArgumentSlot(float& stored) : m_stored(stored), m_value(stored) {} + double& target() { return m_value; } + void commit(bool succeeded) { if (succeeded) m_stored = static_cast(m_value); } + + float& m_stored; + double m_value; +}; +#endif + // Token paste with __LINE__ needs two levels, or you paste the literal text #define BF2_CC_CAT2(a, b) a##b #define BF2_CC_CAT(a, b) BF2_CC_CAT2(a, b) @@ -38,18 +93,17 @@ unsigned char consoleDefaultCategory(); static ::dice::hfe::SetConsoleClassDefaults \ BF2_CC_CAT(s_consoleDefaults, __LINE__)((objectName), (accessLevel), (categoryId)); -// Converts one-based arguments into persistent per-type storage. -// Extract into a temporary and commit only on success so malformed input preserves the previous value. -// String extraction takes one token; normal string arguments bypass this through execute's raw branch. +// Converts one-based arguments into persistent per-type storage, extracting straight into it (see +// ConsoleArgumentSlot). String extraction takes one token; normal string arguments bypass +// this through execute's raw branch. #define BF2_CC_CONVERT(T, oneBasedIndex) \ if (index == (oneBasedIndex)) \ { \ static T s; \ - T tmp = s; \ std::istringstream in(value); \ - in >> tmp; \ - if (!in.fail()) \ - s = tmp; \ + ::dice::hfe::ConsoleArgumentSlot slot(s); \ + in >> slot.target(); \ + slot.commit(!in.fail()); \ m_args[(oneBasedIndex) - 1] = reinterpret_cast(&s); \ } diff --git a/Code/BF2/Core/ConsoleObjects.cpp b/Code/BF2/Core/ConsoleObjects.cpp index 9c7ac76b0..b89bf2e3e 100644 --- a/Code/BF2/Core/ConsoleObjects.cpp +++ b/Code/BF2/Core/ConsoleObjects.cpp @@ -32,6 +32,9 @@ inline std::string registryKey(const ConsoleObject* object) } // anonymous namespace // Default-constructs the lookup hash, binding map and registration-order list. +// RendDX9.dll copy PE 0x1007B7E0, unreached there (no code or data reference): Hash (stack functor +// byte, 3011 = 0xBC3 buckets) via 0x1007B840, the multimap head (0x1007BAF0; nil byte +0x2D set, +// links to itself, size 0), the list head (0x1007B890, size 0), in member order. ConsoleObjects::ConsoleObjects() { } @@ -82,6 +85,8 @@ const ConsoleObjects::ConsoleObjectList& ConsoleObjects::getConsoleObjects() con // Returns the first active binding in the key's equal range, or null. // Inactive bindings stay registered and allow later duplicates to match. +// RendDX9.dll copy PE 0x1007B320 (lower_bound 0x101C0A60, upper_bound 0x1007BA80, vslot +0x2C per +// entry); unreached there (only its dead caller 0x1007B3B0 refers to it). ConsoleObject* ConsoleObjects::findInMultiMap(const std::string& key) { std::multimap::iterator it = @@ -102,6 +107,8 @@ ConsoleObject* ConsoleObjects::findInMultiMap(const std::string& key) // Resolves a console binding by exact name, then case-insensitive get/set prefixes. // The fallback accepts property types 1/3 for get and 1/2 for set. This differs from the command // dispatcher's read/write polarity; preserve those constants until both call paths justify a change. +// RendDX9.dll copy PE 0x1007B3B0 (`retn 8`; _strnicmp, substr(3, size - 3), vslot +0x10 getType), +// unreached there (no code or data reference). ConsoleObject* ConsoleObjects::getConsoleObject(const std::string& objectName, const std::string& methodName) { @@ -133,15 +140,11 @@ ConsoleObject* ConsoleObjects::getConsoleObject(const std::string& objectName, } // Registers a case-insensitive conversion key. Returns false for an existing key without replacing it. +// RendDX9.dll copy: the wrapper PE 0x1007B310 tail-jumps to the Hash member (Hash::insertUnique, +// cited in Core/Hash.h). Unreached in RendDX9 (no code or data reference). bool ConsoleObjects::registerTypeConversion(const std::string& from, const std::string& to) { - const unsigned int bucket = m_typeConversions.bucketOf(from); - - if (m_typeConversions.exists(from, bucket)) - return false; - - m_typeConversions.insert(from, to, bucket); - return true; + return m_typeConversions.insertUnique(from, to); } // typeAsString - @@ -149,6 +152,7 @@ bool ConsoleObjects::registerTypeConversion(const std::string& from, const std:: // A lookup with the key as its own default: an unregistered type name is returned unchanged. The // leading `_InterlockedAdd(&_S_empty_rep_storage.refcount, 1)` in the decompilation is libstdc++ // constructing an empty std::string, i.e. compiler scaffolding, not a member being touched. +// RendDX9.dll copy PE 0x1007B2C0 over the Hash::get copy PE 0x1007BA20; unreached there. std::string ConsoleObjects::typeAsString(const std::string& type) const { std::string converted; diff --git a/Code/BF2/Core/Debug.cpp b/Code/BF2/Core/Debug.cpp index ad0f67080..9a06a0d99 100644 --- a/Code/BF2/Core/Debug.cpp +++ b/Code/BF2/Core/Debug.cpp @@ -88,6 +88,8 @@ Debug::~Debug() } // No bounds check, no locking. +// RendDX9.dll copy PE 0x10074340 (type/callback in ECX/EDX, data on the stack; unreachable in 1.50: +// no code or data references). void setDebugCallback(DebugType type, DebugCallback callback, void* data) { bfGlobal_callback[type] = callback; @@ -96,6 +98,7 @@ void setDebugCallback(DebugType type, DebugCallback callback, void* data) // (the clear() is inlined here and called out of line in turnOffAllDebug - // compiler variance, same source). plain `int` parameter, attested by the mangling. +// RendDX9.dll copy PE 0x10074850 (clear() as a tail jump to the Hash clear). void turnOnAllDebug(int type) { debugOn[type] = true; @@ -103,6 +106,7 @@ void turnOnAllDebug(int type) } +// RendDX9.dll copy PE 0x10074870. void turnOffAllDebug(int type) { debugOn[type] = false; @@ -111,6 +115,9 @@ void turnOffAllDebug(int type) // Enables debugging for module. The exception list is an exclusion list when the type is on // and an inclusion list when it is off; insertion avoids duplicate entries. +// RendDX9.dll copy PE 0x10074890 (fastcall type/module). Its exists-then-insert is one out-of-line +// Hash member there, PE 0x10074940: bucket, exists(), then a node with the key and an empty value +// pushed on the chain, answering whether it inserted; the same operations as below. void turnOnDebug(int type, const std::string& module) { if (debugOn[type]) @@ -119,7 +126,7 @@ void turnOnDebug(int type, const std::string& module) debugModules[type].insert(module, std::string()); } -// Exact mirror, same caller-side guard. +// Exact mirror, same caller-side guard. RendDX9.dll copy PE 0x100748C0. void turnOffDebug(int type, const std::string& module) { if (!debugOn[type]) diff --git a/Code/BF2/Core/Hash.h b/Code/BF2/Core/Hash.h index 4b1acf4dd..74f3a15db 100644 --- a/Code/BF2/Core/Hash.h +++ b/Code/BF2/Core/Hash.h @@ -71,6 +71,8 @@ class Hash }; // Constructs maxSize buckets and explicitly zeroes them. + // RendDX9.dll copy PE 0x1007B840 (`retn 8`: functor reference, maxSize; it stores the functor + // address at +0x08, which this rebuild keeps null). // The default 3011 is [CHOSEN, not recovered] syntax for the observed standard bucket count. explicit Hash(unsigned int maxSize = 3011) { @@ -92,6 +94,7 @@ class Hash } // Returns whether key exists in the specified bucket. The caller must supply a valid reduced bucket index. + // RendDX9.dll copy (StringHashFunc) PE 0x100748F0. bool exists(const K& key, unsigned int bucket) const { for (Node* n = m_buckets[bucket]; n != 0; n = n->next) @@ -114,6 +117,7 @@ class Hash } // Copies the matching value to value and returns true. A miss leaves value unchanged and returns false. + // RendDX9.dll copy (StringHashFunc, string value) PE 0x1007BA20, unreached there. bool get(const K& key, V& value) const { for (Node* n = m_buckets[bucketOf(key)]; n != 0; n = n->next) @@ -128,6 +132,7 @@ class Hash } // Deletes every node while retaining the bucket array and capacity for reuse. + // RendDX9.dll copy (StringHashFunc) PE 0x10074A50. void clear() { for (unsigned int i = 0; i < m_maxSize; ++i) @@ -144,6 +149,7 @@ class Hash } // Removes the first matching key and returns true. Returns false when the key is absent. + // RendDX9.dll copy (StringHashFunc) PE 0x100749C0. bool remove(const K& key) { const unsigned int bucket = bucketOf(key); @@ -167,6 +173,23 @@ class Hash } unsigned int bucketOf(const K& key) const { return HashFunc()(key) % m_maxSize; } + + // Inserts key/value unless the key is already present; answers false for an existing key. + // RendDX9.dll copy (StringHashFunc, string value) PE 0x1007B9A0 (`retn 8`): bucket from the + // hash modulo +0x04, exists, then a 0x3C-byte node whose next is the old head, key and value + // copy-constructed, stored as the head; true. The engine ELF inlines the same steps into + // ConsoleObjects::registerTypeConversion. [PLATFORM] the PE engine allocator can return null, + // and that arm stores the null as the bucket head (dropping the chain) and still answers true; + // operator new here throws instead, so the arm cannot occur. + // [INFERRED] name; the member is unreached in RendDX9 (only the dead wrapper PE 0x1007B310). + bool insertUnique(const K& key, const V& value) + { + const unsigned int bucket = bucketOf(key); + if (exists(key, bucket)) + return false; + insert(key, value, bucket); + return true; + } // [CHOSEN, not recovered] Convenience overloads compute the bucket before forwarding. bool exists(const K& key) const { return exists(key, bucketOf(key)); } void insert(const K& key, const V& value) { insert(key, value, bucketOf(key)); } diff --git a/Code/BF2/Core/LoadStat.cpp b/Code/BF2/Core/LoadStat.cpp index f67ed9bb7..e97d6d954 100644 --- a/Code/BF2/Core/LoadStat.cpp +++ b/Code/BF2/Core/LoadStat.cpp @@ -128,8 +128,19 @@ void LoadStat::registerLoadCallback(void (*fn)()) // nothing is pushed. That matters for a rebuild tempted to add an observer here. void LoadStat::setCurrentFile(const std::string& file) { - // Update the polled loading filename without invoking callbacks or setting a dirty flag. +#if !DEDICATED + // BF2.exe 0x45D610 (all seven FileManager/Win32FileSystem callers): `lea eax,[ecx+28h]; + // push eax; add ecx,0Ch; call basic_string::assign; ret 4`. The client ignores the file name + // and copies the phase name (+0x28 in the MSVC layout, m_string10; resetLoadStats 0x45D6D0 + // clears +0x28 then +0x0C, as the Linux reset clears m_string10 then m_string0C). So the + // loading screen's progressText (endOfRound.swf, dice.bf2.Client.getCurrentLoadFile) shows + // the load phase, never individual files. + (void) file; + m_string0C = m_string10; +#else + // Linux server (0x83C4980): update the polled loading filename, no callback, no dirty flag. m_string0C = file; +#endif } diff --git a/Code/BF2/Core/ModuleRegistry.cpp b/Code/BF2/Core/ModuleRegistry.cpp index fc66af5c9..0cbd511ab 100644 --- a/Code/BF2/Core/ModuleRegistry.cpp +++ b/Code/BF2/Core/ModuleRegistry.cpp @@ -95,13 +95,23 @@ std::list& toolObjectConsoleObjects(); // Scene/Object/Tool #include "../Menu/MenuTeamManager.h" // client factory41053B, team/kit menu data #include "../Menu/ServerBrowserManager.h" // client factory410205, the lists' owner #include "../IO/Input/DX8InputDeviceManager.h" // client InputDX8Module factory rows +#if defined(__APPLE__) +// [CHOSEN, not recovered] macOS port: MacInputDeviceManager answers the DX8 row (docs/macos-s2-4.md). +#include "../IO/Input/MacInputDeviceManager.h" +#endif #include "../IO/Input/InputManager.h" #endif #if !DEDICATED #ifndef NOMINMAX #define NOMINMAX #endif +#if defined(_WIN32) #include // LoadLibraryA / GetProcAddress / FreeLibrary - BfSoundModule +#else +// [CHOSEN, not recovered] The macOS client resolves BF2Audio through the POSIX loader wrappers, +// which answer statically linked images first (docs/macos-port.md). +#include "PluginDll.h" +#endif #include "../Game/Utility/Vars.h" // Vars::getInt("opt-nosound") - BfSoundModule::init #endif #include "System.h" // g_system - io::ModuleIO::init calls resetExactTime @@ -584,7 +594,14 @@ void InputDX8Module::getClassList(std::vector& out) // PE6AC3E6, c { // [PLATFORM] Client table89AE6C supplies these two rows in this order. // Use native ClassRegInfo/factory ABI, never the retail36-byte STL record. +#if defined(__APPLE__) + // [CHOSEN, not recovered] macOS port: the Cocoa-backed manager under the DX8 CID and name, so + // BF2EngineSetup's setSingletonClass("InputDeviceManager", CID_DX8InputDeviceManager) and every + // caller stay unchanged (docs/macos-s2-4.md). + out.push_back(ClassRegInfo{CID_DX8InputDeviceManager, "dice.hfe.io.InputDeviceManager.DX8", &MacInputDeviceManager::create}); +#else out.push_back(ClassRegInfo{CID_DX8InputDeviceManager, "dice.hfe.io.InputDeviceManager.DX8", &DX8InputDeviceManager::create}); +#endif out.push_back(ClassRegInfo{CID_InputManager, "dice.hfe.io.InputManager", &InputManager::create}); } #else @@ -1162,7 +1179,11 @@ bool MathModule::init() bool MathModule::close() { closeMath(); return true; } #if !DEDICATED +#if defined(_WIN32) static HMODULE s_audioLibrary = 0; // BF2.exe ds:0xA24CB0 - the BF2Audio.dll handle +#else +static void* s_audioLibrary = 0; // [CHOSEN] POSIX loader-wrapper handle +#endif #endif bool BfSoundModule::init() { @@ -1185,7 +1206,11 @@ bool BfSoundModule::init() } BfSound* facade = new BfSound; g_bfSound = facade; +#if defined(_WIN32) s_audioLibrary = LoadLibraryA("BF2Audio.dll"); +#else + s_audioLibrary = ::LoadLibrary("BF2Audio.dll"); +#endif if (s_audioLibrary) { typedef ISoundEngine* (*GetSoundEngineFn)(); diff --git a/Code/BF2/Core/MsvcCrtCompat.h b/Code/BF2/Core/MsvcCrtCompat.h new file mode 100644 index 000000000..fb4fa1628 --- /dev/null +++ b/Code/BF2/Core/MsvcCrtCompat.h @@ -0,0 +1,288 @@ +// [CHOSEN, not recovered] MSVC 7.1 CRT functions that client code calls, rebuilt for the native +// POSIX ports with the MSVC observable semantics (return values, truncation, wide-format +// conversions). See docs/macos-port.md, "Win32 and CRT items (S2.5/S2.8)". +// +// Include it only where one of these names is used. On MSVC it is empty: the real CRT is used. +#ifndef CORE_MSVCCRTCOMPAT_H +#define CORE_MSVCCRTCOMPAT_H + +#if !defined(_MSC_VER) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bf2crt { + +// Rewrites an MSVC wide-printf format for the C library. In MSVC's wide family `%s`/`%c` take +// wide arguments and `%S`/`%C` narrow ones (an `h` prefix forces narrow, `l`/`w` wide); C99 uses +// `%ls`/`%lc` for wide and `%s`/`%c` for narrow. `I64` becomes `ll`, `I32` is dropped and `I` +// becomes `z`. Everything else is copied unchanged. +inline std::wstring translateWideFormat(const wchar_t* fmt) +{ + std::wstring out; + if (!fmt) + return out; + for (const wchar_t* p = fmt; *p; ) { + if (*p != L'%') { + out += *p++; + continue; + } + out += *p++; // '%' + if (*p == L'%') { + out += *p++; + continue; + } + while (*p && std::wcschr(L"-+ #0", *p)) // flags + out += *p++; + while (*p == L'*' || (*p >= L'0' && *p <= L'9')) // width + out += *p++; + if (*p == L'.') { // precision + out += *p++; + while (*p == L'*' || (*p >= L'0' && *p <= L'9')) + out += *p++; + } + // Length prefix: 0 none, 'h' narrow, 'l' wide/long, 'w' wide. + wchar_t size = 0; + std::wstring lengthText; + for (;;) { + if (p[0] == L'I' && p[1] == L'6' && p[2] == L'4') { lengthText += L"ll"; p += 3; continue; } + if (p[0] == L'I' && p[1] == L'3' && p[2] == L'2') { p += 3; continue; } + if (p[0] == L'I') { lengthText += L"z"; ++p; continue; } + if (*p == L'h') { size = L'h'; lengthText += *p++; continue; } + if (*p == L'l') { if (size == 0) size = L'l'; lengthText += *p++; continue; } + if (*p == L'w') { size = L'w'; ++p; continue; } + if (*p == L'L' || *p == L'j' || *p == L'z' || *p == L't') { lengthText += *p++; continue; } + break; + } + const wchar_t conv = *p; + if (!conv) + break; + ++p; + switch (conv) { + case L's': + out += (size == L'h') ? L"s" : L"ls"; + break; + case L'S': + out += (size == L'l' || size == L'w') ? L"ls" : L"s"; + break; + case L'c': + out += (size == L'h') ? L"c" : L"lc"; + break; + case L'C': + out += (size == L'l' || size == L'w') ? L"lc" : L"c"; + break; + default: + out += lengthText; + out += conv; + break; + } + } + return out; +} + +// Formats the whole output of an MSVC wide format. Returns false when the C library refuses +// (an encoding error or more than 16M characters). +inline bool formatWideFully(std::vector& out, int& length, const wchar_t* fmt, va_list args) +{ + const std::wstring format = translateWideFormat(fmt); + std::size_t capacity = 256; + for (;;) { + out.assign(capacity, L'\0'); + va_list copy; + va_copy(copy, args); + const int n = std::vswprintf(out.data(), capacity, format.c_str(), copy); + va_end(copy); + if (n >= 0) { + length = n; + return true; + } + if (capacity >= (std::size_t(1) << 24)) + return false; + capacity *= 4; + } +} + +} // namespace bf2crt + +// _vsnwprintf (MSVC 7.1): at most `count` characters are written. A shorter result is +// terminated and its length returned; a result of exactly `count` characters is written without +// a terminator and `count` returned; a longer one writes its first `count` characters, no +// terminator, and returns -1. A format the C library refuses returns -1 and writes nothing. +inline int _vsnwprintf(wchar_t* buffer, std::size_t count, const wchar_t* fmt, va_list args) +{ + std::vector full; + int length = 0; + if (!bf2crt::formatWideFully(full, length, fmt, args)) + return -1; + const std::size_t len = static_cast(length); + if (len < count) { + std::wmemcpy(buffer, full.data(), len + 1); + return length; + } + std::wmemcpy(buffer, full.data(), count); + return len == count ? length : -1; +} + +// _swprintf (MSVC 7.1 legacy, no size argument): the whole result and its terminator are written. +// Returns the length, or -1 for a format the C library refuses. +inline int _swprintf(wchar_t* buffer, const wchar_t* fmt, ...) +{ + va_list args; + va_start(args, fmt); + std::vector full; + int length = 0; + const bool ok = bf2crt::formatWideFully(full, length, fmt, args); + va_end(args); + if (!ok) + return -1; + std::wmemcpy(buffer, full.data(), static_cast(length) + 1); + return length; +} + +// _TRUNCATE and _snprintf_s (MSVC 8 secure CRT): with count == _TRUNCATE, as much as fits in +// sizeInBytes - 1 characters is written and terminated; the answer is the length, or -1 when the +// output was truncated. A finite count also limits the characters written, with the same -1 +// answer when the limit cut the output. +#ifndef _TRUNCATE +#define _TRUNCATE (static_cast(-1)) +#endif +inline int _vsnprintf_s(char* buffer, std::size_t sizeInBytes, std::size_t count, const char* fmt, va_list args) +{ + if (!buffer || sizeInBytes == 0) + return -1; + std::size_t limit = sizeInBytes - 1; + if (count != _TRUNCATE && count < limit) + limit = count; + va_list copy; + va_copy(copy, args); + const int n = std::vsnprintf(buffer, limit + 1, fmt, copy); + va_end(copy); + if (n < 0) { + buffer[0] = '\0'; + return -1; + } + return static_cast(n) > limit ? -1 : n; +} +inline int _snprintf_s(char* buffer, std::size_t sizeInBytes, std::size_t count, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + const int n = _vsnprintf_s(buffer, sizeInBytes, count, fmt, args); + va_end(args); + return n; +} + +// sprintf_s, the array form (MSVC 8 secure CRT): the formatted text with its terminator, or, when +// it does not fit, the invalid-parameter handler, whose default ends the process. That stop is +// kept: the text is reported on stderr and the process aborts. +template +inline int sprintf_s(char (&buffer)[N], const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + const int n = std::vsnprintf(buffer, N, fmt, args); + va_end(args); + if (n < 0 || static_cast(n) >= N) { + buffer[0] = '\0'; + std::fprintf(stderr, "sprintf_s: buffer of %u bytes too small for \"%s\" (invalid parameter)\n", + static_cast(N), fmt); + std::fflush(stderr); + std::abort(); + } + return n; +} + +// __time32_t / _time32: seconds since the epoch as a 32-bit value; -1 once that no longer fits +// (from 2038), as the MSVC function answers. +typedef std::int32_t __time32_t; +inline __time32_t _time32(__time32_t* out) +{ + const std::time_t now = std::time(nullptr); + const __time32_t value = (now < 0 || now > static_cast(INT32_MAX)) + ? static_cast<__time32_t>(-1) : static_cast<__time32_t>(now); + if (out) + *out = value; + return value; +} + +// _time64: 64-bit seconds since the epoch. +inline long long _time64(long long* out) +{ + const long long value = static_cast(std::time(nullptr)); + if (out) + *out = value; + return value; +} + +// _splitpath (MSVC 7.1 splitpath.c, single-byte): a drive is the first two characters when the +// second is ':'; the directory runs to the last '/' or '\\' inclusive; the extension starts at +// the last '.' after it. Each part is truncated to the MSVC limits (_MAX_DRIVE 3, _MAX_DIR 256, +// _MAX_FNAME 256, _MAX_EXT 256, terminator included) and every non-null output is terminated. +// As in MSVC, the caller's buffers must hold those limits. +inline void _splitpath(const char* path, char* drive, char* dir, char* fname, char* ext) +{ + const std::size_t maxDrive = 3, maxDir = 256, maxFname = 256, maxExt = 256; + if (std::strlen(path) >= maxDrive - 2 && path[maxDrive - 2] == ':') { + if (drive) { + std::strncpy(drive, path, maxDrive - 1); + drive[maxDrive - 1] = '\0'; + } + path += maxDrive - 1; + } else if (drive) { + *drive = '\0'; + } + const char* lastSlash = nullptr; + const char* dot = nullptr; + const char* p = path; + for (; *p; ++p) { + if (*p == '/' || *p == '\\') + lastSlash = p + 1; + else if (*p == '.') + dot = p; + } + if (lastSlash) { + if (dir) { + std::size_t len = static_cast(lastSlash - path); + if (len > maxDir - 1) len = maxDir - 1; + std::strncpy(dir, path, len); + dir[len] = '\0'; + } + path = lastSlash; + } else if (dir) { + *dir = '\0'; + } + if (dot && dot >= path) { + if (fname) { + std::size_t len = static_cast(dot - path); + if (len > maxFname - 1) len = maxFname - 1; + std::strncpy(fname, path, len); + fname[len] = '\0'; + } + if (ext) { + std::size_t len = static_cast(p - dot); + if (len > maxExt - 1) len = maxExt - 1; + std::strncpy(ext, dot, len); + ext[len] = '\0'; + } + } else { + if (fname) { + std::size_t len = static_cast(p - path); + if (len > maxFname - 1) len = maxFname - 1; + std::strncpy(fname, path, len); + fname[len] = '\0'; + } + if (ext) + *ext = '\0'; + } +} + +#endif // !_MSC_VER +#endif // CORE_MSVCCRTCOMPAT_H diff --git a/Code/BF2/Core/PlatformCompat.h b/Code/BF2/Core/PlatformCompat.h index 3b8a86143..74220ce0c 100644 --- a/Code/BF2/Core/PlatformCompat.h +++ b/Code/BF2/Core/PlatformCompat.h @@ -19,6 +19,30 @@ #include // alloca #include // std::isfinite, std::isnan +#if !defined(_WIN32) +// [CHOSEN, not recovered] POSIX Interlocked adapters (macOSplan.md, S2.10). +// Targets must be naturally aligned native words, never fields in packed file/packet data. +// Increment/decrement/add return the new value; exchange/add-exchange/CAS return the old value. +template inline T InterlockedIncrement(volatile T* target) +{ return __atomic_add_fetch(target, 1, __ATOMIC_SEQ_CST); } +template inline T InterlockedDecrement(volatile T* target) +{ return __atomic_sub_fetch(target, 1, __ATOMIC_SEQ_CST); } +template inline T InterlockedAdd(volatile T* target, V value) +{ return __atomic_add_fetch(target, static_cast(value), __ATOMIC_SEQ_CST); } +template inline T InterlockedExchangeAdd(volatile T* target, V value) +{ return __atomic_fetch_add(target, static_cast(value), __ATOMIC_SEQ_CST); } +template inline T InterlockedExchange(volatile T* target, V value) +{ return __atomic_exchange_n(target, static_cast(value), __ATOMIC_SEQ_CST); } +template +inline T InterlockedCompareExchange(volatile T* target, V value, C comparand) +{ + T previous = static_cast(comparand); + __atomic_compare_exchange_n(target, &previous, static_cast(value), false, + __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return previous; +} +#endif + // Win32 calling-convention spellings are empty for this non-MSVC native port. #ifndef __cdecl #define __cdecl diff --git a/Code/BF2/Core/PluginDll.cpp b/Code/BF2/Core/PluginDll.cpp index 4f16a7b6d..7456a8f9c 100644 --- a/Code/BF2/Core/PluginDll.cpp +++ b/Code/BF2/Core/PluginDll.cpp @@ -12,6 +12,9 @@ #endif #include "ClassManager.h" +#if defined(BF2_STATIC_PLUGINS) +#include "../../StaticPlugins/StaticPlugins.h" +#endif #if !defined(_WIN32) // [PLATFORM] Global-namespace library wrappers for ELF; placement is [INFERRED]. @@ -24,18 +27,43 @@ void* LoadLibrary(const char* name) const char* const dot = std::strrchr(name, '.'); if (!dot) return 0; +#if defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] The macOS client links its plugin images statically + // (Code/StaticPlugins/StaticPlugins.h); a linked image is answered before dlopen is tried. + if (void* image = bf2staticplugins::find(std::string(name, dot).c_str())) + return image; +#endif std::string file = std::string("lib") + std::string(name, dot); +#if defined(__APPLE__) + // [CHOSEN, not recovered] The macOS port's shared-library suffix (docs/macos-port.md). + file.append(".dylib"); +#else file.append(".so"); +#endif return ::dlopen(file.c_str(), RTLD_LAZY); } void* GetProcAddress(void* handle, const char* name) { +#if defined(BF2_STATIC_PLUGINS) + if (bf2staticplugins::isStaticHandle(handle)) + return bf2staticplugins::symbol(handle, name); +#endif return ::dlsym(handle, name); } bool FreeLibrary(void* handle) { +#if defined(BF2_STATIC_PLUGINS) + // A statically linked image stays mapped for the life of the process; there is nothing to close. + // It is only marked released, so the next load can rebuild its module table + // (StaticPlugins.h, menu re-entry). + if (bf2staticplugins::isStaticHandle(handle)) + { + bf2staticplugins::release(handle); + return true; + } +#endif if (handle) return ::dlclose(handle) == 0; return false; @@ -114,12 +142,35 @@ bool FreeLibraryBf(void* handle, const char* diagnosticName) } #else (void)diagnosticName; -#if defined(__linux__) - // [CHOSEN, not recovered] Native-port design, not retail: unregister AI/console singletons before dlclose - // so a map reload cannot reuse stale objects. Retail ELF 0x83C3400 only closes the library; - // Win32 BF2.exe 0x446CE0 calls deinitDll first. AIModule::close (ELF 0x3EECB0) - // unregisters the AI singleton; preserve that teardown before unmapping native libaidll.so. - if (handle) +#if defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] A linked image that retail unloads per use (SwiffPlayer, on every + // menu exit) gets the Win32 body's deinitDll before the release, so its modules are closed, + // unregistered and released as BF2.exe 0x446CE0 does before FreeLibrary (StaticPlugins.h). + if (bf2staticplugins::isStaticHandle(handle) && bf2staticplugins::unloadsWithDeinit(handle)) + { + DeinitDllFn deinitDll = reinterpret_cast(::GetProcAddress(handle, "deinitDll")); + if (deinitDll) + deinitDll(); + } +#endif +#if defined(__APPLE__) || defined(__linux__) + // [PLATFORM] [CHOSEN, not recovered] Native-port design, not retail: a dlopen'ed image + // (libaidll.dylib, libaidll.so) gets the Win32 body's deinitDll before dlclose. The ELF body (bf2 0x83C3400 -> FreeLibrary 0x83D3170) is the bare + // dlclose, so AIModule::close (libaidll.so 0x3EECB0) never runs and the "AI" simple singleton + // that the IAI constructor (0x3EE430) registered stays in the host registry. The next load's + // IAI constructor then finds "AI" taken and leaves the new BF2AI unregistered, and + // AIConnection::init hands back the old object. [INFERRED] Retail Linux survives this only + // while dlopen maps the reloaded image at the closed one's address, which makes the old vtable + // pointer valid again (not observed on a retail run). dyld does not reuse the address: dlclose unmaps the dylib and the old vtable + // pointer dangles (the second singleplayer game faulted with pc=0 at GameServer::loadPath's + // aiSingleton->init()). The Win32 body (BF2.exe 0x446CE0) calls deinitDll first; AIModule::close + // then unregisters "AI" and the module's console lists, and the reload registers fresh ones. + // Request R4, docs/ai-reconstruct/HANDOFF-client-track.md. + bool dlopened = handle != 0; +#if defined(BF2_STATIC_PLUGINS) + dlopened = dlopened && !bf2staticplugins::isStaticHandle(handle); +#endif + if (dlopened) { DeinitDllFn deinitDll = reinterpret_cast(::GetProcAddress(handle, "deinitDll")); if (deinitDll) diff --git a/Code/BF2/Core/PluginDll.h b/Code/BF2/Core/PluginDll.h index e15291fd1..bd67519a9 100644 --- a/Code/BF2/Core/PluginDll.h +++ b/Code/BF2/Core/PluginDll.h @@ -4,7 +4,9 @@ #define CORE_PLUGINDLL_H #if !defined(_WIN32) -// [PLATFORM] ELF wrappers over dlopen/dlsym/dlclose, defined in PluginDll.cpp. +// [PLATFORM] The ELF's global-namespace LoadLibrary/GetProcAddress/FreeLibrary wrappers over +// dlopen/dlsym/dlclose, defined in PluginDll.cpp. Under BF2_STATIC_PLUGINS (the macOS client) they +// answer the statically linked plugin images first. void* LoadLibrary(const char* name); void* GetProcAddress(void* handle, const char* name); bool FreeLibrary(void* handle); diff --git a/Code/BF2/Core/PosixRegistry.h b/Code/BF2/Core/PosixRegistry.h new file mode 100644 index 000000000..7a5ed1ec6 --- /dev/null +++ b/Code/BF2/Core/PosixRegistry.h @@ -0,0 +1,20 @@ +// [CHOSEN, not recovered] Owner-requested POSIX Registry.con backend. +#ifndef CORE_POSIXREGISTRY_H +#define CORE_POSIXREGISTRY_H + +#if !defined(_WIN32) && !DEDICATED +#include "Registry.h" + +namespace dice { namespace hfe { namespace posixRegistry { + +// Reads a named value from @HOME@/Registry.con. An empty name denotes the default value. +// Returns false for an absent/unreadable file or value, leaving output untouched. +bool readValue(RegKeyCategory category, const std::string& path, + const std::string& name, std::string& output); + +// Tests whether the file contains a value in this key or one of its descendants. +bool keyExists(RegKeyCategory category, const std::string& path); + +} } } +#endif +#endif diff --git a/Code/BF2/Core/Registry.cpp b/Code/BF2/Core/Registry.cpp index 60f4b2510..6ffb8b01f 100644 --- a/Code/BF2/Core/Registry.cpp +++ b/Code/BF2/Core/Registry.cpp @@ -3,6 +3,17 @@ #ifdef _WIN32 #include +#elif !DEDICATED +// [CHOSEN, not recovered] Owner decision: a read-only file in the client's @HOME@. +#include "PosixRegistry.h" +#include +#include +#include +#if defined(__APPLE__) +#include "../Platform/macOS/ClientPaths.h" +#else +#include "../IO/File/FileManager.h" +#endif #endif namespace dice { namespace hfe { @@ -28,7 +39,16 @@ bool readRegistryString(RegKeyCategory category, const std::string& name, path = std::string("SOFTWARE\\Electronic Arts\\EA Games\\") + modName; bool found = false; +#if defined(_M_IX86) if (RegOpenKeyA(root, path.c_str(), &key) == ERROR_SUCCESS) +#else + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): BF2's 32-bit installer + // writes these keys into the 32-bit registry view (WOW6432Node), which a 32-bit process reads + // implicitly; a 64-bit process must ask for that view or it finds no keys (an empty CD key then + // takes translateCdKey's shipped null-blob fault at the first server challenge). Subkeys opened + // relative to this handle stay in the same view. + if (RegOpenKeyExA(root, path.c_str(), 0, KEY_READ | KEY_WOW64_32KEY, &key) == ERROR_SUCCESS) +#endif { BYTE data[1024]; DWORD type; @@ -72,6 +92,95 @@ bool readRegistryString(RegKeyCategory category, const std::string& name, Registry* registry = &rinstance; +#if !defined(_WIN32) && !DEDICATED +// [CHOSEN, not recovered] File syntax and owner decision: docs/macos-r1-registry-file.md. +namespace posixRegistry { +namespace { +std::string trim(const std::string& text) +{ + const auto first = text.find_first_not_of(" \t\r"); + return first == std::string::npos ? std::string() : + text.substr(first, text.find_last_not_of(" \t\r") - first + 1); +} + +std::string fold(std::string text) +{ + for (char& c : text) + if (c >= 'A' && c <= 'Z') + c += 'a' - 'A'; + return text; +} + +std::string keyPath(RegKeyCategory category, const std::string& path) +{ + return fold(std::string(category == RegKeyLocalMachine ? + "HKEY_LOCAL_MACHINE\\" : "HKEY_CURRENT_USER\\") + path); +} + +std::map readFile() +{ + std::map values; +#if defined(__APPLE__) + const std::string home = macos::clientDataDirectory(); +#else + // Use the filesystem's @HOME@ policy when a future POSIX client supplies it. + if (!io::fileManager) + return values; + const std::string home = io::fileManager->getHomeSubstitution(); +#endif + if (home.empty()) + return values; + std::ifstream input(home + "/Registry.con"); + std::string line; + unsigned int number = 0; + while (std::getline(input, line)) { + ++number; + line = trim(line); + if (line.empty() || line[0] == '#' || line[0] == ';') + continue; + const auto separator = line.find('='); + const std::string key = fold(trim(line.substr(0, separator))); + const auto last = key.find_last_of('\\'); + if (separator == std::string::npos || line.find('\0') != std::string::npos || + (key.compare(0, 19, "hkey_local_machine\\") != 0 && + key.compare(0, 18, "hkey_current_user\\") != 0) || + last == std::string::npos || last + 1 == key.size() || + key.find("\\\\") != std::string::npos) { + // Never include values: the file can contain a CD key. + std::fprintf(stderr, "Registry.con: ignoring malformed line %u\n", number); + std::fflush(stderr); + continue; + } + values[key] = trim(line.substr(separator + 1)); + } + if (input.bad()) + values.clear(); + return values; +} +} // namespace + +bool readValue(RegKeyCategory category, const std::string& path, + const std::string& name, std::string& output) +{ + const auto values = readFile(); + const auto found = values.find(keyPath(category, path) + "\\" + + (name.empty() ? "@" : fold(name))); + if (found == values.end()) + return false; + output = found->second; + return true; +} + +bool keyExists(RegKeyCategory category, const std::string& path) +{ + const auto values = readFile(); + const std::string prefix = keyPath(category, path) + "\\"; + const auto found = values.lower_bound(prefix); + return found != values.end() && found->first.compare(0, prefix.size(), prefix) == 0; +} +} // namespace posixRegistry +#endif + // Client PE 0x450FE0. [PLATFORM] ELF 0x83CB6F0 constructs an empty string and // ignores even the supplied default; this is an actual shipped Linux body. std::string Registry::getString(RegKeyCategory category, const std::string& name, @@ -81,6 +190,16 @@ std::string Registry::getString(RegKeyCategory category, const std::string& name std::string result = defaultValue; readRegistryString(category, name, defaultValue, result, modName); return result; +#elif !DEDICATED + // [CHOSEN, not recovered] POSIX clients read Registry.con; missing values retain the + // Windows absent-key defaults introduced in docs/macos-c-asan-heap.md. + const std::string path = std::string("SOFTWARE\\Electronic Arts\\EA Games\\") + + (modName.empty() ? "Battlefield 2" : modName); + std::string result; + if (posixRegistry::readValue(category, path, name, result) || + posixRegistry::readValue(category, path + "\\" + name, "", result)) + return result; + return defaultValue; #else return std::string(""); #endif diff --git a/Code/BF2/Core/StringTokenizer.h b/Code/BF2/Core/StringTokenizer.h new file mode 100644 index 000000000..ec1ca5c1e --- /dev/null +++ b/Code/BF2/Core/StringTokenizer.h @@ -0,0 +1,66 @@ +// A character-set string tokenizer. BF2.exe 0x59E110 (destructor), 0x59E120 (assign), 0x59E1B0 +// (constructor), 0x59E1F0 (nextToken). [INFERRED] class, member and header names and placement: no +// symbol or __FILE__ string names this class. SwiffHost::parseResolution (0x489210) is the menu caller. +// +// Retail layout (x86, 0x40 bytes): +0x00 the text (a VC7.1 std::string), +0x1C a std::bitset<256> +// of delimiter characters, +0x3C the scan position. The native object keeps the same members with +// the native STL; nothing outside the owner reads them. +#ifndef CORE_STRINGTOKENIZER_H +#define CORE_STRINGTOKENIZER_H + +#include +#include + +namespace dice { +namespace hfe { + +class StringTokenizer +{ +public: + // 0x59E1B0: the bitset is zeroed (eight words), the position cleared, then assign(). + StringTokenizer(const std::string& text, const std::string& delimiters) + : m_position(0) + { + assign(text, delimiters); + } + + // 0x59E120: position 0, the text copied, then one bit set per delimiter byte. Bits already + // set by an earlier assign() are kept (the shipped body does not clear the set). + void assign(const std::string& text, const std::string& delimiters) + { + m_position = 0; + m_text = text; + for (std::string::size_type i = 0; i < delimiters.size(); ++i) + m_delimiters.set(static_cast(delimiters[i])); + } + + // 0x59E1F0: `token` is cleared first (std::string::clear). Delimiters are skipped; at the end of the text the answer + // is false and `token` stays empty. Otherwise the run up to the next delimiter (or the end) is + // copied out with substr and the answer is true. The position is left on the delimiter that + // ended the token, so the next call skips it. + bool nextToken(std::string& token) + { + token.clear(); + while (m_position < m_text.size() + && m_delimiters.test(static_cast(m_text[m_position]))) + ++m_position; + if (m_position >= m_text.size()) + return false; + const std::string::size_type start = m_position; + while (m_position < m_text.size() + && !m_delimiters.test(static_cast(m_text[m_position]))) + ++m_position; + token = m_text.substr(start, m_position - start); + return true; + } + +private: + std::string m_text; // retail +0x00 + std::bitset<256> m_delimiters; // retail +0x1C + std::string::size_type m_position; // retail +0x3C +}; + +} // namespace hfe +} // namespace dice + +#endif // CORE_STRINGTOKENIZER_H diff --git a/Code/BF2/Core/StringUtil.cpp b/Code/BF2/Core/StringUtil.cpp index 085535a4e..848a8c527 100644 --- a/Code/BF2/Core/StringUtil.cpp +++ b/Code/BF2/Core/StringUtil.cpp @@ -8,6 +8,7 @@ #include // vsnprintf / sprintf #include #include +#include "MsvcCrtCompat.h" // [CHOSEN, not recovered] _vsnwprintf/_swprintf outside MSVC #ifdef _MSC_VER # include @@ -20,6 +21,7 @@ namespace { // ELF 0x48BE30 (string), 0x48C420 (wstring); engine ELF 0x83D1510/0x83D1A40. +// PE 0x100757A0, 0x10075580: the wstring and string instantiations. template String extractFileExt_internal(const String& path) { @@ -31,6 +33,7 @@ String extractFileExt_internal(const String& path) } // ELF 0x48BEF0 (string), 0x48C4E0 (wstring); engine ELF 0x83D15B0/0x83D1AE0. +// PE 0x10075800, 0x10075600: the wstring and string instantiations. template String extractFileName_internal(const String& path) { @@ -42,6 +45,7 @@ String extractFileName_internal(const String& path) } // ELF 0x48BFB0 (string), 0x48C5A0 (wstring); engine ELF 0x83D1660/0x83D1B90. +// PE 0x10075870, 0x10075680: the wstring and string instantiations. template String extractFilePath_internal(const String& path, Char delimiter) { @@ -52,7 +56,8 @@ String extractFilePath_internal(const String& path, Char delimiter) return path.substr(0, last) + delimiter; } -// ELF 0x48C0A0 (string), 0x48C690 (wstring); engine ELF 0x83D1740/0x83D1C70. +// ELF 0x48C0A0 (string), 0x48C690 (wstring); engine ELF 0x83D1740/0x83D1C70; RendDX9.dll PE 0x10075970 (string). +// PE 0x100759E0: wstring. template String extractFileNameWithoutExt_internal(const String& path) { @@ -62,6 +67,7 @@ String extractFileNameWithoutExt_internal(const String& path) } // ELF 0x48C160 (string), 0x48C750 (wstring); engine ELF 0x83D17F0/0x83D1D20. +// PE 0x10075B50: wstring. template String extractEverythingExceptExt_internal(const String& path) { @@ -71,7 +77,8 @@ String extractEverythingExceptExt_internal(const String& path) return dot == -1 ? normalized : normalized.substr(0, dot); } -// ELF 0x48C230 (string), 0x48C820 (wstring); engine ELF 0x83D18A0/0x83D1DD0. +// ELF 0x48C230 (string), 0x48C820 (wstring); engine ELF 0x83D18A0/0x83D1DD0; RendDX9.dll PE 0x100752C0 (string). +// PE 0x10075350: wstring. template void fixPath_internal(String& path, Char delimiter) { @@ -84,6 +91,7 @@ void fixPath_internal(String& path, Char delimiter) } // ELF 0x48C2D0 (string), 0x48C8A0 (wstring); engine ELF 0x83D1920/0x83D1E50. +// PE 0x10075910: wstring. template void fixPathDelimiters_internal(String& path, Char delimiter) { @@ -94,6 +102,7 @@ void fixPathDelimiters_internal(String& path, Char delimiter) } // ELF 0x48C380 (string), 0x48C950 (wstring); engine ELF 0x83D19C0/0x83D1EF0. +// PE 0x10075AE0, 0x10075BE0: string and wstring instantiations. template String getFixPath_internal(const String& path, Char delimiter) { @@ -103,6 +112,7 @@ String getFixPath_internal(const String& path, Char delimiter) } // ELF 0x48C3D0 (string), 0x48C9A0 (wstring); engine ELF 0x83D1A00/0x83D1F30. +// PE 0x10075300, 0x10075390: string and wstring instantiations. template String getFixPathDelimiters_internal(const String& path, Char delimiter) { @@ -124,7 +134,7 @@ const std::string& getEmptyString() return empty; } -// ELF 0x48BA40. Converts wide text using the active C locale. The existing error check tests count + 1, +// ELF 0x48BA40; RendDX9.dll PE 0x10075430. Converts wide text using the active C locale. The existing error check tests count + 1, // so callers must not rely on it to reject every invalid conversion. std::string makeNarrow(const std::wstring& source) { @@ -155,7 +165,16 @@ std::wstring makeWide(const std::string& source) return result; } -// ELF 0x48A990. Formats into a shared 4-KB buffer and returns a string copy; not reentrant or thread-safe. +// Engine ELF 0x83D0340 (dice::hfe::stringToFloat(std::string const&): atof(c_str()), narrowed +// through fstps/flds); RendDX9.dll PE 0x1007B290 (atof on the SSO buffer or the heap pointer by +// capacity +0x18 >= 16, ST0 returned without a narrowing store: VC7.1 keeps the float return in +// the x87 register, the caller narrows at its store). +float stringToFloat(const std::string& s) +{ + return static_cast(std::atof(s.c_str())); +} + +// ELF 0x48A990; RendDX9.dll PE 0x10074AB0 (the same body over .data 0x10244AF8). Formats into a shared 4-KB buffer and returns a string copy; not reentrant or thread-safe. // A negative vsnprintf result replaces the message with a warning. Successful formatting writes // the terminator at the reported length. Preserve the original runtime-dependent overflow behavior. std::string formatString(const char* fmt, ...) @@ -199,6 +218,7 @@ std::wstring formatWstring(const wchar_t* fmt, ...) #if !DEDICATED // Client PE 431130, all 29 instructions read. Buffer 99C158 is shared, and // _vsnwprintf's -1 result replaces the whole message with the shipped warning. +// PE 0x10074B10: own buffer 0x10245AF8. std::wstring formatString(const wchar_t* fmt, ...) { static wchar_t buffer[4096]; @@ -222,6 +242,7 @@ int compareIgnoreCase(const char* a, const char* b) } // ELF 0x48ABD0. +// PE 0x10074B80 int compareIgnoreCase(const char* a, const char* b, int n) { if (n == 0) @@ -236,18 +257,20 @@ int compareIgnoreCase(const std::string& a, const std::string& b) } // ELF 0x48AB60. +// PE 0x10075040 int compareIgnoreCase(const std::string& a, const std::string& b, int n) { return compareIgnoreCase(a.c_str(), b.c_str(), n); } -// ELF 0x48AC10. +// ELF 0x48AC10; RendDX9.dll PE 0x10075080 (the compare inlined: `_stricmp` on the two c_str()s). bool equalsIgnoreCase(const std::string& a, const std::string& b) { return compareIgnoreCase(a, b) == 0; } // ELF 0x48AC50. +// PE 0x100750C0 bool equalsIgnoreCase(const std::string& a, const std::string& b, int n) { return compareIgnoreCase(a, b, n) == 0; @@ -263,7 +286,7 @@ std::string::size_type lowerCaseFind(const std::string& text, const std::string& return loweredText.find(loweredPattern); } -// ELF 0x48AD60; engine ELF 0x83D06B0. +// ELF 0x48AD60; engine ELF 0x83D06B0; RendDX9.dll PE 0x10074BA0. void eraseSubString(std::string& text, const std::string& pattern) { const std::string::size_type at = text.find(pattern); @@ -272,6 +295,7 @@ void eraseSubString(std::string& text, const std::string& pattern) } // ELF 0x48B9A0; engine ELF 0x83D10F0. Both images explicitly return the input pointer. +// PE 0x10074F60 std::string* replaceAll(std::string* text, const std::string& pattern, const std::string& replacement) { std::string::size_type at = 0; @@ -345,6 +369,7 @@ std::string getFixPathDelimiters(const std::string& s, char c) } // ELF 0x48B410. +// PE 0x100753E0: hidden-result wrapper over 0x10075AE0. std::string getFixPath(const std::string& s, char c) { return getFixPath_internal(s, c); @@ -355,6 +380,7 @@ void fixPath(std::wstring& s, wchar_t c) { fixPath_internal(s, c); } // ELF 0x48B630; engine ELF 0x83D0E00. void fixPathDelimiters(std::wstring& s, wchar_t c) { fixPathDelimiters_internal(s, c); } // ELF 0x48B660; engine ELF 0x83D0E10. +// PE 0x10075410: hidden-result wrapper over 0x10075BE0. std::wstring getFixPath(const std::wstring& s, wchar_t c) { return getFixPath_internal(s, c); } // ELF 0x48B6B0; engine ELF 0x83D0E40. std::wstring getFixPathDelimiters(const std::wstring& s, wchar_t c) { return getFixPathDelimiters_internal(s, c); } @@ -439,7 +465,7 @@ std::string getUpperCase(const std::string& s) return result; } -// ELF 0x48B220. +// ELF 0x48B220; RendDX9.dll PE 0x10074E80. std::string getLowerCase(const std::string& s) { std::string result(s); @@ -449,12 +475,14 @@ std::string getLowerCase(const std::string& s) // ELF 0x48B2E0. Returns the directory through the last slash of either kind, using delimiter for the trailing separator. // Returns an empty string when no separator exists. +// PE 0x100751A0: hidden-result wrapper over 0x10075680. std::string extractFilePath(const std::string& path, char delimiter) { return extractFilePath_internal(path, delimiter); } -// ELF 0x48B260. Returns text after the last dot, or empty for no dot/trailing dot. +// ELF 0x48B260; RendDX9.dll PE 0x10075180 (hidden-result wrapper over 0x10075580). Returns text +// after the last dot, or empty for no dot/trailing dot. // A preceding dot suppresses extensions only when the last dot is at index 2 or later: // ..x yields x, while a..x yields empty. std::string extractFileExt(const std::string& path) @@ -462,7 +490,7 @@ std::string extractFileExt(const std::string& path) return extractFileExt_internal(path); } -// ELF 0x48B870; engine ELF 0x83D0FD0. +// ELF 0x48B870; engine ELF 0x83D0FD0; RendDX9.dll PE 0x10074EC0 (the recursion is a loop there). void removeDoubleSlashes(std::string& path) { const std::string::size_type at = path.find("//"); @@ -474,7 +502,7 @@ void removeDoubleSlashes(std::string& path) } namespace { -// ELF 0x48B700; engine ELF 0x83D0E70. +// ELF 0x48B700; engine ELF 0x83D0E70; RendDX9.dll PE 0x10075220. void goUpInPath_worker(std::string& path) { removeDoubleSlashes(path); @@ -518,12 +546,13 @@ void goUpInPath(std::string& path) path.insert(0, "/"); } -// ELF 0x48B330. Returns the final path component without its last extension. Names without a dot remain unchanged. +// ELF 0x48B330; RendDX9.dll PE 0x100752B0 (hidden-result wrapper over 0x10075970). Returns the final path component without its last extension. Names without a dot remain unchanged. std::string extractFileNameWithoutExt(const std::string& path) { return extractFileNameWithoutExt_internal(path); } // ELF 0x48B2A0. Returns the component after the last slash of either kind. A trailing slash produces an empty name. +// PE 0x10075190: hidden-result wrapper over 0x10075600. std::string extractFileName(const std::string& path) { return extractFileName_internal(path); @@ -532,16 +561,22 @@ std::string extractFileName(const std::string& path) // ELF 0x48B370; engine ELF 0x83D0C30. std::string extractEverythingExceptExt(const std::string& path) { return extractEverythingExceptExt_internal(path); } // ELF 0x48B4B0; engine ELF 0x83D0D00. +// PE 0x100751D0: hidden-result wrapper over 0x100757A0. std::wstring extractFileExt(const std::wstring& path) { return extractFileExt_internal(path); } // ELF 0x48B4F0; engine ELF 0x83D0D30. +// PE 0x100751E0: hidden-result wrapper over 0x10075800. std::wstring extractFileName(const std::wstring& path) { return extractFileName_internal(path); } // ELF 0x48B530; engine ELF 0x83D0D60. +// PE 0x100751F0: hidden-result wrapper over 0x10075870. std::wstring extractFilePath(const std::wstring& path, wchar_t c) { return extractFilePath_internal(path, c); } // ELF 0x48B580; engine ELF 0x83D0D90. +// PE 0x10075340: hidden-result wrapper over 0x100759E0. std::wstring extractFileNameWithoutExt(const std::wstring& path) { return extractFileNameWithoutExt_internal(path); } // ELF 0x48B5C0; engine ELF 0x83D0DC0. +// PE 0x10075400: hidden-result wrapper over 0x10075B50. std::wstring extractEverythingExceptExt(const std::wstring& path) { return extractEverythingExceptExt_internal(path); } // Converts multibyte text to wide characters; failed conversion returns an empty string. +// PE 0x100754F0 std::wstring toWideString(const std::string& s) { const size_t count = mbstowcs(0, s.c_str(), 0) + 1; // + terminator; 0 on an invalid sequence diff --git a/Code/BF2/Core/StringUtil.h b/Code/BF2/Core/StringUtil.h index b29a1c2db..942829a8d 100644 --- a/Code/BF2/Core/StringUtil.h +++ b/Code/BF2/Core/StringUtil.h @@ -20,6 +20,9 @@ std::wstring formatString(const wchar_t* fmt, ...); // Converts multibyte text to wide characters, returning an empty string on failure. [INFERRED] Name. std::wstring toWideString(const std::string& s); +// atof over the text; no error reporting (unparsable text answers 0). +float stringToFloat(const std::string& s); + // Case-insensitive comparison // Four overloads exist. The (const char*, const char*) form is a straight strcasecmp; the // std::string forms null-terminate their operands first and then delegate to it. diff --git a/Code/BF2/Core/System.cpp b/Code/BF2/Core/System.cpp index ae1f0ac42..748ff6cbe 100644 --- a/Code/BF2/Core/System.cpp +++ b/Code/BF2/Core/System.cpp @@ -43,6 +43,12 @@ inline unsigned long long rdtsc() { #if defined(_WIN32) return __rdtsc(); +#elif defined(__aarch64__) + // [CHOSEN, not recovered] arm64 macOS port (untested): the generic timer's virtual count is + // the constant-rate counter that stands in for the TSC; callers calibrate its frequency. + unsigned long long count; + __asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(count)); + return count; #else unsigned int lo, hi; __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); diff --git a/Code/BF2/Core/WeakPtr.h b/Code/BF2/Core/WeakPtr.h index dfe7aa952..1314eec03 100644 --- a/Code/BF2/Core/WeakPtr.h +++ b/Code/BF2/Core/WeakPtr.h @@ -32,6 +32,7 @@ class WeakPtr releaseControl(m_ctrl); } + // PE 0x101326F0: the IPlayer specialization; the other retail copies are identical. WeakPtr& operator=(const WeakPtr& other) { // Both recovered assignment specializations retain the incoming block first. This also diff --git a/Code/BF2/External/BFMeme/Action.cpp b/Code/BF2/External/BFMeme/Action.cpp index 96191df85..769760650 100644 --- a/Code/BF2/External/BFMeme/Action.cpp +++ b/Code/BF2/External/BFMeme/Action.cpp @@ -12,6 +12,8 @@ TypeDescriptor* Action::getClassType() TypeDescriptor* Action::getType() { return getClassType(); } unsigned int Action::getObjectSize() { return sizeof(Action); } bool Action::execute(System*, const Rect*, const NodeState*, const NodeInputEvent*) { return false; } +#if defined(_M_IX86) static_assert(sizeof(Action) == 4, "BFMeme Action layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ActionListAction.cpp b/Code/BF2/External/BFMeme/ActionListAction.cpp index aa9563116..458646439 100644 --- a/Code/BF2/External/BFMeme/ActionListAction.cpp +++ b/Code/BF2/External/BFMeme/ActionListAction.cpp @@ -36,6 +36,8 @@ bool ActionListAction::execute(System* system, const Rect* bounds, const NodeSta } return false; } +#if defined(_M_IX86) static_assert(sizeof(ActionListAction) == 24, "client ActionListAction"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ActionNode.cpp b/Code/BF2/External/BFMeme/ActionNode.cpp index b8718e954..109fc91ae 100644 --- a/Code/BF2/External/BFMeme/ActionNode.cpp +++ b/Code/BF2/External/BFMeme/ActionNode.cpp @@ -31,7 +31,9 @@ class ActionNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return actionNodeInstances; } unsigned int getInstanceSize() override { return sizeof(ActionNode); } }; +#if defined(_M_IX86) static_assert(sizeof(ActionNodeTypeDescriptor) == 16, "ActionNode metadata storage"); +#endif } ActionNode::ActionNode() : m_action(nullptr) {} @@ -71,6 +73,8 @@ bool ActionNode::updateSelf(System* system, const NodeState* state, return true; } +#if defined(_M_IX86) static_assert(sizeof(ActionNode) == 12, "client BFMeme ActionNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp b/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp index bbe29c4f1..299d8d42f 100644 --- a/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp +++ b/Code/BF2/External/BFMeme/AlphaFadeEffect.cpp @@ -1,14 +1,21 @@ // Path [INFERRED]. All primary/metadata targets, eager/factory and differing // bodies read from the client PE before implementation. See the status document. #include "AlphaFadeEffect.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Node.h" #include "Quad.h" #include "TypeDescriptor.h" +#if !defined(_M_IX86) +#include +#include +#endif namespace dice { namespace meme { namespace { -int alphaFadeEffectInstances = 0; // A39FC0, loader-zeroed +int alphaFadeEffectInstances = 0; // A39FC0, loader-zeroed // Concrete descriptor spelling [INFERRED]; complete table94DCD8. class AlphaFadeEffectTypeDescriptor : public TypeDescriptor { @@ -31,6 +38,8 @@ class AlphaFadeEffectTypeDescriptor : public TypeDescriptor // native mulss does not reproduce that case. Both operands are loaded afresh. void multiplyAlpha(float* alpha, const float* factor) { +#if defined(_WIN32) +#if defined(_M_IX86) __asm { mov edx, factor mov eax, alpha @@ -38,6 +47,29 @@ void multiplyAlpha(float* alpha, const float* factor) fmul dword ptr [eax] fstp dword ptr [eax] } +#else + // [PLATFORM] x64: SSE2 arithmetic. The product of two floats is exact in double, so the + // single float rounding matches. The two-NaN case is selected explicitly: fld quiets the + // factor, and a quiet alpha NaN with a larger significand wins over it, as in x87. + const float first = *factor; + const float second = *alpha; + std::uint32_t firstBits, secondBits; + std::memcpy(&firstBits, &first, sizeof firstBits); + std::memcpy(&secondBits, &second, sizeof secondBits); + if ((firstBits & 0x7FFFFFFFu) > 0x7F800000u && (secondBits & 0x7FFFFFFFu) > 0x7F800000u) { + std::uint32_t result = firstBits | 0x00400000u; + if ((secondBits & 0x00400000u) && (secondBits & 0x007FFFFFu) > (result & 0x007FFFFFu)) + result = secondBits; + std::memcpy(alpha, &result, sizeof result); + return; + } + *alpha = static_cast(static_cast(first) * second); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + // [CHOSEN, not recovered] Preserve x87 load, two-NaN payload selection and float store. + *alpha = bf2x87::multiply(*factor, *alpha); +#endif } } @@ -53,7 +85,7 @@ namespace { TypeDescriptor* const registeredAlphaFadeEffectType = AlphaFadeEffect::getClassType(); } -bool AlphaFadeEffect::drawCharacter(System* system, int character, int font, +bool AlphaFadeEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // each component is read, multiplied and stored as float32 before @@ -62,7 +94,7 @@ bool AlphaFadeEffect::drawCharacter(System* system, int character, int font, multiplyAlpha(&corner.color.a, &context->field18); return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool AlphaFadeEffect::drawTexture(System* system, int texture, Quad* quad, +bool AlphaFadeEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { for (auto& corner : quad->corners) @@ -70,6 +102,8 @@ bool AlphaFadeEffect::drawTexture(System* system, int texture, Quad* quad, return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(AlphaFadeEffect) == 4, "Native x86 AlphaFadeEffect allocation"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/AlphaFadeEffect.h b/Code/BF2/External/BFMeme/AlphaFadeEffect.h index 6e1c7ea2f..d4ecaf24e 100644 --- a/Code/BF2/External/BFMeme/AlphaFadeEffect.h +++ b/Code/BF2/External/BFMeme/AlphaFadeEffect.h @@ -11,9 +11,9 @@ class AlphaFadeEffect : public Effect // Inlined83581E/79DD40 construction installs only the primary; no fields. AlphaFadeEffect() = default; TypeDescriptor* getType() override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; // +4C 834F10 - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); }; } } diff --git a/Code/BF2/External/BFMeme/AndData.cpp b/Code/BF2/External/BFMeme/AndData.cpp index 076f196af..47bc039d7 100644 --- a/Code/BF2/External/BFMeme/AndData.cpp +++ b/Code/BF2/External/BFMeme/AndData.cpp @@ -27,7 +27,9 @@ float AndData::getFloat(System* system) return m_second->getFloat(system) != 0.0f ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(AndData) == 16, "client BFMeme AndData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "AndData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/BlendFuncEffect.cpp b/Code/BF2/External/BFMeme/BlendFuncEffect.cpp index ef5d5d7b4..ef433a192 100644 --- a/Code/BF2/External/BFMeme/BlendFuncEffect.cpp +++ b/Code/BF2/External/BFMeme/BlendFuncEffect.cpp @@ -54,7 +54,7 @@ bool BlendFuncEffect::streamProperties(System* system, Stream* stream) "Destination blend func"); } -bool BlendFuncEffect::drawCharacter(System* system, int character, int font, +bool BlendFuncEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // Both words are stamped before the chain continues; retail inlines @@ -63,7 +63,7 @@ bool BlendFuncEffect::drawCharacter(System* system, int character, int font, quad->state0c = m_destination; return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool BlendFuncEffect::drawTexture(System* system, int texture, Quad* quad, +bool BlendFuncEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { quad->state08 = m_source; @@ -71,6 +71,8 @@ bool BlendFuncEffect::drawTexture(System* system, int texture, Quad* quad, return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(BlendFuncEffect) == 12, "PE BlendFuncEffect allocation"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/BlendFuncEffect.h b/Code/BF2/External/BFMeme/BlendFuncEffect.h index fb709c417..076d882de 100644 --- a/Code/BF2/External/BFMeme/BlendFuncEffect.h +++ b/Code/BF2/External/BFMeme/BlendFuncEffect.h @@ -24,9 +24,9 @@ class BlendFuncEffect : public Effect TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); // 8396E0, metadata94EB38 protected: // Both are written straight into the quad's two state words; the class diff --git a/Code/BF2/External/BFMeme/BoolData.cpp b/Code/BF2/External/BFMeme/BoolData.cpp index a5b7d8fdd..1ca27b93a 100644 --- a/Code/BF2/External/BFMeme/BoolData.cpp +++ b/Code/BF2/External/BFMeme/BoolData.cpp @@ -50,7 +50,9 @@ int BoolData::getCharacter(System*, int character) return (value ? "true" : "false")[character]; } +#if defined(_M_IX86) static_assert(sizeof(BoolData) == 12, "client BFMeme BoolData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "BoolData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/CallFunctionAction.cpp b/Code/BF2/External/BFMeme/CallFunctionAction.cpp index 93f3f40e9..96a486765 100644 --- a/Code/BF2/External/BFMeme/CallFunctionAction.cpp +++ b/Code/BF2/External/BFMeme/CallFunctionAction.cpp @@ -32,6 +32,8 @@ bool CallFunctionAction::execute(System* system, const Rect*, const NodeState*, if (!m_function) return false; return m_function->call(system); } +#if defined(_M_IX86) static_assert(sizeof(CallFunctionAction) == 8, "client CallFunctionAction"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ClassIStream.cpp b/Code/BF2/External/BFMeme/ClassIStream.cpp index 7ea2117d7..216571d4f 100644 --- a/Code/BF2/External/BFMeme/ClassIStream.cpp +++ b/Code/BF2/External/BFMeme/ClassIStream.cpp @@ -30,8 +30,8 @@ bool ForwardingIStream::streamInt(int* p, const char* label) { return m_input->s bool ForwardingIStream::streamString(char** p, const char* label) { return m_input->streamString(p,label); } bool ForwardingIStream::streamWideString(wchar_t** p, const char* label) { return m_input->streamWideString(p,label); } bool ForwardingIStream::streamCharacter(wchar_t* p, const char* label) { return m_input->streamCharacter(p,label); } -bool ForwardingIStream::streamTexture(System* s, int* p, const char* label) { return m_input->streamTexture(s,p,label); } -bool ForwardingIStream::streamFont(System* s, int* p, const char* label) { return m_input->streamFont(s,p,label); } +bool ForwardingIStream::streamTexture(System* s, TextureHandle* p, const char* label) { return m_input->streamTexture(s,p,label); } +bool ForwardingIStream::streamFont(System* s, FontHandle* p, const char* label) { return m_input->streamFont(s,p,label); } bool ForwardingIStream::streamSound(System* s, int* p, const char* label) { return m_input->streamSound(s,p,label); } bool ForwardingIStream::streamCollection(System* s, ObjectCollection* p, const char* label) { return m_input->streamCollection(s,p,label); } bool ForwardingIStream::streamEnum(int* p, EnumNext next, EnumName name, const char* label) { return m_input->streamEnum(p,next,name,label); } @@ -49,6 +49,14 @@ ClassIStream::~ClassIStream() char** entry = m_strings; while (*entry) { ::operator delete(*entry); *entry++ = nullptr; } } +// 83C2B0: guarded "dice::meme::ClassIStream" descriptor; base slot 83C1D0 jumps to IStream's +// getter, factory 83C1E0 allocates 0x814 bytes and runs ClassIStream(nullptr) inline. +TypeDescriptor* ClassIStream::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::ClassIStream"); + return &type; +} +TypeDescriptor* ClassIStream::getType() { return getClassType(); } unsigned int ClassIStream::getObjectSize() { return sizeof(ClassIStream); } bool ClassIStream::init(System* system) { @@ -188,7 +196,9 @@ bool readObject(System* system, Object*& value, IStream* input) + static_cast(start))); // Return ignored; signed backward skip is possible. return true; } +#if defined(_M_IX86) static_assert(sizeof(ForwardingIStream) == 16, "forwarding input layout"); static_assert(sizeof(ClassIStream) == 0x814, "class input dictionary layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ClassIStream.h b/Code/BF2/External/BFMeme/ClassIStream.h index 9a33a6d1b..70ecc68c6 100644 --- a/Code/BF2/External/BFMeme/ClassIStream.h +++ b/Code/BF2/External/BFMeme/ClassIStream.h @@ -21,8 +21,8 @@ class ForwardingIStream : public IStream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamCollection(System*, ObjectCollection*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; @@ -40,15 +40,16 @@ class ForwardingIStream : public IStream class ClassIStream : public ForwardingIStream { public: - explicit ClassIStream(IStream* input); // 83BFF0, owns input + // 83BFF0, owns input. The descriptor factory 83C1E0 inlines the same body with a null input. + explicit ClassIStream(IStream* input = nullptr); ~ClassIStream() override; - TypeDescriptor* getType() override; // 83C2B0 [FRONTIER] factory closure + TypeDescriptor* getType() override; // 83C2B0, descriptor table 94F2BC unsigned int getObjectSize() override; int getPosition() override; // 83C140, relative to payload bool setPosition(int) override; bool readShortString(System*, char*, int, const char*) override; bool init(System*); - static TypeDescriptor* getClassType(); // [FRONTIER] no partial publication + static TypeDescriptor* getClassType(); // 83C2B0, base slot 83C1D0 -> IStream private: int m_payloadStart; // +10 char* m_strings[512]; // +14, only first null initialized diff --git a/Code/BF2/External/BFMeme/ClassOStream.cpp b/Code/BF2/External/BFMeme/ClassOStream.cpp index b062b26dd..c35bcd7ae 100644 --- a/Code/BF2/External/BFMeme/ClassOStream.cpp +++ b/Code/BF2/External/BFMeme/ClassOStream.cpp @@ -21,8 +21,8 @@ bool ForwardingOStream::streamInt(int* p, const char* label) { return m_destinat bool ForwardingOStream::streamString(char** p, const char* label) { return m_destination->streamString(p,label); } bool ForwardingOStream::streamWideString(wchar_t** p, const char* label) { return m_destination->streamWideString(p,label); } bool ForwardingOStream::streamCharacter(wchar_t* p, const char* label) { return m_destination->streamCharacter(p,label); } -bool ForwardingOStream::streamTexture(System* s, int* p, const char* label) { return m_destination->streamTexture(s,p,label); } -bool ForwardingOStream::streamFont(System* s, int* p, const char* label) { return m_destination->streamFont(s,p,label); } +bool ForwardingOStream::streamTexture(System* s, TextureHandle* p, const char* label) { return m_destination->streamTexture(s,p,label); } +bool ForwardingOStream::streamFont(System* s, FontHandle* p, const char* label) { return m_destination->streamFont(s,p,label); } bool ForwardingOStream::streamSound(System* s, int* p, const char* label) { return m_destination->streamSound(s,p,label); } bool ForwardingOStream::streamEnum(int* p, EnumNext next, EnumName name, const char* label) { return m_destination->streamEnum(p,next,name,label); } int ForwardingOStream::write(const void* p, int count) { return m_destination->write(p,count); } @@ -116,8 +116,10 @@ bool saveNamedObject(System* system, Object*& value) } return true; } +#if defined(_M_IX86) static_assert(sizeof(ForwardingOStream) == 8, "forwarding stream layout"); static_assert(sizeof(MemoryOStream) == 16, "memory stream layout"); static_assert(sizeof(ClassOStream) == 0x81C, "class output dictionary layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ClassOStream.h b/Code/BF2/External/BFMeme/ClassOStream.h index d241de7a1..6919ac70d 100644 --- a/Code/BF2/External/BFMeme/ClassOStream.h +++ b/Code/BF2/External/BFMeme/ClassOStream.h @@ -21,8 +21,8 @@ class ForwardingOStream : public OStream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; int write(const void*, int) override; diff --git a/Code/BF2/External/BFMeme/ColorEffect.cpp b/Code/BF2/External/BFMeme/ColorEffect.cpp index 80d5ebd30..51019e52a 100644 --- a/Code/BF2/External/BFMeme/ColorEffect.cpp +++ b/Code/BF2/External/BFMeme/ColorEffect.cpp @@ -22,18 +22,20 @@ bool ColorEffect::streamProperties(System* system, Stream* stream) && stream->streamFloat(&m_color.b, "Blue") && stream->streamFloat(&m_color.a, "Alpha"); } -bool ColorEffect::drawCharacter(System* system, int character, int font, +bool ColorEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { for (auto& corner : quad->corners) corner.color = m_color; return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool ColorEffect::drawTexture(System* system, int texture, Quad* quad, RenderContext* context) +bool ColorEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { for (auto& corner : quad->corners) corner.color = m_color; return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(ColorEffect) == 20, "Native x86 ColorEffect layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ColorEffect.h b/Code/BF2/External/BFMeme/ColorEffect.h index 8e794bf9b..e0a7110fa 100644 --- a/Code/BF2/External/BFMeme/ColorEffect.h +++ b/Code/BF2/External/BFMeme/ColorEffect.h @@ -14,9 +14,9 @@ class ColorEffect : public Effect { unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; Color* getColor() override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); private: Color m_color; diff --git a/Code/BF2/External/BFMeme/CullNode.cpp b/Code/BF2/External/BFMeme/CullNode.cpp index d4e4ce0fa..1ad3028ba 100644 --- a/Code/BF2/External/BFMeme/CullNode.cpp +++ b/Code/BF2/External/BFMeme/CullNode.cpp @@ -3,6 +3,9 @@ // 33-slot prefix uses the owner-approved startup exception; inherited // event/reset suffix calls still stop at their known Node callers. #include "CullNode.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Data.h" #include "Stream.h" @@ -31,13 +34,17 @@ class CullNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return cullNodeInstances; } unsigned int getInstanceSize() override { return sizeof(CullNode); } }; +#if defined(_M_IX86) static_assert(sizeof(CullNodeTypeDescriptor) == 16, "CullNode metadata storage"); +#endif // 835F25..835F45 and835F69..835F82 store the rounded float before comparing // the still-extended x87 result. Keep that order, including unordered results // and the sign of values that round to zero. Helper names are [INFERRED]. float decreaseFade(float current, float delta, float duration) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; const float zero = 0.0f; __asm { @@ -53,9 +60,25 @@ float decreaseFade(float current, float delta, float duration) decreased: } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered negative unrounded result is replaced by +0. + const double unrounded = static_cast(current) - static_cast(delta) / duration; + return unrounded < 0.0 ? 0.0f : static_cast(unrounded); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + const float zero = 0.0f; + // [CHOSEN, not recovered] Preserve x87 fade decrease. + result = bf2x87::fade(current, delta, duration, false); + return result; +#endif } float increaseFade(float current, float delta, float duration) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; const float one = 1.0f; __asm { @@ -71,6 +94,20 @@ float increaseFade(float current, float delta, float duration) increased: } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered unrounded result above one is clamped; equal and unordered keep it. + const double unrounded = static_cast(delta) / duration + current; + return unrounded > 1.0 ? 1.0f : static_cast(unrounded); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + const float one = 1.0f; + // [CHOSEN, not recovered] Preserve x87 fade increase. + result = bf2x87::fade(current, delta, duration, true); + return result; +#endif } } @@ -142,6 +179,8 @@ bool CullNode::update(System* system, const NodeState* state, return true; } +#if defined(_M_IX86) static_assert(sizeof(CullNode) == 24, "client BFMeme CullNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/CullVariableActionNode.cpp b/Code/BF2/External/BFMeme/CullVariableActionNode.cpp index 4e28e8111..5fb546620 100644 --- a/Code/BF2/External/BFMeme/CullVariableActionNode.cpp +++ b/Code/BF2/External/BFMeme/CullVariableActionNode.cpp @@ -31,7 +31,9 @@ class CullVariableActionNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return cullVariableActionNodeInstances; } unsigned int getInstanceSize() override { return sizeof(CullVariableActionNode); } }; +#if defined(_M_IX86) static_assert(sizeof(CullVariableActionNodeTypeDescriptor) == 16, "CullVariableActionNode metadata storage"); +#endif } CullVariableActionNode::CullVariableActionNode() : m_variable(nullptr) {} @@ -65,6 +67,8 @@ bool CullVariableActionNode::dispatchEvent(System* system, const Rect* bounds, return m_action->execute(system, bounds, state, event); } +#if defined(_M_IX86) static_assert(sizeof(CullVariableActionNode) == 16, "client BFMeme CullVariableActionNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Data.cpp b/Code/BF2/External/BFMeme/Data.cpp index b6cf76036..323d2d50a 100644 --- a/Code/BF2/External/BFMeme/Data.cpp +++ b/Code/BF2/External/BFMeme/Data.cpp @@ -1,5 +1,11 @@ // All instructions read from BF2.exe. No matching dedicated ELF Data class. +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "Data.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "DataFormatting.h" #include "TypeDescriptor.h" @@ -9,6 +15,9 @@ #include #include #include +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace meme { namespace { char* cloneName(const char* name) @@ -40,12 +49,14 @@ class StringDataTypeDescriptor : public ClassTypeDescriptor // Whole and fractional conversions use different integer widths and overflow behavior. void formatStringDataFloat(float value, char* output, int digits) { +#if defined(_WIN32) double magnitude = value; char* cursor = output; if (value < 0.0f) { *cursor++ = '-'; magnitude = -magnitude; } +#if defined(_M_IX86) unsigned short oldControl, truncControl; __int64 whole; int integral; @@ -63,6 +74,11 @@ void formatStringDataFloat(float value, char* output, int digits) mov eax, dword ptr whole mov integral, eax } +#else + // cvttsd2si truncates like the chopped fistp and yields the same integer-indefinite + // value for NaN and out-of-range input; the low dword is kept, as above. + const int integral = static_cast(_mm_cvttsd_si64(_mm_set_sd(magnitude))); +#endif int remaining = integral; if (remaining == 0) { *cursor++ = '0'; @@ -76,6 +92,7 @@ void formatStringDataFloat(float value, char* output, int digits) while (length != 0) *cursor++ = reverse[--length]; } *cursor++ = '.'; +#if defined(_M_IX86) const double ten = 10.0; int digit; __asm { @@ -99,7 +116,54 @@ void formatStringDataFloat(float value, char* output, int digits) fstp st(0) mov cursor, edi } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // The dec/jnz counter is unsigned: a nonpositive digit count runs 2^32 times, as shipped. + { + double fraction = magnitude - static_cast(integral); + unsigned int count = static_cast(digits); + do { + fraction *= 10.0; + const int digit = _mm_cvttsd_si32(_mm_set_sd(fraction)); + *cursor++ = static_cast(static_cast(digit) + 0x30); + fraction -= static_cast(digit); + } while (--count != 0); + } +#endif *cursor = 0; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + double magnitude = value; + char* cursor = output; + if (value < 0.0f) { + *cursor++ = '-'; + magnitude = -magnitude; + } + unsigned short oldControl, truncControl; + __int64 whole; + int integral; + // [CHOSEN, not recovered] Preserve x87 truncating int64 conversion and low dword. + whole = bf2x87::integer(bf2x87::wide(magnitude)); + integral = bf2x87::lowWord(whole); + int remaining = integral; + if (remaining == 0) { + *cursor++ = '0'; + } else { + char reverse[32]; + int length = 0; + do { + reverse[length++] = static_cast(remaining % 10 + '0'); + remaining /= 10; // signed idiv; overflow-derived negative digits stay negative + } while (remaining != 0); + while (length != 0) *cursor++ = reverse[--length]; + } + *cursor++ = '.'; + const double ten = 10.0; + int digit; + // [CHOSEN, not recovered] Preserve x87 retained fractional remainder. + bf2x87::fractionalDigits(magnitude, integral, digits, cursor); + *cursor = 0; +#endif } // Plain sprintf through literal89E620 ("%i"); no width, precision or @@ -280,8 +344,17 @@ bool BoolRefData::bind(System*, bool* value) namespace { // the wide-character allocation, widening copy and // clone the wide reference class uses. Names [INFERRED]. +#if defined(_WIN32) wchar_t* allocateWide(unsigned int characters) { return static_cast(::operator new(characters * 2)); } +#else +// [CHOSEN, not recovered] The shipped `characters * 2` is the byte size of a 16-bit +// Windows wchar_t. POSIX wchar_t is 32 bits, so the same character count needs +// sizeof(wchar_t) bytes each; `* 2` made every clone/widen write past its allocation +// (docs/macos-c-asan-heap.md). +wchar_t* allocateWide(unsigned int characters) +{ return static_cast(::operator new(characters * sizeof(wchar_t))); } +#endif void widenInto(wchar_t* output, const char* text) { while (*text) *output++ = static_cast(*text++); @@ -446,7 +519,11 @@ bool IntRefData::setFloat(System*, float value) { // Round half away from zero, then the ordinary truncating x86 cast // (fnstcw / or 0C00h / fistp / fldcw). A NaN takes the negative arm. +#if defined(__APPLE__) + *m_value = bf2x87::toIntTruncate(value < 0.0f ? value - 0.5f : value + 0.5f); +#else *m_value = static_cast(value < 0.0f ? value - 0.5f : value + 0.5f); +#endif return true; } bool IntRefData::setString(System* system, const char* value) // 82E110, shared body diff --git a/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp b/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp index d5d525f6f..83dd8c3e5 100644 --- a/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp +++ b/Code/BF2/External/BFMeme/DynamicIndexPointer.cpp @@ -59,6 +59,8 @@ bool DynamicIndexPointer::event2(System* system, int first, int index) system->enqueueEvent(2, mapped, static_cast(first), 0.0f, 0); return true; } +#if defined(_M_IX86) static_assert(sizeof(DynamicIndexPointer) == 60, "client DynamicIndexPointer native layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Effect.cpp b/Code/BF2/External/BFMeme/Effect.cpp index c700df836..04087e8c9 100644 --- a/Code/BF2/External/BFMeme/Effect.cpp +++ b/Code/BF2/External/BFMeme/Effect.cpp @@ -26,33 +26,35 @@ bool updateEffect(System* system, Effect* effect, float delta) } bool drawContextCharacter(RenderContext* context, System* system, int character, - int font, int elementIndex, Quad* quad) + FontHandle font, int elementIndex, Quad* quad) { while (context && !context->effect) context = context->parent; if (!context) return system->drawCharacter(character, font, quad); return context->effect->drawCharacter(system, character, font, elementIndex, quad, context); } -bool drawContextTexture(RenderContext* context, System* system, int texture, +bool drawContextTexture(RenderContext* context, System* system, TextureHandle texture, Quad* quad) { while (context && !context->effect) context = context->parent; if (!context) return system->drawTexture(texture, quad); return context->effect->drawTexture(system, texture, quad, context); } -bool Effect::drawCharacter(System* system, int character, int font, int elementIndex, +bool Effect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // Retail requires a context and dereferences it even when its parent is null. return drawContextCharacter(context->parent, system, character, font, elementIndex, quad); } -bool Effect::drawTexture(System* system, int texture, Quad* quad, +bool Effect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { return drawContextTexture(context->parent, system, texture, quad); } TypeDescriptor* getEffectClassType() { return Effect::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(Effect) == 4, "PE Effect allocation"); static_assert(sizeof(RenderContext) == 28, "seven-word Effect context"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Effect.h b/Code/BF2/External/BFMeme/Effect.h index 767ad32ca..0ac378bde 100644 --- a/Code/BF2/External/BFMeme/Effect.h +++ b/Code/BF2/External/BFMeme/Effect.h @@ -19,17 +19,17 @@ class Effect : public Object virtual bool setColor(float r, float g, float b, float a); virtual Color* getColor(); virtual bool update(System*, float delta); - virtual bool drawCharacter(System*, int character, int font, int elementIndex, + virtual bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*); // +4C 82D810 - virtual bool drawTexture(System*, int texture, Quad*, RenderContext*); + virtual bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*); static TypeDescriptor* getClassType(); // 82D860, factory82D8A0 }; // Named free-function spellings are [INFERRED]. Retail82D730/82D790 use ECX // for context; all callers here are rebuilt together using these typed helpers. -bool drawContextCharacter(RenderContext*, System*, int character, int font, +bool drawContextCharacter(RenderContext*, System*, int character, FontHandle font, int elementIndex, Quad*); -bool drawContextTexture(RenderContext*, System*, int texture, Quad*); +bool drawContextTexture(RenderContext*, System*, TextureHandle texture, Quad*); bool updateEffect(System*, Effect*, float delta); TypeDescriptor* getEffectClassType(); // 82D860, Stream adapter } } diff --git a/Code/BF2/External/BFMeme/EffectNode.cpp b/Code/BF2/External/BFMeme/EffectNode.cpp index ac0a2d97a..dc7941bc6 100644 --- a/Code/BF2/External/BFMeme/EffectNode.cpp +++ b/Code/BF2/External/BFMeme/EffectNode.cpp @@ -30,7 +30,9 @@ class EffectNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return effectNodeInstances; } unsigned int getInstanceSize() override { return sizeof(EffectNode); } }; +#if defined(_M_IX86) static_assert(sizeof(EffectNodeTypeDescriptor) == 16, "EffectNode metadata storage"); +#endif } EffectNode::EffectNode(Effect* effect) : Node(), m_effect(effect) {} @@ -82,6 +84,8 @@ bool EffectNode::updateSelf(System* system, const NodeState*, const Rect*, float return updateEffect(system, m_effect, delta); } +#if defined(_M_IX86) static_assert(sizeof(EffectNode) == 12, "client BFMeme EffectNode"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/EqualData.cpp b/Code/BF2/External/BFMeme/EqualData.cpp index 935886754..8a440d344 100644 --- a/Code/BF2/External/BFMeme/EqualData.cpp +++ b/Code/BF2/External/BFMeme/EqualData.cpp @@ -28,7 +28,9 @@ float EqualData::getFloat(System* system) return firstValue == second->getFloat(system) ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(EqualData) == 16, "client BFMeme EqualData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "EqualData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Event.cpp b/Code/BF2/External/BFMeme/Event.cpp index 89fd1cc60..9c8f56ec4 100644 --- a/Code/BF2/External/BFMeme/Event.cpp +++ b/Code/BF2/External/BFMeme/Event.cpp @@ -20,6 +20,8 @@ bool Event::streamProperties(System* system, Stream* stream) } bool Event::matches(System*, const NodeInputEvent* input) // 83AED0, null input not guarded. { return m_inputIndex == 0 || input->index == m_inputIndex; } +#if defined(_M_IX86) static_assert(sizeof(Event) == 8, "BFMeme Event layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/EventQueue.cpp b/Code/BF2/External/BFMeme/EventQueue.cpp index e18f0dca9..c4f7968b4 100644 --- a/Code/BF2/External/BFMeme/EventQueue.cpp +++ b/Code/BF2/External/BFMeme/EventQueue.cpp @@ -140,7 +140,9 @@ bool EventQueue::process(System* system) m_last = nullptr; return true; } +#if defined(_M_IX86) static_assert(sizeof(QueuedEvent) == 24, "client queue record"); static_assert(sizeof(EventQueue) == 12, "client queue owner"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/FileIStream.cpp b/Code/BF2/External/BFMeme/FileIStream.cpp index d475e3348..6a16a3960 100644 --- a/Code/BF2/External/BFMeme/FileIStream.cpp +++ b/Code/BF2/External/BFMeme/FileIStream.cpp @@ -30,6 +30,8 @@ int FileIStream::read(void* buffer, int bytes) int FileIStream::getPosition() { return m_memory->getPosition(); } bool FileIStream::setPosition(int position) { return static_cast(m_memory->seek(hfe::io::SEEKORIGIN_BEGIN, position)) != 0; } +#if defined(_M_IX86) static_assert(sizeof(FileIStream) == 12, "client file-input visitor layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/FileOStream.cpp b/Code/BF2/External/BFMeme/FileOStream.cpp index d55dcb12c..b156baa0b 100644 --- a/Code/BF2/External/BFMeme/FileOStream.cpp +++ b/Code/BF2/External/BFMeme/FileOStream.cpp @@ -17,6 +17,8 @@ int FileOStream::write(const void* buffer, int bytes) int FileOStream::getPosition() { return m_file->getPosition(); } bool FileOStream::setPosition(int position) { return static_cast(m_file->seek(hfe::io::SEEKORIGIN_BEGIN, position)) != 0; } +#if defined(_M_IX86) static_assert(sizeof(FileOStream) == 8, "client file-output stream layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/FloatData.cpp b/Code/BF2/External/BFMeme/FloatData.cpp index 9c38646e3..8ecd7908a 100644 --- a/Code/BF2/External/BFMeme/FloatData.cpp +++ b/Code/BF2/External/BFMeme/FloatData.cpp @@ -61,7 +61,9 @@ int FloatData::getCharacter(System*, int character) return static_cast(m_text[character]); } +#if defined(_M_IX86) static_assert(sizeof(FloatData) == 20, "client BFMeme FloatData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "FloatData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Function.cpp b/Code/BF2/External/BFMeme/Function.cpp index 8b779c737..1745bc776 100644 --- a/Code/BF2/External/BFMeme/Function.cpp +++ b/Code/BF2/External/BFMeme/Function.cpp @@ -37,6 +37,8 @@ bool Function::call(System* system) if (m_name) systemPrintf(system, "Meme: FunctionCall: %s\r\n", m_name); return true; } +#if defined(_M_IX86) static_assert(sizeof(Function) == 8, "BFMeme Function layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/IStream.cpp b/Code/BF2/External/BFMeme/IStream.cpp index 31b104b63..06b46bc93 100644 --- a/Code/BF2/External/BFMeme/IStream.cpp +++ b/Code/BF2/External/BFMeme/IStream.cpp @@ -2,7 +2,12 @@ #include "IStream.h" #if !DEDICATED #include "System.h" +#include "TypeDescriptor.h" #include +#if !defined(_WIN32) +#include +#include +#endif namespace dice { namespace meme { namespace { // [INFERRED] Factored identical resource-name read sequences839E00/839EB0/839F60. @@ -17,6 +22,15 @@ bool readResourceName(IStream* input, char* name) } IStream::IStream(IStream* source) : m_source(source ? source : this) {} IStream::~IStream() {} // 794CA0, borrowed source is not deleted +// 83A160 is both the +04 slot and the class getter: a guarded "dice::meme::IStream" descriptor +// whose base slot jumps to RuntimeObject's (82B9E0) and whose factory 83A1C0 builds a +// self-sourced eight-byte IStream. +TypeDescriptor* IStream::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::IStream"); + return &type; +} +TypeDescriptor* IStream::getType() { return getClassType(); } unsigned int IStream::getObjectSize() { return sizeof(IStream); } IStream* IStream::getSource() // 839B60; repeated forwarding, no cycle/null guard { @@ -28,8 +42,28 @@ bool IStream::streamUByte(unsigned char* value, const char*) { return getSource( bool IStream::streamByte(char* value, const char*) { return getSource()->read(value, 1) == 1; } bool IStream::streamUShort(unsigned short* value, const char*) { return getSource()->read(value, 2) == 2; } bool IStream::streamShort(short* value, const char*) { return getSource()->read(value, 2) == 2; } +#if defined(_WIN32) bool IStream::streamULong(unsigned long* value, const char*) { return getSource()->read(value, 4) == 4; } bool IStream::streamLong(long* value, const char*) { return getSource()->read(value, 4) == 4; } +#else +// [CHOSEN, not recovered] The wire Long is 32 bits (Windows long). LP64 long is 64 bits, so +// reading 4 bytes into it left the upper half uninitialized: readObject's frame end and its +// "reading differs" check used garbage. Read the 32-bit value and sign/zero-extend it. +bool IStream::streamULong(unsigned long* value, const char*) +{ + std::uint32_t wire; + if (getSource()->read(&wire, 4) != 4) return false; + *value = wire; + return true; +} +bool IStream::streamLong(long* value, const char*) +{ + std::int32_t wire; + if (getSource()->read(&wire, 4) != 4) return false; + *value = wire; + return true; +} +#endif bool IStream::streamFloat(float* value, const char*) { return getSource()->read(value, 4) == 4; } bool IStream::streamBool(bool* value, const char* label) // 839C10, clear before attempted read { @@ -64,9 +98,23 @@ bool IStream::streamWideString(wchar_t** value, const char*) int length; if (!getSource()->streamInt(&length, "Int")) return false; if (length) { +#if defined(_WIN32) *value = static_cast(::operator new((static_cast(length) + 1) * 2)); if (getSource()->read(*value, 2 * length) != 2 * length) return false; (*value)[length] = 0; +#else + // [CHOSEN, not recovered] The wire holds `length` 16-bit Windows wchar_t units + // (UTF-16LE); POSIX wchar_t is 32 bits. Allocate native characters, read the units + // separately and widen each one, so the count and terminator index stay the shipped + // ones. No surrogate pairing: one unit stays one character, as in the Windows buffer. + const unsigned int count = static_cast(length); + *value = static_cast(::operator new((count + 1) * sizeof(wchar_t))); + std::vector units(2u * count); + if (getSource()->read(units.data(), 2 * length) != 2 * length) return false; + for (unsigned int i = 0; i < count; ++i) + (*value)[i] = static_cast(units[2 * i] | (units[2 * i + 1] << 8)); + (*value)[length] = 0; +#endif } return true; } @@ -77,7 +125,7 @@ bool IStream::streamCharacter(wchar_t* value, const char* label) // 839DC0, wire *value = static_cast(temporary); return true; } -bool IStream::streamTexture(System* system, int* texture, const char*) +bool IStream::streamTexture(System* system, TextureHandle* texture, const char*) { *texture = 0; char name[256]; @@ -85,7 +133,7 @@ bool IStream::streamTexture(System* system, int* texture, const char*) *texture = system->loadTexture(name, true); return true; } -bool IStream::streamFont(System* system, int* font, const char*) +bool IStream::streamFont(System* system, FontHandle* font, const char*) { *font = 0; char name[256]; @@ -123,6 +171,8 @@ bool IStream::readShortString(System*, char* buffer, int capacity, const char*) buffer[length] = 0; // equality is allowed above: caller needs space for the terminator return true; } +#if defined(_M_IX86) static_assert(sizeof(IStream) == 8, "BFMeme input stream layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/IStream.h b/Code/BF2/External/BFMeme/IStream.h index bdca54e6f..517b6714e 100644 --- a/Code/BF2/External/BFMeme/IStream.h +++ b/Code/BF2/External/BFMeme/IStream.h @@ -12,7 +12,7 @@ class IStream : public Stream public: explicit IStream(IStream* source = nullptr); // 83A1A0, null source means self ~IStream() override; - TypeDescriptor* getType() override; // 83A160 [FRONTIER] + TypeDescriptor* getType() override; // 83A160, descriptor table 94EC00 unsigned int getObjectSize() override; bool streamUByte(unsigned char*, const char*) override; bool streamByte(char*, const char*) override; @@ -26,8 +26,8 @@ class IStream : public Stream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamCollection(System*, ObjectCollection*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; @@ -39,7 +39,7 @@ class IStream : public Stream virtual bool setPosition(int); // +9C 455400 virtual bool readShortString(System*, char*, int capacity, const char*); // +A0 83A0A0 IStream* getSource(); // 839B60, follows self-terminated chain - static TypeDescriptor* getClassType(); // [FRONTIER] no partial publication + static TypeDescriptor* getClassType(); // 83A160; factory 83A1C0 inlines IStream(nullptr) private: IStream* m_source; // +4 borrowed; destructor does not free }; diff --git a/Code/BF2/External/BFMeme/InputNodeVisitors.cpp b/Code/BF2/External/BFMeme/InputNodeVisitors.cpp index c2e70fba7..6a3d2d0ed 100644 --- a/Code/BF2/External/BFMeme/InputNodeVisitors.cpp +++ b/Code/BF2/External/BFMeme/InputNodeVisitors.cpp @@ -80,11 +80,13 @@ void ReleaseStateNodeVisitor::visit(System* system, Node*& node, const Rect* rec node->visitChildren(system, state, rect, this); } } +#if defined(_M_IX86) static_assert(sizeof(Event1NodeVisitor) == 24, "client event1 visitor"); static_assert(sizeof(Event2NodeVisitor) == 16, "client event2 visitor"); static_assert(sizeof(Event4NodeVisitor) == 20, "client event4 visitor"); static_assert(sizeof(Event5NodeVisitor) == 16, "client event5 visitor, including unwritten index"); static_assert(sizeof(PressStateNodeVisitor) == 8, "client press state visitor"); static_assert(sizeof(ReleaseStateNodeVisitor) == 8, "client release state visitor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/IntData.cpp b/Code/BF2/External/BFMeme/IntData.cpp index c687d0e75..8cd5a29b5 100644 --- a/Code/BF2/External/BFMeme/IntData.cpp +++ b/Code/BF2/External/BFMeme/IntData.cpp @@ -2,6 +2,9 @@ // factory82DB60, eager870360 and every differing body read before recovery. // The class is reachable from Bf2HudBuilder::setNodeLogicShowVariable, which // pairs it with IntRefData under an EqualData. +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "IntData.h" #if !DEDICATED #include "DataFormatting.h" @@ -42,7 +45,11 @@ bool IntData::setFloat(System*, float value) // Round half away from zero, then the ordinary truncating x86 cast // (fnstcw / or 0C00h / fistp / fldcw). A NaN takes the negative arm. // Text/cache refresh is deferred until character access. +#if defined(__APPLE__) + m_value = bf2x87::toIntTruncate(value < 0.0f ? value - 0.5f : value + 0.5f); +#else m_value = static_cast(value < 0.0f ? value - 0.5f : value + 0.5f); +#endif return true; } bool IntData::setString(System* system, const char* value) @@ -66,7 +73,9 @@ int IntData::getCharacter(System*, int character) return static_cast(m_text[character]); } +#if defined(_M_IX86) static_assert(sizeof(IntData) == 20, "client BFMeme IntData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "IntData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/LogicalData.cpp b/Code/BF2/External/BFMeme/LogicalData.cpp index fcc9721c9..e824b8283 100644 --- a/Code/BF2/External/BFMeme/LogicalData.cpp +++ b/Code/BF2/External/BFMeme/LogicalData.cpp @@ -48,7 +48,9 @@ int LogicalData::getCharacter(System* system, int character) return (value ? "true" : "false")[character]; } +#if defined(_M_IX86) static_assert(sizeof(LogicalData) == 16, "client BFMeme LogicalData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "LogicalData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/MoveEffect.cpp b/Code/BF2/External/BFMeme/MoveEffect.cpp index c1ef5df98..32dea370f 100644 --- a/Code/BF2/External/BFMeme/MoveEffect.cpp +++ b/Code/BF2/External/BFMeme/MoveEffect.cpp @@ -51,7 +51,7 @@ void computeMoveOffset(MoveEffect* self, System* system, Data* direction, Data* } } -bool MoveEffect::drawCharacter(System* system, int character, int font, +bool MoveEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { float dx = 0.0f, dy = 0.0f; @@ -75,7 +75,7 @@ bool MoveEffect::drawCharacter(System* system, int character, int font, return drawn; } -bool MoveEffect::drawTexture(System* system, int texture, Quad* quad, +bool MoveEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { float dx = 0.0f, dy = 0.0f; @@ -95,6 +95,8 @@ bool MoveEffect::drawTexture(System* system, int texture, Quad* quad, return drawn; } +#if defined(_M_IX86) static_assert(sizeof(MoveEffect) == 12, "PE MoveEffect allocation"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/MoveEffect.h b/Code/BF2/External/BFMeme/MoveEffect.h index f6648c507..02a35e23e 100644 --- a/Code/BF2/External/BFMeme/MoveEffect.h +++ b/Code/BF2/External/BFMeme/MoveEffect.h @@ -16,9 +16,9 @@ class MoveEffect : public Effect TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); // 832700, metadata94CB6C protected: // Both are borrowed expression nodes sampled every frame. The stream labels diff --git a/Code/BF2/External/BFMeme/MovePointer.cpp b/Code/BF2/External/BFMeme/MovePointer.cpp index 7c6e1eca2..4d27c2eee 100644 --- a/Code/BF2/External/BFMeme/MovePointer.cpp +++ b/Code/BF2/External/BFMeme/MovePointer.cpp @@ -1,7 +1,9 @@ -// Full operational instructions read from BF2.exe. Construction and descriptor -// remain declaration-only while TransformNode identity is unpublished. +// Full operational instructions read from BF2.exe, including construction and the descriptor. // No raw Node suffix dispatch is introduced. #include "MovePointer.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "TransformNode.h" #include "System.h" @@ -14,6 +16,8 @@ namespace { // bits when the caller selects extended precision (82B302..82B384). float moveOffset(float value, float start, float origin) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld value @@ -22,9 +26,22 @@ float moveOffset(float value, float start, float origin) fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(static_cast(value) - start + origin); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 extended subtract/add. + result = bf2x87::offset(value, start, origin); + return result; +#endif } float outlineThickness(float dimension) // 82B6D9..82B6EF and three repeated arms { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld1 @@ -33,6 +50,17 @@ float outlineThickness(float dimension) // 82B6D9..82B6EF and three repeated arm fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(1.0 - dimension + dimension); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 extended cancellation. + result = bf2x87::offset(1.0f, dimension, dimension); + return result; +#endif } TransformNode* asTransform(Node* node) { @@ -127,7 +155,22 @@ class PaintTransformVisitor : public NodeVisitor bool* m_next; }; } +// The only body is the copy inlined in the descriptor factory 82B4E0: Pointer's constructor +// (829140), then every MovePointer field zeroed in declaration order. +MovePointer::MovePointer() + : m_selected(nullptr), m_dragging(false), m_relativeX(0.0f), m_relativeY(0.0f), + m_startX(0.0f), m_startY(0.0f), m_startPositionX(0.0f), m_startPositionY(0.0f), + m_startWidth(0.0f), m_startHeight(0.0f), m_resizing(false) +{ +} MovePointer::~MovePointer() {} // 82B8D0, inherited Pointer owns no graphic +// 82B900: guarded "dice::meme::MovePointer" descriptor (table 94A04C). Its table 949FF0 overrides +// exactly the slots declared in MovePointer.h; the rest are Pointer's. +TypeDescriptor* MovePointer::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::MovePointer"); + return &type; +} TypeDescriptor* MovePointer::getType() { return getClassType(); } unsigned int MovePointer::getObjectSize() { return sizeof(MovePointer); } bool MovePointer::paint(System* system) @@ -215,6 +258,8 @@ bool MovePointer::event2(System* system, int, int) // 82B940; no enabled guard } return true; } +#if defined(_M_IX86) static_assert(sizeof(MovePointer) == 64, "Native x86 MovePointer layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/MovePointer.h b/Code/BF2/External/BFMeme/MovePointer.h index 6e04be26b..7f20b8c79 100644 --- a/Code/BF2/External/BFMeme/MovePointer.h +++ b/Code/BF2/External/BFMeme/MovePointer.h @@ -1,6 +1,5 @@ // Descriptor name82B900 attests dice::meme::MovePointer. Full23-slot table949FF0. -// Native64-byte storage, no STL. Construction/descriptor stay unpublished; -// the TransformNode descriptor remains unresolved. +// Native64-byte storage, no STL. #ifndef BFMEME_MOVEPOINTER_H #define BFMEME_MOVEPOINTER_H #include "Pointer.h" @@ -9,7 +8,7 @@ namespace dice { namespace meme { class TransformNode; class MovePointer : public Pointer { public: - MovePointer(); // inlined82B4E0 [FRONTIER], operational dependency remains open + MovePointer(); // inlined in descriptor factory 82B4E0 ~MovePointer() override; // 82B8D0 -> Pointer destructor TypeDescriptor* getType() override; // 82B900, named descriptor dependency unsigned int getObjectSize() override; @@ -17,7 +16,7 @@ class MovePointer : public Pointer { bool setPosition(System*, float x, float y) override; bool event1(System*, int first, int index, int second) override; bool event2(System*, int first, int index) override; - static TypeDescriptor* getClassType(); // [FRONTIER], no incomplete factory + static TypeDescriptor* getClassType(); // 82B900, base slot 82B4D0 -> Pointer protected: TransformNode* m_selected; // +14, borrowed bool m_dragging; // +18 diff --git a/Code/BF2/External/BFMeme/NameNode.cpp b/Code/BF2/External/BFMeme/NameNode.cpp index c1792decc..ce9e2a3a9 100644 --- a/Code/BF2/External/BFMeme/NameNode.cpp +++ b/Code/BF2/External/BFMeme/NameNode.cpp @@ -73,7 +73,9 @@ bool NameNode::setName(const char* name) } bool NameNode::slot_0x20() { return true; } bool NameNode::slot_0x24() { return true; } +#if defined(_M_IX86) static_assert(sizeof(NameNode) == 12, "client BFMeme NameNode"); static_assert(sizeof(NameNodeTypeDescriptor) == 16, "client NameNode descriptor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/NamedInputStream.cpp b/Code/BF2/External/BFMeme/NamedInputStream.cpp index 66659263b..4cbabb57f 100644 --- a/Code/BF2/External/BFMeme/NamedInputStream.cpp +++ b/Code/BF2/External/BFMeme/NamedInputStream.cpp @@ -40,7 +40,9 @@ int RelativeIStream::getPosition() + static_cast(m_skippedBytes) - static_cast(m_initialPosition)); } +#if defined(_M_IX86) static_assert(sizeof(TeeIStream) == 20, "client recording input layout"); static_assert(sizeof(RelativeIStream) == 24, "client relative input layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp b/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp index b453d1d41..b30d41d21 100644 --- a/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp +++ b/Code/BF2/External/BFMeme/NamedObjectRegistry.cpp @@ -312,11 +312,13 @@ bool NameTreeObjectEntry::stream(System* system, Stream* output) if (m_object && !output->streamObject(system, m_object, "Object", nullptr)) return false; return next ? next->stream(system, output) : true; } -// [FRONTIER] saveNamedObject82AB60 and specialized visitor descriptor defaults -// are still deeper dependencies. No registry/System factory is published. +// saveNamedObject is defined in ClassOStream.cpp; System::init owns registry creation. +// [FRONTIER] Specialized visitor descriptor defaults remain outside this registry. +#if defined(_M_IX86) static_assert(sizeof(NameTreeNode) == 8, "name-tree node layout"); static_assert(sizeof(NameTreeContainer) == 16, "name-tree container layout"); static_assert(sizeof(NameTreeRoot) == 16, "name-tree root layout"); static_assert(sizeof(NameTreeObjectEntry) == 12, "name-tree object entry layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/NativeSavedDispatch.h b/Code/BF2/External/BFMeme/NativeSavedDispatch.h new file mode 100644 index 000000000..c2a348d0c --- /dev/null +++ b/Code/BF2/External/BFMeme/NativeSavedDispatch.h @@ -0,0 +1,89 @@ +// [CHOSEN, not recovered] Native saved-table dispatch for the macOS port. +#ifndef BFMEME_NATIVE_SAVED_DISPATCH_H +#define BFMEME_NATIVE_SAVED_DISPATCH_H +#if defined(__APPLE__) && defined(__LP64__) && !defined(__arm64e__) +#include +#include +#include +#include +#include +#include + +namespace dice { namespace meme { namespace native_dispatch { + +/// Itanium virtual-member encoding; unsupported member kinds stop visibly. x86-64 marks a virtual +/// member by ptr = vtable byte offset + 1; the ARM variant of the C++ ABI (Apple arm64) keeps +/// ptr = vtable byte offset and marks it in adj = 2 * this-adjustment + 1. +struct VirtualMember +{ + std::ptrdiff_t offset; + std::ptrdiff_t adjustment; + + template + static VirtualMember decode(Member member) + { + static_assert(std::is_member_function_pointer::value, "virtual member required"); + struct Representation { std::ptrdiff_t pointer; std::ptrdiff_t adjustment; }; + static_assert(sizeof(Member) == sizeof(Representation), "standard Itanium member encoding required"); + static_assert(sizeof(void (*)()) == sizeof(std::ptrdiff_t), "native function pointer width required"); + Representation bits; + std::memcpy(&bits, &member, sizeof(bits)); +#if defined(__aarch64__) || defined(__arm64__) + const bool supported = (bits.adjustment & 1) && bits.pointer >= 0 && + bits.pointer % sizeof(void (*)()) == 0; + const VirtualMember decoded = {bits.pointer, bits.adjustment >> 1}; +#else + const bool supported = bits.pointer > 0 && (bits.pointer & 1) && + (bits.pointer - 1) % sizeof(void (*)()) == 0; + const VirtualMember decoded = {bits.pointer - 1, bits.adjustment}; +#endif + if (!supported) + { + std::fprintf(stderr, "[FRONTIER] dice::meme::native_dispatch::VirtualMember::decode unsupported virtual member encoding\n"); + std::fflush(stderr); + std::abort(); + } + return decoded; + } + + std::size_t slot() const { return static_cast(offset) / sizeof(void (*)()); } +}; + +template class SavedVirtual; + +/// Captures the adjusted receiver's table, then calls it on a later compatible receiver. +/// Both receivers must have live, layout-compatible subobjects for the selected method. +/// The stored table and its adjustment thunks must remain alive through the call. +template +class SavedVirtual +{ +public: + using Member = R (C::*)(Args...); + + SavedVirtual(C* receiver, Member member) : m_member(VirtualMember::decode(member)) + { + const char* adjusted = reinterpret_cast(receiver) + m_member.adjustment; + std::memcpy(&m_table, adjusted, sizeof(m_table)); + } + + R operator()(C* receiver, Args... args) const + { + // Keep the captured address point (including secondary-base thunks). Only + // this is reloaded/adjusted; reading receiver's current vptr would change + // the recovered capture-before-source-getter semantics. See the port guide. + using Function = R (*)(void*, Args...); + static_assert(sizeof(Function) == sizeof(void*), "native table entry width required"); + Function function; + std::memcpy(&function, m_table + m_member.offset, sizeof(function)); + void* adjusted = reinterpret_cast(receiver) + m_member.adjustment; + return function(adjusted, std::forward(args)...); + } + +private: + VirtualMember m_member; + const char* m_table; +}; + +} } } +#endif +#endif diff --git a/Code/BF2/External/BFMeme/Node.cpp b/Code/BF2/External/BFMeme/Node.cpp index 393495be2..0997e7e3d 100644 --- a/Code/BF2/External/BFMeme/Node.cpp +++ b/Code/BF2/External/BFMeme/Node.cpp @@ -6,9 +6,11 @@ #if !DEDICATED #include "Stream.h" #include "TypeDescriptor.h" +#include "System.h" // Concrete menu node types permit event-20 dispatch while the shared Node suffix remains untyped. #include "../../Menu/Bf2ButtonNode.h" #include "../../Menu/Bf2ObjectMarkerNode.h" +#include "../../Menu/Bf2EditNode.h" #include #include #include @@ -37,7 +39,9 @@ class NodeTypeDescriptor : public TypeDescriptor static int instanceCount; }; int NodeTypeDescriptor::instanceCount = 0; +#if defined(_M_IX86) static_assert(sizeof(NodeTypeDescriptor) == 16, "Node metadata stores its counter separately"); +#endif } TypeDescriptor* Node::getClassType() // 82C190, shared by the virtual getter @@ -199,9 +203,20 @@ bool dispatchNodeEvent15(Node*, System*, const Rect*, const NodeState*) // [CHOSEN, not recovered] [RETIRE-WHEN: node-suffix-call-frontiers] return false; } -bool dispatchNodeEvent16(Node*, System*, const Rect*, const NodeState*) +bool dispatchNodeEvent16(Node* node, System* system, const Rect*, const NodeState*) { - // [FRONTIER] [TEMP] [CHOSEN, not recovered] Event 16 stops because edit and path nodes have nonempty handlers. + // Match exact descriptors while the remaining Node suffix is untyped. BfEditNode/Bf2EditNode + // +A0 (7AA9B0): drop focus and unlock the pointer, then the 455410 false default. + TypeDescriptor* const type = node->getType(); + if (type == BfEditNode::getClassType() || type == Bf2EditNode::getClassType()) { + BfEditNode* const edit = static_cast(node); + if (edit->m_focused) { + edit->m_focused = false; + system->unlockPointer(); + } + return false; + } + // [FRONTIER] [TEMP] [CHOSEN, not recovered] The other edit and path handlers remain unrecovered. // [RETIRE-WHEN: node-suffix-call-frontiers] Implement the typed virtual handlers before replacing this stop. std::fprintf(stderr, "[FRONTIER] dice::meme::dispatchNodeEvent16 reached (Node virtual+A0 - NOT a false default: 5 of 74 tables override it, BfEditNode/Bf2EditNode 7AA9B0, BfEditNodeInt 7AACF0, PathNode/StackPathNode 836A80)\n"); std::fflush(stderr); @@ -274,10 +289,14 @@ void resetNodeSelf(Node*) { } +#if defined(_M_IX86) static_assert(sizeof(Node) == 8, "client BFMeme Node"); +#endif static_assert(sizeof(NodeState) == 8, "client BFMeme interaction state"); static_assert(sizeof(NodeInputEvent) == 20, "client BFMeme input payload"); +#if defined(_M_IX86) static_assert(sizeof(RenderContext) == 28, "client BFMeme effect chain context"); static_assert(sizeof(NodeVisitor) == 8, "client BFMeme three-slot visitor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/NodeState.cpp b/Code/BF2/External/BFMeme/NodeState.cpp index 321e2cf3e..763e5dafd 100644 --- a/Code/BF2/External/BFMeme/NodeState.cpp +++ b/Code/BF2/External/BFMeme/NodeState.cpp @@ -66,7 +66,9 @@ void emitStateEvent(int type, System* system, Node*& eventRoot, const Rect* rect StateEventVisitor visitor(event); visitor.traverse(system, eventRoot, rect, state); } +#if defined(_M_IX86) static_assert(sizeof(StateEventVisitor) == 32, "client state event visitor"); +#endif } void updateNodeState(NodeState* state, System* system, Node* transitionSource, Node* eventRoot, const Rect* rect, float delta, bool pointerInside, bool enabled) diff --git a/Code/BF2/External/BFMeme/NotData.cpp b/Code/BF2/External/BFMeme/NotData.cpp index 9134ca759..34b50550a 100644 --- a/Code/BF2/External/BFMeme/NotData.cpp +++ b/Code/BF2/External/BFMeme/NotData.cpp @@ -31,7 +31,9 @@ float NotData::getFloat(System* system) return m_first->getFloat(system) == 0.0f ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(NotData) == 16, "client BFMeme NotData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "NotData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/OStream.cpp b/Code/BF2/External/BFMeme/OStream.cpp index 6d1da11e0..927ba3fe9 100644 --- a/Code/BF2/External/BFMeme/OStream.cpp +++ b/Code/BF2/External/BFMeme/OStream.cpp @@ -6,6 +6,9 @@ #include "TypeDescriptor.h" #include #include +#if !defined(_WIN32) +#include +#endif namespace dice { namespace meme { namespace { // [INFERRED] Factored identical resource-name write sequences838190/838210/838290. @@ -19,6 +22,14 @@ bool writeResourceName(OStream* output, const char* name) } } OStream::~OStream() {} +// 8383E0: guarded "dice::meme::OStream" descriptor, base slot 82B9E0 (RuntimeObject), factory +// 838420 (four bytes, table 9352A0), size slot 8149E0 (4). +TypeDescriptor* OStream::getClassType() +{ + static ClassTypeDescriptor type("dice::meme::OStream"); + return &type; +} +TypeDescriptor* OStream::getType() { return getClassType(); } unsigned int OStream::getObjectSize() { return sizeof(OStream); } bool OStream::streamUByte(unsigned char* value, const char*) { return write(value, 1) == 1; } bool OStream::streamByte(char* value, const char*) { return write(value, 1) == 1; } @@ -48,7 +59,22 @@ bool OStream::streamWideString(wchar_t** value, const char*) { int length = *value ? static_cast(std::wcslen(*value)) : 0; if (!streamInt(&length, "Int")) return false; +#if defined(_WIN32) if (*value && write(*value, 2 * length) != 2 * length) return false; +#else + // [CHOSEN, not recovered] Keep the Windows wire format: `length` UTF-16LE units. Writing + // 2 * length raw bytes of a 32-bit POSIX wchar_t buffer would emit half the text, mangled. + // Characters above U+FFFF keep their low 16 bits, as the 16-bit getCharacter does. + if (*value) { + std::vector units(2u * static_cast(length)); + for (int i = 0; i < length; ++i) { + const unsigned int unit = static_cast((*value)[i]) & 0xFFFFu; + units[2 * i] = static_cast(unit); + units[2 * i + 1] = static_cast(unit >> 8); + } + if (write(units.data(), 2 * length) != 2 * length) return false; + } +#endif return true; } bool OStream::streamCharacter(wchar_t* value, const char* label) // 838170 uses32-bit serialization @@ -56,9 +82,9 @@ bool OStream::streamCharacter(wchar_t* value, const char* label) // 838170 uses3 int temporary = *value; return streamInt(&temporary, label); } -bool OStream::streamTexture(System* system, int* texture, const char*) +bool OStream::streamTexture(System* system, TextureHandle* texture, const char*) { return writeResourceName(this, system->getTextureName(*texture)); } -bool OStream::streamFont(System* system, int* font, const char*) +bool OStream::streamFont(System* system, FontHandle* font, const char*) { return writeResourceName(this, system->getFontName(*font)); } bool OStream::streamSound(System* system, int* sound, const char*) { return writeResourceName(this, system->getSoundName(*sound)); } @@ -110,6 +136,8 @@ bool writeObject(System* system, Object*& value, OStream* output) return true; } // Descriptor is intentionally unpublished while deeper dependencies stay open. +#if defined(_M_IX86) static_assert(sizeof(OStream) == 4, "BFMeme output stream layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/OStream.h b/Code/BF2/External/BFMeme/OStream.h index 2208b4431..afa64e65e 100644 --- a/Code/BF2/External/BFMeme/OStream.h +++ b/Code/BF2/External/BFMeme/OStream.h @@ -8,7 +8,7 @@ class OStream : public Stream { public: ~OStream() override; // 794CA0 -> RuntimeObject dtor - TypeDescriptor* getType() override; // 8383E0 [FRONTIER] publication + TypeDescriptor* getType() override; // 8383E0, descriptor table 94E954 unsigned int getObjectSize() override; bool streamUByte(unsigned char*, const char*) override; bool streamByte(char*, const char*) override; @@ -22,8 +22,8 @@ class OStream : public Stream bool streamString(char**, const char*) override; bool streamWideString(wchar_t**, const char*) override; bool streamCharacter(wchar_t*, const char*) override; - bool streamTexture(System*, int*, const char*) override; - bool streamFont(System*, int*, const char*) override; + bool streamTexture(System*, TextureHandle*, const char*) override; + bool streamFont(System*, FontHandle*, const char*) override; bool streamSound(System*, int*, const char*) override; bool streamCollection(System*, ObjectCollection*, const char*) override; bool streamEnum(int*, EnumNext, EnumName, const char*) override; @@ -33,7 +33,7 @@ class OStream : public Stream virtual int getPosition(); // +94 80D430; serializer82AA00 virtual bool setPosition(int); virtual bool writeShortString(System*, const char*, const char* label); // +9C 838330 - static TypeDescriptor* getClassType(); // [FRONTIER], no partial factory + static TypeDescriptor* getClassType(); // 8383E0; factory 838420 builds a bare OStream }; } } #endif diff --git a/Code/BF2/External/BFMeme/Object.cpp b/Code/BF2/External/BFMeme/Object.cpp index a6134e73f..fe9a215f7 100644 --- a/Code/BF2/External/BFMeme/Object.cpp +++ b/Code/BF2/External/BFMeme/Object.cpp @@ -84,7 +84,9 @@ bool createRuntimeObject(RuntimeObject*& object, TypeDescriptor* type) created->getType()->addInstance(); return true; } +#if defined(_M_IX86) static_assert(sizeof(RuntimeObject) == 4, "BFMeme RuntimeObject layout"); static_assert(sizeof(Object) == 4, "BFMeme Object layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Object.h b/Code/BF2/External/BFMeme/Object.h index 0b981ec6c..385fb7f96 100644 --- a/Code/BF2/External/BFMeme/Object.h +++ b/Code/BF2/External/BFMeme/Object.h @@ -4,7 +4,21 @@ #define BFMEME_OBJECT_H #include "../../Core/BuildConfig.h" #if !DEDICATED +#include +#include namespace dice { namespace meme { +// Font and texture handles carry the Font* / IMemeTexture* that the menu System returns, so +// they are pointer-sized. MSVC x86 defines intptr_t as int: retail layouts and x86 signatures +// are unchanged. [CHOSEN, not recovered] x64 port, issue #7. +typedef std::intptr_t FontHandle; +typedef std::intptr_t TextureHandle; +#if defined(_M_IX86) +static_assert(std::is_same::value && std::is_same::value, + "x86 meme handles keep the retail int type"); +static_assert(std::is_same::value, + "x86 unsigned handle words keep the retail uint32_t type"); +#endif + class TypeDescriptor; class System; class Stream; // [INFERRED] common stream/visitor identity, not Object-derived. diff --git a/Code/BF2/External/BFMeme/ObjectCollection.cpp b/Code/BF2/External/BFMeme/ObjectCollection.cpp index 43d2c69c3..8144215d0 100644 --- a/Code/BF2/External/BFMeme/ObjectCollection.cpp +++ b/Code/BF2/External/BFMeme/ObjectCollection.cpp @@ -140,6 +140,8 @@ bool ObjectCollection::writeObjects(System* system, OStream* output) object = nullptr; return writeObject(system, object, output); // Always emit the null terminator. } +#if defined(_M_IX86) static_assert(sizeof(ObjectCollection) == 4, "BFMeme collection base layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ObjectList.cpp b/Code/BF2/External/BFMeme/ObjectList.cpp index 2c6e6837f..b82063fcd 100644 --- a/Code/BF2/External/BFMeme/ObjectList.cpp +++ b/Code/BF2/External/BFMeme/ObjectList.cpp @@ -16,7 +16,9 @@ struct ObjectList::Link ~Link() { delete next; } // 839750, reverse free order, no payload deletion static Link* allocate(Object* object) { +#if defined(_M_IX86) static_assert(sizeof(Link) == 12, "client ObjectList link"); +#endif void* memory = ::operator new(sizeof(Link)); return memory ? new(memory) Link(object) : nullptr; } @@ -123,6 +125,8 @@ bool ObjectList::readObjects(System* system, IStream* stream) m_cursor = m_first; return true; } +#if defined(_M_IX86) static_assert(sizeof(ObjectList) == 20, "client concrete ObjectList"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/OrData.cpp b/Code/BF2/External/BFMeme/OrData.cpp index a7f72e4dd..9528d7c38 100644 --- a/Code/BF2/External/BFMeme/OrData.cpp +++ b/Code/BF2/External/BFMeme/OrData.cpp @@ -28,7 +28,9 @@ float OrData::getFloat(System* system) return m_second->getFloat(system) != 0.0f ? 1.0f : 0.0f; } +#if defined(_M_IX86) static_assert(sizeof(OrData) == 16, "client BFMeme OrData"); static_assert(sizeof(ClassTypeDescriptor) == 16, "OrData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/PictureNode.cpp b/Code/BF2/External/BFMeme/PictureNode.cpp index 890fc6e67..53ff5acee 100644 --- a/Code/BF2/External/BFMeme/PictureNode.cpp +++ b/Code/BF2/External/BFMeme/PictureNode.cpp @@ -28,10 +28,12 @@ class PictureNodeTypeDescriptor final : public TypeDescriptor int getInstanceCount() override { return pictureNodeInstances; } unsigned int getInstanceSize() override { return sizeof(PictureNode); } }; +#if defined(_M_IX86) static_assert(sizeof(PictureNodeTypeDescriptor) == 16, "PictureNode metadata storage"); +#endif } -PictureNode::PictureNode(int texture) : Node(), m_texture(texture) {} +PictureNode::PictureNode(TextureHandle texture) : Node(), m_texture(texture) {} TypeDescriptor* PictureNode::getClassType() { static PictureNodeTypeDescriptor type; diff --git a/Code/BF2/External/BFMeme/PictureNode.h b/Code/BF2/External/BFMeme/PictureNode.h index 5c16ea8fa..bc3d8a3b9 100644 --- a/Code/BF2/External/BFMeme/PictureNode.h +++ b/Code/BF2/External/BFMeme/PictureNode.h @@ -6,16 +6,18 @@ namespace dice { namespace meme { class PictureNode : public Node { public: - explicit PictureNode(int texture); + explicit PictureNode(TextureHandle texture); TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; void paintSelf(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) override; static TypeDescriptor* getClassType(); // 836320, factory8362F0 protected: - int m_texture; // +08, signed texture handle + TextureHandle m_texture; // +08, signed texture handle }; +#if defined(_M_IX86) static_assert(sizeof(PictureNode)==12, "native PictureNode prefix storage"); +#endif } } #endif #endif diff --git a/Code/BF2/External/BFMeme/Pointer.cpp b/Code/BF2/External/BFMeme/Pointer.cpp index 8b149c9e2..7a5651b12 100644 --- a/Code/BF2/External/BFMeme/Pointer.cpp +++ b/Code/BF2/External/BFMeme/Pointer.cpp @@ -80,6 +80,8 @@ bool updatePointer(System* s, Pointer* p, float d) { return p && p->isEnabled() bool positionPointer(System* s, Pointer* p, float x, float y) { return p && p->isEnabled() ? p->setPosition(s, x, y) : true; } bool pointerEvent1(System* s, Pointer* p, int a, int i, int b) { return p && p->isEnabled() ? p->event1(s, a, i, b) : true; } bool pointerEvent2(System* s, Pointer* p, int a, int i) { return p && p->isEnabled() ? p->event2(s, a, i) : true; } +#if defined(_M_IX86) static_assert(sizeof(Pointer) == 20, "Pointer has no STL-dependent members"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Quad.cpp b/Code/BF2/External/BFMeme/Quad.cpp index f8639a6c0..fc0815c97 100644 --- a/Code/BF2/External/BFMeme/Quad.cpp +++ b/Code/BF2/External/BFMeme/Quad.cpp @@ -1,5 +1,11 @@ #include "Quad.h" +#include "Stream.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED +#include +#include namespace dice { namespace meme { Quad::Quad() : clip(nullptr), blend(1), state08(7), state0c(8), @@ -66,6 +72,8 @@ Quad::Quad(const Rect* bounds, const Rect* clipping, const Color* color) corners[3].z = z; corners[3].color = *color; } +// PE 0x101C4F00: RendDX9's copy of this body (cosine and sine from fcos/fsin once, then the four +// corners in order); unreachable in 1.50 there: no code or data references. // Each corner rotates about the supplied centre. The cosine and sine // come from the x87 fcos/fsin pair, not the CRT, and both are evaluated once // before the four corners; keep that or the shipped pixel positions move. @@ -74,7 +82,9 @@ Quad::Quad(const Rect* bounds, const Rect* clipping, const Color* color) // stack; the named float locals below reproduce the rounding that matters. void rotateQuad(Quad* quad, const float center[2], float radians) { +#if defined(_WIN32) float cosine, sine; +#if defined(_M_IX86) __asm { fld radians fcos @@ -83,12 +93,31 @@ void rotateQuad(Quad* quad, const float center[2], float radians) fsin fstp sine } +#else + // [PLATFORM] x64: no x87 fcos/fsin. The CRT double results rounded to float match the + // x87 ones except in rare last-bit cases; |radians| >= 2^63 (left unreduced by x87) differs. + cosine = static_cast(std::cos(static_cast(radians))); + sine = static_cast(std::sin(static_cast(radians))); +#endif + for (unsigned int i = 0; i < 4; ++i) { + const float dx = quad->corners[i].x - center[0]; + const float dy = quad->corners[i].y - center[1]; + quad->corners[i].x = dx * cosine + dy * sine + center[0]; + quad->corners[i].y = dy * cosine - dx * sine + center[1]; + } +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float cosine, sine; + // [CHOSEN, not recovered] Preserve x87 float trig stores. + cosine = bf2x87::store(bf2x87::cosine(bf2x87::wide(radians))); + sine = bf2x87::store(bf2x87::sine(bf2x87::wide(radians))); for (unsigned int i = 0; i < 4; ++i) { const float dx = quad->corners[i].x - center[0]; const float dy = quad->corners[i].y - center[1]; quad->corners[i].x = dx * cosine + dy * sine + center[0]; quad->corners[i].y = dy * cosine - dx * sine + center[1]; } +#endif } // Overwrites all four corner colors; no alpha or range handling. @@ -127,7 +156,130 @@ void setQuadBounds(Quad* quad, float x, float y, float width, float height) quad->corners[3].z = z; } +// PE 0x101C4E50 (ecx = quad, out on the stack): the mean of the four corner positions, summed in +// corner order with a float store per addition, then scaled by 0.25. +void quadCenter(const Quad* quad, float out[3]) +{ + out[0] = 0.0f; + out[1] = 0.0f; + out[2] = 0.0f; + out[0] = quad->corners[0].x; + out[1] = quad->corners[0].y; + out[2] = quad->corners[0].z; + for (unsigned int i = 1; i < 4; ++i) { + out[0] = quad->corners[i].x + out[0]; + out[1] = quad->corners[i].y + out[1]; + out[2] = quad->corners[i].z + out[2]; + } + out[0] = out[0] * 0.25f; + out[1] = out[1] * 0.25f; + out[2] = out[2] * 0.25f; +} + +// PE 0x101C5060 (ecx = quad, margin on the stack): grows the quad outward by the margin: corner 0 +// moves by (-mx, -my), corner 1 by (+mx, -my), corner 2 by (+mx, +my), corner 3 by (-mx, +my). +void expandQuad(Quad* quad, const float margin[2]) +{ + quad->corners[0].x = -margin[0] + quad->corners[0].x; + quad->corners[0].y = -margin[1] + quad->corners[0].y; + quad->corners[1].x = quad->corners[1].x + margin[0]; + quad->corners[1].y = -margin[1] + quad->corners[1].y; + quad->corners[2].x = quad->corners[2].x + margin[0]; + quad->corners[2].y = margin[1] + quad->corners[2].y; + quad->corners[3].x = -margin[0] + quad->corners[3].x; + quad->corners[3].y = margin[1] + quad->corners[3].y; +} + +namespace { +// Exchanges the seven leading words (position and colour) of two corners; the eighth word of each +// corner is not touched. +void swapCorners(QuadCorner& a, QuadCorner& b) +{ + const QuadCorner saved = a; + a.x = b.x; + a.y = b.y; + a.z = b.z; + a.color = b.color; + b.x = saved.x; + b.y = saved.y; + b.z = saved.z; + b.color = saved.color; +} +} + +// PE 0x101C50D0 (ecx = quad): corners 0 and 1, then 2 and 3, exchange position and colour. +void flipQuadHorizontal(Quad* quad) +{ + swapCorners(quad->corners[0], quad->corners[1]); + swapCorners(quad->corners[2], quad->corners[3]); +} + +// PE 0x101C5210 (ecx = quad): corners 0 and 3, then 1 and 2, exchange position and colour. +void flipQuadVertical(Quad* quad) +{ + swapCorners(quad->corners[0], quad->corners[3]); + swapCorners(quad->corners[1], quad->corners[2]); +} + +// PE 0x101C4BE0 (ecx = rect, bounds on the stack): false, leaving the rect alone, when the two +// rectangles do not overlap (each edge compared with `>=`, a NaN edge counts as no overlap); +// otherwise trims the rect to the bounds' left, top, right and bottom in that order and answers +// true. [CHOSEN, not recovered] the retail x87 keeps each delta unrounded on the stack; a double +// delta is used here because no 1.50 path executes the body. +bool clipRect(Rect* rect, const Rect* bounds) +{ + if (!(rect->x + rect->width >= bounds->x)) return false; + if (!(rect->y + rect->height >= bounds->y)) return false; + if (!(bounds->x + bounds->width >= rect->x)) return false; + if (!(bounds->height + bounds->y >= rect->y)) return false; + double delta = static_cast(bounds->x) - rect->x; + if (delta > 0.0) { + rect->width = static_cast(rect->width - delta); + rect->x = bounds->x; + } + delta = static_cast(bounds->y) - rect->y; + if (delta > 0.0) { + rect->height = static_cast(rect->height - delta); + rect->y = bounds->y; + } + delta = static_cast(rect->x + rect->width) - (bounds->x + bounds->width); + if (delta > 0.0) + rect->width = static_cast(rect->width - delta); + delta = static_cast(rect->y + rect->height) - (bounds->height + bounds->y); + if (delta > 0.0) + rect->height = static_cast(rect->height - delta); + return true; +} + +// PE 0x101C4B30 (ecx = colour, stream on the stack): streams "Red", "Green", "Blue" and "Alpha" +// into the four floats, stopping at the first refusal. +bool streamColor(Color* color, Stream* stream) +{ + if (!stream->streamFloat(&color->r, "Red")) return false; + if (!stream->streamFloat(&color->g, "Green")) return false; + if (!stream->streamFloat(&color->b, "Blue")) return false; + return stream->streamFloat(&color->a, "Alpha"); +} + +// PE 0x101C4CC0 (ecx = rect, stream on the stack): streams "X", "Y", "Width" and "Height" into the first four floats, +// stopping at the first refusal. +bool streamRect(Rect* rect, Stream* stream) +{ + if (!stream->streamFloat(&rect->x, "X")) return false; + if (!stream->streamFloat(&rect->y, "Y")) return false; + if (!stream->streamFloat(&rect->width, "Width")) return false; + return stream->streamFloat(&rect->height, "Height"); +} + static_assert(sizeof(QuadCorner) == 32, "retail quad corner stride"); +#if defined(_M_IX86) static_assert(sizeof(Quad) == 192, "retail QuadDrawer request size"); +#else +// RendDX9's QuadDrawRequest (GeomMisc/MenuRend/QuadDrawer.cpp) declares an 8-byte clip pointer, +// a pointer texture2 and 0x20 bytes before the corners; with the pointer-sized handle both +// sides place texture2 at +0x20 and the corners at +0x48 on x64. +static_assert(offsetof(Quad, texture2) == 0x20 && offsetof(Quad, corners) == 0x48 + && sizeof(Quad) == 0xC8, "x64 QuadDrawer request layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Quad.h b/Code/BF2/External/BFMeme/Quad.h index a70daabdf..1271d50f3 100644 --- a/Code/BF2/External/BFMeme/Quad.h +++ b/Code/BF2/External/BFMeme/Quad.h @@ -25,7 +25,7 @@ struct Quad int state08, state0c, state10, state14; // +08..+14 unsigned char state18; // +18 unsigned char padding19[3]; // untouched - int texture2; // +1C, opaque texture handle + TextureHandle texture2; // +1C, texture handle; RendDX9 reads an IMemeTexture* std::uint32_t state20[8]; // +20..+3C, all zeroed QuadCorner corners[4]; // +40,+60,+80,+A0 }; @@ -38,6 +38,17 @@ void rotateQuad(Quad*, const float center[2], float radians); void colorQuad(Quad*, const Color*); void translateQuad(Quad*, float dx, float dy, float dz); void setQuadBounds(Quad*, float x, float y, float width, float height); + +// RendDX9's own copies of further Quad / Rect / Color helpers (PE 0x101C4B30..0x101C5210). Every body +// below is unreachable in 1.50: no code or data references. Names and placement are [INFERRED]. + +void quadCenter(const Quad*, float out[3]); // PE 0x101C4E50 +void expandQuad(Quad*, const float margin[2]); // PE 0x101C5060 +void flipQuadHorizontal(Quad*); // PE 0x101C50D0 +void flipQuadVertical(Quad*); // PE 0x101C5210 +bool clipRect(Rect* rect, const Rect* bounds); // PE 0x101C4BE0 +bool streamColor(Color* color, Stream*); // PE 0x101C4B30 +bool streamRect(Rect* rect, Stream*); // PE 0x101C4CC0 } } #endif #endif diff --git a/Code/BF2/External/BFMeme/SetVariableAction.cpp b/Code/BF2/External/BFMeme/SetVariableAction.cpp index 6bd59865e..a57798b7f 100644 --- a/Code/BF2/External/BFMeme/SetVariableAction.cpp +++ b/Code/BF2/External/BFMeme/SetVariableAction.cpp @@ -5,18 +5,37 @@ #include "Data.h" #include "Stream.h" #include "TypeDescriptor.h" +#if defined(__APPLE__) && defined(__LP64__) +#include "NativeSavedDispatch.h" +#endif namespace dice { namespace meme { namespace { // MSVC x86 dispatch captures the destination table before reading the source, then reloads the receiver. // Preserve the saved table: a normal virtual call could select a replacement receiver's implementation. // Helper names and isolation are [INFERRED]. +#if defined(__APPLE__) && defined(__LP64__) +// [CHOSEN, not recovered] Select the compiler's native slot while retaining the saved table. +using DataMethodTable = native_dispatch::SavedVirtual; +DataMethodTable captureDataMethods(Data* data) +{ return DataMethodTable(data, &Data::setFloat); } +#else using DataSetFloatMethod = bool (__thiscall*)(Data*, System*, float); using DataMethodTable = void* const*; DataMethodTable captureDataMethods(Data* data) { return *reinterpret_cast(data); } +// Slot 0x4C/4 is setFloat in both MSVC table layouts (one destructor slot); on x64 the +// __thiscall spelling is ignored and the same table index is read. +#endif void callCapturedSetFloat(DataMethodTable methods, Data* receiver, System* system, float value) +#if defined(__APPLE__) && defined(__LP64__) +// [CHOSEN, not recovered] Native ABI counterpart of the unchanged PE arm below. +{ methods(receiver, system, value); } +#else { reinterpret_cast(methods[0x4C / 4])(receiver, system, value); } +#if defined(_M_IX86) static_assert(sizeof(void*) == 4, "PE Data dispatch is x86"); +#endif +#endif } SetVariableAction::SetVariableAction() : m_variable(nullptr), m_data(nullptr) {} SetVariableAction::~SetVariableAction() {} @@ -47,6 +66,8 @@ bool SetVariableAction::execute(System* system, const Rect*, const NodeState*, c } return false; // The destination setter's result is discarded in retail. } +#if defined(_M_IX86) static_assert(sizeof(SetVariableAction) == 12, "client SetVariableAction"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/SetVariableSineAction.cpp b/Code/BF2/External/BFMeme/SetVariableSineAction.cpp index acf488e05..9c287380e 100644 --- a/Code/BF2/External/BFMeme/SetVariableSineAction.cpp +++ b/Code/BF2/External/BFMeme/SetVariableSineAction.cpp @@ -1,11 +1,17 @@ // [INFERRED] path. Complete table94D000, metadata94CD6C, constructor8330D0, // factory/eager and all differing instructions read. No runtime math shim. #include "SetVariableSineAction.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Data.h" #include "Node.h" #include "Stream.h" #include "TypeDescriptor.h" +#if !defined(_M_IX86) +#include +#endif namespace dice { namespace meme { namespace { // PE832B86..C39, same x87 order and float stores. Helper/name [INFERRED]. @@ -15,9 +21,11 @@ namespace { bool chooseSineValue(float current, float target, float delta, float speed, float braking, float& value) { +#if defined(_WIN32) const float angle = 1.57075f; // 94CB68, bytes56 0E C9 3F float rounded; bool changed = false; +#if defined(_M_IX86) __asm { fld target fld current @@ -90,8 +98,40 @@ bool chooseSineValue(float current, float target, float delta, float speed, fstp st(0) done: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates) and the CRT cosine in + // place of fcos; the argument stays within [0, k], where both agree to double precision. + // Equal or unordered samples write nothing; an unordered braking test takes full speed. + if (current < target) { + const double distance = static_cast(target) - current; + const double step = distance < braking + ? std::cos(angle - distance / braking * angle) * speed * delta + : static_cast(delta) * speed; + const double candidate = step + current; + rounded = candidate > target ? target : static_cast(candidate); + changed = true; + } else if (current > target) { + const double distance = static_cast(current) - target; + const double step = distance < braking + ? std::cos(angle - distance / braking * angle) * speed * delta + : static_cast(delta) * speed; + const double candidate = current - step; + rounded = candidate < target ? target : static_cast(candidate); + changed = true; + } +#endif if (changed) value = rounded; return changed; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float angle = 1.57075f; // 94CB68, bytes56 0E C9 3F + float rounded; + bool changed = false; + // [CHOSEN, not recovered] Preserve x87 ordered movement and retained candidate comparison. + changed = bf2x87::chooseValue(current, target, delta, speed, braking, true, rounded); + if (changed) value = rounded; + return changed; +#endif } } SetVariableSineAction::SetVariableSineAction() : m_brakingDistance(0.0f) {} @@ -127,8 +167,10 @@ bool SetVariableSineAction::execute(System* system, const Rect*, const NodeState } return false; } +#if defined(_M_IX86) static_assert(sizeof(SetVariableSineAction) == 20, "client SetVariableSineAction"); static_assert(sizeof(ClassTypeDescriptor) == 16, "SetVariableSineAction metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp b/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp index c1312d26e..58ed61b27 100644 --- a/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp +++ b/Code/BF2/External/BFMeme/SetVariableSoftAction.cpp @@ -1,6 +1,9 @@ // [INFERRED] path. Complete table94CF98, metadata94CD4C and every differing // body/factory/eager instruction read. #include "SetVariableSoftAction.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "Data.h" #include "Node.h" @@ -14,8 +17,10 @@ namespace { // Equal/unordered initial samples perform no write; unordered candidates survive. bool chooseSoftValue(float current, float target, float delta, float speed, float& value) { +#if defined(_WIN32) float rounded; bool changed = false; +#if defined(_M_IX86) __asm { fld target fld current @@ -57,8 +62,31 @@ bool chooseSoftValue(float current, float target, float delta, float speed, floa fstp st(0) done: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // An ordered current below the target moves up, above it moves down; equal or unordered + // samples write nothing. Only an ordered overshoot of the unrounded candidate clamps. + if (current < target) { + const double candidate = static_cast(delta) * speed + current; + rounded = candidate > target ? target : static_cast(candidate); + changed = true; + } else if (current > target) { + const double candidate = current - static_cast(delta) * speed; + rounded = candidate < target ? target : static_cast(candidate); + changed = true; + } +#endif if (changed) value = rounded; return changed; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float rounded; + bool changed = false; + // [CHOSEN, not recovered] Preserve x87 ordered movement and retained candidate comparison. + changed = bf2x87::chooseValue(current, target, delta, speed, 0.0f, false, rounded); + if (changed) value = rounded; + return changed; +#endif } } SetVariableSoftAction::SetVariableSoftAction() : m_speed(100.0f) {} // 8331A0..AC @@ -93,8 +121,10 @@ bool SetVariableSoftAction::execute(System* system, const Rect*, const NodeState } return false; } +#if defined(_M_IX86) static_assert(sizeof(SetVariableSoftAction) == 16, "client SetVariableSoftAction"); static_assert(sizeof(ClassTypeDescriptor) == 16, "SetVariableSoftAction metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/ShowEffectNode.cpp b/Code/BF2/External/BFMeme/ShowEffectNode.cpp index 68eafd631..0ac03e0c6 100644 --- a/Code/BF2/External/BFMeme/ShowEffectNode.cpp +++ b/Code/BF2/External/BFMeme/ShowEffectNode.cpp @@ -69,7 +69,9 @@ void ShowEffectNode::paint(System* system, const NodeState* state, } Node::paint(system, state, bounds, clip, context); } +#if defined(_M_IX86) static_assert(sizeof(ShowEffectNode) == 12, "client ShowEffectNode prefix storage"); static_assert(sizeof(ShowEffectNodeTypeDescriptor) == 16, "ShowEffectNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/SliderNode.h b/Code/BF2/External/BFMeme/SliderNode.h index 07dbb1716..d6b5bc0ad 100644 --- a/Code/BF2/External/BFMeme/SliderNode.h +++ b/Code/BF2/External/BFMeme/SliderNode.h @@ -41,7 +41,9 @@ class SliderNode : public Node Node* m_child1; // +20, ctor null; the thumb, child index 1 NodeState m_state; // +24/+28, ctor {1.0, 1.0} }; +#if defined(_M_IX86) static_assert(sizeof(SliderNode) == 44, "retail and native SliderNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/External/BFMeme/SplitNode.cpp b/Code/BF2/External/BFMeme/SplitNode.cpp index 60c2b1579..ff23976f2 100644 --- a/Code/BF2/External/BFMeme/SplitNode.cpp +++ b/Code/BF2/External/BFMeme/SplitNode.cpp @@ -76,7 +76,9 @@ namespace { // Eager initializer871650 shares the lazy descriptor, registering before lookup. TypeDescriptor* const registeredSplitNodeType = SplitNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(SplitNode) == 12, "client BFMeme SplitNode"); static_assert(sizeof(SplitNodeTypeDescriptor) == 16, "client SplitNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Stream.cpp b/Code/BF2/External/BFMeme/Stream.cpp index 3da873c8c..13bb4e4c7 100644 --- a/Code/BF2/External/BFMeme/Stream.cpp +++ b/Code/BF2/External/BFMeme/Stream.cpp @@ -7,7 +7,21 @@ #include "Event.h" #include "Action.h" #include "Function.h" +#include +#include namespace dice { namespace meme { +// [FRONTIER] [TEMP] [CHOSEN, not recovered] BF2.exe 83D010 publishes the "dice::meme::Tree" +// descriptor (table 94F4D8, base Object, factory 83CFF0: twelve bytes, table 94F440, two zeroed +// fields). No Tree class exists in this tree, so the descriptor is not published; the null-type +// streamTree branch stops here instead. +// [RETIRE-WHEN: MEME-TREE-FAMILY] Recover dice::meme::Tree (table 94F440 and its bodies), then +// define this as Tree::getClassType() and validate a .con/menu load that streams a tree. +TypeDescriptor* getTreeClassType() +{ + std::fprintf(stderr, "[FRONTIER] dice::meme::getTreeClassType reached\n"); + std::fflush(stderr); + std::abort(); +} TypeDescriptor* getEventClassType() { return Event::getClassType(); } TypeDescriptor* getActionClassType() { return Action::getClassType(); } TypeDescriptor* getFunctionClassType() { return Function::getClassType(); } @@ -24,8 +38,8 @@ bool Stream::streamInt(int*, const char*) { return isPassive(); } bool Stream::streamString(char**, const char*) { return isPassive(); } bool Stream::streamWideString(wchar_t**, const char*) { return isPassive(); } bool Stream::streamCharacter(wchar_t*, const char*) { return isPassive(); } -bool Stream::streamTexture(System*, int*, const char*) { return isPassive(); } -bool Stream::streamFont(System*, int*, const char*) { return isPassive(); } +bool Stream::streamTexture(System*, TextureHandle*, const char*) { return isPassive(); } +bool Stream::streamFont(System*, FontHandle*, const char*) { return isPassive(); } bool Stream::streamSound(System*, int*, const char*) { return isPassive(); } bool Stream::streamCollection(System*, ObjectCollection*, const char*) { return isPassive(); } bool Stream::streamEnum(int*, EnumNext, EnumName, const char*) { return isPassive(); } @@ -94,7 +108,9 @@ bool createObject(System* system, Object*& value, TypeDescriptor* type) deletion.streamObject(system, value, "Object", nullptr); // ignored result return false; } +#if defined(_M_IX86) static_assert(sizeof(Stream) == 4, "BFMeme stream prefix"); static_assert(sizeof(DeletionStream) == 8, "BFMeme deletion visitor"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/Stream.h b/Code/BF2/External/BFMeme/Stream.h index a2cfec252..c1f943921 100644 --- a/Code/BF2/External/BFMeme/Stream.h +++ b/Code/BF2/External/BFMeme/Stream.h @@ -39,8 +39,8 @@ class Stream : public RuntimeObject virtual bool streamString(char**, const char*); // +40 virtual bool streamWideString(wchar_t**, const char*); // +44 virtual bool streamCharacter(wchar_t*, const char*); // +48 - virtual bool streamTexture(System*, int*, const char*); // +4C 837D20 - virtual bool streamFont(System*, int*, const char*); // +50 + virtual bool streamTexture(System*, TextureHandle*, const char*); // +4C 837D20 + virtual bool streamFont(System*, FontHandle*, const char*); // +50 virtual bool streamSound(System*, int*, const char*); // +54 virtual bool streamCollection(System*, ObjectCollection*, const char*); // +58 virtual bool streamEnum(int*, EnumNext, EnumName, const char*); // +5C 837D30 @@ -85,7 +85,7 @@ TypeDescriptor* getActionClassType(); // 83C320, complete Action TypeDescriptor* getEffectClassType(); // 82D860, complete Effect family TypeDescriptor* getFunctionClassType(); // 82E510, complete Function family TypeDescriptor* getNodeClassType(); // 82C190, real native-prefix metadata/factory; suffix caller stops -TypeDescriptor* getTreeClassType(); // 83D010 [FRONTIER] +TypeDescriptor* getTreeClassType(); // 83D010 [FRONTIER] stops; Tree family unrecovered } } #endif #endif diff --git a/Code/BF2/External/BFMeme/Style.cpp b/Code/BF2/External/BFMeme/Style.cpp index 2620f2616..5dc623df3 100644 --- a/Code/BF2/External/BFMeme/Style.cpp +++ b/Code/BF2/External/BFMeme/Style.cpp @@ -26,7 +26,7 @@ char* cloneStyleName(const char* name) // shared helper0x737DC0 } } -Style::Style(const char* name, int font) +Style::Style(const char* name, FontHandle font) : m_font(font), m_name(cloneStyleName(name)) { // Retail deliberately leaves m_shadowFont and both scale fields untouched. @@ -199,7 +199,9 @@ void Style::positionGlyphInt(Rect* output, const GlyphMetrics* metrics, *y = static_cast(floatY); } +#if defined(_M_IX86) static_assert(sizeof(Style) == 24, "PE Style allocation"); +#endif static_assert(sizeof(GlyphMetrics) == 20, "five scalar glyph metrics"); static_assert(sizeof(Rect) == 20, "five scalar drawing bounds"); } } diff --git a/Code/BF2/External/BFMeme/Style.h b/Code/BF2/External/BFMeme/Style.h index 1dd1622ef..c441850cd 100644 --- a/Code/BF2/External/BFMeme/Style.h +++ b/Code/BF2/External/BFMeme/Style.h @@ -22,7 +22,7 @@ struct Rect class Style : public Object { public: - Style(const char* name = 0, int font = 0); + Style(const char* name = 0, FontHandle font = 0); ~Style() override; TypeDescriptor* getType() override; unsigned int getObjectSize() override; @@ -42,8 +42,8 @@ class Style : public Object static TypeDescriptor* getClassType(); // 838C90, descriptor factory838D40 protected: - int m_font; // +04, integer handle - int m_shadowFont; // +08, not written by ctor + FontHandle m_font; // +04, integer handle + FontHandle m_shadowFont; // +08, not written by ctor char* m_name; // +0C, owned clone float m_scale, m_reciprocalScale; // +10/+14, not written by ctor }; diff --git a/Code/BF2/External/BFMeme/System.cpp b/Code/BF2/External/BFMeme/System.cpp index f651a98f8..cb4855caa 100644 --- a/Code/BF2/External/BFMeme/System.cpp +++ b/Code/BF2/External/BFMeme/System.cpp @@ -42,7 +42,9 @@ class SystemTypeDescriptor final : public TypeDescriptor static int instanceCount; }; int SystemTypeDescriptor::instanceCount = 0; +#if defined(_M_IX86) static_assert(sizeof(SystemTypeDescriptor) == 16, "System metadata stores its counter separately"); +#endif // A3970C is a plain dword whose bit zero is set before construction. Retail has no lock and no // exception rollback here; avoid the compiler's C++11 thread-safe function-static guard. @@ -164,19 +166,19 @@ OStream* System::createOutputStream(const char*) { return nullptr; } void System::deleteOutputStream(OStream* stream) { delete stream; } void System::deleteInputStream(IStream* stream) { delete stream; } bool System::pointerPositionChanged(float*, float*) { return true; } -bool System::drawCharacter(int, int, Quad*) { return false; } -bool System::getGlyphMetrics(int, int, GlyphMetrics*) { return false; } -float System::getKerning(int, int, int) { return 0.0f; } -float System::getFontHeight(int) { return 0.0f; } -int System::loadFont(const char*) { return 0; } -const char* System::getFontName(int) { return nullptr; } -bool System::drawTexture(int, Quad*) { return false; } -int System::loadTexture(const char*, bool) { return 0; } -void System::releaseTexture(int) {} // 5AB2A0, real empty default -const char* System::getTextureName(int) { return nullptr; } -float System::getTextureWidth(int) { return 0.0f; } -float System::getTextureHeight(int) { return 0.0f; } -void System::setDefaultTexture(int texture) { m_field054 = texture; } +bool System::drawCharacter(int, FontHandle, Quad*) { return false; } +bool System::getGlyphMetrics(int, FontHandle, GlyphMetrics*) { return false; } +float System::getKerning(int, int, FontHandle) { return 0.0f; } +float System::getFontHeight(FontHandle) { return 0.0f; } +FontHandle System::loadFont(const char*) { return 0; } +const char* System::getFontName(FontHandle) { return nullptr; } +bool System::drawTexture(TextureHandle, Quad*) { return false; } +TextureHandle System::loadTexture(const char*, bool) { return 0; } +void System::releaseTexture(TextureHandle) {} // 5AB2A0, real empty default +const char* System::getTextureName(TextureHandle) { return nullptr; } +float System::getTextureWidth(TextureHandle) { return 0.0f; } +float System::getTextureHeight(TextureHandle) { return 0.0f; } +void System::setDefaultTexture(TextureHandle texture) { m_field054 = texture; } bool System::playSound(int, float) { return false; } // 455420, real default int System::loadSound(const char*) { return 0; } const char* System::getSoundName(int) { return nullptr; } @@ -255,7 +257,9 @@ class EventNodeVisitor : public NodeVisitor private: NodeInputEvent m_event; }; +#if defined(_M_IX86) static_assert(sizeof(EventNodeVisitor) == 28, "client generic event visitor"); +#endif Node* castMenuNode(Object* object) { @@ -355,9 +359,11 @@ void systemPrintf(System* system, const char* format, ...) } } +#if defined(_M_IX86) static_assert(sizeof(Object) == 4, "BF2 client Object prefix size"); static_assert(sizeof(OStream) == 4, "Ref2System embeds a four-byte OStream"); static_assert(sizeof(System) == 0x58, "System has no STL-dependent members"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/System.h b/Code/BF2/External/BFMeme/System.h index 14b29589f..5840fc2ef 100644 --- a/Code/BF2/External/BFMeme/System.h +++ b/Code/BF2/External/BFMeme/System.h @@ -47,24 +47,24 @@ class System : public Object // +6C: Pointer829000 passes addresses of its two float arguments. Pointer // versus reference source spelling and method name are [INFERRED]. virtual bool pointerPositionChanged(float* x, float* y); - virtual bool drawCharacter(int character, int font, Quad*); - virtual bool getGlyphMetrics(int character, int font, GlyphMetrics*); + virtual bool drawCharacter(int character, FontHandle font, Quad*); + virtual bool getGlyphMetrics(int character, FontHandle font, GlyphMetrics*); // Source character spelling [INFERRED]; full dwords cross Font+10 and the // .dif backend deliberately keeps only the low sixteen bits of each key. - virtual float getKerning(int previous, int current, int font); - virtual float getFontHeight(int font); // +7C 829A30 - virtual int loadFont(const char* name); - virtual const char* getFontName(int font); - virtual bool drawTexture(int texture, Quad*); - virtual int loadTexture(const char* name, bool menuPath); // +8C 6212F0 - virtual void releaseTexture(int texture); - virtual const char* getTextureName(int texture); - virtual float getTextureWidth(int texture); - virtual float getTextureHeight(int texture); // +9C 829A30 + virtual float getKerning(int previous, int current, FontHandle font); + virtual float getFontHeight(FontHandle font); // +7C 829A30 + virtual FontHandle loadFont(const char* name); + virtual const char* getFontName(FontHandle font); + virtual bool drawTexture(TextureHandle texture, Quad*); + virtual TextureHandle loadTexture(const char* name, bool menuPath); // +8C 6212F0 + virtual void releaseTexture(TextureHandle texture); + virtual const char* getTextureName(TextureHandle texture); + virtual float getTextureWidth(TextureHandle texture); + virtual float getTextureHeight(TextureHandle texture); // +9C 829A30 // Setter return spelling is [INFERRED]: HUD7583D5 supplies loadTexture's // int handle and discards EAX.5C9490 leaves the stored argument in EAX; // that alone does not prove a source-level return value. - virtual void setDefaultTexture(int texture); // +A0 5C9490 + virtual void setDefaultTexture(TextureHandle texture); // +A0 5C9490 virtual bool playSound(int sound, float volume); // +A4 455420 virtual int loadSound(const char* name); // +A8 4553E0 virtual const char* getSoundName(int sound); // +AC 4553E0 @@ -120,7 +120,7 @@ class System : public Object EventQueue* m_eventQueue; // +48 IStream* m_field04c; // +4C, cache replay input; wrappers borrow it OStream* m_field050; // +50, cache recording output; wrappers borrow it - int m_field054; // +54, default texture handle + TextureHandle m_field054; // +54, default texture handle }; // 0x82A340; exact return is unused by recovered callers, source name [INFERRED]. diff --git a/Code/BF2/External/BFMeme/TextNode.cpp b/Code/BF2/External/BFMeme/TextNode.cpp index 1022bc382..9349be783 100644 --- a/Code/BF2/External/BFMeme/TextNode.cpp +++ b/Code/BF2/External/BFMeme/TextNode.cpp @@ -73,7 +73,9 @@ void drawStyledText(System* system, Style* style, const Rect* bounds, style->drawText(system, data, elementIndex, bounds, clip, context); } +#if defined(_M_IX86) static_assert(sizeof(BfTextNode) == 24, "native BfTextNode storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "BfTextNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/TextNode.h b/Code/BF2/External/BFMeme/TextNode.h index 2b4cc07ae..57ca97378 100644 --- a/Code/BF2/External/BFMeme/TextNode.h +++ b/Code/BF2/External/BFMeme/TextNode.h @@ -26,7 +26,9 @@ class BfTextNode : public Node Data* m_type; // +10, streamed as "Type", borrowed; gates the paint ColorEffect* m_shadow; // +14, owned; the constructor allocates a black one }; +#if defined(_M_IX86) static_assert(sizeof(BfTextNode) == 24, "native BfTextNode storage"); +#endif // A free __fastcall helper, not a member: the System and the Style sit // in ECX/EDX and the rest on the stack. Name [INFERRED]. diff --git a/Code/BF2/External/BFMeme/ToggleData.cpp b/Code/BF2/External/BFMeme/ToggleData.cpp index 443696fec..fa2f60030 100644 --- a/Code/BF2/External/BFMeme/ToggleData.cpp +++ b/Code/BF2/External/BFMeme/ToggleData.cpp @@ -60,7 +60,9 @@ int ToggleData::getCharacter(System* system, int character) Data* selected = m_toggle && m_toggle->getFloat(system) == 0.0f ? m_first : m_second; return selected ? selected->getCharacter(system, character) : 0; } +#if defined(_M_IX86) static_assert(sizeof(ToggleData) == 20, "client ToggleData"); static_assert(sizeof(ToggleDataDescriptor) == 16, "client ToggleData metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/TransformNode.cpp b/Code/BF2/External/BFMeme/TransformNode.cpp index 666df438b..56a5c7b85 100644 --- a/Code/BF2/External/BFMeme/TransformNode.cpp +++ b/Code/BF2/External/BFMeme/TransformNode.cpp @@ -1,5 +1,8 @@ // Transform-node state updates and metadata; unsupported Node suffix calls retain diagnostic stops. #include "TransformNode.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../../Math/PortableX87.h" +#endif #if !DEDICATED #include "NodeState.h" #include "Stream.h" @@ -30,6 +33,8 @@ class TransformNodeTypeDescriptor final : public TypeDescriptor unsigned int getInstanceSize() override { return sizeof(TransformNode); } }; +// PE 0x101C4BA0: RendDX9's standalone copy (ecx = value, stream and the two names on the stack, retn +// 0xC); unreachable in 1.50 there: no code or data references. bool streamPair(hfe::Vec2& value, Stream* stream, const char* first, const char* second) { if (!stream->streamFloat(&value.x, first)) return false; @@ -37,6 +42,8 @@ bool streamPair(hfe::Vec2& value, Stream* stream, const char* first, const char* } float decodedState(float value) // float stores in838F40 and82D340 { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld value @@ -51,6 +58,20 @@ float decodedState(float value) // float stores in838F40 and82D340 fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered negative value is decoded; zero, positive and NaN pass through the + // double round trip, which quiets a signalling NaN as fld/fstp does. + const double loaded = value; + return static_cast(value < 0.0f ? -(loaded + 1.0) : loaded); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 negative-state decoding and float store. + result = bf2x87::store(bf2x87::decoded(value)); + return result; +#endif } float stateRate(const NodeState& state) // 838F40 ->82BD30; System/Node receivers unused { @@ -62,6 +83,8 @@ float stateRate(const NodeState& state) // 838F40 ->82BD30; System/Node receiver } bool sumNotLess(float first, float second, float limit) // 82D49E..4BB, unordered passes { +#if defined(_WIN32) +#if defined(_M_IX86) bool result; __asm { fld first @@ -72,6 +95,19 @@ bool sumNotLess(float first, float second, float limit) // 82D49E..4BB, unordere setp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // setp after test ah,5: false only for an ordered sum below the limit. + const double sum = static_cast(first) + second; + return !(sum < limit); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + bool result; + // [CHOSEN, not recovered] Preserve x87 unordered-or-not-less sum. + result = bf2x87::sumNotLess(first, second, limit); + return result; +#endif } } @@ -154,7 +190,9 @@ void TransformNode::reset() // 82D560; Node's real+C4 dispatch remains a named f if (m_child) m_child->reset(); Node::reset(); } +#if defined(_M_IX86) static_assert(sizeof(TransformNode) == 36, "native x86 TransformNode storage"); static_assert(sizeof(TransformNodeTypeDescriptor) == 16, "native TransformNode metadata"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/TypeDescriptor.cpp b/Code/BF2/External/BFMeme/TypeDescriptor.cpp index d44a33f7c..359d34f8b 100644 --- a/Code/BF2/External/BFMeme/TypeDescriptor.cpp +++ b/Code/BF2/External/BFMeme/TypeDescriptor.cpp @@ -61,6 +61,8 @@ bool TypeDescriptor::isDerivedFrom(TypeDescriptor* base) } return true; } +#if defined(_M_IX86) static_assert(sizeof(TypeDescriptor) == 16, "BFMeme descriptor layout"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/VariableColorEffect.cpp b/Code/BF2/External/BFMeme/VariableColorEffect.cpp index 4ac35d466..cb10cfbca 100644 --- a/Code/BF2/External/BFMeme/VariableColorEffect.cpp +++ b/Code/BF2/External/BFMeme/VariableColorEffect.cpp @@ -34,7 +34,7 @@ bool VariableColorEffect::streamProperties(System* system, Stream* stream) && stream->streamData(system, m_alpha, "Alpha", nullptr); } -bool VariableColorEffect::drawCharacter(System* system, int character, int font, +bool VariableColorEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { // read each current field only after the preceding callback. Each @@ -48,7 +48,7 @@ bool VariableColorEffect::drawCharacter(System* system, int character, int font, return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool VariableColorEffect::drawTexture(System* system, int texture, Quad* quad, +bool VariableColorEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { // 7CAC40 has the same ordered sampling, including independent null defaults. @@ -61,7 +61,9 @@ bool VariableColorEffect::drawTexture(System* system, int texture, Quad* quad, return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(ClassTypeDescriptor) == 16, "VariableColorEffect metadata storage"); +#endif } } #endif diff --git a/Code/BF2/External/BFMeme/VariableColorEffect.h b/Code/BF2/External/BFMeme/VariableColorEffect.h index 3bb8f02ec..7402601b3 100644 --- a/Code/BF2/External/BFMeme/VariableColorEffect.h +++ b/Code/BF2/External/BFMeme/VariableColorEffect.h @@ -14,9 +14,9 @@ class VariableColorEffect : public Effect TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; static TypeDescriptor* getClassType(); protected: Data* m_red; // +04, all borrowed @@ -24,7 +24,9 @@ class VariableColorEffect : public Effect Data* m_blue; // +0C Data* m_alpha; // +10 }; +#if defined(_M_IX86) static_assert(sizeof(VariableColorEffect) == 20, "client VariableColorEffect"); +#endif } } #endif #endif diff --git a/Code/BF2/External/GameSpy/LOCAL_CHANGES.md b/Code/BF2/External/GameSpy/LOCAL_CHANGES.md index 858a2f74f..47cec5138 100644 --- a/Code/BF2/External/GameSpy/LOCAL_CHANGES.md +++ b/Code/BF2/External/GameSpy/LOCAL_CHANGES.md @@ -8,7 +8,17 @@ keep integration changes identifiable in the source. | --- | --- | --- | | `serverbrowsing/sb_serverbrowsing.c`: `ServerBrowserAuxUpdateIP` | Check for an existing server address before starting and appending a new server. | Avoid rejecting the newly appended server as its own duplicate before the synchronous wait. | | `qr2/qr2.c`: `qr2_init_socketA` | Initialize `denyresp2_ip_callback` to `NULL` with the other callbacks. | The enabled query-parser hook must not call an uninitialized function pointer. | +| `common/gsPlatformSocket.h`: `_MACOSX` socket-call macros | Apply the `socklen_t` casting macros to C translation units only. | Macro definitions such as `connect(s,a,al)` rewrite C++ member functions of the same name in engine sources that include the SDK; the engine already passes `socklen_t`. Affects only the macOS port. | Both client and dedicated-server integrations can use these shared SDK files. +S2.10 adds these POSIX-only changes, all [CHOSEN, not recovered]: + +- `common/{linux,macosx}/gsThread*.c`: sequentially consistent atomic increment/decrement, + returning the new value. The SDK previously asserted and returned 1. +- `common/gsCore.c`: sequentially consistent atomic loads/stores for initialization/shutdown + flags and the reference-count read; the C record layout and task-list critical section stay intact. +- `natneg/natneg.c`, `NNProcessData`: reject input shorter than the base header before reading + its magic/type. Packed payloads already copy with `memcpy`. + Changing the SDK revision requires checking the interfaces and behavior used by those integrations. diff --git a/Code/BF2/External/GameSpy/common/gsCore.c b/Code/BF2/External/GameSpy/common/gsCore.c index d23f8f196..777f77562 100644 --- a/Code/BF2/External/GameSpy/common/gsCore.c +++ b/Code/BF2/External/GameSpy/common/gsCore.c @@ -9,6 +9,13 @@ #include "gsAssert.h" #include "../ghttp/ghttp.h" +/* [CHOSEN, not recovered] C SDK publication flags on POSIX use the same sequentially + consistent operations as its Interlocked reference count. Keep the SDK's scalar layout. */ +#if defined(_MACOSX) || defined(_LINUX) +#define GSI_CORE_LOAD(word) __atomic_load_n(&(word), __ATOMIC_SEQ_CST) +#define GSI_CORE_STORE(word, value) __atomic_store_n(&(word), (value), __ATOMIC_SEQ_CST) +#endif + @@ -51,14 +58,22 @@ void gsCoreInitialize() GSCoreMgr* aCore = gsiGetStaticCore(); // Is someone else shutting down the core? +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_true(GSI_CORE_LOAD(aCore->mIsShuttingDown))) +#else while(gsi_is_true(aCore->mIsShuttingDown)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); // yield to other thread // If we're the first reference, initialize the core if (gsiInterlockedIncrement(&aCore->mRefCount) == 1) { // Are we the first ever? +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_false(GSI_CORE_LOAD(aCore->mIsStaticInitComplete))) +#else if (gsi_is_false(aCore->mIsStaticInitComplete)) +#endif { // perform one-time initialization of core critical section gsiInitializeCriticalSection(&aCore->mQueueCrit); @@ -69,7 +84,11 @@ void gsCoreInitialize() #endif // one time init completed +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsStaticInitComplete, gsi_true); +#else aCore->mIsStaticInitComplete = gsi_true; +#endif } // take the critical section to begin initialization @@ -79,7 +98,11 @@ void gsCoreInitialize() // wait here if another thread is concurrently shutting down the core // we may need to wait a few times if the shutdown does not complete immediately +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_true(GSI_CORE_LOAD(aCore->mIsShuttingDown))) +#else while(gsi_is_true(aCore->mIsShuttingDown)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); // Setup the task array @@ -95,14 +118,22 @@ void gsCoreInitialize() // release other threads that may have blocked during init // - this must be the last thing done at end of init +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsInitialized, gsi_true); +#else aCore->mIsInitialized = gsi_true; +#endif } else { // Core is already initialized -OR- another thread will initialize the core // make sure critical section has been initialized +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_false(GSI_CORE_LOAD(aCore->mIsStaticInitComplete))) +#else while(gsi_is_false(aCore->mIsStaticInitComplete)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); // take the critical section @@ -111,7 +142,11 @@ void gsCoreInitialize() gsiLeaveCriticalSection(&aCore->mQueueCrit); // wait for other thread to initial core +#if defined(_MACOSX) || defined(_LINUX) + while(gsi_is_false(GSI_CORE_LOAD(aCore->mIsInitialized))) +#else while(gsi_is_false(aCore->mIsInitialized)) +#endif msleep(GSI_CORE_INIT_YIELD_MS); } } @@ -231,7 +266,11 @@ void gsCoreThink(gsi_time theMS) gsi_time aStartTime = 0; gsi_i32 allTasksAreDead = 1; +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_false(GSI_CORE_LOAD(aCore->mIsInitialized))) +#else if (gsi_is_false(aCore->mIsInitialized)) +#endif return; // enter queue critical section @@ -273,7 +312,11 @@ void gsCoreThink(gsi_time theMS) #endif // shutting down? +#if defined(_MACOSX) || defined(_LINUX) + if (GSI_CORE_LOAD(aCore->mIsShuttingDown) && allTasksAreDead) +#else if (aCore->mIsShuttingDown && allTasksAreDead) +#endif { ghttpCleanup(); @@ -285,7 +328,11 @@ void gsCoreThink(gsi_time theMS) } #endif +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsShuttingDown, 0); +#else aCore->mIsShuttingDown = 0; +#endif } // leave queue critical section @@ -303,7 +350,11 @@ void gsCoreShutdown() int i=0; // If not initialized, just bail +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_false(GSI_CORE_LOAD(aCore->mIsInitialized))) +#else if (gsi_is_false(aCore->mIsInitialized)) +#endif return; // Take the critical section to prevent anyone from re-initializing while @@ -321,7 +372,11 @@ void gsCoreShutdown() // we released the final reference, begin shutdown // no other thread will begin using the core until // mIsShuttingDown has been set back to false +#if defined(_MACOSX) || defined(_LINUX) + GSI_CORE_STORE(aCore->mIsShuttingDown, gsi_true); +#else aCore->mIsShuttingDown = gsi_true; +#endif // Cancel all tasks #ifdef GSICORE_DYNAMIC_TASK_LIST @@ -352,9 +407,17 @@ GSCoreValue gsCoreIsShutdown() { GSCoreMgr* aCore = gsiGetStaticCore(); +#if defined(_MACOSX) || defined(_LINUX) + if (gsi_is_true(GSI_CORE_LOAD(aCore->mIsShuttingDown))) +#else if (gsi_is_true(aCore->mIsShuttingDown)) +#endif return GSCore_SHUTDOWN_PENDING; +#if defined(_MACOSX) || defined(_LINUX) + if (GSI_CORE_LOAD(aCore->mRefCount) == 0) +#else if (aCore->mRefCount == 0) +#endif return GSCore_SHUTDOWN_COMPLETE; // The core isn't shutting down, and ref count > 0, diff --git a/Code/BF2/External/GameSpy/common/gsPlatformSocket.h b/Code/BF2/External/GameSpy/common/gsPlatformSocket.h index ab7f2e079..bb2c5b6d8 100644 --- a/Code/BF2/External/GameSpy/common/gsPlatformSocket.h +++ b/Code/BF2/External/GameSpy/common/gsPlatformSocket.h @@ -588,7 +588,9 @@ int gsiShutdown(SOCKET s, int how); #define EWOULDBLOCK sceNET_EWOULDBLOCK #endif -#if defined(_MACOSX) +// [CHOSEN, not recovered] OpenBF2 macOS port: C only. In C++ these function-like macros rename +// every member called connect/bind/accept (StatsManager::connect); the engine passes socklen_t. +#if defined(_MACOSX) && !defined(__cplusplus) #define accept(s,a,al) accept(s,a,(socklen_t*)(al)) #define bind(s,a,al) bind(s,a,(socklen_t)(al)) #define connect(s,a,al) connect(s,a,(socklen_t)(al)) diff --git a/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c b/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c index a06181697..d5656dcf8 100644 --- a/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c +++ b/Code/BF2/External/GameSpy/common/linux/gsThreadLinux.c @@ -22,14 +22,13 @@ gsi_u32 gsiInterlockedIncrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for LINUX in the current version of the SDK\n"); - return 1; + /* [CHOSEN, not recovered] POSIX atomic increment returns the new value, as Win32 does. */ + return __atomic_add_fetch(value, 1, __ATOMIC_SEQ_CST); } gsi_u32 gsiInterlockedDecrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for LINUX in the current version of the SDK\n"); - return 1; + return __atomic_sub_fetch(value, 1, __ATOMIC_SEQ_CST); } /////////////////////////////////////////////////////////////////////////////// diff --git a/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c b/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c index e0522a5b6..06e4b54e7 100644 --- a/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c +++ b/Code/BF2/External/GameSpy/common/macosx/gsThreadMacOSX.c @@ -23,14 +23,13 @@ gsi_u32 gsiInterlockedIncrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for Mac OSX in the current version of the SDK\n"); - return 1; + /* [CHOSEN, not recovered] POSIX atomic increment returns the new value, as Win32 does. */ + return __atomic_add_fetch(value, 1, __ATOMIC_SEQ_CST); } gsi_u32 gsiInterlockedDecrement(gsi_u32 * value) { - GS_ASSERT_STR(gsi_false, "gsiInterlockIncrement is unsupported for Mac OSX in the current version of the SDK\n"); - return 1; + return __atomic_sub_fetch(value, 1, __ATOMIC_SEQ_CST); } /////////////////////////////////////////////////////////////////////////////// diff --git a/Code/BF2/External/GameSpy/natneg/natneg.c b/Code/BF2/External/GameSpy/natneg/natneg.c index 2f778e751..e85ed9d47 100644 --- a/Code/BF2/External/GameSpy/natneg/natneg.c +++ b/Code/BF2/External/GameSpy/natneg/natneg.c @@ -771,6 +771,13 @@ void NNProcessData(char *data, int len, struct sockaddr_in *fromaddr) NATNegotiator neg; unsigned char ptype; +#if defined(_MACOSX) || defined(_LINUX) + /* [CHOSEN, not recovered] Inspect only a complete header before reading its magic/type. + Payloads below already use memcpy into packed local storage, never atomic word access. */ + if (len < BASEPACKET_SIZE) + return; +#endif + if (!CheckMagic(data)) return; //invalid packet diff --git a/Code/BF2/External/NovintHFX/NovintHFX.h b/Code/BF2/External/NovintHFX/NovintHFX.h index 6c65a7c8c..55fd5c223 100644 --- a/Code/BF2/External/NovintHFX/NovintHFX.h +++ b/Code/BF2/External/NovintHFX/NovintHFX.h @@ -41,5 +41,9 @@ class HapticsSystem { // address. This is neither a pointer variable nor a callable Haptics() function. extern "C" __declspec(dllimport) NovintHFX::HapticsSystem Haptics; static_assert(sizeof(NovintHFX::ApplicationData::mouse_settings) == 28, "SDK ABI"); +#if defined(_M_IX86) static_assert(sizeof(NovintHFX::ApplicationData) == 32, "x86 SDK ABI"); #endif +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the SDK exists only as a +// 32-bit DLL, so an x64 image imports nothing from it; FalconDevice reports no device there. +#endif diff --git a/Code/BF2/External/README.md b/Code/BF2/External/README.md index 7ac699a82..c30fc07f9 100644 --- a/Code/BF2/External/README.md +++ b/Code/BF2/External/README.md @@ -16,6 +16,8 @@ local changes small and documented alongside the affected dependency. | libogg 1.3.6 and libvorbis 1.3.7 | `libogg-1.3.6/` and `libvorbis-1.3.7/`; Xiph.Org sources | BF2Audio Ogg/Vorbis decoding | | Dear ImGui | `imgui/`; `v1.92.9b-docking`, commit `b48d1af` | Editor UI | | ImGuizmo | `ImGuizmo/`; tag `1.10`, commit `b796ac3` | Editor transform gizmo | +| FFmpeg Bink decoders | `ffmpeg-bink/`; seven unmodified files of FFmpeg 7.1.1 plus an OpenBF2 shim ([README](ffmpeg-bink/README.md)), LGPL-2.1+ | Bink movie playback on macOS and Windows x64 (`RendDX9Abi/BinkFFmpeg.cpp`); Windows x86 uses RAD's `binkw32.dll` | +| meshoptimizer | `meshoptimizer/`; `src/meshoptimizer.h` and `src/stripifier.cpp` of zeux/meshoptimizer tag `v1.3`, unmodified, MIT ([LICENSE](meshoptimizer/LICENSE.md)) | macOS D3DX subset: `D3DXConvertMeshSubsetToSingleStrip` (`Platform/Gfx/Metal/D3DXMesh.cpp`) | The table describes the vendored inputs, not a promise that every SDK module is part of each executable. Build manifests select the files for each image. @@ -24,7 +26,9 @@ covered by the claim that an upstream library is unmodified. The individual sources and license files govern their respective components. Keep the [Python license](python-embedded/py-src-2.3.4/LICENSE), -[Dear ImGui license](imgui/LICENSE.txt), and [ImGuizmo license](ImGuizmo/LICENSE) +[FFmpeg LGPL notice](ffmpeg-bink/COPYING.LGPLv2.1), +[Dear ImGui license](imgui/LICENSE.txt), [ImGuizmo license](ImGuizmo/LICENSE) and +[meshoptimizer license](meshoptimizer/LICENSE.md) with their distributions. Other dependencies carry notices in their source files and accompanying upstream documentation. diff --git a/Code/BF2/External/base/container.cpp b/Code/BF2/External/base/container.cpp index 65a48c313..948a8ab68 100644 --- a/Code/BF2/External/base/container.cpp +++ b/Code/BF2/External/base/container.cpp @@ -173,7 +173,13 @@ void tu_string::encode_utf8_from_wchar(tu_string* result, const uint16* wstr) #ifdef _WIN32 return ::stricmp(a, b); #else - return strcasecmp(a, b); + // [CHOSEN, not recovered] Qualified: Core/PlatformCompat.h (force-included on POSIX) defines + // `stricmp` as `strcasecmp`, which renames this member to tu_string::strcasecmp. An + // unqualified call then found the member itself (unbounded self-recursion, which -O2 + // folded into a garbage result), so every tu_stringi comparison failed and no + // stringi_hash lookup ever matched: _global.Object/Array/ASSetPropFlags and all + // menu namespaces were "absent" to ActionScript (docs/macos-c-asan-heap.md). + return ::strcasecmp(a, b); #endif } diff --git a/Code/BF2/External/base/container.h b/Code/BF2/External/base/container.h index d1111397e..274fb044e 100644 --- a/Code/BF2/External/base/container.h +++ b/Code/BF2/External/base/container.h @@ -472,8 +472,12 @@ class hash { assert(m_table); m_table->m_entry_count++; - unsigned int hash_value = hash_functor()(key); - int index = hash_value & m_table->m_size_mask; + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the stored hash + // keeps the functor's full size_t, as find_index() compares it. The upstream unsigned int, + // widened through entry()'s int parameter, sign-extended on x64 and lost every key whose + // hash had bit 31 set. Same 32-bit values on x86. + size_t hash_value = hash_functor()(key); + int index = (int) (hash_value & m_table->m_size_mask); entry* natural_entry = &(E(index)); @@ -643,7 +647,7 @@ class hash { : m_next_in_chain(e.m_next_in_chain), m_hash_value(e.m_hash_value), first(e.first), second(e.second) { } - entry(const T& key, const U& value, int next_in_chain, int hash_value) + entry(const T& key, const U& value, int next_in_chain, size_t hash_value) // [CHOSEN, not recovered] x64 (issue 7): was int : m_next_in_chain(next_in_chain), m_hash_value(hash_value), first(key), second(value) { } @@ -846,7 +850,7 @@ class hash { } // Force new_size to be a power of two. - int bits = fchop(log2((float)(new_size-1)) + 1); + int bits = fchop(tu_util::log2((float)(new_size-1)) + 1); assert((1 << bits) >= new_size); new_size = 1 << bits; diff --git a/Code/BF2/External/base/tu_math.h b/Code/BF2/External/base/tu_math.h index 8dcfa69a8..64214d7d1 100644 --- a/Code/BF2/External/base/tu_math.h +++ b/Code/BF2/External/base/tu_math.h @@ -13,7 +13,10 @@ #include // OSX doesn't have single precision math functions defined in math.h -#ifdef __MACH__ +// [BUILD-FIX SwiffPlayer: every supported macOS SDK declares the float functions, and these macros +// rename unrelated identifiers (renddx9abi::logf). The Windows build never took this branch, so +// it stays off on macOS too and the menu player uses the same float math everywhere.] +#if defined(__MACH__) && 0 #define sinf sin #define cosf cos #define tanf tan diff --git a/Code/BF2/External/base/tu_types.h b/Code/BF2/External/base/tu_types.h index d6d7ffaf5..53a562f71 100644 --- a/Code/BF2/External/base/tu_types.h +++ b/Code/BF2/External/base/tu_types.h @@ -15,7 +15,9 @@ #include -#if defined(__i386__) || defined(_WIN32) +// [BUILD-FIX SwiffPlayer: the 64-bit macOS client (docs/macos-port.md) adds x86-64 and AArch64, +// both little-endian with 32-bit int and 64-bit long long. Without them base falls back to SDL.] +#if defined(__i386__) || defined(_WIN32) || defined(__x86_64__) || defined(__aarch64__) // On known little-endian platforms, define this stuff. #define _TU_LITTLE_ENDIAN_ 1 diff --git a/Code/BF2/External/base/utility.cpp b/Code/BF2/External/base/utility.cpp index 262805c0f..51235b658 100644 --- a/Code/BF2/External/base/utility.cpp +++ b/Code/BF2/External/base/utility.cpp @@ -14,7 +14,11 @@ int tu_testbed_assert_break(const char* filename, int linenum, const char* expression) { // @@ TODO output print error message +#if defined(_M_IX86) __asm { int 3 } +#else + __debugbreak(); // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): no inline asm +#endif return 0; } diff --git a/Code/BF2/External/base/utility.h b/Code/BF2/External/base/utility.h index 3a06b30ec..c64079d97 100644 --- a/Code/BF2/External/base/utility.h +++ b/Code/BF2/External/base/utility.h @@ -24,8 +24,17 @@ // On windows, replace ANSI assert with our own, for a less annoying // debugging experience. //int tu_testbed_assert_break(const char* filename, int linenum, const char* expression); +#if !defined(_M_IX86) +#include // __debugbreak, the x64 arm below +#endif #undef assert +#if defined(_M_IX86) #define assert(x) if (!(x)) { __asm { int 3 } } // tu_testbed_assert_break(__FILE__, __LINE__, #x)) +#else +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): no inline asm on x64; +// the same breakpoint through the intrinsic. +#define assert(x) if (!(x)) { __debugbreak(); } +#endif #endif // not NDEBUG #endif // _WIN32 @@ -74,11 +83,19 @@ void operator delete[](void* ptr); // some misc handy math functions // +// [BUILD-FIX SwiffPlayer: fmax, fmin and log2(float) live in namespace tu_util and are called +// qualified. libc++'s brings std::fmax/fmin/log2(float) into the global namespace, where +// these global definitions conflict. The C library versions answer differently for NaN and +// signed-zero inputs (fmax(NaN, 1) is 1 there, NaN or 1 here depending on order), so gameswf keeps +// its own comparisons on every toolchain.] +namespace tu_util { +inline float fmax(float a, float b) { if (a < b) return b; else return a; } +inline float fmin(float a, float b) { if (a < b) return a; else return b; } +} + inline int iabs(int i) { if (i < 0) return -i; else return i; } inline int imax(int a, int b) { if (a < b) return b; else return a; } -inline float fmax(float a, float b) { if (a < b) return b; else return a; } inline int imin(int a, int b) { if (a < b) return a; else return b; } -inline float fmin(float a, float b) { if (a < b) return a; else return b; } inline int iclamp(int i, int min, int max) { @@ -88,13 +105,15 @@ inline int iclamp(int i, int min, int max) { inline float fclamp(float f, float xmin, float xmax) { assert( xmin <= xmax ); - return fmax(xmin, fmin(f, xmax)); + return tu_util::fmax(xmin, tu_util::fmin(f, xmax)); } inline float flerp(float a, float b, float f) { return (b - a) * f + a; } const float LN_2 = 0.693147180559945f; -inline float log2(float f) { return logf(f) / LN_2; } +namespace tu_util { +inline float log2(float f) { return logf(f) / LN_2; } // [BUILD-FIX SwiffPlayer: see fmax above.] +} inline int fchop( float f ) { return (int) f; } // replace w/ inline asm if desired inline int frnd(float f) { return fchop(f + 0.5f); } // replace with inline asm if desired diff --git a/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md b/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md index d6a8cb10d..237d97530 100644 --- a/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md +++ b/Code/BF2/External/gameswf/GAMESWF_DIVERGENCES.md @@ -29,7 +29,7 @@ versions. | Area | Main files | Behavior to preserve | | --- | --- | --- | -| Build configuration | `gameswf_shape.cpp`, build manifest | Disable the optional OpenGL shape-debug path. Exclude the inactive XMLSocket translation unit, whose unconditional SDL include is unavailable in this build. | +| Build configuration | `gameswf_shape.cpp`, `base/tu_types.h`, build manifest | Disable the optional OpenGL shape-debug path. Exclude the inactive XMLSocket translation unit, whose unconditional SDL include is unavailable in this build. Treat x86-64 and AArch64 as known little-endian targets so the 64-bit macOS client does not fall back to SDL's type header, and keep `base/tu_math.h`'s obsolete OS X float-math macros (`logf` to `log` and the rest) off on macOS, as on Windows. `base/utility.h`'s `fmax`, `fmin` and `log2(float)` live in namespace `tu_util` and every caller (`base/container.h`, `gameswf_types.cpp`, `gameswf_text.cpp`, `gameswf_impl.cpp`, `fclamp`) calls them qualified: libc++ declares the C library overloads at global scope, and gameswf's comparisons answer differently for NaN and signed-zero inputs, so its own versions stay in use on every toolchain. | | Host access and images | `gameswf.h`, `gameswf_action.*`, `gameswf_impl.*`, `gameswf_render.*` | Global-object access, named bitmap exports, external bitmap creation policy, texture loading, and background-color readback. Exported names must own their string storage. | | ActionScript objects | `gameswf_action.*`, `gameswf_string.cpp` | Properties and prototype accessors, class registration, object literals, inheritance, constructor dispatch, `this`/`super`, array/string methods, enumeration, and object conversion. | | VM state | `gameswf_action.*` | Tolerant stack underflow, timeline variables, caller register banks, and function register save/restore. | @@ -37,7 +37,9 @@ versions. | Sprite lifetime and timelines | `gameswf_impl.*`, `gameswf_dlist.*` | Deferred removals, dead-clip access, construct/load ordering, label and numeric goto behavior, timeline state changes, and action-queue draining before execution. | | Drawing and bounds | `gameswf_shape.*`, `gameswf_styles.h`, `gameswf_impl.*` | Runtime shapes, image clips, owned runtime definitions, local clip extents, and scale-aware width/height updates. | | Text and localization | `gameswf_text.cpp`, `gameswf_font.h`, `gameswf_string.cpp`, render interfaces | Renderer-managed text lines, editing/focus/selection, independent narrow and wide values, and font-leading terms for caret and auto-height. | -| Mouse input | `gameswf_impl.*`, `gameswf_button.*`, `gameswf_text.cpp` | Per-character dispatch, capture across press/release, handler names, and capture release when a containing sprite is hidden. | +| Mouse input | `gameswf_impl.*`, `gameswf_button.*`, `gameswf_text.cpp` | Per-character dispatch, capture across press/release, handler names, and capture release when a containing sprite is hidden or leaves its display list (removed or replaced). | +| x64 portability ([issue #7](https://github.com/B2BF/OpenBF2/issues/7)) | `base/container.h`, `base/utility.*`, `gameswf_action.cpp` | Hash entries store the functor's full `size_t` hash, the value lookups compare (the upstream `int` round trip sign-extended on x64 and lost keys). Object and function address strings print the whole pointer, so object identity through string comparison holds above 4 GB. The debug-only assert breakpoint uses `__debugbreak` where inline asm is unavailable. x86 code generation and output are unchanged. Marked `[CHOSEN, not recovered] x64`. | +| Movie teardown ([issue #7](https://github.com/B2BF/OpenBF2/issues/7)) | `gameswf.h`, `gameswf_action.*`, `gameswf_impl.*`, `gameswf_dlist.*`, `gameswf_text.cpp`, `gameswf_button.cpp`, `SwiffPlayer/SwiffPlayer.cpp` | Every `as_object_interface` registers itself while it exists. `~SwiffPlayer` releases its movie: `release_script_objects` clears every registered clip and object - a clip's environment, handlers and children (without UNLOAD, so no script runs), an object's members, accessors and prototype - and the library definitions' `registerClass` bindings, which breaks the script reference cycles that kept each menu's clip tree, and the clips removed during play, alive. The instance and definition references are then dropped and `action_clear()` resets `_global`, the per-menu script reset the shipped DLL unload gives. The movie library stays cached (dropping it leaks each definition through its sprite-definition and font back references). The global steps run only when the dying player is the only live one (a live-player count); otherwise they are skipped and logged, and only the player's own instance and definition references are dropped. Marked `[CHOSEN, not recovered]`. | ## Constraints for changes diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp b/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp index 2678ca924..6f02ff89c 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffCrashLog.cpp @@ -3,13 +3,28 @@ // Frame-chain tracing requires frame pointers; stack scans can include stale return addresses. // [RETIRE-WHEN: RW-89] Remove with the other SwiffPlayer tracers. -#define WIN32_LEAN_AND_MEAN -#define NOMINMAX -#include #include #include #include "../../../../RendDX9Abi/Frontier.h" +#if !defined(_WIN32) +// [CHOSEN, not recovered] Native POSIX ports: the logger is built on Windows' vectored exception +// handling and x86 CONTEXT registers, and is not available. Asking for it reports that once, so a +// tester does not wait for a crash log that cannot come; nothing is installed. +void swiffCrashLogInstall() +{ + static bool reported = false; + const char* e = getenv("BF2_SWIFFPLAYER_CRASHLOG"); + if (reported || !e || !*e || *e == '0') return; + reported = true; + ::renddx9abi::logf("[crash] BF2_SWIFFPLAYER_CRASHLOG is set, but the first-fault logger exists " + "only on Windows; nothing installed"); +} +#else +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + namespace { bool moduleOf(const void* addr, char* name, size_t nameCap, unsigned* rva) @@ -62,9 +77,11 @@ LONG WINAPI crashHandler(EXCEPTION_POINTERS* ep) (void*)ep->ExceptionRecord->ExceptionInformation[1]); const CONTEXT* c = ep->ContextRecord; +#if defined(_M_IX86) ::renddx9abi::logf("[crash] eax=%08X ebx=%08X ecx=%08X edx=%08X esi=%08X edi=%08X ebp=%08X esp=%08X", (unsigned)c->Eax, (unsigned)c->Ebx, (unsigned)c->Ecx, (unsigned)c->Edx, (unsigned)c->Esi, (unsigned)c->Edi, (unsigned)c->Ebp, (unsigned)c->Esp); + const uintptr_t stackPointer = (uintptr_t)c->Esp; // EBP chain. const void* const* frame = (const void* const*)c->Ebp; @@ -80,13 +97,23 @@ LONG WINAPI crashHandler(EXCEPTION_POINTERS* ep) if (next <= frame) break; frame = next; } +#else + // [CHOSEN, not recovered] x64: the 64-bit registers; x64 code keeps no frame-pointer chain, so + // only the return-address scan below runs. + ::renddx9abi::logf("[crash] rax=%016llX rbx=%016llX rcx=%016llX rdx=%016llX rsi=%016llX rdi=%016llX", + (unsigned long long)c->Rax, (unsigned long long)c->Rbx, (unsigned long long)c->Rcx, + (unsigned long long)c->Rdx, (unsigned long long)c->Rsi, (unsigned long long)c->Rdi); + ::renddx9abi::logf("[crash] rbp=%016llX rsp=%016llX rip=%016llX", + (unsigned long long)c->Rbp, (unsigned long long)c->Rsp, (unsigned long long)c->Rip); + const uintptr_t stackPointer = (uintptr_t)c->Rsp; +#endif // Return-address scan (frame-pointer independent; includes stale entries). - const void* const* sp = (const void* const*)((uintptr_t)c->Esp & ~(uintptr_t)3); + const void* const* sp = (const void* const*)(stackPointer & ~(uintptr_t)(sizeof(void*) - 1)); int hits = 0; for (int i = 0; i < 4096 && hits < 80; ++i, ++sp) { - if (!readable(sp, 4)) break; + if (!readable(sp, sizeof(void*))) break; const void* v = *sp; if (!moduleOf(v, mod, sizeof mod, &rva)) continue; if (_strnicmp(mod, "SwiffPlayer", 11) != 0 && _strnicmp(mod, "RendDX9", 7) != 0 @@ -125,3 +152,4 @@ void swiffCrashLogInstall() ::atexit(&swiffCrashLogUninstall); ::renddx9abi::logf("[crash] logger installed (BF2_SWIFFPLAYER_CRASHLOG)"); } +#endif // _WIN32 diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffNativesRecovered.inl b/Code/BF2/External/gameswf/SwiffPlayer/SwiffNativesRecovered.inl new file mode 100644 index 000000000..4917c3038 --- /dev/null +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffNativesRecovered.inl @@ -0,0 +1,4421 @@ +// =================================================================================================== +// c-swiff-natives: the retail natives the port had not registered (docs/macos-c-swiff-natives.md). +// SwiffPlayer.dll 1.50 (base 0x10000000); every body below was read instruction by instruction with +// objdump. Calling convention of the shipped callbacks: ecx = the result as_value, [ebp+8] = the +// argument vector, [ebp+0x10] = first_arg; argument n is element first_arg - n (fn.arg(n) here); the +// int3 after the bounds test is the debug assert and has no counterpart. Result writes build a +// temporary as_value (type 1 string, 2 number, 3 Boolean) and assign it through sub_10009920. +// =================================================================================================== + +// ---- dice.bf2.Profile -------------------------------------------------------------------------- + +// sub_1005D050 "getMinimumAge": the shipped body is a bare `ret 0Ch`. +// The AS result is left untouched (undefined). +void as_profile_getMinimumAge(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getMinimumAge"); +} + +// sub_1005D080 "clearComparePlayer": player host +0x218 setPendingRecord(0, "") with a constructed +// empty string (0x100D7835). No AS result. +void as_profile_clearComparePlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_clearComparePlayer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string empty(""); + h->setPendingRecord(0, empty); // +0x218 +} + +// sub_1005D110 "setNamePrefix": GlobalSettings by name first, then arg 0 to_string (sub_1008D0F0) +// into a std::string, copied by value into GlobalSettings +0x2C setNamePrefix. No AS result. +void as_profile_setNamePrefix(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setNamePrefix"); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GlobalSettings")); + const std::string prefix(fn.arg(0).to_string()); + static_cast(gs)->setNamePrefix(prefix); // +0x2C +} + +// sub_1005D190 "setSelectedAge": arg 0 to_number (sub_1008B570) and the value popped (fstp st0). +// Nothing is stored and no AS result is written. +void as_profile_setSelectedAge(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setSelectedAge"); + (void) fn.arg(0).to_number(); +} + +// sub_1005D220 "setUseAdvancedServerBrowser": GeneralSettings by name, then arg 0 to_bool +// (sub_1008B6B0), GeneralSettings +0xA4. No AS result. +void as_profile_setUseAdvancedServerBrowser(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setUseAdvancedServerBrowser"); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + const bool value = fn.arg(0).to_bool(); + static_cast(gs)->setUseAdvancedServerBrowser(value); // +0xA4 +} + +// sub_1005D350 "setComparePlayer": the host first, then ProfileManager +0x44 isLoggedIn. Logged out: +// host +0x244 handleProfileTransition("connection to profile server lost") and return. Otherwise +// id = (int) arg 0 (fistp, truncating control word); a zero id does nothing. A non-zero id takes +// arg 1 to_string, host +0x218 setPendingRecord(id, name), host +0x220 setSelectedPlayerId(id). +void as_profile_setComparePlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_setComparePlayer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* pm = classManager->getSingleton(renddx9abi::HostString("ProfileManager")); + if (!static_cast(pm)->isLoggedIn()) // +0x44 + { + h->handleProfileTransition(std::string("connection to profile server lost")); // +0x244 + return; + } + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (id == 0) + return; + const std::string name(fn.arg(1).to_string()); + h->setPendingRecord(id, name); // +0x218 + h->setSelectedPlayerId(id); // +0x220 +} + +// sub_1005D5B0 "getSelectedAge": the constant 13.0 (0x100DDEC8) as a number. +void as_profile_getSelectedAge(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getSelectedAge"); + fn.result->set_double(13.0); +} + +// sub_1005D800 "deleteCurrentProfile": inside the registry SwiffHost's busy cursor (sub_10013520); +// player host, LocalProfileManager, ProfileManager. Logged out (+0x44): host +0x244 with "connection +// to profile server lost" and Boolean false. Logged in: ProfileManager +0x30 getProfileId(out) (its +// Boolean ignored) is compared with host +0x21C getSelectedPlayerId; a mismatch posts message +// {type 1, code 0, "you can only delete your active profile"} through host +0x1E4 and answers false. +// A match calls ProfileManager +0x38 deleteProfile: false answers false; true reads +0x34 +// getUniqueNick(out) into an empty string, LocalProfileManager +0x68 setGamespyNick(it), +0x40 +// saveCurrentProfile, and answers true. +void as_profile_deleteCurrentProfile(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_deleteCurrentProfile"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + IBase* pmBase = classManager->getSingleton(renddx9abi::HostString("ProfileManager")); + IProfileManager* pm = static_cast(pmBase); + if (!pm->isLoggedIn()) // +0x44 + { + h->handleProfileTransition(std::string("connection to profile server lost")); // +0x244 + fn.result->set_bool(false); + busyClose(busy); + return; + } + int profileId; // uninitialised in the shipped frame as well + (void) pm->getProfileId(profileId); // +0x30 + if (h->getSelectedPlayerId() != profileId) // +0x21C + { + const std::string text("you can only delete your active profile"); + SwiffHostMessage message; + message.type = 1; + message.code = 0; + message.text = text; + (void) h->postMessage(message); // +0x1E4 + fn.result->set_bool(false); + busyClose(busy); + return; + } + if (!pm->deleteProfile()) // +0x38 + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + std::string nick; + (void) pm->getUniqueNick(nick); // +0x34 + static_cast(lpm)->setGamespyNick(nick); // +0x68 + (void) static_cast(lpm)->saveCurrentProfile(); // +0x40 + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_1005DA70 "newGamespyProfile": inside the busy cursor; player host, LocalProfileManager, +// ProfileManager. Logged out: host +0x244 "connection to profile server lost", Boolean false. +// Logged in: nick = arg 0, country = arg 1 (both to_string); ProfileManager +0x20 +// createProfile(nick, country). Refused: +0x4C requestNickSuggestions(nick), Boolean false. +// Created: LocalProfileManager +0x68 setGamespyNick(nick), +0x40 saveCurrentProfile, Boolean true. +void as_profile_newGamespyProfile(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_newGamespyProfile"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + IProfileManager* pm = static_cast( + classManager->getSingleton(renddx9abi::HostString("ProfileManager"))); + if (!pm->isLoggedIn()) // +0x44 + { + h->handleProfileTransition(std::string("connection to profile server lost")); // +0x244 + fn.result->set_bool(false); + busyClose(busy); + return; + } + const std::string nick(fn.arg(0).to_string()); + const std::string country(fn.arg(1).to_string()); + if (!pm->createProfile(nick, country)) // +0x20 + { + (void) pm->requestNickSuggestions(nick); // +0x4C + fn.result->set_bool(false); + busyClose(busy); + return; + } + static_cast(lpm)->setGamespyNick(nick); // +0x68 + (void) static_cast(lpm)->saveCurrentProfile(); // +0x40 + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_1005DCE0 "deleteLocalProfile": inside the busy cursor; the player host is fetched and +// discarded; LocalProfileManager; index = (int) arg 0; Boolean of +0x28 deleteProfile(index). +void as_profile_deleteLocalProfile(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_deleteLocalProfile"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + const bool deleted = static_cast(lpm)->deleteProfile(index); // +0x28 + fn.result->set_bool(deleted); + busyClose(busy); +} + +// sub_1005DDD0 "getUseAdvancedServerBrowser": Boolean of GeneralSettings +0xA0. +void as_profile_getUseAdvancedServerBrowser(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getUseAdvancedServerBrowser"); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + fn.result->set_bool(static_cast(gs)->getUseAdvancedServerBrowser()); // +0xA0 +} + +// sub_1005E100 "getStatPlayer": host +0x21C getSelectedPlayerId as a number. +void as_profile_getStatPlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getStatPlayer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_double(static_cast(h->getSelectedPlayerId())); // +0x21C +} + +// sub_1005E2A0 "searchPlayer" / sub_10060D80 "searchUniquePlayer": inside the busy cursor; the +// player host, arg 0 to_string. An empty name or one whose first byte is ' ' fails. Otherwise host +// +0x3C getSearchForPlayer() +0x10 search(name, unique, false). searchPlayer answers that Boolean +// (false on the early refusal). searchUniquePlayer answers a number: -1.0 (0x100D8868) on a refusal +// or an empty result, else the first row's profile id from a second getSearchForPlayer() +0x18 +// getPlayers(rows) (its Boolean ignored). +static bool searchNameUsable(const std::string& name) +{ + return !name.empty() && name.c_str()[0] != ' '; +} +void as_profile_searchPlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_searchPlayer"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + if (searchNameUsable(name) + && static_cast(h->getSearchForPlayer())->search(name, false, false)) // +0x3C, +0x10 + fn.result->set_bool(true); + else + fn.result->set_bool(false); + busyClose(busy); +} +void as_profile_searchUniquePlayer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_searchUniquePlayer"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + if (searchNameUsable(name) + && static_cast(h->getSearchForPlayer())->search(name, true, false)) // +0x3C, +0x10 + { + std::vector rows; + (void) static_cast(h->getSearchForPlayer())->getPlayers(rows); // +0x3C, +0x18 + if (rows.empty()) + fn.result->set_double(-1.0); + else + fn.result->set_double(static_cast(rows[0].profileId)); + } + else + fn.result->set_double(-1.0); + busyClose(busy); +} + +// sub_1005F4A0 "getSprint": team = (int) arg 0, kit = (int) arg 1 (both converted before the lookup), +// MenuTeamManager by name, +0x30 getTeam(team), kits[kit] (no bounds test, 108-byte rows, +0x58): +// the number 1.0f (0x100D7EA0) - sprintStaminaDissipationFactor, evaluated on the x87 stack. +void as_profile_getSprint(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getSprint"); + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); + const int kit = bf2x87::toIntTruncate(fn.arg(1).to_number()); + IMenuTeamManager* tm = static_cast( + classManager->getSingleton(renddx9abi::HostString("MenuTeamManager"))); + MenuTeam* row = tm->getTeam(static_cast(team)); // +0x30 + const double factor = static_cast(row->kits[kit].sprintStaminaDissipationFactor); + fn.result->set_double(1.0 - factor); +} + +// sub_1005FD90 "getNumOnlineProfiles" / sub_1005FEE0 "getNumOfflineProfiles": LocalProfileManager by +// name; absent: the number 0. Present: +0x48 getLocalProfiles(rows, true) (Boolean ignored) and the +// count of rows whose gamespyNick (+0x54) is != "" (online, operator!=) or == "" (offline, operator==). +static void countLocalProfiles(const gameswf::fn_call& fn, bool online) +{ + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + if (!lpm) + { + fn.result->set_double(0.0); + return; + } + std::vector rows; + (void) static_cast(lpm)->getLocalProfiles(rows, true); // +0x48 + int count = 0; + for (unsigned int i = 0; i < rows.size(); ++i) + if (online ? (rows[i].gamespyNick != "") : (rows[i].gamespyNick == "")) + ++count; + fn.result->set_double(static_cast(count)); +} +void as_profile_getNumOnlineProfiles(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getNumOnlineProfiles"); + countLocalProfiles(fn, true); +} +void as_profile_getNumOfflineProfiles(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_profile_getNumOfflineProfiles"); + countLocalProfiles(fn, false); +} + +// ---- dice.bf2.Multiplay ------------------------------------------------------------------------ + +// The player host's current browser list: host +0x134 getServerListKind() (a temporary that dies +// after the call) handed to +0x7C getServerList. Every Multiplay row below that touches the +// browser starts this way. +static IServerBrowser* currentServerList(ISwiffHost* h) +{ + return h->getServerList(h->getServerListKind()); // +0x134, +0x7C +} + +// sub_10050B70 "refreshBrowser": the current list; when present, +0x2C requeueRecords (Boolean +// ignored). No AS result. +void as_multiplay_refreshBrowser(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_refreshBrowser"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IServerBrowser* list = currentServerList(h); + if (list) + (void) list->requeueRecords(); // +0x2C +} + +// sub_10050C10 "stopDownloadDemo": host +0x44 getDemoLibrary() +0x3C cancelDownload (Boolean +// ignored). No AS result. +void as_multiplay_stopDownloadDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_stopDownloadDemo"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + (void) static_cast(h->getDemoLibrary())->cancelDownload(); // +0x44, +0x3C +} + +// sub_10050C80 "clearHistory": inside the busy cursor, the player host (discarded) and +// GeneralSettings +0x154 clearServerHistory. No AS result. +void as_multiplay_clearHistory(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_clearHistory"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + static_cast(gs)->clearServerHistory(); // +0x154 + busyClose(busy); +} + +// sub_10051480 "setHighestPing": the current list; when present, (int) arg 0 into +0x5C setMaxPing. +// An absent list leaves the argument unread. No AS result. +void as_multiplay_setHighestPing(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_setHighestPing"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IServerBrowser* list = currentServerList(h); + if (list) + list->setMaxPing(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x5C +} + +// sub_100519C0 "setFilter": the player host is fetched and discarded; arg 0 to_string is assigned to +// the DLL-global free-text clause (unk_100F8810). No AS result. +void as_multiplay_setFilter(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_setFilter"); + (void) g_swiffPlayerInstance->getSwiffHost(); + const std::string text(fn.arg(0).to_string()); + s_textFilter = text; +} + +// sub_10051A20 "sort": inside the busy cursor; the player host; key = arg 0 to_string, ascending = +// arg 1 to_bool, mode = (int) arg 2, all converted before the list is fetched; then the current +// list's +0x38 sort(key, ascending, mode), no null test. No AS result. +void as_multiplay_sort(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_sort"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string key(fn.arg(0).to_string()); + const bool ascending = fn.arg(1).to_bool(); + const int mode = bf2x87::toIntTruncate(fn.arg(2).to_number()); + currentServerList(h)->sort(key, ascending, mode); // +0x38 + busyClose(busy); +} + +// sub_10051F00 "deleteDemo": the player host first, then (int) arg 0, host +0x44 getDemoLibrary() +// +0x20 removeEntry(index) (Boolean ignored). No AS result. +void as_multiplay_deleteDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_deleteDemo"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + (void) static_cast(h->getDemoLibrary())->removeEntry(static_cast(index)); // +0x20 +} + +// sub_100523E0 "hasDemoDownloadFailed": Boolean of host +0x44 getDemoLibrary() +0x4C. +void as_multiplay_hasDemoDownloadFailed(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_hasDemoDownloadFailed"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(static_cast(h->getDemoLibrary())->hasDownloadFailed()); // +0x4C +} + +// sub_10052450 "getScrollFadeSpeed": host +0x314 (the credits scroller's fade speed) as a number. +void as_multiplay_getScrollFadeSpeed(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getScrollFadeSpeed"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_double(static_cast(h->getIntF08())); // +0x314 +} + +// sub_100526A0 "isServerBrowserBusy": Boolean of the current list's +0x1C isBrowsing, no null test. +void as_multiplay_isServerBrowserBusy(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_isServerBrowserBusy"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const bool busy = currentServerList(h)->isBrowsing(); // +0x1C + fn.result->set_bool(busy); +} + +// sub_100528A0 "validateIp": arg 0 to_string, Boolean of host +0x250 isDottedQuad. +void as_multiplay_validateIp(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_validateIp"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string address(fn.arg(0).to_string()); + fn.result->set_bool(h->isDottedQuad(address)); // +0x250 +} + +// sub_10052AF0 "playNow": the player host; both in-game server-info keys cleared (sub_100136B0: +// unk_100F7040 = "", dword_100F3240 = 0; sub_100626D0: unk_100F8B14 = "", dword_100F88CC = 0); host +// +0xB8 isGameRunning(&running) with running pre-set false. A running game returns with the AS +// result untouched. Otherwise, inside the busy cursor, the Boolean of host +0x16C playNow. +void as_multiplay_playNow(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_playNow"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + s_ingameAddressA = ""; s_ingamePortA = 0; + s_ingameAddressB = ""; s_ingamePortB = 0; + bool running = false; + (void) h->isGameRunning(&running); // +0xB8 + if (running) + return; + BusyHost busy = busyOpen(); + fn.result->set_bool(h->playNow()); // +0x16C + busyClose(busy); +} + +// "%s %d" (0x100DD398) of a GeneralSettings row's address and query port, the key the favourites +// and history rows are matched by, case-insensitively (sub_10003870: _stricmp(row, key) == 0). +static bool serverEntryMatches(const GeneralServerEntry* e, const std::string& key) +{ + const std::string rowKey = swiffFormatString("%s %d", e->address.c_str(), e->queryPort); + return ::_stricmp(rowKey.c_str(), key.c_str()) == 0; +} +// The message the favourites rows post: type 1, code 0, the text assigned into a default record. +static void postMenuMessage(ISwiffHost* h, const char* literal) +{ + const std::string text(literal); + SwiffHostMessage message; + message.type = 1; + message.code = 0; + message.text = text; + (void) h->postMessage(message); // +0x1E4 +} + +// sub_10052C80 "addFavourite": the player host, GeneralSettings, then the busy cursor; name = arg 0, +// address = arg 1 (to_string), port = (int) arg 2; key = "%s %d"(address, port). Host +0x250 +// isDottedQuad(address) false posts "Not a valid ip" and answers false. Otherwise a favourite whose +// key matches posts "Server already in favorites" and answers false; none: GeneralSettings +0x11C +// addFavouriteServer(address, port, name) and true. +void as_multiplay_addFavourite(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_addFavourite"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + BusyHost busy = busyOpen(); + const std::string name(fn.arg(0).to_string()); + const std::string address(fn.arg(1).to_string()); + const int port = bf2x87::toIntTruncate(fn.arg(2).to_number()); + const std::string key = swiffFormatString("%s %d", address.c_str(), port); + if (!h->isDottedQuad(address)) // +0x250 + { + postMenuMessage(h, "Not a valid ip"); + fn.result->set_bool(false); + busyClose(busy); + return; + } + for (unsigned int i = 0; i < static_cast(gs->getNumFavouriteServers()); ++i) // +0x120 + { + if (serverEntryMatches(gs->getFavouriteServer(i), key)) // +0x124 + { + postMenuMessage(h, "Server already in favorites"); + fn.result->set_bool(false); + busyClose(busy); + return; + } + } + gs->addFavouriteServer(address, port, name); // +0x11C + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_10053060 "removeFavourite": the player host (discarded), GeneralSettings, then the busy cursor; +// key = arg 0. The first favourite whose "%s %d" key matches is removed through +0x12C +// removeFavouriteServerEntry(index) (Boolean ignored) and the answer is true; no match answers false. +void as_multiplay_removeFavourite(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_removeFavourite"); + (void) g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + BusyHost busy = busyOpen(); + const std::string key(fn.arg(0).to_string()); + for (unsigned int i = 0; i < static_cast(gs->getNumFavouriteServers()); ++i) // +0x120 + { + if (serverEntryMatches(gs->getFavouriteServer(i), key)) // +0x124 + { + (void) gs->removeFavouriteServerEntry(i); // +0x12C + fn.result->set_bool(true); + busyClose(busy); + return; + } + } + fn.result->set_bool(false); + busyClose(busy); +} + +// sub_10053230 "addHistoryToFavourites": the busy cursor, the player host, GeneralSettings; key = +// arg 0. No history row (+0x13C count, +0x140 row) with that key answers false. For the first match, +// a favourite with the same key posts "Server allready in favourites" [sic] and answers false; +// otherwise +0x11C addFavouriteServer(row address, row query port, row name) and true. +void as_multiplay_addHistoryToFavourites(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_addHistoryToFavourites"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + const std::string key(fn.arg(0).to_string()); + GeneralServerEntry* row = 0; + for (unsigned int i = 0; i < static_cast(gs->getServerHistoryCount()); ++i) // +0x13C + { + GeneralServerEntry* e = gs->getServerHistory(i); // +0x140 + if (serverEntryMatches(e, key)) { row = e; break; } + } + if (!row) + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + for (unsigned int i = 0; i < static_cast(gs->getNumFavouriteServers()); ++i) // +0x120 + { + if (serverEntryMatches(gs->getFavouriteServer(i), key)) // +0x124 + { + postMenuMessage(h, "Server allready in favourites"); + fn.result->set_bool(false); + busyClose(busy); + return; + } + } + gs->addFavouriteServer(row->address, row->queryPort, row->name); // +0x11C + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_10053540 "removeHistory": the busy cursor, the player host (discarded), GeneralSettings; key = +// arg 0. The first history row whose key matches is removed through +0x148 removeServerHistoryEntry +// (Boolean ignored), answering true; no match answers false. +void as_multiplay_removeHistory(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_removeHistory"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + const std::string key(fn.arg(0).to_string()); + for (unsigned int i = 0; i < static_cast(gs->getServerHistoryCount()); ++i) // +0x13C + { + if (serverEntryMatches(gs->getServerHistory(i), key)) // +0x140 + { + (void) gs->removeServerHistoryEntry(i); // +0x148 + fn.result->set_bool(true); + busyClose(busy); + return; + } + } + fn.result->set_bool(false); + busyClose(busy); +} + +// sub_10053E50 "getNumDemoBookmarks": LocalProfileManager +0xA8 as a number (fild, signed). +void as_multiplay_getNumDemoBookmarks(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getNumDemoBookmarks"); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int count = static_cast(static_cast(lpm)->getNumDemoBookmarks()); // +0xA8 + fn.result->set_double(static_cast(count)); +} + +// sub_10053EE0 "isDownloadingDemo": Boolean of host +0x44 getDemoLibrary() +0x28 isDownloading. +void as_multiplay_isDownloadingDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_isDownloadingDemo"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(static_cast(h->getDemoLibrary())->isDownloading()); // +0x28 +} + +// sub_10053F50 "getDownloadingHostname" / sub_10053FE0 "getDownloadingUrl" / sub_10054070 +// "getDownloadingDate": host +0x44 getDemoLibrary() +0x2C / +0x30 / +0x34 (const std::string&), +// copied, published as a string. +void as_multiplay_getDownloadingHostname(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingHostname"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value(static_cast(h->getDemoLibrary())->getDownloadName()); // +0x2C + fn.result->set_tu_string(tu_string(value.c_str())); +} +void as_multiplay_getDownloadingUrl(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingUrl"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value(static_cast(h->getDemoLibrary())->getDownloadUrl()); // +0x30 + fn.result->set_tu_string(tu_string(value.c_str())); +} +void as_multiplay_getDownloadingDate(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingDate"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value(static_cast(h->getDemoLibrary())->getDownloadDescription()); // +0x34 + fn.result->set_tu_string(tu_string(value.c_str())); +} + +// sub_10054100 "getDownloadingProgress": host +0x44 getDemoLibrary() +0x38 (float) as a number. +void as_multiplay_getDownloadingProgress(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getDownloadingProgress"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_double(static_cast( + static_cast(h->getDemoLibrary())->getDownloadProgress())); // +0x38 +} + +// sub_10054160 "downloadDemo": the busy cursor, the player host, LocalProfileManager; index = +// (int) arg 0; +0xAC getDemoBookmark(index). None answers false. Otherwise host +0x44 +// getDemoLibrary() +0x48 setPendingBookmark(index), then (fetched again) +0x14 download(bookmark +// +0x00, +0x38, +0x54) with its Boolean ignored, and the answer is true. +void as_multiplay_downloadDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_downloadDemo"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + LocalDemoBookmark* bookmark = + static_cast(lpm)->getDemoBookmark(static_cast(index)); // +0xAC + if (!bookmark) + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + static_cast(h->getDemoLibrary())->setPendingBookmark(index); // +0x48 + (void) static_cast(h->getDemoLibrary())->download( + bookmark->field00, bookmark->field38, bookmark->field54); // +0x14 + fn.result->set_bool(true); + busyClose(busy); +} + +// sub_100542C0 "deleteDemoBookmark": the busy cursor, the player host (discarded), +// LocalProfileManager; Boolean of +0xB0 removeDemoBookmark((int) arg 0). +void as_multiplay_deleteDemoBookmark(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_deleteDemoBookmark"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + fn.result->set_bool(static_cast(lpm)->removeDemoBookmark( + static_cast(index))); // +0xB0 + busyClose(busy); +} + +// sub_10054940 "addFavouriteServer": the busy cursor, GeneralSettings, the player host; the row id +// "%s %d %d" (0x100D99BC: address, query port, host port; the same unbounded %s as joinServer, +// bounded here the same way [CHOSEN, not recovered]). A favourite already at (address, query port) +// (+0x134 findFavouriteServer) answers false. Otherwise the current list's +0x3C getRecord(address, +// queryPort, false, false): none answers false; a record is added as +0x11C addFavouriteServer( +// entry.address, entry.queryPort, entry.hostName) and the answer is true. +void as_multiplay_addFavouriteServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_addFavouriteServer"); + BusyHost busy = busyOpen(); + IGeneralSettings* gs = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string id(fn.arg(0).to_string()); + std::string address; + char buf[260] = {0}; + int queryPort = 0, hostPort = 0; + ::sscanf(id.c_str(), "%259s %d %d", buf, &queryPort, &hostPort); + address = buf; + if (gs->findFavouriteServer(address, queryPort)) // +0x134 + { + fn.result->set_bool(false); + busyClose(busy); + return; + } + ServerBrowserRecord* rec = currentServerList(h)->getRecord(address, queryPort, false, false); // +0x3C + if (!rec) + fn.result->set_bool(false); + else + { + gs->addFavouriteServer(rec->entry.address, rec->entry.queryPort, rec->entry.hostName); // +0x11C + fn.result->set_bool(true); + } + busyClose(busy); +} + +// sub_10054B20 "removeFavouriteServer": the busy cursor, the player host and GeneralSettings are +// fetched, and the answer is false. The shipped body removes nothing. +void as_multiplay_removeFavouriteServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_removeFavouriteServer"); + BusyHost busy = busyOpen(); + (void) g_swiffPlayerInstance->getSwiffHost(); + (void) classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); + fn.result->set_bool(false); + busyClose(busy); +} + +// sub_10055350 "getSelectedServerFilterGameMode" / sub_100555E0 "getSelectedFilterGameModeId": host +// +0x120 getModInfo() +0x1C getCurrentMod(); an empty gameModes vector (Mod +0x10C) answers "". The +// Id row publishes gameModes[0]; the other publishes ModInfo +0x4C getNameFromGameMode(gameModes[0]). +void as_multiplay_getSelectedServerFilterGameMode(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getSelectedServerFilterGameMode"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const IModInfo::Mod* mod = static_cast(h->getModInfo())->getCurrentMod(); // +0x120, +0x1C + if (mod->gameModes.empty()) + { + fn.result->set_tu_string(tu_string("")); + return; + } + const std::string first(mod->gameModes[0]); + const std::string name = static_cast(h->getModInfo())->getNameFromGameMode(first); // +0x4C + fn.result->set_tu_string(tu_string(name.c_str())); +} +void as_multiplay_getSelectedFilterGameModeId(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getSelectedFilterGameModeId"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const IModInfo::Mod* mod = static_cast(h->getModInfo())->getCurrentMod(); // +0x120, +0x1C + if (mod->gameModes.empty()) + { + fn.result->set_tu_string(tu_string("")); + return; + } + const std::string first(mod->gameModes[0]); + fn.result->set_tu_string(tu_string(first.c_str())); +} + +// sub_100563B0 "getMapPathFromName": name = arg 0; every mod of host +0x120 getModInfo() +0x14 +// getModList() (re-fetched each step) and every map of it is searched for map.name == name +// (operator==). No match publishes the name itself. A match builds a string as_value from the map's +// path and destroys it without assigning it (100564D6..100564F2: sub_10007680, then sub_1008A2F0, +// no sub_10009920): the AS result stays untouched. Observed shipped defect, preserved. +void as_multiplay_getMapPathFromName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getMapPathFromName"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + for (unsigned int m = 0; m < static_cast(h->getModInfo())->getModList()->size(); ++m) // +0x14 + { + const IModInfo::Mod& mod = (*static_cast(h->getModInfo())->getModList())[m]; + for (unsigned int i = 0; i < mod.maps.size(); ++i) + { + if (mod.maps[i].name == name) + { + const tu_string discarded(mod.maps[i].path.c_str()); // built, never assigned + (void) discarded; + return; + } + } + } + fn.result->set_tu_string(tu_string(name.c_str())); +} + +// sub_10057310 "playDemo": the busy cursor, the player host, (int) arg 0; host +0x44 +// getDemoLibrary() +0x1C getEntry(index). None: nothing. An entry queues menu event 12 with the +// entry's path (+0x20) as its only argument through host +0x2C pushEvent. No AS result. +void as_multiplay_playDemo(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_playDemo"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + DemoLibraryEntry* entry = + static_cast(h->getDemoLibrary())->getEntry(static_cast(index)); // +0x1C + if (entry) + { + const std::string path(entry->path); + MenuEvent event; + event.type = 12; + event.args.push_back(path); + (void) h->pushEvent(event); // +0x2C + } + busyClose(busy); +} + +// sub_10057450 "getMapName": index = (int) arg 0; host +0xFC getServerEntries(rows). False answers +// the number 0. Otherwise the row at index publishes its map (+0); an index past the end answers "". +void as_multiplay_getMapName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_multiplay_getMapName"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); + std::vector rows; + if (!h->getServerEntries(rows)) // +0xFC + { + fn.result->set_double(0.0); + return; + } + for (unsigned int i = 0; i < rows.size(); ++i) + { + if (i == static_cast(index)) + { + fn.result->set_tu_string(tu_string(rows[i].map.c_str())); + return; + } + } + fn.result->set_tu_string(tu_string("")); +} + +// ---- dice.bf2.Sound (the VoIP rows) ----------------------------------------------------------- + +// byte_100F8B4C: "VoIP initialised". Only voipInitialize's client arm (0x1006913F) raises it, after +// the Bf2VoipClient has answered, so it stays false while the port has no client. +static bool s_voipInitialized = false; + +// Every VoIP row reads the player (dword_100F2F20) and its +0x8C getBf2VoipClient. BF2.exe's +// BF2VoipClient is not reconstructed (BF2ClientSeams.h, RW-94), so the port's player answers null and +// the rows take their shipped null-client exits, recovered below. The client arms stop here. +// [TEMP] [FRONTIER] [CHOSEN, not recovered] [RETIRE-WHEN: voip-client-hud-seam] Replace each stop +// with the recovered arm once BF2VoipClient and its vtable are reconstructed. +static void* voipPlayerClient(SwiffPlayer* player) +{ + return player ? player->getBf2VoipClient() : 0; // player +0x8C +} +static void voipClientArmFrontier(const char* row, const char* range) +{ + ::renddx9abi::logf("[FRONTIER] dice::hfe::ui::as_sound_%s: the Bf2VoipClient arm (%s) is not " + "reconstructed (RW-94)", row, range); + ::fprintf(stderr, "[FRONTIER] dice::hfe::ui::as_sound_%s: the Bf2VoipClient arm (%s) is not " + "reconstructed (RW-94)\n", row, range); + ::fflush(stderr); + ::abort(); +} + +// sub_10069010 "voipInitialize": no player or no client answers Boolean false (0x1006925B). +void as_sound_voipInitialize(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipInitialize"); + SwiffPlayer* player = g_swiffPlayerInstance; + if (!player || !voipPlayerClient(player)) + { + fn.result->set_bool(false); + return; + } + voipClientArmFrontier("voipInitialize", "1006903D..10069259"); +} + +// sub_100692B0 "voipSetEnable": the player read, AudioSettings by name; no player, no AudioSettings, +// VoIP not initialised or no client returns without an AS result. +void as_sound_voipSetEnable(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipSetEnable"); + SwiffPlayer* player = g_swiffPlayerInstance; + IBase* as = classManager->getSingleton(renddx9abi::HostString("AudioSettings")); + if (!player || !as || !s_voipInitialized || !voipPlayerClient(player)) + return; + voipClientArmFrontier("voipSetEnable", "10069318..100693A7"); +} + +// sub_100693C0 "voipGetEnable": VoIP not initialised answers false; otherwise AudioSettings by name, +// absent answers false, present answers the Boolean of +0x38 getVoipEnabled. No client involved. +void as_sound_voipGetEnable(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetEnable"); + if (!s_voipInitialized) + { + fn.result->set_bool(false); + return; + } + IBase* as = classManager->getSingleton(renddx9abi::HostString("AudioSettings")); + if (!as) + { + fn.result->set_bool(false); + return; + } + fn.result->set_bool(audioSettingsOf(as)->getVoipEnabled()); // +0x38 +} + +// The rows whose first test is player, then client, and whose null exits leave the AS result +// untouched: voipStartTest 100694E0, voipSetTransmitVolume 10069750, voipGetTransmitVolume 10069840, +// voipSetRecieveVolume 100698C0, voipGetRecieveVolume 100699B0, voipSetThresholdVolume 10069A30, +// voipGetThresholdVolume 10069B30, voipSetBoost 10069BA0, voipGetBoost 10069CA0, voipIsBoostEnabled +// 10069D80, voipSetUsePushToTalk 10069E10, voipGetUsePushToTalk 10069F50. +#define VOIP_CLIENT_ROW(row, range) \ + void as_sound_##row(const gameswf::fn_call& fn) \ + { \ + SWF_AS_TRACE("as_sound_" #row); \ + SwiffPlayer* player = g_swiffPlayerInstance; \ + if (!player || !voipPlayerClient(player)) \ + return; \ + voipClientArmFrontier(#row, range); \ + } +VOIP_CLIENT_ROW(voipStartTest, "1006950A..1006960B") +VOIP_CLIENT_ROW(voipSetTransmitVolume, "1006977A..10069831") +VOIP_CLIENT_ROW(voipGetTransmitVolume, "10069862..100698B1") +VOIP_CLIENT_ROW(voipSetRecieveVolume, "100698EA..100699A1") +VOIP_CLIENT_ROW(voipGetRecieveVolume, "100699D2..10069A21") +VOIP_CLIENT_ROW(voipSetThresholdVolume, "10069A5A..10069B20") +VOIP_CLIENT_ROW(voipGetThresholdVolume, "10069B4F..10069B93") +VOIP_CLIENT_ROW(voipSetBoost, "10069BCA..10069C88") +VOIP_CLIENT_ROW(voipGetBoost, "10069CCA..10069D73") +VOIP_CLIENT_ROW(voipIsBoostEnabled, "10069DA2..10069E05") +VOIP_CLIENT_ROW(voipSetUsePushToTalk, "10069E3A..10069F3E") +VOIP_CLIENT_ROW(voipGetUsePushToTalk, "10069F72..10069FD5") +#undef VOIP_CLIENT_ROW + +// sub_10069FE0 "voipSendingVoice" / sub_1006A0F0 "voipGetSendingVoiceVolume": the result is first +// set to Boolean false / the number 0; then no player or no client returns. +void as_sound_voipSendingVoice(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipSendingVoice"); + fn.result->set_bool(false); + SwiffPlayer* player = g_swiffPlayerInstance; + if (!player || !voipPlayerClient(player)) + return; + voipClientArmFrontier("voipSendingVoice", "1006A047..1006A0DC"); +} +void as_sound_voipGetSendingVoiceVolume(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_sound_voipGetSendingVoiceVolume"); + fn.result->set_double(0.0); + SwiffPlayer* player = g_swiffPlayerInstance; + if (!player || !voipPlayerClient(player)) + return; + voipClientArmFrontier("voipGetSendingVoiceVolume", "1006A155..1006A1F2"); +} + +// ---- dice.bf2.Mod ------------------------------------------------------------------------------ + +// dword_100EC604: the mod row the Mod page selected, -1 at load (.data initialiser), written only by +// Mod.selectMod. +static int s_selectedModIndex = -1; + +// sub_1004F630 "getNumMods": host +0x190 getModCount(&n), n pre-set 0; false answers 0, true n. +void as_mod_getNumMods(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getNumMods"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + int count = 0; + if (!h->getModCount(&count)) // +0x190 + fn.result->set_double(0.0); + else + fn.result->set_double(static_cast(count)); +} + +// sub_1004F6E0 "browseHomepage" / sub_1004F750 "activateMod": with a selection, a default Mod record +// (sub_100224E0 / sub_10022580) filled by host +0x194 getModAt(selection, &mod); a filled record is +// handed to +0x19C requestBrowseModHomepage / +0x198 requestActivateMod (Booleans ignored). No AS +// result. requestActivateMod's parameter is the record itself, whose first member is the path. +void as_mod_browseHomepage(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_browseHomepage"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = s_selectedModIndex; + if (index == -1) + return; + IModInfo::Mod mod; + if (h->getModAt(index, &mod)) // +0x194 + (void) h->requestBrowseModHomepage(&mod); // +0x19C +} +void as_mod_activateMod(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_activateMod"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int index = s_selectedModIndex; + if (index == -1) + return; + IModInfo::Mod mod; + if (h->getModAt(index, &mod)) // +0x194 + (void) h->requestActivateMod(&mod.path); // +0x198 +} + +// sub_1004F800 "selectMod": (int) arg 0 into dword_100EC604 (fistp straight to the global). No AS +// result and no player access. +void as_mod_selectMod(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_selectMod"); + s_selectedModIndex = bf2x87::toIntTruncate(fn.arg(0).to_number()); +} + +// sub_1004F840 "activateModAndJoinServer": the player host; mod = "mods/" + arg 0, address = arg 1, +// port = (int) arg 2; host +0x368(mod, address, port), Boolean ignored (BF2.exe 0x626200 is `mov al, +// 1; ret 0Ch`). No AS result. +void as_mod_activateModAndJoinServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_activateModAndJoinServer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + std::string mod(fn.arg(0).to_string()); + mod = std::string("mods/") + mod; + const std::string address(fn.arg(1).to_string()); + const int port = bf2x87::toIntTruncate(fn.arg(2).to_number()); + (void) h->slot368(mod, address, port); // +0x368 +} + +// sub_1004FA00 "getModTitle" / sub_1004FB60 "getModDesc": the player host, then a dice String +// object (0x64 bytes, sub_1009BB10). No selection, or getModAt refusing: narrow "" with the wide side +// cleared. A record: the title (+0x38) / desc (+0x54) key localised through host +0xA8 +// (sub_1004F5E0) into the wide side, the narrow side "". +static void publishModLocalised(const gameswf::fn_call& fn, std::string IModInfo::Mod::* field) +{ + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + gameswf::as_object_interface* text = gameswf::create_dice_string_object(0, 0); + const int index = s_selectedModIndex; + if (index == -1) + { + gameswf::assign_dice_string_object_narrow(text, ""); + fn.result->set_as_object_interface(text); + return; + } + IModInfo::Mod mod; + if (!h->getModAt(index, &mod)) // +0x194 + gameswf::assign_dice_string_object_narrow(text, ""); + else + { + std::wstring wide; + (void) g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(wide, mod.*field); // +0xA8 + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); + } + fn.result->set_as_object_interface(text); +} +void as_mod_getModTitle(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getModTitle"); + publishModLocalised(fn, &IModInfo::Mod::title); +} +void as_mod_getModDesc(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getModDesc"); + publishModLocalised(fn, &IModInfo::Mod::desc); +} + +// sub_1004FCC0 "getModPath", sub_1004FFE0 "getModUrl", sub_10050120 "getModLogo", sub_10050260 +// "getModVersion": no selection or getModAt refusing answers ""; a record publishes its path (+0x00), +// url (+0x70), logo (+0xA8) or version (+0xE0) as a plain string. +static void publishModField(const gameswf::fn_call& fn, std::string IModInfo::Mod::* field) +{ + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + if (s_selectedModIndex == -1) + { + fn.result->set_tu_string(tu_string("")); + return; + } + IModInfo::Mod mod; + if (!h->getModAt(s_selectedModIndex, &mod)) // +0x194 + fn.result->set_tu_string(tu_string("")); + else + fn.result->set_tu_string(tu_string((mod.*field).c_str())); +} +void as_mod_getModPath(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModPath"); publishModField(fn, &IModInfo::Mod::path); } +void as_mod_getModUrl(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModUrl"); publishModField(fn, &IModInfo::Mod::url); } +void as_mod_getModLogo(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModLogo"); publishModField(fn, &IModInfo::Mod::logo); } +void as_mod_getModVersion(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_mod_getModVersion"); publishModField(fn, &IModInfo::Mod::version); } + +// sub_1004FE00 "getModPathShort": as getModPath, but only the characters after the first '/' or '\' +// of the path, appended one at a time (operator+= char) to an empty string. +void as_mod_getModPathShort(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_mod_getModPathShort"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + if (s_selectedModIndex == -1) + { + fn.result->set_tu_string(tu_string("")); + return; + } + IModInfo::Mod mod; + if (!h->getModAt(s_selectedModIndex, &mod)) // +0x194 + { + fn.result->set_tu_string(tu_string("")); + return; + } + std::string tail(""); + bool past = false; + for (unsigned int i = 0; i < mod.path.size(); ++i) + { + if (!past) + { + if (mod.path[i] == '/' || mod.path[i] == '\\') + past = true; + } + else + tail += mod.path[i]; + } + fn.result->set_tu_string(tu_string(tail.c_str())); +} + +// ---- dice.bf2.Logic ---------------------------------------------------------------------------- + +// sub_1004C950 "cacheCredits": the player host (discarded), player +0x28 getRender() +0xF4 +// preloadCredits (answer ignored). No AS result. +void as_logic_cacheCredits(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_cacheCredits"); + (void) g_swiffPlayerInstance->getSwiffHost(); + (void) g_swiffPlayerInstance->getRender()->preloadCredits(); // +0x28, +0xF4 +} + +// sub_1004CA70 "quit": inside the busy cursor; the player host, LocalProfileManager; with a current +// profile (+0x44) +0x40 saveCurrentProfile, otherwise +0xC4 saveGlobalSettings (Booleans ignored); +// then host +0xB0 requestQuit. No AS result. +void as_logic_quit(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_quit"); + BusyHost busy = busyOpen(); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + ILocalProfileManager* lpm = static_cast( + classManager->getSingleton(renddx9abi::HostString("LocalProfileManager"))); + if (lpm->getCurrentProfile()) // +0x44 + (void) lpm->saveCurrentProfile(); // +0x40 + else + (void) lpm->saveGlobalSettings(); // +0xC4 + (void) h->requestQuit(); // +0xB0 + busyClose(busy); +} + +// sub_1004CB60 "assert": the shipped body is a bare `ret 0Ch`. +void as_logic_assert(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_assert"); +} + +// sub_1004CB70 "setActivateReason": host +0xC0 setMessageId((int) arg 0). No AS result. +void as_logic_setActivateReason(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_setActivateReason"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + h->setMessageId(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0xC0 +} + +// sub_1004CF80 "setScrollSpeed": host +0x32C with arg 0 as a float (fstp dword). No AS result. +void as_logic_setScrollSpeed(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_setScrollSpeed"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + h->setFloatF0C(static_cast(fn.arg(0).to_number())); // +0x32C +} + +// sub_1004CFD0 "setCommandLine": host +0x2C0 with (int) arg 0 (the port names the slot setPage). +void as_logic_setCommandLine(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_setCommandLine"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + h->setPage(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x2C0 +} + +// sub_1004D350 "getRandomCreditsTexture": the player host (discarded), player +0x28 getRender() +// +0x100 getRandomCreditsName, published as a string. +void as_logic_getRandomCreditsTexture(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getRandomCreditsTexture"); + (void) g_swiffPlayerInstance->getSwiffHost(); + const std::string name = g_swiffPlayerInstance->getRender()->getRandomCreditsName(); // +0x28, +0x100 + fn.result->set_tu_string(tu_string(name.c_str())); +} + +// sub_1004D810 "getCommandlineServer" / sub_1004D890 "getCommandlineServerPassword": host +0xDC +// getJoinAddressSetting / +0xE0 getPasswordSetting (GSJoinAddress / GSPassword), as strings. +void as_logic_getCommandlineServer(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getCommandlineServer"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value = h->getJoinAddressSetting(); // +0xDC + fn.result->set_tu_string(tu_string(value.c_str())); +} +void as_logic_getCommandlineServerPassword(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getCommandlineServerPassword"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string value = h->getPasswordSetting(); // +0xE0 + fn.result->set_tu_string(tu_string(value.c_str())); +} + +// sub_1004DAA0 "getAbsoluteFileName": host +0x234 resolveMenuPath(arg 0), as a string. +void as_logic_getAbsoluteFileName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getAbsoluteFileName"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const std::string path(fn.arg(0).to_string()); + const std::string value = h->resolveMenuPath(path); // +0x234 + fn.result->set_tu_string(tu_string(value.c_str())); +} + +// sub_1004DE30 "restartExe": menu event 18 (0x12) with no arguments through host +0x2C pushEvent. +void as_logic_restartExe(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_restartExe"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + MenuEvent event; + event.type = 0x12; + (void) h->pushEvent(event); // +0x2C +} + +// ---- dice.bf2.PlayerStats ---------------------------------------------------------------------- + +// sub_10059E00 "getPreviousRankLevel", sub_10059EE0 "getNextRankLevel", sub_1005A1E0 +// "getRankNotificationLevel": the player host, ProfileManager (+0x30 getProfileId when present, the +// id pre-set 0), a rank record {time(), 0, 0, 0, 0} and host +0x284 getRankInfo(id, &record). False +// answers 0. True answers record.rank through host +0x1B8 getRankB / +0x1BC getRankC, or record.rank +// itself. +static bool currentRankRecord(ISwiffHost* h, IPlayerRankInfo::RankInfo& record) +{ + IBase* pm = classManager->getSingleton(renddx9abi::HostString("ProfileManager")); + int id = 0; + if (pm) + (void) static_cast(pm)->getProfileId(id); // +0x30 + record.timestamp = static_cast(::time(0)); + record.profileId = 0; record.rank = 0; record.change = 0; record.decrease = 0; + return h->getRankInfo(id, &record); // +0x284 +} +void as_playerstats_getPreviousRankLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getPreviousRankLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IPlayerRankInfo::RankInfo record; + int value = 0; + if (currentRankRecord(h, record)) + value = h->getRankB(record.rank); // +0x1B8 + fn.result->set_double(static_cast(value)); +} +void as_playerstats_getNextRankLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getNextRankLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IPlayerRankInfo::RankInfo record; + int value = 0; + if (currentRankRecord(h, record)) + value = h->getRankC(record.rank); // +0x1BC + fn.result->set_double(static_cast(value)); +} +void as_playerstats_getRankNotificationLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getRankNotificationLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + IPlayerRankInfo::RankInfo record; + int value = 0; + if (currentRankRecord(h, record)) + value = record.rank; + fn.result->set_double(static_cast(value)); +} + +// sub_1005A3B0 "refreshUnlocks" / sub_1005A490 "refreshStats": Boolean of host +0x1C8 fetchUnlocks / +// +0x1AC fetchPlayerStats((int) arg 0). +void as_playerstats_refreshUnlocks(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_refreshUnlocks"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(h->fetchUnlocks(bf2x87::toIntTruncate(fn.arg(0).to_number()))); // +0x1C8 +} +void as_playerstats_refreshStats(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_refreshStats"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + fn.result->set_bool(h->fetchPlayerStats(bf2x87::toIntTruncate(fn.arg(0).to_number()))); // +0x1AC +} + +// sub_1005A9B0 "getUnlocks": id = (int) arg 0; an unlock cache {time(), 0, 0, 0, {}} and the Boolean +// of host +0x1C4 getUnlocks(id, &cache). +void as_playerstats_getUnlocks(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getUnlocks"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + IPlayerUnlocks::UnlockCache cache; + cache.field0 = static_cast(::time(0)); + cache.field4 = 0; cache.available = 0; cache.selected = 0; + fn.result->set_bool(h->getUnlocks(id, &cache)); // +0x1C4 +} + +// sub_1005BBA0 "getStats": id = (int) arg 0; a default stats record (sub_10020A80) and the Boolean +// of host +0x1B0 getPlayerStatsRecord(id, record). +void as_playerstats_getStats(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_playerstats_getStats"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + dice::hfe::SwiffPlayerStatsRecord record; + fn.result->set_bool(h->getPlayerStatsRecord(id, record)); // +0x1B0 +} + +// sub_1005B0E0 "getOpponentKills", sub_1005B1A0 "getVictimKills", sub_1005BAE0 "getRoadKills": a +// default stats record, host +0x1B0 getPlayerStatsRecord(+0x21C getSelectedPlayerId, record); false +// answers 0, true the record's vmks (+520), mvks (+484) or vrk (+2672) as a number. +static void publishStatsKills(const gameswf::fn_call& fn, int dice::hfe::SwiffPlayerStatsRecord::* field) +{ + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + dice::hfe::SwiffPlayerStatsRecord record; + if (!h->getPlayerStatsRecord(h->getSelectedPlayerId(), record)) // +0x21C, +0x1B0 + fn.result->set_double(0.0); + else + fn.result->set_double(static_cast(record.*field)); +} +void as_playerstats_getOpponentKills(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentKills"); publishStatsKills(fn, &dice::hfe::SwiffPlayerStatsRecord::vmks); } +void as_playerstats_getVictimKills(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimKills"); publishStatsKills(fn, &dice::hfe::SwiffPlayerStatsRecord::mvks); } +void as_playerstats_getRoadKills(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getRoadKills"); publishStatsKills(fn, &dice::hfe::SwiffPlayerStatsRecord::vrk); } + +// ---- dice.bf2.ServerInfo ----------------------------------------------------------------------- + +// sub_10062940 "getSponsorText": a default record through the in-game fetch (sub_100627F0), the +// sponsor text (details +160) with every "|" replaced by "\n" (sub_100037D0), as a string. +void as_serverinfo_getSponsorText(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_serverinfo_getSponsorText"); + CachedRecord record; + fetchInGameServerRecord(record); + std::string text(record.details.sponsorText); + for (std::string::size_type at = text.find("|"); at != std::string::npos; at = text.find("|", at + 1)) + text.replace(at, 1, "\n"); + fn.result->set_tu_string(tu_string(text.c_str())); +} + +// sub_10062BA0 "getMapName": the in-game record's map name (entry +144), as a string. +void as_serverinfo_getMapName(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_serverinfo_getMapName"); + CachedRecord record; + fetchInGameServerRecord(record); + fn.result->set_tu_string(tu_string(record.entry.mapName.c_str())); +} + +// sub_10062C50 "getMaxPlayers": the in-game record's max players (entry +100), as a number. +void as_serverinfo_getMaxPlayers(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_serverinfo_getMaxPlayers"); + CachedRecord record; + fetchInGameServerRecord(record); + fn.result->set_double(static_cast(record.entry.maxPlayers)); +} + +// sub_10062CF0 "getGameModeTitle", sub_10062DA0 "getGameModeDescription", sub_10062E50 +// "getBackgroundTitle", sub_10062F00 "getBackgroundDescription": all four publish the in-game +// record's game mode string (entry +108; each reads [ebp-1F0h] with the capacity at [ebp-1DCh]). +// The identical bodies are shipped behaviour. +static void publishInGameGameMode(const gameswf::fn_call& fn) +{ + CachedRecord record; + fetchInGameServerRecord(record); + fn.result->set_tu_string(tu_string(record.entry.gameMode.c_str())); +} +void as_serverinfo_getGameModeTitle(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getGameModeTitle"); publishInGameGameMode(fn); } +void as_serverinfo_getGameModeDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getGameModeDescription"); publishInGameGameMode(fn); } +void as_serverinfo_getBackgroundTitle(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getBackgroundTitle"); publishInGameGameMode(fn); } +void as_serverinfo_getBackgroundDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_serverinfo_getBackgroundDescription"); publishInGameGameMode(fn); } + +// ---- dice.bf2.Singleplay / Shader --------------------------------------------------------------- + +// sub_10068BF0 "getBotSkills" / sub_10068C00 "setBotSkills": the player host is fetched and nothing +// else happens; no AS result. +void as_singleplay_getBotSkills(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_singleplay_getBotSkills"); + (void) g_swiffPlayerInstance->getSwiffHost(); +} +void as_singleplay_setBotSkills(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_singleplay_setBotSkills"); + (void) g_swiffPlayerInstance->getSwiffHost(); +} + +// sub_10068C10 "chooseMission": id = (int) arg 0; host +0xEC getSinglePlayerLevels(rows). True: the +// first row whose index equals id goes to host +0xE8 requestHostServer (Boolean ignored). No AS +// result. +void as_singleplay_chooseMission(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_singleplay_chooseMission"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); + std::vector rows; + if (!h->getSinglePlayerLevels(rows)) // +0xEC + return; + for (unsigned int i = 0; i < rows.size(); ++i) + { + if (rows[i].index == id) + { + (void) h->requestHostServer(&rows[i]); // +0xE8 + return; + } + } +} + +// sub_10068A10 "setShader": the player host (discarded); name = arg 0, technique = (int) arg 1; +// player +0x70 (renderSetPairState -> SwiffRender::setTextureTechnique). No AS result. +void as_shader_setShader(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_shader_setShader"); + (void) g_swiffPlayerInstance->getSwiffHost(); + const std::string name(fn.arg(0).to_string()); + const int technique = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#if defined(_MSC_VER) + g_swiffPlayerInstance->renderSetPairState(reinterpret_cast(&name), technique); // +0x70 +#else + g_swiffPlayerInstance->renderSetPairState(name, technique); // +0x70 +#endif +} + +// ---- dice.bf2.ControlSettings.mapInput --------------------------------------------------------- + +// sub_1000EDA0 "mapInput": the player host; ControlSettings +0x80 activateMouse; the edited map +// selected (sub_1000E250); input = (int) arg 0. Input -1: the selection restored (sub_1000E2E0), +// ControlSettings +0x84 deactivateMouse, Boolean true. Otherwise alternate = arg 1, second = arg 2 +// (to_bool), arg 3 to_bool and dropped; gameInput = (unk_100F3138 == "_defaultGameControlMap"); +// ControlSettings +0x30 mapNextInput(input, alternate, 0, second, gameInput). Answer 1: restore, +// deactivateMouse, post {3, 0, "dup" + getMappedInputName (+0x90)} through host +0x1E4, Boolean false. +// Answer 2: restore, deactivateMouse, false. Any other answer: restore, deactivateMouse, true. +// BF2.exe's +0x30 (0x4B2CA0) returns the manager's full EAX (+0x38), compared here with 1 and 2; +// both are declared int. The port's manager capture is a CHOSEN-STUB answering 0, so only the last +// arm is reachable until the capture routine (ELF 0x8497AC0) is recovered. +void as_controlsettings_mapInput(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_controlsettings_mapInput"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + controlSettingsOf(controlSettingsSingleton())->activateMouse(); // +0x80 + selectEditedControlMap(); + const int input = bf2x87::toIntTruncate(fn.arg(0).to_number()); + if (input != -1) + { + const bool alternate = fn.arg(1).to_bool(); + const bool second = fn.arg(2).to_bool(); + (void) fn.arg(3).to_bool(); + const bool gameInput = (s_editedControlMap == "_defaultGameControlMap"); + const int answer = controlSettingsOf(controlSettingsSingleton())->mapNextInput( + input, alternate, 0, second, gameInput); // +0x30 + if (answer == 1) + { + restoreControlMapSelection(); + controlSettingsOf(controlSettingsSingleton())->deactivateMouse(); // +0x84 + const std::string mapped = controlSettingsOf(controlSettingsSingleton())->getMappedInputName(); // +0x90 + const std::string dup("dup"); + const std::string text = std::string(dup) + mapped; + SwiffHostMessage message; + message.type = 3; + message.code = 0; + message.text = text; + (void) h->postMessage(message); // +0x1E4 + fn.result->set_bool(false); + return; + } + if (answer == 2) + { + restoreControlMapSelection(); + controlSettingsOf(controlSettingsSingleton())->deactivateMouse(); // +0x84 + fn.result->set_bool(false); + return; + } + } + restoreControlMapSelection(); + controlSettingsOf(controlSettingsSingleton())->deactivateMouse(); // +0x84 + fn.result->set_bool(true); +} + +// The registrations, in the shipped registrars' order within each namespace (address of the +// name push; the callback address is the sub_ named in each body above). +static void registerRecoveredNatives(SwiffAsNamespace** ns, const char* const* names, int count) +{ + for (int i = 0; i < count; ++i) + { + const char* n = names[i]; + if (::strcmp(n, "ControlSettings") == 0) + { + ns[i]->registerNativeCompatibleMethod("mapInput"); // 1000F163 -> sub_1000EDA0 + } + else if (::strcmp(n, "Logic") == 0) + { + ns[i]->registerNativeCompatibleMethod("quit"); // 1004DF60 -> sub_1004CA70 + ns[i]->registerNativeCompatibleMethod("assert"); // 1004E0CB -> sub_1004CB60 + ns[i]->registerNativeCompatibleMethod("setActivateReason"); // 1004E17B -> sub_1004CB70 + ns[i]->registerNativeCompatibleMethod("getAbsoluteFileName"); // 1004E2DB -> sub_1004DAA0 + ns[i]->registerNativeCompatibleMethod("getCommandlineServer"); // 1004E5F3 -> sub_1004D810 + ns[i]->registerNativeCompatibleMethod("getCommandlineServerPassword"); // 1004E64B -> sub_1004D890 + ns[i]->registerNativeCompatibleMethod("setCommandLine"); // 1004E90B -> sub_1004CFD0 + ns[i]->registerNativeCompatibleMethod("restartExe"); // 1004E9BB -> sub_1004DE30 + ns[i]->registerNativeCompatibleMethod("setScrollSpeed"); // 1004EA6B -> sub_1004CF80 + ns[i]->registerNativeCompatibleMethod("cacheCredits"); // 1004EB1B -> sub_1004C950 + ns[i]->registerNativeCompatibleMethod("getRandomCreditsTexture"); // 1004EB73 -> sub_1004D350 + } + else if (::strcmp(n, "Mod") == 0) + { + ns[i]->registerNativeCompatibleMethod("getNumMods"); // 10050410 -> sub_1004F630 + ns[i]->registerNativeCompatibleMethod("browseHomepage"); // 10050473 -> sub_1004F6E0 + ns[i]->registerNativeCompatibleMethod("activateMod"); // 100504CB -> sub_1004F750 + ns[i]->registerNativeCompatibleMethod("selectMod"); // 10050523 -> sub_1004F800 + ns[i]->registerNativeCompatibleMethod("getModTitle"); // 1005057B -> sub_1004FA00 + ns[i]->registerNativeCompatibleMethod("getModDesc"); // 100505D3 -> sub_1004FB60 + ns[i]->registerNativeCompatibleMethod("getModPath"); // 1005062B -> sub_1004FCC0 + ns[i]->registerNativeCompatibleMethod("getModPathShort"); // 10050683 -> sub_1004FE00 + ns[i]->registerNativeCompatibleMethod("getModUrl"); // 100506DB -> sub_1004FFE0 + ns[i]->registerNativeCompatibleMethod("getModLogo"); // 10050733 -> sub_10050120 + ns[i]->registerNativeCompatibleMethod("getModVersion"); // 1005078B -> sub_10050260 + ns[i]->registerNativeCompatibleMethod("activateModAndJoinServer"); // 1005083B -> sub_1004F840 + } + else if (::strcmp(n, "Multiplay") == 0) + { + ns[i]->registerNativeCompatibleMethod("addFavouriteServer"); // 10057B7B -> sub_10054940 + ns[i]->registerNativeCompatibleMethod("removeFavouriteServer"); // 10057BD3 -> sub_10054B20 + ns[i]->registerNativeCompatibleMethod("getMapName"); // 10057C83 -> sub_10057450 + ns[i]->registerNativeCompatibleMethod("setFilter"); // 10057FF3 -> sub_100519C0 + ns[i]->registerNativeCompatibleMethod("sort"); // 1005804B -> sub_10051A20 + ns[i]->registerNativeCompatibleMethod("refreshBrowser"); // 100580FB -> sub_10050B70 + ns[i]->registerNativeCompatibleMethod("setHighestPing"); // 10058203 -> sub_10051480 + ns[i]->registerNativeCompatibleMethod("isDownloadingDemo"); // 1005830B -> sub_10053EE0 + ns[i]->registerNativeCompatibleMethod("getDownloadingHostname"); // 10058363 -> sub_10053F50 + ns[i]->registerNativeCompatibleMethod("getDownloadingUrl"); // 100583BB -> sub_10053FE0 + ns[i]->registerNativeCompatibleMethod("getDownloadingDate"); // 10058413 -> sub_10054070 + ns[i]->registerNativeCompatibleMethod("getDownloadingProgress"); // 1005846B -> sub_10054100 + ns[i]->registerNativeCompatibleMethod("downloadDemo"); // 100584C3 -> sub_10054160 + ns[i]->registerNativeCompatibleMethod("deleteDemoBookmark"); // 1005851B -> sub_100542C0 + ns[i]->registerNativeCompatibleMethod("getNumDemoBookmarks"); // 10058573 -> sub_10053E50 + ns[i]->registerNativeCompatibleMethod("playDemo"); // 100585CB -> sub_10057310 + ns[i]->registerNativeCompatibleMethod("clearHistory"); // 10058BA3 -> sub_10050C80 + ns[i]->registerNativeCompatibleMethod("addHistoryToFavourites"); // 10058BFB -> sub_10053230 + ns[i]->registerNativeCompatibleMethod("removeHistory"); // 10058C53 -> sub_10053540 + ns[i]->registerNativeCompatibleMethod("removeFavourite"); // 10058CAB -> sub_10053060 + ns[i]->registerNativeCompatibleMethod("addFavourite"); // 10058D03 -> sub_10052C80 + ns[i]->registerNativeCompatibleMethod("validateIp"); // 10058D5B -> sub_100528A0 + ns[i]->registerNativeCompatibleMethod("playNow"); // 10058E0B -> sub_10052AF0 + ns[i]->registerNativeCompatibleMethod("getSelectedFilterGameModeId"); // 10059123 -> sub_100555E0 + ns[i]->registerNativeCompatibleMethod("getMapPathFromName"); // 10059283 -> sub_100563B0 + ns[i]->registerNativeCompatibleMethod("getSelectedServerFilterGameMode"); // 100592DB -> sub_10055350 + ns[i]->registerNativeCompatibleMethod("isServerBrowserBusy"); // 10059333 -> sub_100526A0 + ns[i]->registerNativeCompatibleMethod("getScrollFadeSpeed"); // 10059543 -> sub_10052450 + ns[i]->registerNativeCompatibleMethod("stopDownloadDemo"); // 1005959B -> sub_10050C10 + ns[i]->registerNativeCompatibleMethod("deleteDemo"); // 100595F3 -> sub_10051F00 + ns[i]->registerNativeCompatibleMethod("hasDemoDownloadFailed"); // 1005964B -> sub_100523E0 + } + else if (::strcmp(n, "PlayerStats") == 0) + { + ns[i]->registerNativeCompatibleMethod("getStats"); // 1005C2C0 -> sub_1005BBA0 + ns[i]->registerNativeCompatibleMethod("refreshStats"); // 1005C323 -> sub_1005A490 + ns[i]->registerNativeCompatibleMethod("getUnlocks"); // 1005C37B -> sub_1005A9B0 + ns[i]->registerNativeCompatibleMethod("refreshUnlocks"); // 1005C3D3 -> sub_1005A3B0 + ns[i]->registerNativeCompatibleMethod("getRankNotificationLevel"); // 1005C743 -> sub_1005A1E0 + ns[i]->registerNativeCompatibleMethod("getPreviousRankLevel"); // 1005C79B -> sub_10059E00 + ns[i]->registerNativeCompatibleMethod("getNextRankLevel"); // 1005C7F3 -> sub_10059EE0 + ns[i]->registerNativeCompatibleMethod("getRoadKills"); // 1005C8FB -> sub_1005BAE0 + ns[i]->registerNativeCompatibleMethod("getOpponentKills"); // 1005CB0B -> sub_1005B0E0 + ns[i]->registerNativeCompatibleMethod("getVictimKills"); // 1005CC13 -> sub_1005B1A0 + } + else if (::strcmp(n, "Profile") == 0) + { + ns[i]->registerNativeCompatibleMethod("searchUniquePlayer"); // 1006158B -> sub_10060D80 + ns[i]->registerNativeCompatibleMethod("searchPlayer"); // 100615E3 -> sub_1005E2A0 + ns[i]->registerNativeCompatibleMethod("setComparePlayer"); // 1006163B -> sub_1005D350 + ns[i]->registerNativeCompatibleMethod("clearComparePlayer"); // 10061693 -> sub_1005D080 + ns[i]->registerNativeCompatibleMethod("getStatPlayer"); // 10061743 -> sub_1005E100 + ns[i]->registerNativeCompatibleMethod("getUseAdvancedServerBrowser"); // 1006184B -> sub_1005DDD0 + ns[i]->registerNativeCompatibleMethod("setUseAdvancedServerBrowser"); // 100618A3 -> sub_1005D220 + ns[i]->registerNativeCompatibleMethod("deleteLocalProfile"); // 10061AB3 -> sub_1005DCE0 + ns[i]->registerNativeCompatibleMethod("getSprint"); // 10061C6B -> sub_1005F4A0 + ns[i]->registerNativeCompatibleMethod("newGamespyProfile"); // 10061F83 -> sub_1005DA70 + ns[i]->registerNativeCompatibleMethod("deleteCurrentProfile"); // 10061FDB -> sub_1005D800 + ns[i]->registerNativeCompatibleMethod("getSelectedAge"); // 100621EB -> sub_1005D5B0 + ns[i]->registerNativeCompatibleMethod("setSelectedAge"); // 10062243 -> sub_1005D190 + ns[i]->registerNativeCompatibleMethod("getMinimumAge"); // 1006229B -> sub_1005D050 + ns[i]->registerNativeCompatibleMethod("getNumOnlineProfiles"); // 1006234B -> sub_1005FD90 + ns[i]->registerNativeCompatibleMethod("getNumOfflineProfiles"); // 100623A3 -> sub_1005FEE0 + ns[i]->registerNativeCompatibleMethod("setNamePrefix"); // 10062453 -> sub_1005D110 + } + else if (::strcmp(n, "ServerInfo") == 0) + { + ns[i]->registerNativeCompatibleMethod("getSponsorText"); // 100631E0 -> sub_10062940 + ns[i]->registerNativeCompatibleMethod("getMapName"); // 100632F3 -> sub_10062BA0 + ns[i]->registerNativeCompatibleMethod("getMaxPlayers"); // 1006334C -> sub_10062C50 + ns[i]->registerNativeCompatibleMethod("getGameModeTitle"); // 100633A5 -> sub_10062CF0 + ns[i]->registerNativeCompatibleMethod("getGameModeDescription"); // 100633FE -> sub_10062DA0 + ns[i]->registerNativeCompatibleMethod("getBackgroundTitle"); // 10063457 -> sub_10062E50 + ns[i]->registerNativeCompatibleMethod("getBackgroundDescription"); // 100634B0 -> sub_10062F00 + } + else if (::strcmp(n, "Shader") == 0) + { + ns[i]->registerNativeCompatibleMethod("setShader"); // 10068B16 -> sub_10068A10 + } + else if (::strcmp(n, "Singleplay") == 0) + { + ns[i]->registerNativeCompatibleMethod("chooseMission"); // 10068DDA -> sub_10068C10 + ns[i]->registerNativeCompatibleMethod("getBotSkills"); // 10068E3F -> sub_10068BF0 + ns[i]->registerNativeCompatibleMethod("setBotSkills"); // 10068E9C -> sub_10068C00 + } + else if (::strcmp(n, "Sound") == 0) + { + ns[i]->registerNativeCompatibleMethod("voipInitialize"); // 1006A313 -> sub_10069010 + ns[i]->registerNativeCompatibleMethod("voipSetEnable"); // 1006A36B -> sub_100692B0 + ns[i]->registerNativeCompatibleMethod("voipGetEnable"); // 1006A3C3 -> sub_100693C0 + ns[i]->registerNativeCompatibleMethod("voipSetBoost"); // 1006A41B -> sub_10069BA0 + ns[i]->registerNativeCompatibleMethod("voipGetBoost"); // 1006A473 -> sub_10069CA0 + ns[i]->registerNativeCompatibleMethod("voipStartTest"); // 1006A4CB -> sub_100694E0 + ns[i]->registerNativeCompatibleMethod("voipSetTransmitVolume"); // 1006A57B -> sub_10069750 + ns[i]->registerNativeCompatibleMethod("voipGetTransmitVolume"); // 1006A5D3 -> sub_10069840 + ns[i]->registerNativeCompatibleMethod("voipSetRecieveVolume"); // 1006A62B -> sub_100698C0 + ns[i]->registerNativeCompatibleMethod("voipGetRecieveVolume"); // 1006A683 -> sub_100699B0 + ns[i]->registerNativeCompatibleMethod("voipSetThresholdVolume"); // 1006A6DB -> sub_10069A30 + ns[i]->registerNativeCompatibleMethod("voipGetThresholdVolume"); // 1006A733 -> sub_10069B30 + ns[i]->registerNativeCompatibleMethod("voipIsBoostEnabled"); // 1006A83B -> sub_10069D80 + ns[i]->registerNativeCompatibleMethod("voipSendingVoice"); // 1006A893 -> sub_10069FE0 + ns[i]->registerNativeCompatibleMethod("voipGetSendingVoiceVolume"); // 1006A8EB -> sub_1006A0F0 + ns[i]->registerNativeCompatibleMethod("voipSetUsePushToTalk"); // 1006A943 -> sub_10069E10 + ns[i]->registerNativeCompatibleMethod("voipGetUsePushToTalk"); // 1006A99B -> sub_10069F50 + } + } +} + +// ---- dice.bf2.HapticSettings (the Falcon force-feedback page) ------------------------------------ +// 265 rows, registered by the HapticSettings registrar (0x10044590). The rows fall into 31 code +// shapes; each shape was read once in full and the per-row constants (vtable slots, components) +// extracted from every row by comparing the rows of a shape constant by constant +// (docs/macos-c-swiff-natives.md). +// IHapticSettings' slot order (Game/HapticSettings.h, 505 slots, +0x10 first) matches every +// "+XX" annotation there; the slot each row calls is named in its body. + +// dword_100F8530: the page the recoil rows read (0 infantry weapons, otherwise vehicle weapons). +static int s_hapticSettingsPage = 0; + +static IHapticSettings* hapticSettings() +{ + return static_cast(classManager->getSingleton(renddx9abi::HostString("HapticSettings"))); +} + +// unk_100F3870: the three threshold names (static initialiser 0x100D5D40). The setters search the +// three (`cmp edi, 54h`); the getters' loop bound is 0x16C, thirteen 28-byte slots, so a name that is +// none of the three walks into the adjacent DLL globals (0x100F38C4..) in the shipped image. +// [CHOSEN, not recovered] The port searches the three for both and answers -1 for anything else, +// which is what the setters do. +static int hapticThresholdLevel(const std::string& key) +{ + static const char* const kNames[3] = { + "BFHQ_physicsthresholdlow", "BFHQ_physicsthresholdmedium", "BFHQ_physicsthresholdhigh" }; + for (int i = 0; i < 3; ++i) + if (key.compare(kNames[i]) == 0) + return i; + return -1; +} + +// The two weapon-name tables (static initialiser 0x100D5D80 / 0x100D5E60): unk_100F6C70, the 13 +// infantry names (0x16C bytes), and unk_100F3310, the 7 vehicle names (0xC4 bytes). The +// getWeaponInitial rows read single slots of them (0x100F6C70 [0], 0x100F3310 [0], 0x100F3348 [2], +// 0x100F3364 [3]). +static const char* const kHapticInfantryWeapons[13] = { + "BFHQ_assaultrifles", "BFHQ_grenadelauncher", "BFHQ_carbines", "BFHQ_lightmachineguns", + "BFHQ_sniperrifles", "BFHQ_pistols", "BFHQ_ataa", "BFHQ_submachineguns", "BFHQ_shotguns", + "BFHQ_knife", "BFHQ_defibrillator", "BFHQ_explosives", "BFHQ_handgrenade" }; +static const char* const kHapticVehicleWeapons[7] = { + "BFHQ_v_lightmachineguns", "BFHQ_v_heavymachineguns", "BFHQ_v_helicopterguns", + "BFHQ_v_airplaneguns", "BFHQ_v_missiles", "BFHQ_v_tankcannons", "BFHQ_v_tankmachineguns" }; + +// The recoil rows' weapon class: page 0 searches the 13 infantry names and answers the index; +// another page searches the 7 vehicle names and answers index + 100 (0x64). No match answers -1. +static int hapticWeaponClass(const std::string& key) +{ + if (s_hapticSettingsPage == 0) + { + for (int i = 0; i < 13; ++i) + if (key.compare(kHapticInfantryWeapons[i]) == 0) + return i; + return -1; + } + for (int i = 0; i < 7; ++i) + if (key.compare(kHapticVehicleWeapons[i]) == 0) + return i + 100; + return -1; +} + +// The two list builders are declared with the other getListEntries branches inside SwiffPlayer.cpp's +// anonymous namespace; their definitions join it. +namespace { + +// One selector row (both branches): the row keyed by the table name (sub_1001C770), its localised +// text as a dice String column (sub_10013600 + sub_1001CB80), and "selected" = 1 on the first row +// only (sub_10019970). The running count starts at 0 (edi, stored over the third argument at +// 0x1002289C) and is the published totalCount (sub_10019B00). +static void pushHapticSelectRow(ListResult& r, ListHost h, const char* name, int& count) +{ + r.beginRowStr(name); + pushLocalised(r, h, name); + if (count == 0) + r.setInt("selected", 1); + ++count; +} + +// General.getListEntries "weaponselect" (0x10030F66..0x1003136F): the rows follow the page +// (dword_100F8530, jump table 0x100316B0). 0: the 13 infantry names. 1 (land): the vehicle names +// except [2] helicopter and [3] airplane guns. 2 (air): [3] airplane guns and [4] missiles. +// 3 (heli): [2] helicopter guns and [4] missiles. 4 (sea): [0] alone. Any other page: no row. +static void listHapticWeaponSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h) +{ + r.begin(); + int count = 0; + switch (s_hapticSettingsPage) + { + case 0: + for (int i = 0; i < 13; ++i) + pushHapticSelectRow(r, h, kHapticInfantryWeapons[i], count); + break; + case 1: + for (int i = 0; i < 7; ++i) + if (i != 2 && i != 3) + pushHapticSelectRow(r, h, kHapticVehicleWeapons[i], count); + break; + case 2: + for (int i = 0; i < 7; ++i) + if (i == 3 || i == 4) + pushHapticSelectRow(r, h, kHapticVehicleWeapons[i], count); + break; + case 3: + for (int i = 0; i < 7; ++i) + if (i == 2 || i == 4) + pushHapticSelectRow(r, h, kHapticVehicleWeapons[i], count); + break; + case 4: + pushHapticSelectRow(r, h, kHapticVehicleWeapons[0], count); + break; + default: + break; + } + r.setTotalCount(count); + fn.result->set_as_object_interface(r.arr.get_ptr()); +} + +// General.getListEntries "thresholdselect" (0x10031374..0x1003147B): the three threshold names +// (unk_100F3870), the first selected; every page. +static void listHapticThresholdSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h) +{ + static const char* const kNames[3] = { + "BFHQ_physicsthresholdlow", "BFHQ_physicsthresholdmedium", "BFHQ_physicsthresholdhigh" }; + r.begin(); + int count = 0; + for (int i = 0; i < 3; ++i) + pushHapticSelectRow(r, h, kNames[i], count); + r.setTotalCount(count); + fn.result->set_as_object_interface(r.arr.get_ptr()); +} + +} // namespace + +// apply / reset tail (0x10035176..0x100351B4): LocalProfileManager by name; present with a current +// profile (+0x44): +0x40 saveCurrentProfile. +static void hapticSaveCurrentProfile() +{ + IBase* lpm = classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); + if (lpm && static_cast(lpm)->getCurrentProfile()) + (void) static_cast(lpm)->saveCurrentProfile(); +} + +// The selection page state: two DLL-global std::strings, default-constructed empty by the static +// initialisers 0x100D6250 / 0x100D6270 and touched by no other code. setWeaponSelect* stores the +// name into the first (0x100F8550, text at +4 = unk_100F8554); setThresholdSelect* into the second +// (0x100F8534, text unk_100F8538). All five categories share each string. +static std::string s_hapticWeaponSelect; // 0x100F8550 +static std::string s_hapticThresholdSelect; // 0x100F8534 + +// getWeaponInitial* (sub_10036D10 and its four twins): arg 0 to_number, fistp under a chop control +// word; 1 publishes the table name as a plain string (as_value type 1), anything else the name's +// dice String through sub_10036B70 - a third copy of the localised-String helper the VideoSettings +// rows use (sub_1006B310): the player's host first, an empty key's narrow String, otherwise the +0xA8 +// localisation in a wide one. +static void publishHapticInitialName(const gameswf::fn_call& fn, const char* name) +{ + if (bf2x87::toIntTruncate(fn.arg(0).to_number()) == 1) + fn.result->set_tu_string(tu_string(name)); + else + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString(name))); +} + +// setThresholdSelect* (sub_10036DF0 and its four twins): arg 0 to_string; the result is the bool +// _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, published before the name is stored. +static void storeHapticThresholdSelect(const gameswf::fn_call& fn) +{ + const std::string name(fn.arg(0).to_string()); + fn.result->set_bool(::_stricmp(name.c_str(), "BFHQ_physicsthresholdhigh") == 0); + s_hapticThresholdSelect = name; +} + +typedef Vec3 (IHapticSettings::*HapticVecGetter)(); +typedef void (IHapticSettings::*HapticVecSetter)(float x, float y, float z); + +// One vector store, the block every setter runs once for its own slot and, on a match, once more +// for the generic slot: HapticSettings by name three times, the getter twice (a, b), then the setter +// with the new value in its component and the rest taken from a and b: X (v, b.y, a.z), +// Y (b.x, v, a.z), Z (b.x, a.y, v). The mirror passes of the vehicle rows reach the singleton through +// sub_10035100, the same lookup. +static void hapticStoreComponent(HapticVecGetter get, HapticVecSetter set, int component, float value) +{ + IHapticSettings* first = hapticSettings(); + IHapticSettings* second = hapticSettings(); + IHapticSettings* target = hapticSettings(); + const Vec3 a = (first->*get)(); + const Vec3 b = (second->*get)(); + if (component == 0) + (target->*set)(value, b.y, a.z); + else if (component == 1) + (target->*set)(b.x, value, a.z); + else + (target->*set)(b.x, a.y, value); +} + +// The local player's vehicle category the vehicle rows compare against (template +0x22C, the +// IPlayerControlObjectTemplate base, slot +0x24): LAND 0 (test eax, eax), SEA 1, AIR 2, HELI 3. +// SOLDIER rows test "on foot" instead. +enum HapticMirrorCategory { kHapticSoldier = -1, kHapticLand = 0, kHapticSea = 1, kHapticAir = 2, kHapticHeli = 3 }; + +// The 75 vector setters (sub_1003C5F0 .. sub_100436B0, one shape; constants per row checked against +// every row's disassembly): arg 0 to_number stored as float into the category slot, then +// playerManager +0x30 getLocalHumanPlayer. +// * SOLDIER rows: no local player, or the player on foot (+0x44 getVehicle == +0xA0 +// getDefaultVehicle): the value is mirrored into the generic slot. In a vehicle: nothing more. +// * Vehicle rows: no local player: nothing more. Otherwise the vehicle's template field (+0x14) is +// read before the on-foot test, on foot ends the row, and a vehicle whose template is taken as +// a PlayerControlObjectTemplate with no check (the shipped add 0x22C) and whose +// getVehicleCategory equals the row's category gets the mirror (port guard: see the body). +static void hapticVectorSetter(const gameswf::fn_call& fn, HapticVecGetter get, HapticVecSetter set, + int component, int category, + HapticVecGetter mirrorGet, HapticVecSetter mirrorSet) +{ + const float value = static_cast(fn.arg(0).to_number()); + hapticStoreComponent(get, set, component, value); + world::IPlayer* player = reinterpret_cast(playerManager)->getLocalHumanPlayer(); // +0x30 + if (category == kHapticSoldier) + { + if (player && player->getVehicle() != player->getDefaultVehicle()) // +0x44 / +0xA0 + return; + hapticStoreComponent(mirrorGet, mirrorSet, component, value); + return; + } + if (!player) + return; + world::IObject* vehicle = player->getVehicle(); // +0x44 + // [CHOSEN, not recovered] Retail reads the template field (+0x14) here with no null test and, + // after the on-foot test, takes template + 0x22C as the IPlayerControlObjectTemplate base with + // no type test. A dead player's vehicle is the free camera (template MultiPlayerFreeCamera, a + // FreeCameraTemplate of 0x188 bytes): retail's +0x22C read lands past that object in whatever + // heap memory follows; the 64-bit port's layout puts a non-canonical pointer there (GP fault + // in the owner's in-game APPLY while dead, 2026-11-02). Neither out-of-bounds value can be + // reproduced, so the port asks the template for the interface (as SupplyObjectTemplate:: + // testVehicleType does) and treats a missing vehicle, a missing template or a template that is + // not a PlayerControlObjectTemplate as "category does not match": no mirror. The MSVC x86 + // build keeps the shipped code (byte-identical goal); only non-x86 builds take the guard. +#if defined(_MSC_VER) && defined(_M_IX86) + // Shipped x86 path, unchanged (no null or type test). + const world::IObjectTemplate* tmpl = vehicle->getTemplate(); // +0x14 + if (vehicle == player->getDefaultVehicle()) // +0xA0 + return; + const world::IPlayerControlObjectTemplate* pco = + static_cast(tmpl); // +0x22C + if (pco->getVehicleCategory() != category) // +0x24 + return; +#else + if (!vehicle) + return; + const world::IObjectTemplate* tmpl = vehicle->getTemplate(); // +0x14 + if (vehicle == player->getDefaultVehicle()) // +0xA0 + return; + const world::IPlayerControlObjectTemplate* pco = tmpl + ? static_cast( + tmpl->queryInterface(world::IID_IPlayerControlObjectTemplate)) // retail: +0x22C + : 0; + if (!pco || pco->getVehicleCategory() != category) // +0x24 + return; +#endif + hapticStoreComponent(mirrorGet, mirrorSet, component, value); +} + +// sub_10035140 "apply": HapticSettings +0x18, then LocalProfileManager by name: present with a current profile (+0x44), +0x40 saveCurrentProfile. +void as_hapticsettings_apply(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_apply"); + (void) hapticSettings()->apply(); // +0x18 + hapticSaveCurrentProfile(); +} + +// sub_100351C0 "reset": HapticSettings +0x20, then LocalProfileManager by name: present with a current profile (+0x44), +0x40 saveCurrentProfile. +void as_hapticsettings_reset(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_reset"); + hapticSettings()->setDefaultValues(); // +0x20 + hapticSaveCurrentProfile(); +} + +// sub_10035240 "cancel": HapticSettings +0x24 loadCurrentProfileFile. +void as_hapticsettings_cancel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_cancel"); + hapticSettings()->loadCurrentProfileFile(); // +0x24 +} + +// sub_10037AB0 "getControlBoxLengthSOLDIER_X": HapticSettings by name, +0x54 getControlBoxLengthSOLDIER() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSOLDIER_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthSOLDIER(); // +0x54 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037B30 "getControlBoxStiffnessSOLDIER_X": HapticSettings by name, +0x5C getControlBoxStiffnessSOLDIER() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSOLDIER_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSOLDIER(); // +0x5C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037BB0 "getControlBoxLengthLAND_X": HapticSettings by name, +0x84 getControlBoxLengthLAND() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthLAND_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthLAND(); // +0x84 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037C40 "getControlBoxStiffnessLAND_X": HapticSettings by name, +0x8C getControlBoxStiffnessLAND() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessLAND_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessLAND(); // +0x8C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037CD0 "getControlBoxLengthAIR_X": HapticSettings by name, +0x64 getControlBoxLengthAIR() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthAIR_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthAIR(); // +0x64 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037D50 "getControlBoxStiffnessAIR_X": HapticSettings by name, +0x6C getControlBoxStiffnessAIR() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessAIR_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessAIR(); // +0x6C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037DD0 "getControlBoxLengthHELI_X": HapticSettings by name, +0x74 getControlBoxLengthHELI() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthHELI_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthHELI(); // +0x74 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037E50 "getControlBoxStiffnessHELI_X": HapticSettings by name, +0x7C getControlBoxStiffnessHELI() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessHELI_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessHELI(); // +0x7C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037ED0 "getControlBoxLengthSEA_X": HapticSettings by name, +0x94 getControlBoxLengthSEA() by value, component x as a number. +void as_hapticsettings_getControlBoxLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSEA_X"); + const Vec3 v = hapticSettings()->getControlBoxLengthSEA(); // +0x94 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037F60 "getControlBoxStiffnessSEA_X": HapticSettings by name, +0x9C getControlBoxStiffnessSEA() by value, component x as a number. +void as_hapticsettings_getControlBoxStiffnessSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSEA_X"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSEA(); // +0x9C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10037FF0 "getControlBoxLengthSOLDIER_Y": HapticSettings by name, +0x54 getControlBoxLengthSOLDIER() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSOLDIER_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthSOLDIER(); // +0x54 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038070 "getControlBoxStiffnessSOLDIER_Y": HapticSettings by name, +0x5C getControlBoxStiffnessSOLDIER() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSOLDIER_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSOLDIER(); // +0x5C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100380F0 "getControlBoxLengthLAND_Y": HapticSettings by name, +0x84 getControlBoxLengthLAND() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthLAND_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthLAND(); // +0x84 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038180 "getControlBoxStiffnessLAND_Y": HapticSettings by name, +0x8C getControlBoxStiffnessLAND() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessLAND_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessLAND(); // +0x8C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038210 "getControlBoxLengthAIR_Y": HapticSettings by name, +0x64 getControlBoxLengthAIR() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthAIR_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthAIR(); // +0x64 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038290 "getControlBoxStiffnessAIR_Y": HapticSettings by name, +0x6C getControlBoxStiffnessAIR() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessAIR_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessAIR(); // +0x6C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038310 "getControlBoxLengthHELI_Y": HapticSettings by name, +0x74 getControlBoxLengthHELI() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthHELI_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthHELI(); // +0x74 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038390 "getControlBoxStiffnessHELI_Y": HapticSettings by name, +0x7C getControlBoxStiffnessHELI() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessHELI_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessHELI(); // +0x7C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038410 "getControlBoxLengthSEA_Y": HapticSettings by name, +0x94 getControlBoxLengthSEA() by value, component y as a number. +void as_hapticsettings_getControlBoxLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSEA_Y"); + const Vec3 v = hapticSettings()->getControlBoxLengthSEA(); // +0x94 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100384A0 "getControlBoxStiffnessSEA_Y": HapticSettings by name, +0x9C getControlBoxStiffnessSEA() by value, component y as a number. +void as_hapticsettings_getControlBoxStiffnessSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSEA_Y"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSEA(); // +0x9C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10038530 "getControlBoxLengthSOLDIER_Z": HapticSettings by name, +0x54 getControlBoxLengthSOLDIER() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSOLDIER_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthSOLDIER(); // +0x54 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100385B0 "getControlBoxStiffnessSOLDIER_Z": HapticSettings by name, +0x5C getControlBoxStiffnessSOLDIER() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSOLDIER_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSOLDIER(); // +0x5C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038630 "getControlBoxLengthLAND_Z": HapticSettings by name, +0x84 getControlBoxLengthLAND() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthLAND_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthLAND(); // +0x84 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100386C0 "getControlBoxStiffnessLAND_Z": HapticSettings by name, +0x8C getControlBoxStiffnessLAND() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessLAND_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessLAND(); // +0x8C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038750 "getControlBoxLengthAIR_Z": HapticSettings by name, +0x64 getControlBoxLengthAIR() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthAIR_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthAIR(); // +0x64 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100387D0 "getControlBoxStiffnessAIR_Z": HapticSettings by name, +0x6C getControlBoxStiffnessAIR() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessAIR_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessAIR(); // +0x6C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038850 "getControlBoxLengthHELI_Z": HapticSettings by name, +0x74 getControlBoxLengthHELI() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthHELI_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthHELI(); // +0x74 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100388D0 "getControlBoxStiffnessHELI_Z": HapticSettings by name, +0x7C getControlBoxStiffnessHELI() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessHELI_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessHELI(); // +0x7C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038950 "getControlBoxLengthSEA_Z": HapticSettings by name, +0x94 getControlBoxLengthSEA() by value, component z as a number. +void as_hapticsettings_getControlBoxLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxLengthSEA_Z"); + const Vec3 v = hapticSettings()->getControlBoxLengthSEA(); // +0x94 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_100389E0 "getControlBoxStiffnessSEA_Z": HapticSettings by name, +0x9C getControlBoxStiffnessSEA() by value, component z as a number. +void as_hapticsettings_getControlBoxStiffnessSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getControlBoxStiffnessSEA_Z"); + const Vec3 v = hapticSettings()->getControlBoxStiffnessSEA(); // +0x9C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10038A70 "getAimSensitivitySOLDIER_X": HapticSettings by name, +0xBC getAimSensitivitySOLDIER() by value, component x as a number. +void as_hapticsettings_getAimSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySOLDIER_X"); + const Vec3 v = hapticSettings()->getAimSensitivitySOLDIER(); // +0xBC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038B00 "getAimSensitivityLengthSOLDIER_X": HapticSettings by name, +0xC4 getAimSensitivityLengthSOLDIER() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSOLDIER_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSOLDIER(); // +0xC4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038B90 "getTurnSensitivitySOLDIER_X": HapticSettings by name, +0xCC getTurnSensitivitySOLDIER() by value, component x as a number. +void as_hapticsettings_getTurnSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySOLDIER_X"); + const Vec3 v = hapticSettings()->getTurnSensitivitySOLDIER(); // +0xCC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038C20 "getAimSensitivityLAND_X": HapticSettings by name, +0x104 getAimSensitivityLAND() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLAND_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLAND(); // +0x104 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038CB0 "getAimSensitivityLengthLAND_X": HapticSettings by name, +0x10C getAimSensitivityLengthLAND() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthLAND_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthLAND(); // +0x10C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038D40 "getTurnSensitivityLAND_X": HapticSettings by name, +0x114 getTurnSensitivityLAND() by value, component x as a number. +void as_hapticsettings_getTurnSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityLAND_X"); + const Vec3 v = hapticSettings()->getTurnSensitivityLAND(); // +0x114 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038DD0 "getAimSensitivityAIR_X": HapticSettings by name, +0xD4 getAimSensitivityAIR() by value, component x as a number. +void as_hapticsettings_getAimSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityAIR_X"); + const Vec3 v = hapticSettings()->getAimSensitivityAIR(); // +0xD4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038E60 "getAimSensitivityLengthAIR_X": HapticSettings by name, +0xDC getAimSensitivityLengthAIR() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthAIR_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthAIR(); // +0xDC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038EF0 "getTurnSensitivityAIR_X": HapticSettings by name, +0xE4 getTurnSensitivityAIR() by value, component x as a number. +void as_hapticsettings_getTurnSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityAIR_X"); + const Vec3 v = hapticSettings()->getTurnSensitivityAIR(); // +0xE4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10038F80 "getAimSensitivityHELI_X": HapticSettings by name, +0xEC getAimSensitivityHELI() by value, component x as a number. +void as_hapticsettings_getAimSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityHELI_X"); + const Vec3 v = hapticSettings()->getAimSensitivityHELI(); // +0xEC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10039010 "getAimSensitivityLengthHELI_X": HapticSettings by name, +0xF4 getAimSensitivityLengthHELI() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthHELI_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthHELI(); // +0xF4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_100390A0 "getTurnSensitivityHELI_X": HapticSettings by name, +0xFC getTurnSensitivityHELI() by value, component x as a number. +void as_hapticsettings_getTurnSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityHELI_X"); + const Vec3 v = hapticSettings()->getTurnSensitivityHELI(); // +0xFC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10039130 "getAimSensitivitySEA_X": HapticSettings by name, +0x11C getAimSensitivitySEA() by value, component x as a number. +void as_hapticsettings_getAimSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySEA_X"); + const Vec3 v = hapticSettings()->getAimSensitivitySEA(); // +0x11C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_100391C0 "getAimSensitivityLengthSEA_X": HapticSettings by name, +0x124 getAimSensitivityLengthSEA() by value, component x as a number. +void as_hapticsettings_getAimSensitivityLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSEA_X"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSEA(); // +0x124 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_10039250 "getTurnSensitivitySEA_X": HapticSettings by name, +0x12C getTurnSensitivitySEA() by value, component x as a number. +void as_hapticsettings_getTurnSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySEA_X"); + const Vec3 v = hapticSettings()->getTurnSensitivitySEA(); // +0x12C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_100392E0 "getAimSensitivitySOLDIER_Y": HapticSettings by name, +0xBC getAimSensitivitySOLDIER() by value, component y as a number. +void as_hapticsettings_getAimSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySOLDIER_Y"); + const Vec3 v = hapticSettings()->getAimSensitivitySOLDIER(); // +0xBC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039370 "getAimSensitivityLengthSOLDIER_Y": HapticSettings by name, +0xC4 getAimSensitivityLengthSOLDIER() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSOLDIER_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSOLDIER(); // +0xC4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039400 "getTurnSensitivitySOLDIER_Y": HapticSettings by name, +0xCC getTurnSensitivitySOLDIER() by value, component y as a number. +void as_hapticsettings_getTurnSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySOLDIER_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivitySOLDIER(); // +0xCC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039490 "getAimSensitivityLAND_Y": HapticSettings by name, +0x104 getAimSensitivityLAND() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLAND_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLAND(); // +0x104 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039520 "getAimSensitivityLengthLAND_Y": HapticSettings by name, +0x10C getAimSensitivityLengthLAND() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthLAND_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthLAND(); // +0x10C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100395B0 "getTurnSensitivityLAND_Y": HapticSettings by name, +0x114 getTurnSensitivityLAND() by value, component y as a number. +void as_hapticsettings_getTurnSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityLAND_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivityLAND(); // +0x114 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039640 "getAimSensitivityAIR_Y": HapticSettings by name, +0xD4 getAimSensitivityAIR() by value, component y as a number. +void as_hapticsettings_getAimSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityAIR_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityAIR(); // +0xD4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100396D0 "getAimSensitivityLengthAIR_Y": HapticSettings by name, +0xDC getAimSensitivityLengthAIR() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthAIR_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthAIR(); // +0xDC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039760 "getTurnSensitivityAIR_Y": HapticSettings by name, +0xE4 getTurnSensitivityAIR() by value, component y as a number. +void as_hapticsettings_getTurnSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityAIR_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivityAIR(); // +0xE4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100397F0 "getAimSensitivityHELI_Y": HapticSettings by name, +0xEC getAimSensitivityHELI() by value, component y as a number. +void as_hapticsettings_getAimSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityHELI_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityHELI(); // +0xEC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039880 "getAimSensitivityLengthHELI_Y": HapticSettings by name, +0xF4 getAimSensitivityLengthHELI() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthHELI_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthHELI(); // +0xF4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039910 "getTurnSensitivityHELI_Y": HapticSettings by name, +0xFC getTurnSensitivityHELI() by value, component y as a number. +void as_hapticsettings_getTurnSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityHELI_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivityHELI(); // +0xFC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_100399A0 "getAimSensitivitySEA_Y": HapticSettings by name, +0x11C getAimSensitivitySEA() by value, component y as a number. +void as_hapticsettings_getAimSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySEA_Y"); + const Vec3 v = hapticSettings()->getAimSensitivitySEA(); // +0x11C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039A30 "getAimSensitivityLengthSEA_Y": HapticSettings by name, +0x124 getAimSensitivityLengthSEA() by value, component y as a number. +void as_hapticsettings_getAimSensitivityLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSEA_Y"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSEA(); // +0x124 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039AC0 "getTurnSensitivitySEA_Y": HapticSettings by name, +0x12C getTurnSensitivitySEA() by value, component y as a number. +void as_hapticsettings_getTurnSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySEA_Y"); + const Vec3 v = hapticSettings()->getTurnSensitivitySEA(); // +0x12C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_10039B50 "getAimSensitivitySOLDIER_Z": HapticSettings by name, +0xBC getAimSensitivitySOLDIER() by value, component z as a number. +void as_hapticsettings_getAimSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySOLDIER_Z"); + const Vec3 v = hapticSettings()->getAimSensitivitySOLDIER(); // +0xBC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039BE0 "getAimSensitivityLengthSOLDIER_Z": HapticSettings by name, +0xC4 getAimSensitivityLengthSOLDIER() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSOLDIER_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSOLDIER(); // +0xC4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039C70 "getTurnSensitivitySOLDIER_Z": HapticSettings by name, +0xCC getTurnSensitivitySOLDIER() by value, component z as a number. +void as_hapticsettings_getTurnSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySOLDIER_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivitySOLDIER(); // +0xCC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039D00 "getAimSensitivityLAND_Z": HapticSettings by name, +0x104 getAimSensitivityLAND() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLAND_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLAND(); // +0x104 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039D90 "getAimSensitivityLengthLAND_Z": HapticSettings by name, +0x10C getAimSensitivityLengthLAND() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthLAND_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthLAND(); // +0x10C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039E20 "getTurnSensitivityLAND_Z": HapticSettings by name, +0x114 getTurnSensitivityLAND() by value, component z as a number. +void as_hapticsettings_getTurnSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityLAND_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivityLAND(); // +0x114 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039EB0 "getAimSensitivityAIR_Z": HapticSettings by name, +0xD4 getAimSensitivityAIR() by value, component z as a number. +void as_hapticsettings_getAimSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityAIR_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityAIR(); // +0xD4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039F40 "getAimSensitivityLengthAIR_Z": HapticSettings by name, +0xDC getAimSensitivityLengthAIR() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthAIR_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthAIR(); // +0xDC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_10039FD0 "getTurnSensitivityAIR_Z": HapticSettings by name, +0xE4 getTurnSensitivityAIR() by value, component z as a number. +void as_hapticsettings_getTurnSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityAIR_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivityAIR(); // +0xE4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A060 "getAimSensitivityHELI_Z": HapticSettings by name, +0xEC getAimSensitivityHELI() by value, component z as a number. +void as_hapticsettings_getAimSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityHELI_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityHELI(); // +0xEC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A0F0 "getAimSensitivityLengthHELI_Z": HapticSettings by name, +0xF4 getAimSensitivityLengthHELI() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthHELI_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthHELI(); // +0xF4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A180 "getTurnSensitivityHELI_Z": HapticSettings by name, +0xFC getTurnSensitivityHELI() by value, component z as a number. +void as_hapticsettings_getTurnSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivityHELI_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivityHELI(); // +0xFC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A210 "getAimSensitivitySEA_Z": HapticSettings by name, +0x11C getAimSensitivitySEA() by value, component z as a number. +void as_hapticsettings_getAimSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivitySEA_Z"); + const Vec3 v = hapticSettings()->getAimSensitivitySEA(); // +0x11C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A2A0 "getAimSensitivityLengthSEA_Z": HapticSettings by name, +0x124 getAimSensitivityLengthSEA() by value, component z as a number. +void as_hapticsettings_getAimSensitivityLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getAimSensitivityLengthSEA_Z"); + const Vec3 v = hapticSettings()->getAimSensitivityLengthSEA(); // +0x124 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A330 "getTurnSensitivitySEA_Z": HapticSettings by name, +0x12C getTurnSensitivitySEA() by value, component z as a number. +void as_hapticsettings_getTurnSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getTurnSensitivitySEA_Z"); + const Vec3 v = hapticSettings()->getTurnSensitivitySEA(); // +0x12C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A3C0 "getPhysicsSOLDIERScale_X": HapticSettings by name, +0x134 getPhysicsSOLDIERScale() by value, component x as a number. +void as_hapticsettings_getPhysicsSOLDIERScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERScale_X"); + const Vec3 v = hapticSettings()->getPhysicsSOLDIERScale(); // +0x134 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003A450 "getPhysicsSOLDIERScale_Y": HapticSettings by name, +0x134 getPhysicsSOLDIERScale() by value, component y as a number. +void as_hapticsettings_getPhysicsSOLDIERScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsSOLDIERScale(); // +0x134 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003A4E0 "getPhysicsSOLDIERScale_Z": HapticSettings by name, +0x134 getPhysicsSOLDIERScale() by value, component z as a number. +void as_hapticsettings_getPhysicsSOLDIERScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsSOLDIERScale(); // +0x134 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003A570 "getPhysicsSOLDIERTransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x184 getPhysicsSOLDIERTransitionValue(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERTransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERTransitionValue(level))); // +0x184 +} + +// sub_1003A670 "getPhysicsSOLDIERSmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x19C getPhysicsSOLDIERSmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERSmoothTimeX(level))); // +0x19C +} + +// sub_1003A770 "getPhysicsSOLDIERSmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x1A4 getPhysicsSOLDIERSmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERSmoothTimeY(level))); // +0x1A4 +} + +// sub_1003A870 "getPhysicsSOLDIERSmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x1AC getPhysicsSOLDIERSmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsSOLDIERSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSOLDIERSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSOLDIERSmoothTimeZ(level))); // +0x1AC +} + +// sub_1003A970 "getPhysicsLANDScale_X": HapticSettings by name, +0x1FC getPhysicsLANDScale() by value, component x as a number. +void as_hapticsettings_getPhysicsLANDScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDScale_X"); + const Vec3 v = hapticSettings()->getPhysicsLANDScale(); // +0x1FC (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003AA00 "getPhysicsLANDScale_Y": HapticSettings by name, +0x1FC getPhysicsLANDScale() by value, component y as a number. +void as_hapticsettings_getPhysicsLANDScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsLANDScale(); // +0x1FC (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003AA90 "getPhysicsLANDScale_Z": HapticSettings by name, +0x1FC getPhysicsLANDScale() by value, component z as a number. +void as_hapticsettings_getPhysicsLANDScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsLANDScale(); // +0x1FC (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003AB20 "getPhysicsLANDTransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x24C getPhysicsLANDTransitionValue(level) as a number. +void as_hapticsettings_getPhysicsLANDTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDTransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDTransitionValue(level))); // +0x24C +} + +// sub_1003AC20 "getPhysicsLANDSmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x264 getPhysicsLANDSmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsLANDSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDSmoothTimeX(level))); // +0x264 +} + +// sub_1003AD20 "getPhysicsLANDSmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x26C getPhysicsLANDSmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsLANDSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDSmoothTimeY(level))); // +0x26C +} + +// sub_1003AE20 "getPhysicsLANDSmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x274 getPhysicsLANDSmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsLANDSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsLANDSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsLANDSmoothTimeZ(level))); // +0x274 +} + +// sub_1003AF20 "getPhysicsAIRScale_X": HapticSettings by name, +0x2C4 getPhysicsAIRScale() by value, component x as a number. +void as_hapticsettings_getPhysicsAIRScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRScale_X"); + const Vec3 v = hapticSettings()->getPhysicsAIRScale(); // +0x2C4 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003AFB0 "getPhysicsAIRScale_Y": HapticSettings by name, +0x2C4 getPhysicsAIRScale() by value, component y as a number. +void as_hapticsettings_getPhysicsAIRScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsAIRScale(); // +0x2C4 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003B040 "getPhysicsAIRScale_Z": HapticSettings by name, +0x2C4 getPhysicsAIRScale() by value, component z as a number. +void as_hapticsettings_getPhysicsAIRScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsAIRScale(); // +0x2C4 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003B0D0 "getPhysicsAIRTransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x314 getPhysicsAIRTransitionValue(level) as a number. +void as_hapticsettings_getPhysicsAIRTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRTransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRTransitionValue(level))); // +0x314 +} + +// sub_1003B1D0 "getPhysicsAIRSmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x32C getPhysicsAIRSmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsAIRSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRSmoothTimeX(level))); // +0x32C +} + +// sub_1003B2D0 "getPhysicsAIRSmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x334 getPhysicsAIRSmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsAIRSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRSmoothTimeY(level))); // +0x334 +} + +// sub_1003B3D0 "getPhysicsAIRSmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x33C getPhysicsAIRSmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsAIRSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsAIRSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsAIRSmoothTimeZ(level))); // +0x33C +} + +// sub_1003B4D0 "getPhysicsHELIScale_X": HapticSettings by name, +0x38C getPhysicsHELIScale() by value, component x as a number. +void as_hapticsettings_getPhysicsHELIScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELIScale_X"); + const Vec3 v = hapticSettings()->getPhysicsHELIScale(); // +0x38C (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003B560 "getPhysicsHELIScale_Y": HapticSettings by name, +0x38C getPhysicsHELIScale() by value, component y as a number. +void as_hapticsettings_getPhysicsHELIScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELIScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsHELIScale(); // +0x38C (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003B5F0 "getPhysicsHELIScale_Z": HapticSettings by name, +0x38C getPhysicsHELIScale() by value, component z as a number. +void as_hapticsettings_getPhysicsHELIScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELIScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsHELIScale(); // +0x38C (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003B680 "getPhysicsHELITransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x3DC getPhysicsHELITransitionValue(level) as a number. +void as_hapticsettings_getPhysicsHELITransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELITransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELITransitionValue(level))); // +0x3DC +} + +// sub_1003B780 "getPhysicsHELISmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x3F4 getPhysicsHELISmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsHELISmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELISmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELISmoothTimeX(level))); // +0x3F4 +} + +// sub_1003B880 "getPhysicsHELISmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x3FC getPhysicsHELISmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsHELISmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELISmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELISmoothTimeY(level))); // +0x3FC +} + +// sub_1003B980 "getPhysicsHELISmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x404 getPhysicsHELISmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsHELISmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsHELISmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsHELISmoothTimeZ(level))); // +0x404 +} + +// sub_1003BA80 "getPhysicsSEAScale_X": HapticSettings by name, +0x454 getPhysicsSEAScale() by value, component x as a number. +void as_hapticsettings_getPhysicsSEAScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEAScale_X"); + const Vec3 v = hapticSettings()->getPhysicsSEAScale(); // +0x454 (sret) + fn.result->set_double(static_cast(v.x)); +} + +// sub_1003BB10 "getPhysicsSEAScale_Y": HapticSettings by name, +0x454 getPhysicsSEAScale() by value, component y as a number. +void as_hapticsettings_getPhysicsSEAScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEAScale_Y"); + const Vec3 v = hapticSettings()->getPhysicsSEAScale(); // +0x454 (sret) + fn.result->set_double(static_cast(v.y)); +} + +// sub_1003BBA0 "getPhysicsSEAScale_Z": HapticSettings by name, +0x454 getPhysicsSEAScale() by value, component z as a number. +void as_hapticsettings_getPhysicsSEAScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEAScale_Z"); + const Vec3 v = hapticSettings()->getPhysicsSEAScale(); // +0x454 (sret) + fn.result->set_double(static_cast(v.z)); +} + +// sub_1003BC30 "getPhysicsSEATransition": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4A4 getPhysicsSEATransitionValue(level) as a number. +void as_hapticsettings_getPhysicsSEATransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEATransition"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEATransitionValue(level))); // +0x4A4 +} + +// sub_1003BD30 "getPhysicsSEASmoothTime_X": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4BC getPhysicsSEASmoothTimeX(level) as a number. +void as_hapticsettings_getPhysicsSEASmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEASmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEASmoothTimeX(level))); // +0x4BC +} + +// sub_1003BE30 "getPhysicsSEASmoothTime_Y": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4C4 getPhysicsSEASmoothTimeY(level) as a number. +void as_hapticsettings_getPhysicsSEASmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEASmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEASmoothTimeY(level))); // +0x4C4 +} + +// sub_1003BF30 "getPhysicsSEASmoothTime_Z": arg 0 to_string looked up in the threshold names (unk_100F3870), HapticSettings by name, +0x4CC getPhysicsSEASmoothTimeZ(level) as a number. +void as_hapticsettings_getPhysicsSEASmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getPhysicsSEASmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getPhysicsSEASmoothTimeZ(level))); // +0x4CC +} + +// sub_1003C030 "getDamageScale": HapticSettings by name, +0x51C as a number. +void as_hapticsettings_getDamageScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getDamageScale"); + fn.result->set_double(static_cast(hapticSettings()->getDamageScale())); // +0x51C +} + +// sub_1003C0B0 "getRecoilPunchScale": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x524 getRecoilPunchScale(class) as a number. +void as_hapticsettings_getRecoilPunchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilPunchScale"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilPunchScale(weaponClass))); // +0x524 +} + +// sub_1003C200 "getRecoilPunchTime": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x52C getRecoilPunchTime(class) as a number. +void as_hapticsettings_getRecoilPunchTime(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilPunchTime"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilPunchTime(weaponClass))); // +0x52C +} + +// sub_1003C350 "getRecoilYawScale": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x534 getRecoilYawScale(class) as a number. +void as_hapticsettings_getRecoilYawScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilYawScale"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilYawScale(weaponClass))); // +0x534 +} + +// sub_1003C4A0 "getRecoilPitchScale": arg 0 to_string mapped to a weapon class (the page selects the infantry or the vehicle names), HapticSettings by name, +0x53C getRecoilPitchScale(class) as a number. +void as_hapticsettings_getRecoilPitchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getRecoilPitchScale"); + const std::string key(fn.arg(0).to_string()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + fn.result->set_double(static_cast(hs->getRecoilPitchScale(weaponClass))); // +0x53C +} + +// sub_10043820 "setPhysicsSOLDIERScale_X": arg 0 as a float, three HapticSettings lookups, +0x134 twice, +0x138(value, second.y, first.z). +void as_hapticsettings_setPhysicsSOLDIERScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSOLDIERScale(); + const Vec3 second = b->getPhysicsSOLDIERScale(); + c->setPhysicsSOLDIERScale(value, second.y, first.z); // +0x138 +} + +// sub_10043900 "setPhysicsSOLDIERScale_Y": arg 0 as a float, three HapticSettings lookups, +0x134 twice, +0x138(second.x, value, first.z). +void as_hapticsettings_setPhysicsSOLDIERScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSOLDIERScale(); + const Vec3 second = b->getPhysicsSOLDIERScale(); + c->setPhysicsSOLDIERScale(second.x, value, first.z); // +0x138 +} + +// sub_100439E0 "setPhysicsSOLDIERScale_Z": arg 0 as a float, three HapticSettings lookups, +0x134 twice, +0x138(second.x, first.y, value). +void as_hapticsettings_setPhysicsSOLDIERScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSOLDIERScale(); + const Vec3 second = b->getPhysicsSOLDIERScale(); + c->setPhysicsSOLDIERScale(second.x, first.y, value); // +0x138 +} + +// sub_10035380 "setPhysicsSOLDIERTransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x188 setPhysicsSOLDIERTransitionValue(level, value). +void as_hapticsettings_setPhysicsSOLDIERTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERTransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERTransitionValue(level, value); // +0x188 +} + +// sub_10035460 "setPhysicsSOLDIERSmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x1A0 setPhysicsSOLDIERSmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsSOLDIERSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERSmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x1A0 +} + +// sub_10035550 "setPhysicsSOLDIERSmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x1A8 setPhysicsSOLDIERSmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsSOLDIERSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERSmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x1A8 +} + +// sub_10035640 "setPhysicsSOLDIERSmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x1B0 setPhysicsSOLDIERSmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsSOLDIERSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSOLDIERSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSOLDIERSmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x1B0 +} + +// sub_10043AC0 "setPhysicsLANDScale_X": arg 0 as a float, three HapticSettings lookups, +0x1FC twice, +0x200(value, second.y, first.z). +void as_hapticsettings_setPhysicsLANDScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsLANDScale(); + const Vec3 second = b->getPhysicsLANDScale(); + c->setPhysicsLANDScale(value, second.y, first.z); // +0x200 +} + +// sub_10043BA0 "setPhysicsLANDScale_Y": arg 0 as a float, three HapticSettings lookups, +0x1FC twice, +0x200(second.x, value, first.z). +void as_hapticsettings_setPhysicsLANDScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsLANDScale(); + const Vec3 second = b->getPhysicsLANDScale(); + c->setPhysicsLANDScale(second.x, value, first.z); // +0x200 +} + +// sub_10043C80 "setPhysicsLANDScale_Z": arg 0 as a float, three HapticSettings lookups, +0x1FC twice, +0x200(second.x, first.y, value). +void as_hapticsettings_setPhysicsLANDScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsLANDScale(); + const Vec3 second = b->getPhysicsLANDScale(); + c->setPhysicsLANDScale(second.x, first.y, value); // +0x200 +} + +// sub_10035730 "setPhysicsLANDTransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x250 setPhysicsLANDTransitionValue(level, value). +void as_hapticsettings_setPhysicsLANDTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDTransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDTransitionValue(level, value); // +0x250 +} + +// sub_10035810 "setPhysicsLANDSmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x268 setPhysicsLANDSmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsLANDSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDSmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x268 +} + +// sub_10035900 "setPhysicsLANDSmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x270 setPhysicsLANDSmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsLANDSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDSmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x270 +} + +// sub_100359F0 "setPhysicsLANDSmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x278 setPhysicsLANDSmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsLANDSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsLANDSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsLANDSmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x278 +} + +// sub_10043D60 "setPhysicsAIRScale_X": arg 0 as a float, three HapticSettings lookups, +0x2C4 twice, +0x2C8(value, second.y, first.z). +void as_hapticsettings_setPhysicsAIRScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsAIRScale(); + const Vec3 second = b->getPhysicsAIRScale(); + c->setPhysicsAIRScale(value, second.y, first.z); // +0x2C8 +} + +// sub_10043E40 "setPhysicsAIRScale_Y": arg 0 as a float, three HapticSettings lookups, +0x2C4 twice, +0x2C8(second.x, value, first.z). +void as_hapticsettings_setPhysicsAIRScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsAIRScale(); + const Vec3 second = b->getPhysicsAIRScale(); + c->setPhysicsAIRScale(second.x, value, first.z); // +0x2C8 +} + +// sub_10043F20 "setPhysicsAIRScale_Z": arg 0 as a float, three HapticSettings lookups, +0x2C4 twice, +0x2C8(second.x, first.y, value). +void as_hapticsettings_setPhysicsAIRScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsAIRScale(); + const Vec3 second = b->getPhysicsAIRScale(); + c->setPhysicsAIRScale(second.x, first.y, value); // +0x2C8 +} + +// sub_10035AE0 "setPhysicsAIRTransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x318 setPhysicsAIRTransitionValue(level, value). +void as_hapticsettings_setPhysicsAIRTransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRTransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRTransitionValue(level, value); // +0x318 +} + +// sub_10035BC0 "setPhysicsAIRSmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x330 setPhysicsAIRSmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsAIRSmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRSmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRSmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x330 +} + +// sub_10035CB0 "setPhysicsAIRSmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x338 setPhysicsAIRSmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsAIRSmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRSmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRSmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x338 +} + +// sub_10035DA0 "setPhysicsAIRSmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x340 setPhysicsAIRSmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsAIRSmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsAIRSmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsAIRSmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x340 +} + +// sub_10044000 "setPhysicsHELIScale_X": arg 0 as a float, three HapticSettings lookups, +0x38C twice, +0x390(value, second.y, first.z). +void as_hapticsettings_setPhysicsHELIScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELIScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsHELIScale(); + const Vec3 second = b->getPhysicsHELIScale(); + c->setPhysicsHELIScale(value, second.y, first.z); // +0x390 +} + +// sub_100440E0 "setPhysicsHELIScale_Y": arg 0 as a float, three HapticSettings lookups, +0x38C twice, +0x390(second.x, value, first.z). +void as_hapticsettings_setPhysicsHELIScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELIScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsHELIScale(); + const Vec3 second = b->getPhysicsHELIScale(); + c->setPhysicsHELIScale(second.x, value, first.z); // +0x390 +} + +// sub_100441C0 "setPhysicsHELIScale_Z": arg 0 as a float, three HapticSettings lookups, +0x38C twice, +0x390(second.x, first.y, value). +void as_hapticsettings_setPhysicsHELIScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELIScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsHELIScale(); + const Vec3 second = b->getPhysicsHELIScale(); + c->setPhysicsHELIScale(second.x, first.y, value); // +0x390 +} + +// sub_10035E90 "setPhysicsHELITransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x3E0 setPhysicsHELITransitionValue(level, value). +void as_hapticsettings_setPhysicsHELITransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELITransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELITransitionValue(level, value); // +0x3E0 +} + +// sub_10035F70 "setPhysicsHELISmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x3F8 setPhysicsHELISmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsHELISmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELISmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELISmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x3F8 +} + +// sub_10036060 "setPhysicsHELISmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x400 setPhysicsHELISmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsHELISmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELISmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELISmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x400 +} + +// sub_10036150 "setPhysicsHELISmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x408 setPhysicsHELISmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsHELISmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsHELISmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsHELISmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x408 +} + +// sub_100442A0 "setPhysicsSEAScale_X": arg 0 as a float, three HapticSettings lookups, +0x454 twice, +0x458(value, second.y, first.z). +void as_hapticsettings_setPhysicsSEAScale_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEAScale_X"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSEAScale(); + const Vec3 second = b->getPhysicsSEAScale(); + c->setPhysicsSEAScale(value, second.y, first.z); // +0x458 +} + +// sub_10044380 "setPhysicsSEAScale_Y": arg 0 as a float, three HapticSettings lookups, +0x454 twice, +0x458(second.x, value, first.z). +void as_hapticsettings_setPhysicsSEAScale_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEAScale_Y"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSEAScale(); + const Vec3 second = b->getPhysicsSEAScale(); + c->setPhysicsSEAScale(second.x, value, first.z); // +0x458 +} + +// sub_10044460 "setPhysicsSEAScale_Z": arg 0 as a float, three HapticSettings lookups, +0x454 twice, +0x458(second.x, first.y, value). +void as_hapticsettings_setPhysicsSEAScale_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEAScale_Z"); + const float value = static_cast(fn.arg(0).to_number()); + IHapticSettings* a = hapticSettings(); + IHapticSettings* b = hapticSettings(); + IHapticSettings* c = hapticSettings(); + const Vec3 first = a->getPhysicsSEAScale(); + const Vec3 second = b->getPhysicsSEAScale(); + c->setPhysicsSEAScale(second.x, first.y, value); // +0x458 +} + +// sub_10036240 "setPhysicsSEATransition": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4A8 setPhysicsSEATransitionValue(level, value). +void as_hapticsettings_setPhysicsSEATransition(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEATransition"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEATransitionValue(level, value); // +0x4A8 +} + +// sub_10036320 "setPhysicsSEASmoothTime_X": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4C0 setPhysicsSEASmoothTimeX(level, (int) value). +void as_hapticsettings_setPhysicsSEASmoothTime_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEASmoothTime_X"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEASmoothTimeX(level, bf2x87::toIntTruncate(static_cast(value))); // +0x4C0 +} + +// sub_10036410 "setPhysicsSEASmoothTime_Y": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4C8 setPhysicsSEASmoothTimeY(level, (int) value). +void as_hapticsettings_setPhysicsSEASmoothTime_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEASmoothTime_Y"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEASmoothTimeY(level, bf2x87::toIntTruncate(static_cast(value))); // +0x4C8 +} + +// sub_10036500 "setPhysicsSEASmoothTime_Z": arg 0 to_string, arg 1 as a float, the threshold level (3-entry loop), HapticSettings by name, +0x4D0 setPhysicsSEASmoothTimeZ(level, (int) value). +void as_hapticsettings_setPhysicsSEASmoothTime_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setPhysicsSEASmoothTime_Z"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int level = hapticThresholdLevel(key); + IHapticSettings* hs = hapticSettings(); + hs->setPhysicsSEASmoothTimeZ(level, bf2x87::toIntTruncate(static_cast(value))); // +0x4D0 +} + +// sub_100365F0 "setDamageScale": arg 0 as a float, then HapticSettings by name, +0x520. +void as_hapticsettings_setDamageScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setDamageScale"); + const float value = static_cast(fn.arg(0).to_number()); + hapticSettings()->setDamageScale(value); // +0x520 +} + +// sub_10036660 "setRecoilPunchScale": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x528 setRecoilPunchScale(class, value). +void as_hapticsettings_setRecoilPunchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilPunchScale"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilPunchScale(weaponClass, value); // +0x528 +} + +// sub_10036790 "setRecoilPunchTime": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x530 setRecoilPunchTime(class, value). +void as_hapticsettings_setRecoilPunchTime(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilPunchTime"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilPunchTime(weaponClass, value); // +0x530 +} + +// sub_100368C0 "setRecoilYawScale": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x538 setRecoilYawScale(class, value). +void as_hapticsettings_setRecoilYawScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilYawScale"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilYawScale(weaponClass, value); // +0x538 +} + +// sub_100369F0 "setRecoilPitchScale": arg 0 to_string, arg 1 as a float, the weapon class, HapticSettings by name, +0x540 setRecoilPitchScale(class, value). +void as_hapticsettings_setRecoilPitchScale(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setRecoilPitchScale"); + const std::string key(fn.arg(0).to_string()); + const float value = static_cast(fn.arg(1).to_number()); + const int weaponClass = hapticWeaponClass(key); + IHapticSettings* hs = hapticSettings(); + hs->setRecoilPitchScale(weaponClass, value); // +0x540 +} + +// sub_10036B20 "setHapticSettingsPage": (int) arg 0 into dword_100F8530. +void as_hapticsettings_setHapticSettingsPage(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setHapticSettingsPage"); + s_hapticSettingsPage = bf2x87::toIntTruncate(fn.arg(0).to_number()); +} + +// sub_10044540 "getHapticSettingsPage": dword_100F8530 as a number. +void as_hapticsettings_getHapticSettingsPage(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getHapticSettingsPage"); + fn.result->set_double(static_cast(s_hapticSettingsPage)); +} + +// sub_1003C5F0 "setControlBoxLengthSOLDIER_X": vector setter, component x: +0x54 getControlBoxLengthSOLDIER / +0x58 setControlBoxLengthSOLDIER; mirror +0x54 getControlBoxLengthSOLDIER / +0x48 setControlBoxLength (on foot or no local player). +void as_hapticsettings_setControlBoxLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLengthSOLDIER, 0, kHapticSoldier, + &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLength); +} + +// sub_1003C7D0 "setControlBoxStiffnessSOLDIER_X": vector setter, component x: +0x5C getControlBoxStiffnessSOLDIER / +0x60 setControlBoxStiffnessSOLDIER; mirror +0x5C getControlBoxStiffnessSOLDIER / +0x50 setControlBoxStiffness (on foot or no local player). +void as_hapticsettings_setControlBoxStiffnessSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffnessSOLDIER, 0, kHapticSoldier, + &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D130 "setControlBoxLengthLAND_X": vector setter, component x: +0x84 getControlBoxLengthLAND / +0x88 setControlBoxLengthLAND; mirror +0x84 getControlBoxLengthLAND / +0x48 setControlBoxLength (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLengthLAND, 0, kHapticLand, + &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLength); +} + +// sub_1003D2A0 "setControlBoxStiffnessLAND_X": vector setter, component x: +0x8C getControlBoxStiffnessLAND / +0x90 setControlBoxStiffnessLAND; mirror +0x8C getControlBoxStiffnessLAND / +0x50 setControlBoxStiffness (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxStiffnessLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffnessLAND, 0, kHapticLand, + &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D9D0 "setControlBoxLengthAIR_X": vector setter, component x: +0x64 getControlBoxLengthAIR / +0x68 setControlBoxLengthAIR; mirror +0x64 getControlBoxLengthAIR / +0x48 setControlBoxLength (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLengthAIR, 0, kHapticAir, + &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLength); +} + +// sub_1003DB30 "setControlBoxStiffnessAIR_X": vector setter, component x: +0x6C getControlBoxStiffnessAIR / +0x70 setControlBoxStiffnessAIR; mirror +0x6C getControlBoxStiffnessAIR / +0x50 setControlBoxStiffness (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxStiffnessAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffnessAIR, 0, kHapticAir, + &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003E210 "setControlBoxLengthHELI_X": vector setter, component x: +0x74 getControlBoxLengthHELI / +0x78 setControlBoxLengthHELI; mirror +0x74 getControlBoxLengthHELI / +0x48 setControlBoxLength (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLengthHELI, 0, kHapticHeli, + &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E370 "setControlBoxStiffnessHELI_X": vector setter, component x: +0x7C getControlBoxStiffnessHELI / +0x80 setControlBoxStiffnessHELI; mirror +0x7C getControlBoxStiffnessHELI / +0x50 setControlBoxStiffness (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxStiffnessHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffnessHELI, 0, kHapticHeli, + &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003EA50 "setControlBoxLengthSEA_X": vector setter, component x: +0x94 getControlBoxLengthSEA / +0x98 setControlBoxLengthSEA; mirror +0x94 getControlBoxLengthSEA / +0x48 setControlBoxLength (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLengthSEA, 0, kHapticSea, + &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLength); +} + +// sub_1003EBC0 "setControlBoxStiffnessSEA_X": vector setter, component x: +0x9C getControlBoxStiffnessSEA / +0xA0 setControlBoxStiffnessSEA; mirror +0x9C getControlBoxStiffnessSEA / +0x50 setControlBoxStiffness (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxStiffnessSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffnessSEA, 0, kHapticSea, + &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003C9B0 "setControlBoxLengthSOLDIER_Y": vector setter, component y: +0x54 getControlBoxLengthSOLDIER / +0x58 setControlBoxLengthSOLDIER; mirror +0x54 getControlBoxLengthSOLDIER / +0x48 setControlBoxLength (on foot or no local player). +void as_hapticsettings_setControlBoxLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLengthSOLDIER, 1, kHapticSoldier, + &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLength); +} + +// sub_1003CB90 "setControlBoxStiffnessSOLDIER_Y": vector setter, component y: +0x5C getControlBoxStiffnessSOLDIER / +0x60 setControlBoxStiffnessSOLDIER; mirror +0x5C getControlBoxStiffnessSOLDIER / +0x50 setControlBoxStiffness (on foot or no local player). +void as_hapticsettings_setControlBoxStiffnessSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffnessSOLDIER, 1, kHapticSoldier, + &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D410 "setControlBoxLengthLAND_Y": vector setter, component y: +0x84 getControlBoxLengthLAND / +0x88 setControlBoxLengthLAND; mirror +0x84 getControlBoxLengthLAND / +0x48 setControlBoxLength (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLengthLAND, 1, kHapticLand, + &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLength); +} + +// sub_1003D580 "setControlBoxStiffnessLAND_Y": vector setter, component y: +0x8C getControlBoxStiffnessLAND / +0x90 setControlBoxStiffnessLAND; mirror +0x8C getControlBoxStiffnessLAND / +0x50 setControlBoxStiffness (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxStiffnessLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffnessLAND, 1, kHapticLand, + &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003DC90 "setControlBoxLengthAIR_Y": vector setter, component y: +0x64 getControlBoxLengthAIR / +0x68 setControlBoxLengthAIR; mirror +0x64 getControlBoxLengthAIR / +0x48 setControlBoxLength (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLengthAIR, 1, kHapticAir, + &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLength); +} + +// sub_1003DDF0 "setControlBoxStiffnessAIR_Y": vector setter, component y: +0x6C getControlBoxStiffnessAIR / +0x70 setControlBoxStiffnessAIR; mirror +0x6C getControlBoxStiffnessAIR / +0x50 setControlBoxStiffness (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxStiffnessAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffnessAIR, 1, kHapticAir, + &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003E4D0 "setControlBoxLengthHELI_Y": vector setter, component y: +0x74 getControlBoxLengthHELI / +0x78 setControlBoxLengthHELI; mirror +0x74 getControlBoxLengthHELI / +0x48 setControlBoxLength (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLengthHELI, 1, kHapticHeli, + &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E630 "setControlBoxStiffnessHELI_Y": vector setter, component y: +0x7C getControlBoxStiffnessHELI / +0x80 setControlBoxStiffnessHELI; mirror +0x7C getControlBoxStiffnessHELI / +0x50 setControlBoxStiffness (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxStiffnessHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffnessHELI, 1, kHapticHeli, + &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003ED30 "setControlBoxLengthSEA_Y": vector setter, component y: +0x94 getControlBoxLengthSEA / +0x98 setControlBoxLengthSEA; mirror +0x94 getControlBoxLengthSEA / +0x48 setControlBoxLength (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLengthSEA, 1, kHapticSea, + &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLength); +} + +// sub_1003EEA0 "setControlBoxStiffnessSEA_Y": vector setter, component y: +0x9C getControlBoxStiffnessSEA / +0xA0 setControlBoxStiffnessSEA; mirror +0x9C getControlBoxStiffnessSEA / +0x50 setControlBoxStiffness (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxStiffnessSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffnessSEA, 1, kHapticSea, + &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003CD70 "setControlBoxLengthSOLDIER_Z": vector setter, component z: +0x54 getControlBoxLengthSOLDIER / +0x58 setControlBoxLengthSOLDIER; mirror +0x54 getControlBoxLengthSOLDIER / +0x48 setControlBoxLength (on foot or no local player). +void as_hapticsettings_setControlBoxLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLengthSOLDIER, 2, kHapticSoldier, + &IHapticSettings::getControlBoxLengthSOLDIER, &IHapticSettings::setControlBoxLength); +} + +// sub_1003CF50 "setControlBoxStiffnessSOLDIER_Z": vector setter, component z: +0x5C getControlBoxStiffnessSOLDIER / +0x60 setControlBoxStiffnessSOLDIER; mirror +0x5C getControlBoxStiffnessSOLDIER / +0x50 setControlBoxStiffness (on foot or no local player). +void as_hapticsettings_setControlBoxStiffnessSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffnessSOLDIER, 2, kHapticSoldier, + &IHapticSettings::getControlBoxStiffnessSOLDIER, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003D6F0 "setControlBoxLengthLAND_Z": vector setter, component z: +0x84 getControlBoxLengthLAND / +0x88 setControlBoxLengthLAND; mirror +0x84 getControlBoxLengthLAND / +0x48 setControlBoxLength (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLengthLAND, 2, kHapticLand, + &IHapticSettings::getControlBoxLengthLAND, &IHapticSettings::setControlBoxLength); +} + +// sub_1003D860 "setControlBoxStiffnessLAND_Z": vector setter, component z: +0x8C getControlBoxStiffnessLAND / +0x90 setControlBoxStiffnessLAND; mirror +0x8C getControlBoxStiffnessLAND / +0x50 setControlBoxStiffness (vehicle category kHapticLand). +void as_hapticsettings_setControlBoxStiffnessLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffnessLAND, 2, kHapticLand, + &IHapticSettings::getControlBoxStiffnessLAND, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003DF50 "setControlBoxLengthAIR_Z": vector setter, component z: +0x64 getControlBoxLengthAIR / +0x68 setControlBoxLengthAIR; mirror +0x64 getControlBoxLengthAIR / +0x48 setControlBoxLength (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLengthAIR, 2, kHapticAir, + &IHapticSettings::getControlBoxLengthAIR, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E0B0 "setControlBoxStiffnessAIR_Z": vector setter, component z: +0x6C getControlBoxStiffnessAIR / +0x70 setControlBoxStiffnessAIR; mirror +0x6C getControlBoxStiffnessAIR / +0x50 setControlBoxStiffness (vehicle category kHapticAir). +void as_hapticsettings_setControlBoxStiffnessAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffnessAIR, 2, kHapticAir, + &IHapticSettings::getControlBoxStiffnessAIR, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003E790 "setControlBoxLengthHELI_Z": vector setter, component z: +0x74 getControlBoxLengthHELI / +0x78 setControlBoxLengthHELI; mirror +0x74 getControlBoxLengthHELI / +0x48 setControlBoxLength (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLengthHELI, 2, kHapticHeli, + &IHapticSettings::getControlBoxLengthHELI, &IHapticSettings::setControlBoxLength); +} + +// sub_1003E8F0 "setControlBoxStiffnessHELI_Z": vector setter, component z: +0x7C getControlBoxStiffnessHELI / +0x80 setControlBoxStiffnessHELI; mirror +0x7C getControlBoxStiffnessHELI / +0x50 setControlBoxStiffness (vehicle category kHapticHeli). +void as_hapticsettings_setControlBoxStiffnessHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffnessHELI, 2, kHapticHeli, + &IHapticSettings::getControlBoxStiffnessHELI, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003F010 "setControlBoxLengthSEA_Z": vector setter, component z: +0x94 getControlBoxLengthSEA / +0x98 setControlBoxLengthSEA; mirror +0x94 getControlBoxLengthSEA / +0x48 setControlBoxLength (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxLengthSEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLengthSEA, 2, kHapticSea, + &IHapticSettings::getControlBoxLengthSEA, &IHapticSettings::setControlBoxLength); +} + +// sub_1003F180 "setControlBoxStiffnessSEA_Z": vector setter, component z: +0x9C getControlBoxStiffnessSEA / +0xA0 setControlBoxStiffnessSEA; mirror +0x9C getControlBoxStiffnessSEA / +0x50 setControlBoxStiffness (vehicle category kHapticSea). +void as_hapticsettings_setControlBoxStiffnessSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setControlBoxStiffnessSEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffnessSEA, 2, kHapticSea, + &IHapticSettings::getControlBoxStiffnessSEA, &IHapticSettings::setControlBoxStiffness); +} + +// sub_1003F2F0 "setAimSensitivitySOLDIER_X": vector setter, component x: +0xBC getAimSensitivitySOLDIER / +0xC0 setAimSensitivitySOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xA8 setAimSensitivity (on foot or no local player). +void as_hapticsettings_setAimSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivitySOLDIER, 0, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivity); +} + +// sub_1003F4E0 "setAimSensitivityLengthSOLDIER_X": vector setter, component x: +0xC4 getAimSensitivityLengthSOLDIER / +0xC8 setAimSensitivityLengthSOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xB0 setAimSensitivityLength (on foot or no local player). The mirror reads the other two components through +0xBC getAimSensitivitySOLDIER, not +0xC4 (retail; the Y and Z rows use +0xC4). +void as_hapticsettings_setAimSensitivityLengthSOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLengthSOLDIER, 0, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivityLength); +} + +// sub_1003F6D0 "setTurnSensitivitySOLDIER_X": vector setter, component x: +0xCC getTurnSensitivitySOLDIER / +0xD0 setTurnSensitivitySOLDIER; mirror +0xCC getTurnSensitivitySOLDIER / +0xB8 setTurnSensitivity (on foot or no local player). +void as_hapticsettings_setTurnSensitivitySOLDIER_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySOLDIER_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivitySOLDIER, 0, kHapticSoldier, + &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivity); +} + +// sub_10040460 "setAimSensitivityLAND_X": vector setter, component x: +0x104 getAimSensitivityLAND / +0x108 setAimSensitivityLAND; mirror +0x104 getAimSensitivityLAND / +0xA8 setAimSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivityLAND, 0, kHapticLand, + &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivity); +} + +// sub_100405D0 "setAimSensitivityLengthLAND_X": vector setter, component x: +0x10C getAimSensitivityLengthLAND / +0x110 setAimSensitivityLengthLAND; mirror +0x10C getAimSensitivityLengthLAND / +0xB0 setAimSensitivityLength (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLengthLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLengthLAND, 0, kHapticLand, + &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040740 "setTurnSensitivityLAND_X": vector setter, component x: +0x114 getTurnSensitivityLAND / +0x118 setTurnSensitivityLAND; mirror +0x114 getTurnSensitivityLAND / +0xB8 setTurnSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setTurnSensitivityLAND_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityLAND_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivityLAND, 0, kHapticLand, + &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivity); +} + +// sub_10041150 "setAimSensitivityAIR_X": vector setter, component x: +0xD4 getAimSensitivityAIR / +0xD8 setAimSensitivityAIR; mirror +0xD4 getAimSensitivityAIR / +0xA8 setAimSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivityAIR, 0, kHapticAir, + &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivity); +} + +// sub_100412C0 "setAimSensitivityLengthAIR_X": vector setter, component x: +0xDC getAimSensitivityLengthAIR / +0xE0 setAimSensitivityLengthAIR; mirror +0xDC getAimSensitivityLengthAIR / +0xB0 setAimSensitivityLength (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityLengthAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLengthAIR, 0, kHapticAir, + &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10041430 "setTurnSensitivityAIR_X": vector setter, component x: +0xE4 getTurnSensitivityAIR / +0xE8 setTurnSensitivityAIR; mirror +0xE4 getTurnSensitivityAIR / +0xB8 setTurnSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setTurnSensitivityAIR_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityAIR_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivityAIR, 0, kHapticAir, + &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivity); +} + +// sub_10041E40 "setAimSensitivityHELI_X": vector setter, component x: +0xEC getAimSensitivityHELI / +0xF0 setAimSensitivityHELI; mirror +0xEC getAimSensitivityHELI / +0xA8 setAimSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivityHELI, 0, kHapticHeli, + &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivity); +} + +// sub_10041FB0 "setAimSensitivityLengthHELI_X": vector setter, component x: +0xF4 getAimSensitivityLengthHELI / +0xF8 setAimSensitivityLengthHELI; mirror +0xF4 getAimSensitivityLengthHELI / +0xB0 setAimSensitivityLength (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityLengthHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLengthHELI, 0, kHapticHeli, + &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10042120 "setTurnSensitivityHELI_X": vector setter, component x: +0xFC getTurnSensitivityHELI / +0x100 setTurnSensitivityHELI; mirror +0xFC getTurnSensitivityHELI / +0xB8 setTurnSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setTurnSensitivityHELI_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityHELI_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivityHELI, 0, kHapticHeli, + &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivity); +} + +// sub_10042B30 "setAimSensitivitySEA_X": vector setter, component x: +0x11C getAimSensitivitySEA / +0x120 setAimSensitivitySEA; mirror +0x11C getAimSensitivitySEA / +0xA8 setAimSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivitySEA, 0, kHapticSea, + &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivity); +} + +// sub_10042CA0 "setAimSensitivityLengthSEA_X": vector setter, component x: +0x124 getAimSensitivityLengthSEA / +0x128 setAimSensitivityLengthSEA; mirror +0x124 getAimSensitivityLengthSEA / +0xB0 setAimSensitivityLength (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivityLengthSEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLengthSEA, 0, kHapticSea, + &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10042E10 "setTurnSensitivitySEA_X": vector setter, component x: +0x12C getTurnSensitivitySEA / +0x130 setTurnSensitivitySEA; mirror +0x12C getTurnSensitivitySEA / +0xB8 setTurnSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setTurnSensitivitySEA_X(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySEA_X"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivitySEA, 0, kHapticSea, + &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivity); +} + +// sub_1003F8C0 "setAimSensitivitySOLDIER_Y": vector setter, component y: +0xBC getAimSensitivitySOLDIER / +0xC0 setAimSensitivitySOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xA8 setAimSensitivity (on foot or no local player). +void as_hapticsettings_setAimSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivitySOLDIER, 1, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivity); +} + +// sub_1003FAB0 "setAimSensitivityLengthSOLDIER_Y": vector setter, component y: +0xC4 getAimSensitivityLengthSOLDIER / +0xC8 setAimSensitivityLengthSOLDIER; mirror +0xC4 getAimSensitivityLengthSOLDIER / +0xB0 setAimSensitivityLength (on foot or no local player). +void as_hapticsettings_setAimSensitivityLengthSOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLengthSOLDIER, 1, kHapticSoldier, + &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLength); +} + +// sub_1003FCA0 "setTurnSensitivitySOLDIER_Y": vector setter, component y: +0xCC getTurnSensitivitySOLDIER / +0xD0 setTurnSensitivitySOLDIER; mirror +0xCC getTurnSensitivitySOLDIER / +0xB8 setTurnSensitivity (on foot or no local player). +void as_hapticsettings_setTurnSensitivitySOLDIER_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySOLDIER_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivitySOLDIER, 1, kHapticSoldier, + &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivity); +} + +// sub_100408B0 "setAimSensitivityLAND_Y": vector setter, component y: +0x104 getAimSensitivityLAND / +0x108 setAimSensitivityLAND; mirror +0x104 getAimSensitivityLAND / +0xA8 setAimSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivityLAND, 1, kHapticLand, + &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivity); +} + +// sub_10040A20 "setAimSensitivityLengthLAND_Y": vector setter, component y: +0x10C getAimSensitivityLengthLAND / +0x110 setAimSensitivityLengthLAND; mirror +0x10C getAimSensitivityLengthLAND / +0xB0 setAimSensitivityLength (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLengthLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLengthLAND, 1, kHapticLand, + &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040B90 "setTurnSensitivityLAND_Y": vector setter, component y: +0x114 getTurnSensitivityLAND / +0x118 setTurnSensitivityLAND; mirror +0x114 getTurnSensitivityLAND / +0xB8 setTurnSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setTurnSensitivityLAND_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityLAND_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivityLAND, 1, kHapticLand, + &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivity); +} + +// sub_100415A0 "setAimSensitivityAIR_Y": vector setter, component y: +0xD4 getAimSensitivityAIR / +0xD8 setAimSensitivityAIR; mirror +0xD4 getAimSensitivityAIR / +0xA8 setAimSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivityAIR, 1, kHapticAir, + &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivity); +} + +// sub_10041710 "setAimSensitivityLengthAIR_Y": vector setter, component y: +0xDC getAimSensitivityLengthAIR / +0xE0 setAimSensitivityLengthAIR; mirror +0xDC getAimSensitivityLengthAIR / +0xB0 setAimSensitivityLength (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityLengthAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLengthAIR, 1, kHapticAir, + &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10041880 "setTurnSensitivityAIR_Y": vector setter, component y: +0xE4 getTurnSensitivityAIR / +0xE8 setTurnSensitivityAIR; mirror +0xE4 getTurnSensitivityAIR / +0xB8 setTurnSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setTurnSensitivityAIR_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityAIR_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivityAIR, 1, kHapticAir, + &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivity); +} + +// sub_10042290 "setAimSensitivityHELI_Y": vector setter, component y: +0xEC getAimSensitivityHELI / +0xF0 setAimSensitivityHELI; mirror +0xEC getAimSensitivityHELI / +0xA8 setAimSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivityHELI, 1, kHapticHeli, + &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivity); +} + +// sub_10042400 "setAimSensitivityLengthHELI_Y": vector setter, component y: +0xF4 getAimSensitivityLengthHELI / +0xF8 setAimSensitivityLengthHELI; mirror +0xF4 getAimSensitivityLengthHELI / +0xB0 setAimSensitivityLength (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityLengthHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLengthHELI, 1, kHapticHeli, + &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10042570 "setTurnSensitivityHELI_Y": vector setter, component y: +0xFC getTurnSensitivityHELI / +0x100 setTurnSensitivityHELI; mirror +0xFC getTurnSensitivityHELI / +0xB8 setTurnSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setTurnSensitivityHELI_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityHELI_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivityHELI, 1, kHapticHeli, + &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivity); +} + +// sub_10042F80 "setAimSensitivitySEA_Y": vector setter, component y: +0x11C getAimSensitivitySEA / +0x120 setAimSensitivitySEA; mirror +0x11C getAimSensitivitySEA / +0xA8 setAimSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivitySEA, 1, kHapticSea, + &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivity); +} + +// sub_100430F0 "setAimSensitivityLengthSEA_Y": vector setter, component y: +0x124 getAimSensitivityLengthSEA / +0x128 setAimSensitivityLengthSEA; mirror +0x124 getAimSensitivityLengthSEA / +0xB0 setAimSensitivityLength (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivityLengthSEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLengthSEA, 1, kHapticSea, + &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10043260 "setTurnSensitivitySEA_Y": vector setter, component y: +0x12C getTurnSensitivitySEA / +0x130 setTurnSensitivitySEA; mirror +0x12C getTurnSensitivitySEA / +0xB8 setTurnSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setTurnSensitivitySEA_Y(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySEA_Y"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivitySEA, 1, kHapticSea, + &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivity); +} + +// sub_1003FE90 "setAimSensitivitySOLDIER_Z": vector setter, component z: +0xBC getAimSensitivitySOLDIER / +0xC0 setAimSensitivitySOLDIER; mirror +0xBC getAimSensitivitySOLDIER / +0xA8 setAimSensitivity (on foot or no local player). +void as_hapticsettings_setAimSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivitySOLDIER, 2, kHapticSoldier, + &IHapticSettings::getAimSensitivitySOLDIER, &IHapticSettings::setAimSensitivity); +} + +// sub_10040080 "setAimSensitivityLengthSOLDIER_Z": vector setter, component z: +0xC4 getAimSensitivityLengthSOLDIER / +0xC8 setAimSensitivityLengthSOLDIER; mirror +0xC4 getAimSensitivityLengthSOLDIER / +0xB0 setAimSensitivityLength (on foot or no local player). +void as_hapticsettings_setAimSensitivityLengthSOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLengthSOLDIER, 2, kHapticSoldier, + &IHapticSettings::getAimSensitivityLengthSOLDIER, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040270 "setTurnSensitivitySOLDIER_Z": vector setter, component z: +0xCC getTurnSensitivitySOLDIER / +0xD0 setTurnSensitivitySOLDIER; mirror +0xCC getTurnSensitivitySOLDIER / +0xB8 setTurnSensitivity (on foot or no local player). +void as_hapticsettings_setTurnSensitivitySOLDIER_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySOLDIER_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivitySOLDIER, 2, kHapticSoldier, + &IHapticSettings::getTurnSensitivitySOLDIER, &IHapticSettings::setTurnSensitivity); +} + +// sub_10040D00 "setAimSensitivityLAND_Z": vector setter, component z: +0x104 getAimSensitivityLAND / +0x108 setAimSensitivityLAND; mirror +0x104 getAimSensitivityLAND / +0xA8 setAimSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivityLAND, 2, kHapticLand, + &IHapticSettings::getAimSensitivityLAND, &IHapticSettings::setAimSensitivity); +} + +// sub_10040E70 "setAimSensitivityLengthLAND_Z": vector setter, component z: +0x10C getAimSensitivityLengthLAND / +0x110 setAimSensitivityLengthLAND; mirror +0x10C getAimSensitivityLengthLAND / +0xB0 setAimSensitivityLength (vehicle category kHapticLand). +void as_hapticsettings_setAimSensitivityLengthLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLengthLAND, 2, kHapticLand, + &IHapticSettings::getAimSensitivityLengthLAND, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10040FE0 "setTurnSensitivityLAND_Z": vector setter, component z: +0x114 getTurnSensitivityLAND / +0x118 setTurnSensitivityLAND; mirror +0x114 getTurnSensitivityLAND / +0xB8 setTurnSensitivity (vehicle category kHapticLand). +void as_hapticsettings_setTurnSensitivityLAND_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityLAND_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivityLAND, 2, kHapticLand, + &IHapticSettings::getTurnSensitivityLAND, &IHapticSettings::setTurnSensitivity); +} + +// sub_100419F0 "setAimSensitivityAIR_Z": vector setter, component z: +0xD4 getAimSensitivityAIR / +0xD8 setAimSensitivityAIR; mirror +0xD4 getAimSensitivityAIR / +0xA8 setAimSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivityAIR, 2, kHapticAir, + &IHapticSettings::getAimSensitivityAIR, &IHapticSettings::setAimSensitivity); +} + +// sub_10041B60 "setAimSensitivityLengthAIR_Z": vector setter, component z: +0xDC getAimSensitivityLengthAIR / +0xE0 setAimSensitivityLengthAIR; mirror +0xDC getAimSensitivityLengthAIR / +0xB0 setAimSensitivityLength (vehicle category kHapticAir). +void as_hapticsettings_setAimSensitivityLengthAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLengthAIR, 2, kHapticAir, + &IHapticSettings::getAimSensitivityLengthAIR, &IHapticSettings::setAimSensitivityLength); +} + +// sub_10041CD0 "setTurnSensitivityAIR_Z": vector setter, component z: +0xE4 getTurnSensitivityAIR / +0xE8 setTurnSensitivityAIR; mirror +0xE4 getTurnSensitivityAIR / +0xB8 setTurnSensitivity (vehicle category kHapticAir). +void as_hapticsettings_setTurnSensitivityAIR_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityAIR_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivityAIR, 2, kHapticAir, + &IHapticSettings::getTurnSensitivityAIR, &IHapticSettings::setTurnSensitivity); +} + +// sub_100426E0 "setAimSensitivityHELI_Z": vector setter, component z: +0xEC getAimSensitivityHELI / +0xF0 setAimSensitivityHELI; mirror +0xEC getAimSensitivityHELI / +0xA8 setAimSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivityHELI, 2, kHapticHeli, + &IHapticSettings::getAimSensitivityHELI, &IHapticSettings::setAimSensitivity); +} + +// sub_10042850 "setAimSensitivityLengthHELI_Z": vector setter, component z: +0xF4 getAimSensitivityLengthHELI / +0xF8 setAimSensitivityLengthHELI; mirror +0xF4 getAimSensitivityLengthHELI / +0xB0 setAimSensitivityLength (vehicle category kHapticHeli). +void as_hapticsettings_setAimSensitivityLengthHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLengthHELI, 2, kHapticHeli, + &IHapticSettings::getAimSensitivityLengthHELI, &IHapticSettings::setAimSensitivityLength); +} + +// sub_100429C0 "setTurnSensitivityHELI_Z": vector setter, component z: +0xFC getTurnSensitivityHELI / +0x100 setTurnSensitivityHELI; mirror +0xFC getTurnSensitivityHELI / +0xB8 setTurnSensitivity (vehicle category kHapticHeli). +void as_hapticsettings_setTurnSensitivityHELI_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivityHELI_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivityHELI, 2, kHapticHeli, + &IHapticSettings::getTurnSensitivityHELI, &IHapticSettings::setTurnSensitivity); +} + +// sub_100433D0 "setAimSensitivitySEA_Z": vector setter, component z: +0x11C getAimSensitivitySEA / +0x120 setAimSensitivitySEA; mirror +0x11C getAimSensitivitySEA / +0xA8 setAimSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivitySEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivitySEA, 2, kHapticSea, + &IHapticSettings::getAimSensitivitySEA, &IHapticSettings::setAimSensitivity); +} + +// sub_10043540 "setAimSensitivityLengthSEA_Z": vector setter, component z: +0x124 getAimSensitivityLengthSEA / +0x128 setAimSensitivityLengthSEA; mirror +0x124 getAimSensitivityLengthSEA / +0xB0 setAimSensitivityLength (vehicle category kHapticSea). +void as_hapticsettings_setAimSensitivityLengthSEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setAimSensitivityLengthSEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLengthSEA, 2, kHapticSea, + &IHapticSettings::getAimSensitivityLengthSEA, &IHapticSettings::setAimSensitivityLength); +} + +// sub_100436B0 "setTurnSensitivitySEA_Z": vector setter, component z: +0x12C getTurnSensitivitySEA / +0x130 setTurnSensitivitySEA; mirror +0x12C getTurnSensitivitySEA / +0xB8 setTurnSensitivity (vehicle category kHapticSea). +void as_hapticsettings_setTurnSensitivitySEA_Z(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setTurnSensitivitySEA_Z"); + hapticVectorSetter(fn, &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivitySEA, 2, kHapticSea, + &IHapticSettings::getTurnSensitivitySEA, &IHapticSettings::setTurnSensitivity); +} + +// sub_10035290 "setWeaponSelectSOLDIER": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectSOLDIER"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10036CA0 "getWeaponSelectSOLDIER": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectSOLDIER"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10036D10 "getWeaponInitialSOLDIER": arg 0 == 1 -> the name at 0x100F6C70 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialSOLDIER"); + publishHapticInitialName(fn, kHapticInfantryWeapons[0]); +} + +// sub_10036DF0 "setThresholdSelectSOLDIER": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectSOLDIER"); + storeHapticThresholdSelect(fn); +} + +// sub_10036EB0 "getThresholdSelectSOLDIER": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectSOLDIER"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_10036F20 "getThresholdInitialSOLDIER": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialSOLDIER(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialSOLDIER"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_100352C0 "setWeaponSelectLAND": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectLAND"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10036F70 "getWeaponSelectLAND": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectLAND"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10036FE0 "getWeaponInitialLAND": arg 0 == 1 -> the name at 0x100F3310 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialLAND"); + publishHapticInitialName(fn, kHapticVehicleWeapons[0]); +} + +// sub_100370C0 "setThresholdSelectLAND": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectLAND"); + storeHapticThresholdSelect(fn); +} + +// sub_10037180 "getThresholdSelectLAND": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectLAND"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_100371F0 "getThresholdInitialLAND": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialLAND(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialLAND"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_100352F0 "setWeaponSelectAIR": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectAIR"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10037240 "getWeaponSelectAIR": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectAIR"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_100372B0 "getWeaponInitialAIR": arg 0 == 1 -> the name at 0x100F3364 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialAIR"); + publishHapticInitialName(fn, kHapticVehicleWeapons[3]); +} + +// sub_10037390 "setThresholdSelectAIR": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectAIR"); + storeHapticThresholdSelect(fn); +} + +// sub_10037450 "getThresholdSelectAIR": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectAIR"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_100374C0 "getThresholdInitialAIR": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialAIR(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialAIR"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_10035320 "setWeaponSelectHELI": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectHELI"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_10037510 "getWeaponSelectHELI": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectHELI"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10037580 "getWeaponInitialHELI": arg 0 == 1 -> the name at 0x100F3348 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialHELI"); + publishHapticInitialName(fn, kHapticVehicleWeapons[2]); +} + +// sub_10037660 "setThresholdSelectHELI": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectHELI"); + storeHapticThresholdSelect(fn); +} + +// sub_10037720 "getThresholdSelectHELI": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectHELI"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_10037790 "getThresholdInitialHELI": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialHELI(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialHELI"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + +// sub_10035350 "setWeaponSelectSEA": arg 0 to_string stored into the shared weapon selection (0x100F8550). +void as_hapticsettings_setWeaponSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setWeaponSelectSEA"); + s_hapticWeaponSelect = fn.arg(0).to_string(); +} + +// sub_100377E0 "getWeaponSelectSEA": the shared weapon selection (unk_100F8554) as a plain string. +void as_hapticsettings_getWeaponSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponSelectSEA"); + fn.result->set_tu_string(tu_string(s_hapticWeaponSelect.c_str())); +} + +// sub_10037850 "getWeaponInitialSEA": arg 0 == 1 -> the name at 0x100F3310 as a plain string, else its localised dice String (sub_10036B70). +void as_hapticsettings_getWeaponInitialSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getWeaponInitialSEA"); + publishHapticInitialName(fn, kHapticVehicleWeapons[0]); +} + +// sub_10037930 "setThresholdSelectSEA": arg 0 to_string; result _stricmp(name, "BFHQ_physicsthresholdhigh") == 0, then the name stored into the shared threshold selection (0x100F8534). +void as_hapticsettings_setThresholdSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_setThresholdSelectSEA"); + storeHapticThresholdSelect(fn); +} + +// sub_100379F0 "getThresholdSelectSEA": the shared threshold selection (unk_100F8538) as a plain string. +void as_hapticsettings_getThresholdSelectSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdSelectSEA"); + fn.result->set_tu_string(tu_string(s_hapticThresholdSelect.c_str())); +} + +// sub_10037A60 "getThresholdInitialSEA": the localised dice String (sub_10036B70) of unk_100F3870, "BFHQ_physicsthresholdlow"; no argument read. +void as_hapticsettings_getThresholdInitialSEA(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_hapticsettings_getThresholdInitialSEA"); + fn.result->set_as_object_interface(videoSettingsLocalisedString(renddx9abi::HostString("BFHQ_physicsthresholdlow"))); +} + + +static void registerHapticNatives(SwiffAsNamespace** ns, const char* const* names, int count) +{ + for (int i = 0; i < count; ++i) + { + if (::strcmp(names[i], "HapticSettings") != 0) + continue; + ns[i]->registerNativeCompatibleMethod("apply"); // 1004460F + ns[i]->registerNativeCompatibleMethod("reset"); // 10044676 + ns[i]->registerNativeCompatibleMethod("cancel"); // 100446CE + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSOLDIER_X"); // 10044744 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSOLDIER_X"); // 100447B4 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthLAND_X"); // 10044830 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessLAND_X"); // 100448AC + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthAIR_X"); // 10044928 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessAIR_X"); // 100449A4 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthHELI_X"); // 10044A20 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessHELI_X"); // 10044A9C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSEA_X"); // 10044B18 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSEA_X"); // 10044B94 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSOLDIER_Y"); // 10044C10 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSOLDIER_Y"); // 10044C8C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthLAND_Y"); // 10044D08 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessLAND_Y"); // 10044D84 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthAIR_Y"); // 10044E00 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessAIR_Y"); // 10044E7C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthHELI_Y"); // 10044EF8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessHELI_Y"); // 10044F74 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSEA_Y"); // 10044FF0 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSEA_Y"); // 1004506C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSOLDIER_Z"); // 100450E8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSOLDIER_Z"); // 10045164 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthLAND_Z"); // 100451E0 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessLAND_Z"); // 1004525C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthAIR_Z"); // 100452D8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessAIR_Z"); // 10045354 + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthHELI_Z"); // 100453D0 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessHELI_Z"); // 1004544C + ns[i]->registerNativeCompatibleMethod("getControlBoxLengthSEA_Z"); // 100454C8 + ns[i]->registerNativeCompatibleMethod("getControlBoxStiffnessSEA_Z"); // 10045544 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySOLDIER_X"); // 100455C0 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSOLDIER_X"); // 1004563C + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySOLDIER_X"); // 100456B8 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLAND_X"); // 10045734 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthLAND_X"); // 100457B0 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityLAND_X"); // 1004582C + ns[i]->registerNativeCompatibleMethod("getAimSensitivityAIR_X"); // 100458A8 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthAIR_X"); // 10045924 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityAIR_X"); // 100459A0 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityHELI_X"); // 10045A1C + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthHELI_X"); // 10045A98 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityHELI_X"); // 10045B14 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySEA_X"); // 10045B90 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSEA_X"); // 10045C0C + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySEA_X"); // 10045C88 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySOLDIER_Y"); // 10045D04 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSOLDIER_Y"); // 10045D80 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySOLDIER_Y"); // 10045DFC + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLAND_Y"); // 10045E78 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthLAND_Y"); // 10045EF4 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityLAND_Y"); // 10045F70 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityAIR_Y"); // 10045FEC + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthAIR_Y"); // 10046068 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityAIR_Y"); // 100460E4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityHELI_Y"); // 10046160 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthHELI_Y"); // 100461DC + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityHELI_Y"); // 10046258 + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySEA_Y"); // 100462D4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSEA_Y"); // 10046350 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySEA_Y"); // 100463CC + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySOLDIER_Z"); // 10046448 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSOLDIER_Z"); // 100464C4 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySOLDIER_Z"); // 10046540 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLAND_Z"); // 100465BC + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthLAND_Z"); // 10046638 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityLAND_Z"); // 100466B4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityAIR_Z"); // 10046730 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthAIR_Z"); // 100467AC + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityAIR_Z"); // 10046828 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityHELI_Z"); // 100468A4 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthHELI_Z"); // 10046920 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivityHELI_Z"); // 1004699C + ns[i]->registerNativeCompatibleMethod("getAimSensitivitySEA_Z"); // 10046A18 + ns[i]->registerNativeCompatibleMethod("getAimSensitivityLengthSEA_Z"); // 10046A94 + ns[i]->registerNativeCompatibleMethod("getTurnSensitivitySEA_Z"); // 10046B10 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERScale_X"); // 10046B8C + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERScale_Y"); // 10046C08 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERScale_Z"); // 10046C84 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERTransition"); // 10046D00 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERSmoothTime_X"); // 10046D7C + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERSmoothTime_Y"); // 10046DF8 + ns[i]->registerNativeCompatibleMethod("getPhysicsSOLDIERSmoothTime_Z"); // 10046E74 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDScale_X"); // 10046EF0 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDScale_Y"); // 10046F6C + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDScale_Z"); // 10046FE8 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDTransition"); // 10047064 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDSmoothTime_X"); // 100470E0 + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDSmoothTime_Y"); // 1004715C + ns[i]->registerNativeCompatibleMethod("getPhysicsLANDSmoothTime_Z"); // 100471D8 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRScale_X"); // 10047254 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRScale_Y"); // 100472D0 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRScale_Z"); // 1004734C + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRTransition"); // 100473C8 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRSmoothTime_X"); // 10047444 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRSmoothTime_Y"); // 100474C0 + ns[i]->registerNativeCompatibleMethod("getPhysicsAIRSmoothTime_Z"); // 1004753C + ns[i]->registerNativeCompatibleMethod("getPhysicsHELIScale_X"); // 100475B8 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELIScale_Y"); // 10047634 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELIScale_Z"); // 100476B0 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELITransition"); // 1004772C + ns[i]->registerNativeCompatibleMethod("getPhysicsHELISmoothTime_X"); // 100477A8 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELISmoothTime_Y"); // 10047824 + ns[i]->registerNativeCompatibleMethod("getPhysicsHELISmoothTime_Z"); // 100478A0 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEAScale_X"); // 1004791C + ns[i]->registerNativeCompatibleMethod("getPhysicsSEAScale_Y"); // 10047998 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEAScale_Z"); // 10047A14 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEATransition"); // 10047A90 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEASmoothTime_X"); // 10047B0C + ns[i]->registerNativeCompatibleMethod("getPhysicsSEASmoothTime_Y"); // 10047B88 + ns[i]->registerNativeCompatibleMethod("getPhysicsSEASmoothTime_Z"); // 10047C04 + ns[i]->registerNativeCompatibleMethod("getDamageScale"); // 10047C80 + ns[i]->registerNativeCompatibleMethod("getRecoilPunchScale"); // 10047CFC + ns[i]->registerNativeCompatibleMethod("getRecoilPunchTime"); // 10047D78 + ns[i]->registerNativeCompatibleMethod("getRecoilYawScale"); // 10047DF4 + ns[i]->registerNativeCompatibleMethod("getRecoilPitchScale"); // 10047E70 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSOLDIER_X"); // 10047EEC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSOLDIER_X"); // 10047F68 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthLAND_X"); // 10047FE4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessLAND_X"); // 10048060 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthAIR_X"); // 100480DC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessAIR_X"); // 10048158 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthHELI_X"); // 100481D4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessHELI_X"); // 10048250 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSEA_X"); // 100482CC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSEA_X"); // 10048348 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSOLDIER_Y"); // 100483C4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSOLDIER_Y"); // 10048440 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthLAND_Y"); // 100484BC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessLAND_Y"); // 10048538 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthAIR_Y"); // 100485B4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessAIR_Y"); // 10048630 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthHELI_Y"); // 100486AC + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessHELI_Y"); // 10048728 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSEA_Y"); // 100487A4 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSEA_Y"); // 10048820 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSOLDIER_Z"); // 1004889C + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSOLDIER_Z"); // 10048918 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthLAND_Z"); // 10048994 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessLAND_Z"); // 10048A10 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthAIR_Z"); // 10048A8C + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessAIR_Z"); // 10048B08 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthHELI_Z"); // 10048B84 + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessHELI_Z"); // 10048C00 + ns[i]->registerNativeCompatibleMethod("setControlBoxLengthSEA_Z"); // 10048C7C + ns[i]->registerNativeCompatibleMethod("setControlBoxStiffnessSEA_Z"); // 10048CF8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySOLDIER_X"); // 10048D74 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSOLDIER_X"); // 10048DF0 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySOLDIER_X"); // 10048E6C + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLAND_X"); // 10048EE8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthLAND_X"); // 10048F64 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityLAND_X"); // 10048FE0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityAIR_X"); // 1004905C + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthAIR_X"); // 100490D8 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityAIR_X"); // 10049154 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityHELI_X"); // 100491D0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthHELI_X"); // 1004924C + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityHELI_X"); // 100492C8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySEA_X"); // 10049344 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSEA_X"); // 100493C0 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySEA_X"); // 1004943C + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySOLDIER_Y"); // 100494B8 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSOLDIER_Y"); // 10049534 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySOLDIER_Y"); // 100495B0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLAND_Y"); // 1004962C + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthLAND_Y"); // 100496A8 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityLAND_Y"); // 10049724 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityAIR_Y"); // 100497A0 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthAIR_Y"); // 1004981C + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityAIR_Y"); // 10049898 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityHELI_Y"); // 10049914 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthHELI_Y"); // 10049990 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityHELI_Y"); // 10049A0C + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySEA_Y"); // 10049A88 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSEA_Y"); // 10049B04 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySEA_Y"); // 10049B80 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySOLDIER_Z"); // 10049BFC + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSOLDIER_Z"); // 10049C78 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySOLDIER_Z"); // 10049CF4 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLAND_Z"); // 10049D70 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthLAND_Z"); // 10049DEC + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityLAND_Z"); // 10049E68 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityAIR_Z"); // 10049EE4 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthAIR_Z"); // 10049F60 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityAIR_Z"); // 10049FDC + ns[i]->registerNativeCompatibleMethod("setAimSensitivityHELI_Z"); // 1004A058 + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthHELI_Z"); // 1004A0D4 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivityHELI_Z"); // 1004A150 + ns[i]->registerNativeCompatibleMethod("setAimSensitivitySEA_Z"); // 1004A1CC + ns[i]->registerNativeCompatibleMethod("setAimSensitivityLengthSEA_Z"); // 1004A248 + ns[i]->registerNativeCompatibleMethod("setTurnSensitivitySEA_Z"); // 1004A2C4 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERScale_X"); // 1004A340 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERScale_Y"); // 1004A3BC + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERScale_Z"); // 1004A438 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERTransition"); // 1004A4B4 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERSmoothTime_X"); // 1004A530 + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERSmoothTime_Y"); // 1004A5AC + ns[i]->registerNativeCompatibleMethod("setPhysicsSOLDIERSmoothTime_Z"); // 1004A628 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDScale_X"); // 1004A6A4 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDScale_Y"); // 1004A720 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDScale_Z"); // 1004A79C + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDTransition"); // 1004A818 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDSmoothTime_X"); // 1004A894 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDSmoothTime_Y"); // 1004A910 + ns[i]->registerNativeCompatibleMethod("setPhysicsLANDSmoothTime_Z"); // 1004A98C + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRScale_X"); // 1004AA08 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRScale_Y"); // 1004AA84 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRScale_Z"); // 1004AB00 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRTransition"); // 1004AB7C + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRSmoothTime_X"); // 1004ABF8 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRSmoothTime_Y"); // 1004AC74 + ns[i]->registerNativeCompatibleMethod("setPhysicsAIRSmoothTime_Z"); // 1004ACF0 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELIScale_X"); // 1004AD6C + ns[i]->registerNativeCompatibleMethod("setPhysicsHELIScale_Y"); // 1004ADE8 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELIScale_Z"); // 1004AE64 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELITransition"); // 1004AEE0 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELISmoothTime_X"); // 1004AF5C + ns[i]->registerNativeCompatibleMethod("setPhysicsHELISmoothTime_Y"); // 1004AFD8 + ns[i]->registerNativeCompatibleMethod("setPhysicsHELISmoothTime_Z"); // 1004B054 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEAScale_X"); // 1004B0D0 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEAScale_Y"); // 1004B14C + ns[i]->registerNativeCompatibleMethod("setPhysicsSEAScale_Z"); // 1004B1C8 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEATransition"); // 1004B244 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEASmoothTime_X"); // 1004B2C0 + ns[i]->registerNativeCompatibleMethod("setPhysicsSEASmoothTime_Y"); // 1004B33C + ns[i]->registerNativeCompatibleMethod("setPhysicsSEASmoothTime_Z"); // 1004B3B8 + ns[i]->registerNativeCompatibleMethod("setDamageScale"); // 1004B434 + ns[i]->registerNativeCompatibleMethod("setRecoilPunchScale"); // 1004B4B0 + ns[i]->registerNativeCompatibleMethod("setRecoilPunchTime"); // 1004B52C + ns[i]->registerNativeCompatibleMethod("setRecoilYawScale"); // 1004B5A8 + ns[i]->registerNativeCompatibleMethod("setRecoilPitchScale"); // 1004B624 + ns[i]->registerNativeCompatibleMethod("setWeaponSelectSOLDIER"); // 1004B6A0 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectSOLDIER"); // 1004B71C + ns[i]->registerNativeCompatibleMethod("getWeaponInitialSOLDIER"); // 1004B798 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectSOLDIER"); // 1004B814 + ns[i]->registerNativeCompatibleMethod("getThresholdSelectSOLDIER"); // 1004B890 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialSOLDIER"); // 1004B90C + ns[i]->registerNativeCompatibleMethod("setWeaponSelectLAND"); // 1004B988 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectLAND"); // 1004BA04 + ns[i]->registerNativeCompatibleMethod("getWeaponInitialLAND"); // 1004BA80 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectLAND"); // 1004BAFC + ns[i]->registerNativeCompatibleMethod("getThresholdSelectLAND"); // 1004BB78 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialLAND"); // 1004BBF4 + ns[i]->registerNativeCompatibleMethod("setWeaponSelectAIR"); // 1004BC70 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectAIR"); // 1004BCEC + ns[i]->registerNativeCompatibleMethod("getWeaponInitialAIR"); // 1004BD68 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectAIR"); // 1004BDE4 + ns[i]->registerNativeCompatibleMethod("getThresholdSelectAIR"); // 1004BE60 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialAIR"); // 1004BEDC + ns[i]->registerNativeCompatibleMethod("setWeaponSelectHELI"); // 1004BF58 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectHELI"); // 1004BFD4 + ns[i]->registerNativeCompatibleMethod("getWeaponInitialHELI"); // 1004C050 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectHELI"); // 1004C0CC + ns[i]->registerNativeCompatibleMethod("getThresholdSelectHELI"); // 1004C148 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialHELI"); // 1004C1C4 + ns[i]->registerNativeCompatibleMethod("setWeaponSelectSEA"); // 1004C240 + ns[i]->registerNativeCompatibleMethod("getWeaponSelectSEA"); // 1004C2BC + ns[i]->registerNativeCompatibleMethod("getWeaponInitialSEA"); // 1004C338 + ns[i]->registerNativeCompatibleMethod("setThresholdSelectSEA"); // 1004C3B4 + ns[i]->registerNativeCompatibleMethod("getThresholdSelectSEA"); // 1004C430 + ns[i]->registerNativeCompatibleMethod("getThresholdInitialSEA"); // 1004C4AC + ns[i]->registerNativeCompatibleMethod("setHapticSettingsPage"); // 1004C528 + ns[i]->registerNativeCompatibleMethod("getHapticSettingsPage"); // 1004C5A4 + } +} diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp index 564174978..63e36760c 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.cpp @@ -1,15 +1,48 @@ // SwiffPlayer lifecycle, movie pipeline, renderer adapter, and ActionScript bindings. // [CHOSEN, not recovered] Rebuilt client/plugin ABI only: https://github.com/B2BF/OpenBF2/issues/7. -// Internal fixed-layout storage and unresolved host frontiers remain in place. +// Internal records use native std containers; unresolved host frontiers remain in place. #ifdef BF2_IMAGE_SWIFFPLAYER +#include "../../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. #include "SwiffPlayer.h" +#include "../../../Core/MsvcCrtCompat.h" // [CHOSEN, not recovered] sprintf_s, __time32_t/_time32, _time64 outside MSVC +#if defined(__APPLE__) +#include "../../../Platform/macOS/CocoaHost.h" +#include +#include +// [CHOSEN, not recovered] macOS: the two user32 calls the ActionScript bindings make, on the Cocoa +// host. SetCursor takes the host's cursor tokens (SwiffHost::getCursor) and answers the previous +// one; GetKeyState is called only for VK_CAPITAL (20), whose toggle bit is the Caps Lock state. +static void* SetCursor(void* cursor) +{ + static void* s_current = 0; + void* const previous = s_current; + s_current = cursor; + ::dice::hfe::macos::CocoaHost::instance().setCursor(cursor); + return previous; +} +static short GetKeyState(int vkey) +{ + if (vkey != 20) { + // [FRONTIER] [TEMP] Only VK_CAPITAL has a mapping. [RETIRE-WHEN: swiff-getkeystate-keys] + std::fprintf(stderr, "[FRONTIER] SwiffPlayer GetKeyState(%d) reached: only VK_CAPITAL is mapped on macOS\n", vkey); + std::fflush(stderr); + std::abort(); + } + return (::dice::hfe::macos::CocoaHost::instance().modifierFlags() & ::dice::hfe::macos::HostModCapsLock) ? 1 : 0; +} +#endif #include "../../../../RendDX9Abi/BfMemory.h" #include "../../../../RendDX9Abi/HfeAbi.h" -#include "../../../../RendDX9Abi/Vc71String.h" // retained fixed-layout internal strings -#include "../../../../RendDX9Abi/Vc71Vector.h" // the +1104 queued-mouse vector +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Use the renderer's shared native slots and signatures. +#include "../../../../SwiffPlayerAbi/NativeRenderCalls.h" +#else +#include "../../../Menu/ISwiffRender.h" // the typed render calls of the dice.bf2.Logic credits natives +#endif +#include #include "../../../Menu/ISwiffHost.h" // native storage calls share the owner's std::string ABI #include "../../../Menu/IServerBrowser.h" // stopBrowser's list handle (+0x30 stopUpdate) @@ -27,13 +60,23 @@ #include "../../../Game/DemoRecorder/DemoLibrary.h" // native: Multiplay's bookmark flag pair #include "../../../Menu/IMenuTeamManager.h" // native: the typed team -> kit -> equipment walk behind getEquipmentName & co #include "../../../Menu/ServerLogoManager.h" // native: the typed logo cache behind Multiplay.downloadServerLogo +#include "../../../Game/Persistence/SearchForPlayer.h" // native: Profile.searchPlayer / searchUniquePlayer (host +0x3C) +#include "../../../Game/HapticSettings.h" // native: IHapticSettings, the dice.bf2.HapticSettings rows +#include "../../../Scene/Object/PlayerManager.h" // native: the HapticSettings vector setters' local player (+0x30) +#include "../../../Game/Objects/IPlayer.h" // native: getVehicle / getDefaultVehicle (PE +0x44 / +0xA0) +#include "../../../Game/Objects/IObject.h" // native: the vehicle's template field (+0x14) +#include "../../../Game/Objects/PlayerControlObjectTemplate.h" // native: getVehicleCategory (PE base +0x22C, slot +0x24) +#include "../../../Core/Ids.h" // native: IID_IPlayerControlObjectTemplate (the port guard in the haptic vector setters) #include "base/tu_file.h" // the file_opener_callback return type #include "base/image.h" // image::rgb / image::rgba (create_bitmap_info_rgb/rgba read w/h) #include "gameswf_action.h" // as_object / as_value / get_global_object - the AS-bridge graph build +#include "gameswf_log.h" // [TEMP] c-swf-disconnect: SWF_LIST_TRACE #include #include +#include +#include // offsetof: SwiffRenderHandler::renderContext #include #include // memset, memcpy #include // time(): the stamp the host records carry @@ -49,18 +92,19 @@ namespace hfe { // engine VFS the file opener reads SWFs through. extern IClassManager* classManager; extern IBase* fileManager; +// playerManager (dword_100EFEE0, "PlayerManager" stored by initDll): the HapticSettings vector +// setters ask it for the local human player (+0x30). Typed IBase* as PluginEntry.cpp keeps it. +extern IBase* playerManager; namespace ui { -// The internal object layout remains fixed while the rebuilt client and gameswf share it. -// Reject an accidental reorder or added member at compile time. - -static_assert(sizeof(SwiffPlayer) == 1120, "SwiffPlayer must be 0x460 bytes (IDB dice_hfe_SwiffPlayer_BF2)"); - // dword_100F2F20 in the shipped image - the ctor stores `this` here. Read by the fscommand sink to // find the live player. File-scope, one instance, matching the shipped global. static SwiffPlayer* g_swiffPlayerInstance = 0; +// [CHOSEN, not recovered] issue #7: the players constructed and not yet destroyed. The movie +// teardown's global steps (SwiffPlayer::releaseMovie) run only when the dying player is the last. +static int s_livePlayers = 0; // The gameswf modifier-key latches the shipped image keeps as file-scope bytes (byte_100F8EE8/9/A/B), // NOT as object members - notifyChar/notifyKeyState/resetModifierState touch these. @@ -153,6 +197,20 @@ static bool asLogEnabled() return s_on != 0; } +static bool inputLogEnabled() +{ + const char* value = ::getenv("BF2_SWIFFPLAYER_INPUTLOG"); + return value && value[0] == '1' && value[1] == '\0'; +} + +static bool mouseLogEnabled() { return asLogEnabled() || inputLogEnabled(); } + +static void swiffInputLogCb(bool, const char* message) +{ + if (message && ::strncmp(message, "[mouse]", 7) == 0) + ::renddx9abi::logf("%s", message); +} + // [TEMP] [CHOSEN, not recovered] BF2_SWIFFPLAYER_STREAMLOG=N traces player inputs and displays. // Logs the first N displays, then every 100th; disabled unless configured. @@ -289,6 +347,29 @@ struct SwfAsTraceScope const char* name; SwfAsTraceScope(const gameswf::fn_call& f, const char* n) : fn(f), name(n) { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: menu -> engine calls for the [swf-list] tracer, one line each + // with the first arguments. Outside a mouse pass a name is logged 20 times, then muted + // (per-frame polls); inside a mouse pass every call is logged. + if (gameswf::swf_list_trace_on()) + { + static std::map s_counts; + int& count = s_counts[name]; + if (gameswf::g_swf_mouse_pass_depth > 0 || count < 20) + { + char args[200]; + int len = 0; + args[0] = '\0'; + for (int i = 0; i < fn.nargs && i < 4 && len < (int)sizeof(args) - 1; ++i) + { + const char* a = fn.arg(i).to_string(); + len += ::snprintf(args + len, sizeof(args) - len, "%s\"%.40s\"", i ? "," : "", a ? a : ""); + } + SWF_LIST_TRACE("as %s(%s)%s", name, args, count == 19 && gameswf::g_swf_mouse_pass_depth == 0 ? " [muted from now on outside mouse passes]" : ""); + } + count++; + } +#endif if (!asLogEnabled()) return; ::renddx9abi::logf("[as] enter %s (nargs=%d)", name, fn.nargs); for (int i = 0; i < fn.nargs; ++i) @@ -299,6 +380,20 @@ struct SwfAsTraceScope } ~SwfAsTraceScope() { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: a result that differs from this call's previous one (messages + // and states the menu polls), always inside a mouse pass. + if (gameswf::swf_list_trace_on()) + { + static std::map s_last; + const char* r = fn.result ? fn.result->to_string() : 0; + std::string now = r ? r : ""; + std::string& last = s_last[name]; + if (now != last || gameswf::g_swf_mouse_pass_depth > 0) + SWF_LIST_TRACE("as %s -> \"%.80s\"", name, now.c_str()); + last = now; + } +#endif if (!asLogEnabled()) return; const char* s = fn.result ? fn.result->to_string() : 0; ::renddx9abi::logf("[as] leave %s -> \"%s\"", name, s ? s : ""); @@ -324,7 +419,7 @@ void as_cursor_setCursor(const gameswf::fn_call& fn) SWF_AS_TRACE("as_cursor_setCursor"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); const std::string name(fn.arg(0).to_string()); - (void) h->setPlayerRenderCapability0(static_cast(reinterpret_cast(&name))); // +0x68 + (void) h->setPlayerRenderCapability0(reinterpret_cast(&name)); // +0x68 } // Requests the cursor name through a preconstructed string. Returns the string, or the @@ -334,7 +429,7 @@ void as_cursor_getCursor(const gameswf::fn_call& fn) SWF_AS_TRACE("as_cursor_getCursor"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); std::string out; - const bool ok = h->setPlayerRenderCapability1(static_cast(reinterpret_cast(&out))); // +0x70 + const bool ok = h->setPlayerRenderCapability1(reinterpret_cast(&out)); // +0x70 fn.result->set_tu_string(tu_string(ok ? out.c_str() : "undefined")); } @@ -486,33 +581,6 @@ void as_profile_getLoginStatus(const gameswf::fn_call& fn) fn.result->set_double(status); } -// The original VC7.1 LocalProfileManager vector: the allocator word first, then first/last/end -// (sub_10060030 zeroes the three words after a one-word head and reads the count from them). A -// three-word layout put the callee's writes one slot off: retail runs R..AA counted 0 profiles and -// the movie took the first-time "newbie" page instead of "login". -struct Vc71Vector { int alloc; char* first; char* last; char* end; }; - -// One local profile record (176 bytes): six VC7.1 std::strings, destroyed in the shipped order by -// sub_1001DC10 (+140, +112, +84, +56, +28, +0), then the vector buffer goes back to the engine heap -// (sub_1001FE70 -> bf_free). The retained vc71::string storage now uses the shared native CRT. -// Fields the original list bodies read: [0] the profile id GlobalSettings compares, -// [1] profileName, [2] the offline display name, [3] the GameSpy nick (empty = offline), [5] password. -struct LocalProfileRecord { vc71::string s[6]; char tail[8]; }; -static_assert(sizeof(LocalProfileRecord) == 176, "LocalProfileRecord must be 176 bytes (sub_10015040)"); - -static void destroyLocalProfiles(Vc71Vector& v) -{ - if (!v.first) return; - const int n = static_cast((v.last - v.first) / 176); - for (int i = 0; i < n; ++i) - { - LocalProfileRecord* r = reinterpret_cast(v.first + 176 * i); - for (int k = 5; k >= 0; --k) r->s[k].~string(); - } - ::renddx9abi::engineFree(v.first); - v.first = v.last = v.end = 0; -} - // unguarded registry lookup; absent singleton -> numeric 0. // A present owner fills an empty vector with validOnly=true, return ignored. // Its signed count is assigned before record strings and vector storage die. @@ -530,6 +598,7 @@ void as_profile_getNumLocalProfiles(const gameswf::fn_call& fn) // Forward declarations of the SwiffHost dispatch helpers used by the AS bodies below; they are // defined further down, beside the other rc*/host* raw-vtable helpers. +#if defined(_MSC_VER) inline bool hostIsGameRunning(void* h, bool* out); inline int hostGetActivateReason(void* h); inline void hostSetActivateReason(void* h, int v); @@ -553,6 +622,7 @@ inline void hostSetIndexedInt(void* h, int index, int value); inline void* hostGetServerLogoManager(void* h); inline void hostGetJoinPassword(void* h, void* outStr); inline void hostSetJoinPassword(void* h, const void* str); +#endif // Logic callbacks dispatch through the player's ISwiffHost. @@ -632,7 +702,7 @@ void as_locale_getString(const gameswf::fn_call& fn) renddx9abi::HostString ids(fn.arg(0).to_string()); std::wstring out; h->getLocalizedString(out, ids); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(out.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(out.c_str())); fn.result->set_as_object_interface(text); } @@ -671,7 +741,11 @@ void as_logic_setDecimals(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_setDecimals"); const float value = static_cast(fn.arg(0).to_number()); +#if defined(__APPLE__) + const int decimals = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int decimals = static_cast(fn.arg(1).to_number()); +#endif const std::string format = swiffFormatString("%%.%df", decimals); const std::string text = swiffFormatString(format.c_str(), static_cast(value)); fn.result->set_tu_string(tu_string(text.c_str())); @@ -769,7 +843,7 @@ struct ListResult void pushWide(const wchar_t* w, int n) { gameswf::array_object_push(row.get_ptr(), - gameswf::as_value(gameswf::create_dice_string_object(reinterpret_cast(w), n))); + gameswf::as_value(gameswf::create_dice_string_object(BF2_DICE_UTF16(w), n))); } void pushNarrow(const char* v) { gameswf::array_object_push(row.get_ptr(), gameswf::as_value(tu_string(v ? v : ""))); } // sub_1001CC50 - an int column: "%d" through the shipped 256-byte global (byte_100F78F0), then @@ -780,7 +854,7 @@ struct ListResult void setWide(const char* key, const wchar_t* w, int n) { rowObj->set_member(key, gameswf::as_value( - gameswf::create_dice_string_object(reinterpret_cast(w), n))); + gameswf::create_dice_string_object(BF2_DICE_UTF16(w), n))); } void setTotalCount(int n) { @@ -858,7 +932,7 @@ void as_endofround_getMapDescription(const gameswf::fn_call& fn) const std::string& key = !map->briefingLocId.empty() ? map->briefingLocId : map->briefing; HostWide wide; g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(wide, key); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } fn.result->set_as_object_interface(text); } @@ -902,7 +976,7 @@ void as_endofround_getMapGameModeDescription(const gameswf::fn_call& fn) const std::string& key = !mt->locId.empty() ? mt->locId : mt->description; HostWide wide; g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(wide, key); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); found = true; break; } @@ -953,7 +1027,11 @@ void as_endofround_getTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getTeamName"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif const std::string name = h->getTeamName(team); // +0x17C fn.result->set_tu_string(tu_string(name.c_str())); } @@ -964,7 +1042,11 @@ void as_endofround_getNumVictories(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getNumVictories"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif SwiffEndOfRoundSummary summary; (void) h->getEndOfRoundSummary(summary); // +0x1A4 fn.result->set_double((double) summary.teams[team].roundsWon); // team unchecked @@ -991,7 +1073,11 @@ void as_endofround_getTicketHistorySum(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getTicketHistorySum"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif SwiffEndOfRoundSummary summary; if (!h->getEndOfRoundSummary(summary)) { @@ -1025,7 +1111,11 @@ void as_endofround_getPreviousTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getPreviousTeamName"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif fn.result->set_tu_string(tu_string(h->getEndOfRoundInfo()->teams[team].name.c_str())); // team unchecked } @@ -1039,7 +1129,11 @@ void as_endofround_getSquadTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getSquadTeamName"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int team = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int team = (int) fn.arg(0).to_number(); +#endif const SwiffEndOfRoundInfo* rec = h->getEndOfRoundInfo(); gameswf::as_object_interface* text = gameswf::create_dice_string_object(0, 0); HostWide title; @@ -1055,7 +1149,7 @@ void as_endofround_getSquadTeamName(const gameswf::fn_call& fn) const std::string key = std::string("EOR_best") + name + "squad"; hostLocaliseAlways(std::string(key.c_str()), title); } - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(title.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(title.c_str())); fn.result->set_as_object_interface(text); } @@ -1098,7 +1192,7 @@ void as_endofround_getPreviousMapDescription(const gameswf::fn_call& fn) { HostWide wide; hostLocaliseAlways(map->briefingLocId != "" ? map->briefingLocId : map->briefing, wide); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } fn.result->set_as_object_interface(text); } @@ -1150,7 +1244,7 @@ void as_endofround_getPreviousMapGameModeDescription(const gameswf::fn_call& fn) if (mt->players != size) continue; HostWide wide; hostLocaliseAlways(mt->locId != "" ? mt->locId : mt->description, wide); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); found = true; break; } @@ -1176,7 +1270,11 @@ void as_endofround_getPreviousMapGameModeName(const gameswf::fn_call& fn) void as_endofround_getKitNameFromId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getKitNameFromId"); +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = (int) fn.arg(0).to_number(); +#endif const char* name = ""; switch (id) { @@ -1199,7 +1297,11 @@ void as_endofround_getTeamNameOfPlayerAtPosition(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_endofround_getTeamNameOfPlayerAtPosition"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int position = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int position = (int) fn.arg(0).to_number(); +#endif std::string team(""); if (h->getEndOfRoundInfo()->topPlayers[position].name != "") team = h->getEndOfRoundInfo()->topPlayers[position].team; @@ -1483,7 +1585,9 @@ static const char* serverOsIcon(const char* os) // queries use separate caches; sponsors may issue a query on a cache miss. Joining clears // the separate in-game server-info keys. +#if !defined(__APPLE__) extern "C" __declspec(dllimport) void* __stdcall SetCursor(void* cursor); +#endif typedef ServerBrowserRecord CachedRecord; struct RecordCache { @@ -1784,7 +1888,7 @@ static gameswf::as_object_interface* videoSettingsLocalisedString(const renddx9a { (void) h->getLocalizedString(wide, key); // +0xA8 text = gameswf::create_dice_string_object(nullptr, 0); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } return text; } @@ -1832,7 +1936,11 @@ static void markCustomVideoScheme() static void setVideoIntOwnerFirst(const gameswf::fn_call& fn, VsIntSetter setter) { IVideoSettings* vs = videoSettings(); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (vs->*setter)(value); markCustomVideoScheme(); } @@ -1843,7 +1951,11 @@ static void setVideoIntOwnerFirst(const gameswf::fn_call& fn, VsIntSetter setter // kept per row. No result. static void setVideoIntArgumentFirst(const gameswf::fn_call& fn, VsIntSetter setter) { +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (videoSettings()->*setter)(value); markCustomVideoScheme(); } @@ -2077,6 +2189,9 @@ static void listLeaderboardPlayers(const gameswf::fn_call& fn, ListResult& r, Li static void listLeaderboardTop(const gameswf::fn_call& fn, ListResult& r, ListHost h); static void listMapList(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end); static void listGameModes(const gameswf::fn_call& fn, ListResult& r, ListHost h, int start, int end, bool withAll); +// The HapticSettings page's two selectors, defined with the HapticSettings rows (SwiffNativesRecovered.inl). +static void listHapticWeaponSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h); +static void listHapticThresholdSelect(const gameswf::fn_call& fn, ListResult& r, ListHost h); void as_general_getListEntries(const gameswf::fn_call& fn) { @@ -2112,8 +2227,16 @@ void as_general_getListEntries(const gameswf::fn_call& fn) tok[t++] = tu_string(b, (int)(c - b)); } } +#if defined(__APPLE__) + const int start = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int start = (int) fn.arg(1).to_number(); +#endif +#if defined(__APPLE__) + const int count = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int count = (int) fn.arg(2).to_number(); +#endif const int end = (count == -1) ? start + 99999 : start + count; ListResult r; @@ -2224,7 +2347,7 @@ void as_general_getListEntries(const gameswf::fn_call& fn) int total = 0; int greyed = 0, emittedRows = 0; // diagnostic only, reported under the AS log below int gateNoMod = 0, gateVersion = 0, gateNoMap = 0; - vc71::string firstMod, firstMap; // retained internal diagnostic storage + std::string firstMod, firstMap; // retained internal diagnostic storage IModInfo* modInfo = static_cast(h->getModInfo()); // +0x120 const int count = serverRecordCount(h->getServerList(std::string("inet"))->getRecords()); total = count; @@ -2391,6 +2514,111 @@ void as_general_getListEntries(const gameswf::fn_call& fn) fn.result->set_as_object_interface(r.arr.get_ptr()); return; } + // SwiffPlayer.dll 0x10023EBF..0x10024B00 (favourites pass, then the "history" pass at + // 0x10024AA2): row keys, icon columns and the "-"/"*" columns in the order shown here. + if (tok[0] == "favouriteServers") + { + IGeneralSettings* settings = static_cast( + classManager->getSingleton(renddx9abi::HostString("GeneralSettings"))); + IModInfo* modInfo = static_cast(h->getModInfo()); + r.begin(); + unsigned int emitted = 0; + unsigned int total = 0; + const unsigned int window = static_cast(end - start); + // The history pass deliberately starts at zero, even when start exceeds + // the favourites count. Both passes share the emitted-row budget. + for (int pass = 0; pass != 2; ++pass) + { + const bool favourite = pass == 0; + const char* kind = favourite ? "favourites" : "history"; + const unsigned int count = serverRecordCount(h->getServerList(std::string(kind))->getRecords()); + total += count; + for (unsigned int index = favourite ? static_cast(start) : 0; + index < count && emitted < window; ++index) + { + const ServerBrowserRecordList* records = h->getServerList(std::string(kind))->getRecords(); + if (records->records.empty()) continue; + const ServerBrowserEntry& e = records->records[index].entry; + const IModInfo::Mod* mod = modInfo->getModFromName(e.gameVariant); + const std::string mapPath = modInfo->getMapPathFromMap(mod, e.mapName); + const IModInfo::Map* knownMap = modInfo->findMapFromMod(mod, mapPath); + char id[128]; + ::_snprintf(id, sizeof(id) - 1, "%s %d %d", e.address.c_str(), e.queryPort, e.hostPort); + id[sizeof(id) - 1] = 0; + r.beginRowStr(id); + r.setString("ip", e.address.c_str()); + r.setInt("port", e.queryPort); + r.setInt("pb", e.antiCheat ? 1 : 0); + const std::string ourVersion = h->getVersionStringValue(); + const bool xpack1 = h->getExpansionPack(e.gameVariant) == 1; + const bool xpack2 = h->getExpansionPack(e.gameVariant) == 2; + if (e.maxPlayers <= 0 || (!mod && !xpack1 && !xpack2) + || (mod && (e.gameVersion != ourVersion || !knownMap))) + r.setInt("disabled", 1); + r.setInt("xpack1", xpack1 ? 1 : 0); + r.setInt("xpack2", xpack2 ? 1 : 0); + r.setInt("plasma", e.plasma ? 1 : 0); + if (!knownMap) r.setInt("mapnotinstalled", 1); + if (knownMap) + r.setString("mapName", modInfo->getMapPathFromMap(mod, e.mapName).c_str()); + else + r.setString("mapName", " "); + r.setInt("mapMode", e.maxPlayers); + r.setString("gameMode", e.gameMode.c_str()); + r.setInt("maxPlayers", e.maxPlayers); + r.setInt("mapSize", e.mapSize); + r.pushNarrow(e.fps >= 30.0f ? "images/serverIcons/Serverload_green.png" + : e.fps >= 20.0f ? "images/serverIcons/Serverload_orange.png" + : "images/serverIcons/Serverload_red.png"); + r.pushNarrow(serverOsIcon(e.os.c_str())); + if (mod) + { + const std::string icon = "#" + mod->path + "/" + mod->icon; + r.pushNarrow(icon.c_str()); + } + else r.pushNarrow("images/serverIcons/modNotInstalled.png"); + r.pushNarrow(e.ranked ? "images/serverIcons/ranked.png" : ""); + r.pushNarrow(e.voip ? "images/serverIcons/battlecom.png" : ""); + r.pushNarrow(e.antiCheat ? "images/serverIcons/punkbuster.png" : ""); + r.pushNarrow(e.pure ? "images/serverIcons/PureContent.png" : ""); + r.pushNarrow(e.password ? "images/serverIcons/passwordenabled.png" : ""); + const GeneralServerEntry* saved = favourite + ? settings->findFavouriteServer(e.address, e.queryPort) + : settings->findServerHistory(e.address, e.queryPort); + if (e.maxPlayers == 0) + { + // An unanswered record without a saved entry retains only + // its icon columns, as in the shipped menu bridge. + if (saved) + { + r.pushNarrow(saved->name.c_str()); + r.pushNarrow("-"); r.pushNarrow("-"); r.pushNarrow("-"); + r.pushNarrow(favourite ? "*" : "-"); + } + } + else + { + r.pushNarrow(saved ? saved->name.c_str() : e.hostName.c_str()); + r.pushInt(e.ping); + char players[64]; + ::_snprintf(players, sizeof(players) - 1, "%d/%d (%d)", + e.numPlayers, e.maxPlayers, e.reservedSlots); + players[sizeof(players) - 1] = 0; + r.pushNarrow(players); + r.pushNarrow(e.mapName.c_str()); + if (favourite) r.pushNarrow("*"); + else if (saved) r.pushInt(saved->lastPlayed); + else r.pushNarrow("-"); + } + r.setInt("password", e.password ? 1 : 0); + if (favourite) r.setInt("isFavourite", 1); + ++emitted; + } + } + r.setTotalCount(total); + fn.result->set_as_object_interface(r.arr.get_ptr()); + return; + } if (tok[0] == "installedMaps") { // Lists current-mod maps supporting the selected mode, one row per map size. @@ -3001,6 +3229,9 @@ void as_general_getListEntries(const gameswf::fn_call& fn) // Local-server game modes and browser-filter game modes with an additional All choice. if (tok[0] == "gmodes") { listGameModes(fn, r, h, start, end, false); return; } if (tok[0] == "sfgmodes") { listGameModes(fn, r, h, start, end, true); return; } + // The HapticSettings selectors (10030F66 "weaponselect", 10031374 "thresholdselect"); they read no window. + if (tok[0] == "weaponselect") { listHapticWeaponSelect(fn, r, h); return; } + if (tok[0] == "thresholdselect") { listHapticThresholdSelect(fn, r, h); return; } if (tok[0] == "cmapbg" || tok[0] == "cmapgm" || tok[0] == "buddiesOnline" || tok[0] == "buddies" || tok[0] == "buddyRequests" || tok[0] == "buddyMessages" || tok[0] == "gamespyNicknameSuggestions") { @@ -3021,13 +3252,12 @@ void as_general_getListEntries(const gameswf::fn_call& fn) // The callback reads no arguments and leaves the AS result untouched. struct SwiffHostRequest { - int id; - int alloc; - vc71::string* first; - vc71::string* last; - vc71::string* end; + int id; // +0 + std::vector args; // +4 (retail: a VC7.1 vector of strings) }; +#if !defined(__APPLE__) extern "C" __declspec(dllimport) void* __stdcall SetCursor(void* cursor); +#endif void as_profile_logout(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_profile_logout"); @@ -3051,6 +3281,7 @@ void as_profile_logout(const gameswf::fn_call& fn) } } + void as_logic_disconnectGame(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_disconnectGame"); @@ -3139,7 +3370,9 @@ void as_logic_joinCommandlineServer(const gameswf::fn_call& fn) } // sub_1004D450 - dice.bf2.Logic.isCapsLockPressed: GetKeyState(VK_CAPITAL) & 1, a boolean. No host. +#if !defined(__APPLE__) extern "C" __declspec(dllimport) short __stdcall GetKeyState(int vkey); +#endif void as_logic_isCapsLockPressed(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_isCapsLockPressed"); @@ -3200,6 +3433,32 @@ void as_logic_setStorageString(const gameswf::fn_call& fn) h->setStorageString(a, b); } +// sub_1004D170 (registered at 0x1004E3E3 as "eraseStorageString", string 0x100DD020): fetch the +// player's host (dword_100F2F20 +0x5C), construct a string from arg 0 (no nargs guard; the +// shipped argument index check is the debug int3), call host +0x240, destroy it. No AS result. +void as_logic_eraseStorageString(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_eraseStorageString"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + renddx9abi::HostString key(fn.arg(0).to_string()); + h->removeStorageString(key); // +0x240 +} + +// sub_1004D5B0 (registered at 0x1004E43B as "getDefaultLevel", string 0x100DD010): fetch the +// player's host, construct an empty string, call host +0xA4 getSpStartupMap(out) and ignore its +// Boolean, then publish the string as the AS result (as_value type 1 built by sub_10007680 from +// c_str()). mainMenu.swf's createDefaultTraining (the welcome page's PLAY SINGLEPLAYER) passes this +// value to Multiplay.addMapToMapList; without the binding the call answered undefined, the empty +// path added no entry, and createServer's hostServer posted "nomapsselected". +void as_logic_getDefaultLevel(const gameswf::fn_call& fn) +{ + SWF_AS_TRACE("as_logic_getDefaultLevel"); + ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); + renddx9abi::HostString out; // the host assigns to this already constructed string + (void) h->getSpStartupMap(out); // +0xA4 + fn.result->set_tu_string(tu_string(out.c_str())); +} + } // anonymous namespace // Queues the named engine sound. Host refusal publishes numeric -1; success leaves @@ -3360,7 +3619,11 @@ void as_videosettings_getViewDistanceScale(const gameswf::fn_call& fn) void as_videosettings_setVideoOptionScheme(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_videosettings_setVideoOptionScheme"); +#if defined(__APPLE__) + const int scheme = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int scheme = static_cast(fn.arg(0).to_number()); +#endif videoSettings()->setVideoOptionScheme(scheme); // +0xDC videoSettings()->applyVideoOptionScheme(0); // +0x30 } @@ -3496,6 +3759,7 @@ void as_logic_enableScroller(const gameswf::fn_call& fn) h->setFlagF10(fn.arg(0).to_bool()); } + // Stops updates on the current browser list when it exists. Requires player/host. // Destroys the list-kind string before stopping; writes no AS result. void as_multiplay_stopBrowser(const gameswf::fn_call& fn) @@ -3598,7 +3862,11 @@ void as_profile_loginOnlineAccount(const gameswf::fn_call& fn) bool result = false; if (h->checkDisc()) { +#if defined(__APPLE__) + const int number = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int number = (int) fn.arg(0).to_number(); +#endif const std::string password = fn.arg(1).to_string(); const bool remember = fn.arg(2).to_bool(); if (lpm->login(number, std::string(""), password)) @@ -3699,7 +3967,11 @@ void as_profile_loginOfflineAccount(const gameswf::fn_call& fn) (void) g_swiffPlayerInstance->getSwiffHost(); ILocalProfileManager* lpm = static_cast( classManager->getSingleton(renddx9abi::HostString("LocalProfileManager"))); +#if defined(__APPLE__) + const int number = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int number = (int) fn.arg(0).to_number(); +#endif const std::string password(""); const std::string name(""); fn.result->set_bool(lpm->login(number, name, password)); @@ -3720,7 +3992,7 @@ void as_profile_getFirstCountry(const gameswf::fn_call& fn) std::wstring w; h->getLocalizedString(w, key); tu_string utf8; - tu_string::encode_utf8_from_wchar(&utf8, reinterpret_cast(w.c_str())); + tu_string::encode_utf8_from_wchar(&utf8, BF2_DICE_UTF16(w.c_str())); fn.result->set_tu_string(utf8); } @@ -3745,7 +4017,11 @@ void as_multiplay_setConnectToIpPort(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setConnectToIpPort"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + h->setConnectToIpPort(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x308, truncated +#else h->setConnectToIpPort(static_cast(fn.arg(0).to_number())); // +0x308, truncated +#endif } void as_multiplay_setConnectToIpHost(const gameswf::fn_call& fn) @@ -3768,7 +4044,9 @@ static int hostPlayerId() // The 20-byte rank-change record SwiffHost +644(playerId, record&) fills: {time(now), 0, rank, // promoted, demoted} as sub_10059A80/sub_10059C40 lay it out on their stacks. struct RankChangeRecord { int now; int zero; int rank; int promoted; int demoted; }; +#if !defined(__APPLE__) extern "C" __int64 __cdecl _time64(__int64*); +#endif // ISwiffHost +0x284 (getRankInfo). The native host's IPlayerRankInfo::RankInfo // {timestamp, profileId, rank, change, decrease} is the same five ints in the same order; a record @@ -3784,7 +4062,7 @@ static bool hostRankInfo(void* h, int playerId, RankChangeRecord& r) // ISwiffHost supplies the rank's locale key ("-" when unknown) and next promotion/demotion rank. // Copy the native string result into the retained internal key storage. -static void hostRankKey(void* h, int rankId, vc71::string& key) +static void hostRankKey(void* h, int rankId, std::string& key) { if (!h) return; key = static_cast(h)->getRankName(rankId).c_str(); @@ -3797,7 +4075,7 @@ static int hostNextRank(void* h, int rankId) // Locale.getString through SwiffHost +168 (getLocalizedString) into a wide string - defined with the // PlayerStats favourites below, used by every localising row. -static void hostLocaliseKey(void* h, const vc71::string& key, vc71::wstring& out); +static void hostLocaliseKey(void* h, const std::string& key, std::wstring& out); // sub_10059A80 - dice.bf2.PlayerStats.getPromotedRank(): the record's rank when the host filled it // and promoted >= 1, else 0. @@ -3833,14 +4111,22 @@ void as_playerstats_getNextPromotionRank(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getNextPromotionRank"); void* h = asHost(); +#if defined(__APPLE__) + const int rank = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int rank = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; +#endif fn.result->set_double(h ? (double) hostNextRank(h, rank) : 0.0); } void as_playerstats_getNextDemomotionRank(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getNextDemomotionRank"); void* h = asHost(); +#if defined(__APPLE__) + const int rank = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int rank = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; +#endif fn.result->set_double(h ? (double) hostNextRank(h, rank) : 0.0); } @@ -3851,130 +4137,159 @@ void as_playerstats_getRankString(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getRankString"); void* h = asHost(); +#if defined(__APPLE__) + const int rank = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int rank = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; - vc71::wstring text; +#endif + std::wstring text; if (h) { - vc71::string key; + std::string key; hostRankKey(h, rank, key); hostLocaliseKey(h, key, text); } fn.result->set_as_object_interface( - gameswf::create_dice_string_object(reinterpret_cast(text.c_str()), (int) text.size())); + gameswf::create_dice_string_object(BF2_DICE_UTF16(text.c_str()), (int) text.size())); } -// The player stats record SwiffHost +432(playerId, record&) fills: 3720 bytes, laid out by the -// shipped ctor/dtor pair sub_10020A80 / sub_10020E80 - VC7.1 std::strings at the byte offsets below -// (14 singles, 19 pairs at 528+68k {+0,+40}, 10 at 1820+40k, 7 pairs at 2224+64k {+0,+36}, 13 pairs -// at 2676+68k {+0,+36}, 4 singles), a vector at 3688 (allocator word, first/last/end zeroed), the -// creation time at 3704, every other word zero. Only what the callers read is interpreted: the rank -// id at +160 (getCurrentRankId). The vector at 3688 holds 40-byte elements with a std::string at -// +12 (sub_1001F210 destroys each, then bf_frees the buffer). +// The player stats record SwiffHost +432(playerId, record&) fills, laid out by the shipped +// ctor/dtor pair sub_10020A80 / sub_10020E80 (the +N comments are the retail offsets of its +// 3720-byte VC7.1 layout). Construction zeroes every int, leaves every string empty and stamps the +// creation time. Only what the callers read is interpreted: the rank id at +160 +// (getCurrentRankId), the rows the playerStats lists show, the favourites and the opponent/victim +// pairs. The map rows (+3688) are 40-byte retail elements with a string at +12. struct PlayerStatsRecord { - enum { SIZE = 3720 }; - unsigned char bytes[SIZE]; - static void offsets(int* out, int& n) + struct Weapon // 68 bytes in retail { - static const int singles[] = { 4, 44, 72, 192, 220, 248, 276, 304, 344, 372, 400, 428, 456, 492, 3564, 3596, 3628, 3660 }; - n = 0; - for (int i = 0; i < (int) (sizeof(singles) / sizeof(singles[0])); ++i) out[n++] = singles[i]; - for (int k = 0; k < 19; ++k) { out[n++] = 528 + 68 * k; out[n++] = 528 + 68 * k + 40; } - for (int k = 0; k < 10; ++k) { out[n++] = 1820 + 40 * k; } - for (int k = 0; k < 7; ++k) { out[n++] = 2224 + 64 * k; out[n++] = 2224 + 64 * k + 36; } - for (int k = 0; k < 13; ++k) { out[n++] = 2676 + 68 * k; out[n++] = 2676 + 68 * k + 36; } - } - PlayerStatsRecord() + std::string time; // +0 + int kills = 0; // +28 + int deaths = 0; // +32 + int accuracy = 0; // +36 + std::string kd; // +40 + }; + struct Army // 40 bytes in retail { - ::memset(bytes, 0, SIZE); - int off[128]; int n; offsets(off, n); - for (int i = 0; i < n; ++i) new (bytes + off[i]) vc71::string(""); - *reinterpret_cast(bytes + 3704) = (int) _time64(0); - } - ~PlayerStatsRecord() + std::string time; // +0 + int wins = 0; // +28 + int losses = 0; // +32 + int bestRound = 0; // +36 + }; + struct Kit // 64 bytes in retail { - int off[128]; int n; offsets(off, n); - for (int i = n - 1; i >= 0; --i) reinterpret_cast(bytes + off[i])->~string(); - char* first = *reinterpret_cast(bytes + 3692); - char* last = *reinterpret_cast(bytes + 3696); - if (first) - { - for (char* e = first; e != last; e += 40) reinterpret_cast(e + 12)->~string(); - ::renddx9abi::engineFree(first); - } - } + std::string time; // +0 + int kills = 0; // +28 + int deaths = 0; // +32 + std::string kd; // +36 + }; + struct Vehicle // 68 bytes in retail + { + std::string time; // +0 + int kills = 0; // +28 + int deaths = 0; // +32 + std::string kd; // +36 + int roadKills = 0; // +64 + }; + struct MapRow // 40 bytes in retail + { + int id = 0; // +0 + int wins = 0; // +4 + int losses = 0; // +8 + std::string time; // +12 + }; + + int playerId = 0; // +0 + std::string nick; // +4 + int scor = 0, wins = 0, loss = 0; // +32 +36 +40 + std::string jond, lbtl; // +44 +72 + int twsc = 0, cpcp = 0, cacp = 0, dfcp = 0, kila = 0; // +100..+116 + int heal = 0, rviv = 0, rsup = 0, rpar = 0, tgte = 0; // +120..+136 + int dkas_dsab = 0; // +140 + int unknown144[3] = { 0, 0, 0 }; // +144..+152 no reader + int cdsc = 0, rank = 0; // +156 +160 + int unknown164 = 0; // +164 no reader + int cmsc = 0, kick = 0, ban = 0, kill = 0, deth = 0, suic = 0; // +168..+188 + std::string ospm, klpm, dtpm, klpr, dtpr; // +192..+304 + int bksk = 0, wdsk = 0, bbrs = 0; // +332..+340 + std::string tcdr, tsql, tsqm, tlwf; // +344..+428 + std::string mvns; // +456 + int mvks = 0, mvrs = 0; // +484 +488 + std::string vmns; // +492 + int vmks = 0, vmrs = 0; // +520 +524 + Weapon weapons[19]; // +528 + Army armies[10]; // +1820 + int osaa = 0; // +2220 + Kit kits[7]; // +2224 + int vrk = 0; // +2672 + Vehicle vehicles[13]; // +2676 + int fkit = 0; std::string fkitTime; // +3560 +3564 + int fveh = 0; std::string fvehTime; // +3592 +3596 + int fwea = 0; std::string fweaTime; // +3624 +3628 + int fmap = 0; std::string fmapTime; // +3656 +3660 + std::vector maps; // +3688 + int fetchedAt; // +3704 + int de6 = 0, de7 = 0, de8 = 0; // +3708..+3716 + + PlayerStatsRecord() : fetchedAt((int) _time64(0)) {} }; -// The native host's typed SwiffPlayerStatsRecord (Menu/ISwiffHost.h) laid out into the VC7.1 byte -// image the rows below read: the shipped offsets, each string assigned into the image's -// pre-constructed vc71::string. The map rows go into the image's vector at +3688 (40-byte -// {id, wins, losses, time} elements on the engine heap, which the image's destructor frees) since -// getListEntries("playerStats 16") walks them. +// The native host's typed SwiffPlayerStatsRecord (Menu/ISwiffHost.h) copied into the record the +// rows below read, each string assigned from its c_str(). The map rows go into the record's +// vector since getListEntries("playerStats 16") walks them. static void statsRecordToImage(const dice::hfe::SwiffPlayerStatsRecord& r, PlayerStatsRecord& img) { - unsigned char* b = img.bytes; - struct W - { - static void i(unsigned char* b, int off, int v) { *reinterpret_cast(b + off) = v; } - static void s(unsigned char* b, int off, const std::string& v) { *reinterpret_cast(b + off) = v.c_str(); } - }; - W::i(b, 0, r.playerId); W::s(b, 4, r.nick); W::i(b, 32, r.scor); W::i(b, 36, r.wins); W::i(b, 40, r.loss); - W::s(b, 44, r.jond); W::s(b, 72, r.lbtl); - W::i(b, 100, r.twsc); W::i(b, 104, r.cpcp); W::i(b, 108, r.cacp); W::i(b, 112, r.dfcp); W::i(b, 116, r.kila); - W::i(b, 120, r.heal); W::i(b, 124, r.rviv); W::i(b, 128, r.rsup); W::i(b, 132, r.rpar); W::i(b, 136, r.tgte); - W::i(b, 140, r.dkas_dsab); W::i(b, 156, r.cdsc); W::i(b, 160, r.rank); W::i(b, 168, r.cmsc); W::i(b, 172, r.kick); - W::i(b, 176, r.ban); W::i(b, 180, r.kill); W::i(b, 184, r.deth); W::i(b, 188, r.suic); - W::s(b, 192, r.ospm); W::s(b, 220, r.klpm); W::s(b, 248, r.dtpm); W::s(b, 276, r.klpr); W::s(b, 304, r.dtpr); - W::i(b, 332, r.bksk); W::i(b, 336, r.wdsk); W::i(b, 340, r.bbrs); - W::s(b, 344, r.tcdr); W::s(b, 372, r.tsql); W::s(b, 400, r.tsqm); W::s(b, 428, r.tlwf); - W::s(b, 456, r.mvns); W::i(b, 484, r.mvks); W::i(b, 488, r.mvrs); - W::s(b, 492, r.vmns); W::i(b, 520, r.vmks); W::i(b, 524, r.vmrs); + img.playerId = r.playerId; img.nick = r.nick.c_str(); img.scor = r.scor; img.wins = r.wins; img.loss = r.loss; + img.jond = r.jond.c_str(); img.lbtl = r.lbtl.c_str(); + img.twsc = r.twsc; img.cpcp = r.cpcp; img.cacp = r.cacp; img.dfcp = r.dfcp; img.kila = r.kila; + img.heal = r.heal; img.rviv = r.rviv; img.rsup = r.rsup; img.rpar = r.rpar; img.tgte = r.tgte; + img.dkas_dsab = r.dkas_dsab; img.cdsc = r.cdsc; img.rank = r.rank; img.cmsc = r.cmsc; img.kick = r.kick; + img.ban = r.ban; img.kill = r.kill; img.deth = r.deth; img.suic = r.suic; + img.ospm = r.ospm.c_str(); img.klpm = r.klpm.c_str(); img.dtpm = r.dtpm.c_str(); img.klpr = r.klpr.c_str(); img.dtpr = r.dtpr.c_str(); + img.bksk = r.bksk; img.wdsk = r.wdsk; img.bbrs = r.bbrs; + img.tcdr = r.tcdr.c_str(); img.tsql = r.tsql.c_str(); img.tsqm = r.tsqm.c_str(); img.tlwf = r.tlwf.c_str(); + img.mvns = r.mvns.c_str(); img.mvks = r.mvks; img.mvrs = r.mvrs; + img.vmns = r.vmns.c_str(); img.vmks = r.vmks; img.vmrs = r.vmrs; for (int k = 0; k < 19; k++) { - const int o = 528 + 68 * k; - W::s(b, o, r.weapons[k].time); W::i(b, o + 28, r.weapons[k].kills); W::i(b, o + 32, r.weapons[k].deaths); - W::i(b, o + 36, r.weapons[k].accuracy); W::s(b, o + 40, r.weapons[k].kd); + PlayerStatsRecord::Weapon& o = img.weapons[k]; + o.time = r.weapons[k].time.c_str(); o.kills = r.weapons[k].kills; o.deaths = r.weapons[k].deaths; + o.accuracy = r.weapons[k].accuracy; o.kd = r.weapons[k].kd.c_str(); } for (int k = 0; k < 10; k++) { - const int o = 1820 + 40 * k; - W::s(b, o, r.armies[k].time); W::i(b, o + 28, r.armies[k].wins); W::i(b, o + 32, r.armies[k].losses); - W::i(b, o + 36, r.armies[k].bestRound); + PlayerStatsRecord::Army& o = img.armies[k]; + o.time = r.armies[k].time.c_str(); o.wins = r.armies[k].wins; o.losses = r.armies[k].losses; + o.bestRound = r.armies[k].bestRound; } - W::i(b, 2220, r.osaa); + img.osaa = r.osaa; for (int k = 0; k < 7; k++) { - const int o = 2224 + 64 * k; - W::s(b, o, r.kits[k].time); W::i(b, o + 28, r.kits[k].kills); W::i(b, o + 32, r.kits[k].deaths); - W::s(b, o + 36, r.kits[k].kd); + PlayerStatsRecord::Kit& o = img.kits[k]; + o.time = r.kits[k].time.c_str(); o.kills = r.kits[k].kills; o.deaths = r.kits[k].deaths; + o.kd = r.kits[k].kd.c_str(); } - W::i(b, 2672, r.vrk); + img.vrk = r.vrk; for (int k = 0; k < 13; k++) { - const int o = 2676 + 68 * k; - W::s(b, o, r.vehicles[k].time); W::i(b, o + 28, r.vehicles[k].kills); W::i(b, o + 32, r.vehicles[k].deaths); - W::s(b, o + 36, r.vehicles[k].kd); W::i(b, o + 64, r.vehicles[k].roadKills); + PlayerStatsRecord::Vehicle& o = img.vehicles[k]; + o.time = r.vehicles[k].time.c_str(); o.kills = r.vehicles[k].kills; o.deaths = r.vehicles[k].deaths; + o.kd = r.vehicles[k].kd.c_str(); o.roadKills = r.vehicles[k].roadKills; } - W::i(b, 3560, r.fkit); W::s(b, 3564, r.fkitTime); W::i(b, 3592, r.fveh); W::s(b, 3596, r.fvehTime); - W::i(b, 3624, r.fwea); W::s(b, 3628, r.fweaTime); W::i(b, 3656, r.fmap); W::s(b, 3660, r.fmapTime); - W::i(b, 3704, (int) r.fetchedAt); W::i(b, 3708, r.de6); W::i(b, 3712, r.de7); W::i(b, 3716, r.de8); + img.fkit = r.fkit; img.fkitTime = r.fkitTime.c_str(); img.fveh = r.fveh; img.fvehTime = r.fvehTime.c_str(); + img.fwea = r.fwea; img.fweaTime = r.fweaTime.c_str(); img.fmap = r.fmap; img.fmapTime = r.fmapTime.c_str(); + img.fetchedAt = (int) r.fetchedAt; img.de6 = r.de6; img.de7 = r.de7; img.de8 = r.de8; const unsigned int maps = static_cast(r.maps.size()); if (maps) { - char* first = static_cast(::renddx9abi::engineAlloc(40 * maps)); - if (first) + img.maps.resize(maps); + for (unsigned int k = 0; k < maps; ++k) { - for (unsigned int k = 0; k < maps; ++k) - { - char* e = first + 40 * k; - *reinterpret_cast(e) = r.maps[k].id; - *reinterpret_cast(e + 4) = r.maps[k].wins; - *reinterpret_cast(e + 8) = r.maps[k].losses; - new (e + 12) vc71::string(r.maps[k].time.c_str()); - } - *reinterpret_cast(b + 3692) = first; // {alloc, first, last, end} - *reinterpret_cast(b + 3696) = first + 40 * maps; - *reinterpret_cast(b + 3700) = first + 40 * maps; + PlayerStatsRecord::MapRow& e = img.maps[k]; + e.id = r.maps[k].id; + e.wins = r.maps[k].wins; + e.losses = r.maps[k].losses; + e.time = r.maps[k].time.c_str(); } } } @@ -4008,26 +4323,16 @@ void as_profile_getCurrentRankId(const gameswf::fn_call& fn) const int id = hostSelectedPlayerId(h); PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) hostFillStatsRecord(h, id, *rec); - v = (double) *reinterpret_cast(rec->bytes + 160); + v = (double) rec->rank; delete rec; } fn.result->set_double(v); } -// Retained original message layout: {type, code, text}, with a VC7.1 string. +// Retained original message record: {type, code, text}. // Shipped getLastType/getLastText/getLastCode constructed it before the host filled it. // Active native callbacks exchange the typed SwiffHostMessage instead. -struct HostMessage { int type; int code; vc71::string text; }; - -// The VC7.1 layout of dice::hfe::ProfileInformation (Game/ProfileManager.h): the profile id, six -// 28-byte strings and four ints, 188 bytes - what BF2.exe 4A4AD0 reads and the shipped row builds -// on its stack (sub_1005CEC0 constructs it: id 0, six empty strings; sub_1005D0D0 destroys it). -struct Vc71ProfileInformation -{ - int profileId; - vc71::string nick, uniqueNick, email, firstName, lastName, country; - int sex, birthYear, birthMonth, birthDay; -}; +struct HostMessage { int type; int code; std::string text; }; // Creates an online account and local profile from the movie's twelve account arguments. // Requires initialized host/profile managers. A missing disc, password mismatch or failed @@ -4062,13 +4367,29 @@ void as_profile_createOnlineAccount(const gameswf::fn_call& fn) const bool remember = fn.arg(4).to_bool(); const std::string firstName = fn.arg(5).to_string(); const std::string lastName = fn.arg(6).to_string(); +#if defined(__APPLE__) + const int birthYear = bf2x87::toIntTruncate(fn.arg(7).to_number()); +#else const int birthYear = (int) fn.arg(7).to_number(); +#endif +#if defined(__APPLE__) + const int birthMonth = bf2x87::toIntTruncate(fn.arg(8).to_number()); +#else const int birthMonth = (int) fn.arg(8).to_number(); +#endif +#if defined(__APPLE__) + const int birthDay = bf2x87::toIntTruncate(fn.arg(9).to_number()); +#else const int birthDay = (int) fn.arg(9).to_number(); +#endif std::string country = fn.arg(10).to_string(); if (country == "none") country = "US"; +#if defined(__APPLE__) + const int sex = bf2x87::toIntTruncate(fn.arg(11).to_number()); +#else const int sex = (int) fn.arg(11).to_number(); +#endif if (password != confirm) { (void) h->postMessage(SwiffHostMessage(1, std::string("password does not match"), 0)); @@ -4177,8 +4498,16 @@ void as_messagehandler_raiseMessage(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_messagehandler_raiseMessage"); const std::string text(fn.arg(0).to_string()); +#if defined(__APPLE__) + const int type = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int type = static_cast(fn.arg(1).to_number()); +#endif +#if defined(__APPLE__) + const int code = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int code = static_cast(fn.arg(2).to_number()); +#endif SwiffHostMessage message; message.type = type; @@ -4191,7 +4520,7 @@ void as_messagehandler_raiseMessage(const gameswf::fn_call& fn) // dice.MessageHandler.getPunkBusterMessage(), and // promoted. The global player's host (unguarded), then its +0x354, and the text of the string it // answers published as a string - the VC7.1 small-buffer read `cmp [eax+18h],10h` is exactly -// vc71::string::c_str(). No argument, no check. +0x354 is the slot this tree calls getServerMod +// std::string::c_str(). No argument, no check. +0x354 is the slot this tree calls getServerMod // (BF2.exe 0x489060, `lea eax,[ecx+0F30h]`: the host's +0xF30 string, the one +0x350 assigns); // the shipped reads that same field as the PunkBuster message. [INFERRED] which name is the source's. void as_messagehandler_getPunkBusterMessage(const gameswf::fn_call& fn) @@ -4271,7 +4600,11 @@ void as_profile_setStatPlayer(const gameswf::fn_call& fn) if (pm && pmIsLoggedIn(pm)) { if (fn.nargs < 1) return; +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = (int) fn.arg(0).to_number(); +#endif static_cast(h)->setSelectedPlayerId(id); // +0x220 return; } @@ -4343,7 +4676,11 @@ void as_profile_isMyProfile(const gameswf::fn_call& fn) bool result = false; if (pm && pmIsLoggedIn(pm)) { +#if defined(__APPLE__) + const int id = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : 0; +#else const int id = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : 0; +#endif for (unsigned i = 0; ; ++i) { OnlineProfile* obj = static_cast(pm)->getCurrentProfile(); // +0x2C, re-fetched per step as shipped @@ -4360,7 +4697,7 @@ void as_profile_isMyProfile(const gameswf::fn_call& fn) // Looks up equipment case-insensitively across teams/kits and copies its localization keys. // Copy native host records into the retained internal key storage. -struct EquipmentKeys { vc71::string name, displayKey, descriptionKey; }; +struct EquipmentKeys { std::string name, displayKey, descriptionKey; }; static bool findEquipmentByName(const char* name, EquipmentKeys& out) { if (!classManager) return false; @@ -4393,11 +4730,11 @@ static bool findEquipmentByName(const char* name, EquipmentKeys& out) // sub_1005CF10 - the shared tail: Locale.getString through SwiffHost +168 (wide out-param, narrow // key) into a dice String object (narrow part empty, as shipped - ledger #38). -static void setLocalisedStringObject(const gameswf::fn_call& fn, const vc71::string& key) +static void setLocalisedStringObject(const gameswf::fn_call& fn, const std::string& key) { - vc71::wstring out; + std::wstring out; hostLocaliseKey(asHost(), key, out); - fn.result->set_as_object_interface(gameswf::create_dice_string_object(reinterpret_cast(out.c_str()), (int) out.size())); + fn.result->set_as_object_interface(gameswf::create_dice_string_object(BF2_DICE_UTF16(out.c_str()), (int) out.size())); } // sub_1005F700 - dice.bf2.Profile.getEquipmentName(name): the equipment record's localised display @@ -4406,7 +4743,7 @@ static void setLocalisedStringObject(const gameswf::fn_call& fn, const vc71::str void as_profile_getEquipmentName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_profile_getEquipmentName"); - vc71::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); + std::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); EquipmentKeys rec; if (!findEquipmentByName(name.c_str(), rec)) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } setLocalisedStringObject(fn, rec.displayKey.size() ? rec.displayKey : rec.name); @@ -4417,7 +4754,7 @@ void as_profile_getEquipmentName(const gameswf::fn_call& fn) void as_profile_getEquipmentDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_profile_getEquipmentDescription"); - vc71::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); + std::string name(fn.nargs >= 1 ? fn.arg(0).to_string() : ""); EquipmentKeys rec; if (!findEquipmentByName(name.c_str(), rec)) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } setLocalisedStringObject(fn, rec.descriptionKey); @@ -4432,13 +4769,13 @@ void as_multiplay_getBrowser(const gameswf::fn_call& fn) fn.result->set_tu_string(tu_string(kind.c_str())); } -// Keep the original unlock record fields alongside the native host's typed items. +// The original unlock record fields with the native host's typed items as its vector. // The original 32-byte record held {time(now), int, count, int, a VC7.1 vector}; shipped callers // zeroed it, stamped time(), and freed its vector buffer afterwards (sub_1006DBA0 = bf_free). struct UnlockRecord { - int now; int a; int count; int b; Vc71Vector unlocks; - std::vector items; // the typed host's {id, status} list; the legacy field stays empty + int now; int a; int count; int b; + std::vector items; // +16: the typed host's {id, status} list }; // Read the typed host's unlock entries. @@ -4452,8 +4789,7 @@ static int unlockIdAt(const UnlockRecord& rec, int i) } static void releaseUnlockRecord(UnlockRecord& rec) { - if (rec.unlocks.first) ::renddx9abi::engineFree(rec.unlocks.first); - rec.unlocks.first = rec.unlocks.last = rec.unlocks.end = 0; + rec.items.clear(); } // ISwiffHost +0x1C4 (getUnlocks): the ProfileManager's profile id keys the query; @@ -4463,7 +4799,6 @@ static void fillUnlockRecord(void* h, UnlockRecord& rec) { const int id = hostPlayerId(); rec.now = (int) ::time(0); rec.a = 0; rec.count = 0; rec.b = 0; - rec.unlocks.alloc = 0; rec.unlocks.first = rec.unlocks.last = rec.unlocks.end = 0; if (!h) return; IPlayerUnlocks::UnlockCache cache; cache.field0 = rec.now; cache.field4 = 0; cache.available = 0; cache.selected = 0; @@ -4523,7 +4858,7 @@ static bool fetchPlayerStats(void* h, PlayerStatsRecord& rec) } // sub_100598E0 / sub_1005CF10 - Locale.getString through SwiffHost +168 into a wide string. -static void hostLocaliseKey(void* h, const vc71::string& key, vc71::wstring& out) +static void hostLocaliseKey(void* h, const std::string& key, std::wstring& out) { if (!h) return; std::wstring text; @@ -4535,7 +4870,7 @@ static void hostLocaliseKey(void* h, const vc71::string& key, vc71::wstring& out // (getMapFromGameSpyId): {std::string key at +0, std::string name at +28, ...} - getFavouriteId // reads the key, getFavouriteName localises the name. Native reads the typed IModInfo::Map // (path, name - the same two leading strings). -static bool hostMapStrings(void* h, int mapId, vc71::string& key, vc71::string& name) +static bool hostMapStrings(void* h, int mapId, std::string& key, std::string& name) { if (!h) return false; IBase* mm = static_cast(h)->getModInfo(); @@ -4558,29 +4893,32 @@ void as_playerstats_getFavouriteName(const gameswf::fn_call& fn) void* h = asHost(); PlayerStatsRecord* rec = new PlayerStatsRecord(); if (!fetchPlayerStats(h, *rec)) { fn.result->set_double(0.0); delete rec; return; } +#if defined(__APPLE__) + const int kind = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : -1; +#else const int kind = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : -1; - vc71::wstring text(L" "); +#endif + std::wstring text(L" "); bool haveText = true; - const unsigned char* b = rec->bytes; switch (kind) { - case 0: { const int i = *reinterpret_cast(b + 3560); if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, vc71::string(kFavouriteKitKeys[i]), text); break; } - case 1: { const int i = *reinterpret_cast(b + 3592); if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, vc71::string(kFavouriteVehicleKeys[i]), text); break; } - case 2: { const int i = *reinterpret_cast(b + 3624); if (i != -1 && i >= 0 && i < 13) hostLocaliseKey(h, vc71::string(kFavouriteWeaponKeys[i]), text); break; } + case 0: { const int i = rec->fkit; if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, std::string(kFavouriteKitKeys[i]), text); break; } + case 1: { const int i = rec->fveh; if (i != -1 && i >= 0 && i < 7) hostLocaliseKey(h, std::string(kFavouriteVehicleKeys[i]), text); break; } + case 2: { const int i = rec->fwea; if (i != -1 && i >= 0 && i < 13) hostLocaliseKey(h, std::string(kFavouriteWeaponKeys[i]), text); break; } case 3: { - const int i = *reinterpret_cast(b + 3656); + const int i = rec->fmap; if (i != -1) { - vc71::string key, mapName; + std::string key, mapName; if (hostMapStrings(h, i, key, mapName)) hostLocaliseKey(h, mapName, text); - else hostLocaliseKey(h, vc71::string("Unknown Map"), text); + else hostLocaliseKey(h, std::string("Unknown Map"), text); } break; } default: haveText = false; break; } delete rec; fn.result->set_as_object_interface(gameswf::create_dice_string_object( - haveText ? reinterpret_cast(text.c_str()) : 0, haveText ? (int) text.size() : 0)); + haveText ? BF2_DICE_UTF16(text.c_str()) : 0, haveText ? (int) text.size() : 0)); } // sub_1005B680 - dice.bf2.PlayerStats.getFavouriteId(kind): the favourite index printed with "%d" @@ -4592,16 +4930,19 @@ void as_playerstats_getFavouriteId(const gameswf::fn_call& fn) void* h = asHost(); PlayerStatsRecord* rec = new PlayerStatsRecord(); if (!fetchPlayerStats(h, *rec)) { fn.result->set_double(0.0); delete rec; return; } +#if defined(__APPLE__) + const int kind = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : -1; +#else const int kind = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : -1; - const unsigned char* b = rec->bytes; +#endif char num[32]; num[0] = 0; - vc71::string out(""); + std::string out(""); switch (kind) { - case 0: ::sprintf_s(num, "%d", *reinterpret_cast(b + 3560)); out = num; break; - case 1: ::sprintf_s(num, "%d", *reinterpret_cast(b + 3592)); out = num; break; - case 2: ::sprintf_s(num, "%d", *reinterpret_cast(b + 3624)); out = num; break; - case 3: { vc71::string key, mapName; if (hostMapStrings(h, *reinterpret_cast(b + 3656), key, mapName)) out = key; break; } + case 0: ::sprintf_s(num, "%d", rec->fkit); out = num; break; + case 1: ::sprintf_s(num, "%d", rec->fveh); out = num; break; + case 2: ::sprintf_s(num, "%d", rec->fwea); out = num; break; + case 3: { std::string key, mapName; if (hostMapStrings(h, rec->fmap, key, mapName)) out = key; break; } default: break; } delete rec; @@ -4616,17 +4957,22 @@ void as_playerstats_getFavouriteTime(const gameswf::fn_call& fn) void* h = asHost(); PlayerStatsRecord* rec = new PlayerStatsRecord(); if (!fetchPlayerStats(h, *rec)) { fn.result->set_double(0.0); delete rec; return; } +#if defined(__APPLE__) + const int kind = fn.nargs >= 1 ? bf2x87::toIntTruncate(fn.arg(0).to_number()) : -1; +#else const int kind = fn.nargs >= 1 ? (int) fn.arg(0).to_number() : -1; - static const int kTimeOffset[4] = { 3564, 3596, 3628, 3660 }; - vc71::string out(""); - if (kind >= 0 && kind < 4) out = *reinterpret_cast(rec->bytes + kTimeOffset[kind]); +#endif + static std::string PlayerStatsRecord::* const kTime[4] = { + &PlayerStatsRecord::fkitTime, &PlayerStatsRecord::fvehTime, &PlayerStatsRecord::fweaTime, &PlayerStatsRecord::fmapTime }; + std::string out(""); + if (kind >= 0 && kind < 4) out = rec->*kTime[kind]; delete rec; fn.result->set_tu_string(tu_string(out.c_str())); } // The shipped DLL's selected-unlock name (unk_100F8838, a std::string): written by selectFirstUnlock // and selectUnlock, read by getCurrentUnlockDescription and unlock. -static vc71::string s_selectedUnlock(""); +static std::string s_selectedUnlock(""); // bfhq statistics and equipment-list bindings for the selected statistics player. @@ -4637,8 +4983,8 @@ static vc71::string s_selectedUnlock(""); static int s_equipmentIndex = 0; // unk_100F88A8 / unk_100F888C - the equipment names Profile.setSelectedEquipment and // Profile.setSelectedUnlockEquipment store; "wpstats" / "wpunlockstats" read them. -static vc71::string s_selectedEquipment(""); -static vc71::string s_selectedUnlockEquipment(""); +static std::string s_selectedEquipment(""); +static std::string s_selectedUnlockEquipment(""); // sub_10017DC0 - dice.General.setEquipmentIndex(n): arg0 (the trapping accessor) to a number, // stored by `fistp` under a control word forced to chop (fnstcw / or ah,0Ch / fldcw at @@ -4646,7 +4992,11 @@ static vc71::string s_selectedUnlockEquipment(""); void as_general_setEquipmentIndex(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_general_setEquipmentIndex"); +#if defined(__APPLE__) + s_equipmentIndex = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else s_equipmentIndex = (int) fn.arg(0).to_number(); +#endif } // sub_1005D1C0 / sub_1005D1F0 - dice.bf2.Profile.setSelectedEquipment(name) and @@ -4672,9 +5022,6 @@ struct StatsTable { ListResult& r; ListHost h; - const unsigned char* b; - int i(int off) const { return *reinterpret_cast(b + off); } - const char* s(int off) const { return reinterpret_cast(b + off)->c_str(); } void label(int id, const char* key) { r.beginRow(id); @@ -4682,17 +5029,17 @@ struct StatsTable hostLocalise(h, key, w); r.pushWide(w.c_str(), (int) w.size()); } - void intRow(const char* key, int off) { label(0, key); r.pushInt(i(off)); } - void strRow(const char* key, int off) { label(0, key); r.pushNarrow(s(off)); } + void intRow(const char* key, int value) { label(0, key); r.pushInt(value); } + void strRow(const char* key, const std::string& value) { label(0, key); r.pushNarrow(value.c_str()); } // cases 12..15: the favourite index is the row id, "_%d" of it, then its time string. - void favouriteRow(const char* format, int indexOff, int timeOff) + void favouriteRow(const char* format, int index, const std::string& time) { - r.beginRow(i(indexOff)); + r.beginRow(index); char text[64]; - ::_snprintf(text, sizeof(text) - 1, format, i(indexOff)); + ::_snprintf(text, sizeof(text) - 1, format, index); text[sizeof(text) - 1] = 0; r.pushNarrow(text); - r.pushNarrow(s(timeOff)); + r.pushNarrow(time.c_str()); } }; @@ -4704,7 +5051,7 @@ const char* const kArmyFlags[10] = { // sub_10003580 - the shipped in-place lowercase "unlockeq" keys its name map with: the five Latin-1 // capitals Å Ä Ö Ü É become å ä ö ü é explicitly, every other byte goes through tolower() - which // under the "C" locale changes A-Z only. [INFERRED] the locale: BF2.exe sets none this DLL sees. -void shippedLowercase(const char* src, vc71::string& out) +void shippedLowercase(const char* src, std::string& out) { const unsigned int n = (unsigned int) ::strlen(src); char local[128]; @@ -4742,108 +5089,108 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost const int playerId = hostSelectedPlayerId(h); PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) hostFillStatsRecord(h, playerId, *rec); - StatsTable t = { r, h, rec->bytes }; + StatsTable t = { r, h }; int total = 0; switch (which) { case 0: // the overview - t.intRow("BFHQ_overallscore", 32); - t.intRow("BFHQ_teamworkscore", 100); - t.intRow("BFHQ_combatscore", 168); - t.intRow("BFHQ_commanderscore", 156); - t.strRow("BFHQ_enlisted", 44); - t.strRow("BFHQ_lastbattle", 72); + t.intRow("BFHQ_overallscore", rec->scor); // +32 + t.intRow("BFHQ_teamworkscore", rec->twsc); // +100 + t.intRow("BFHQ_combatscore", rec->cmsc); // +168 + t.intRow("BFHQ_commanderscore", rec->cdsc); // +156 + t.strRow("BFHQ_enlisted", rec->jond); // +44 + t.strRow("BFHQ_lastbattle", rec->lbtl); // +72 total = 6; break; case 1: // teamwork - t.intRow("BFHQ_teamworkscore", 100); - t.intRow("BFHQ_capturecp", 104); - t.intRow("BFHQ_capturecpassist", 108); - t.intRow("BFHQ_defendcp", 112); - t.intRow("BFHQ_killassist", 116); - t.intRow("BFHQ_heal", 120); - t.intRow("BFHQ_revive", 124); - t.intRow("BFHQ_support", 128); - t.intRow("BFHQ_repair", 132); - t.intRow("BFHQ_driverscore", 140); + t.intRow("BFHQ_teamworkscore", rec->twsc); // +100 + t.intRow("BFHQ_capturecp", rec->cpcp); // +104 + t.intRow("BFHQ_capturecpassist", rec->cacp); // +108 + t.intRow("BFHQ_defendcp", rec->dfcp); // +112 + t.intRow("BFHQ_killassist", rec->kila); // +116 + t.intRow("BFHQ_heal", rec->heal); // +120 + t.intRow("BFHQ_revive", rec->rviv); // +124 + t.intRow("BFHQ_support", rec->rsup); // +128 + t.intRow("BFHQ_repair", rec->rpar); // +132 + t.intRow("BFHQ_driverscore", rec->dkas_dsab); // +140 total = 10; break; case 2: // combat - t.intRow("BFHQ_combatscore", 168); - t.intRow("BFHQ_kills", 180); - t.intRow("BFHQ_deaths", 184); - t.strRow("BFHQ_scoreperminute", 192); - t.strRow("BFHQ_killsperminute", 220); - t.strRow("BFHQ_deathsperminute", 248); - t.strRow("BFHQ_killsperround", 276); - t.strRow("BFHQ_deathsperround", 304); - t.intRow("BFHQ_killstreak", 332); - t.intRow("BFHQ_deathstreak", 336); + t.intRow("BFHQ_combatscore", rec->cmsc); // +168 + t.intRow("BFHQ_kills", rec->kill); // +180 + t.intRow("BFHQ_deaths", rec->deth); // +184 + t.strRow("BFHQ_scoreperminute", rec->ospm); // +192 + t.strRow("BFHQ_killsperminute", rec->klpm); // +220 + t.strRow("BFHQ_deathsperminute", rec->dtpm); // +248 + t.strRow("BFHQ_killsperround", rec->klpr); // +276 + t.strRow("BFHQ_deathsperround", rec->dtpr); // +304 + t.intRow("BFHQ_killstreak", rec->bksk); // +332 + t.intRow("BFHQ_deathstreak", rec->wdsk); // +336 total = 10; break; case 3: // the personal panel - t.intRow("BFHQ_STATS_PERSONAL_globalscore", 32); - t.intRow("BFHQ_STATS_PERSONAL_wins", 36); - t.intRow("BFHQ_STATS_PERSONAL_loss", 40); - t.strRow("BFHQ_PROFILES_PLAYERINFO_enlisted", 44); - t.strRow("BFHQ_PROFILES_PLAYERINFO_lastbattle", 72); + t.intRow("BFHQ_STATS_PERSONAL_globalscore", rec->scor); // +32 + t.intRow("BFHQ_STATS_PERSONAL_wins", rec->wins); // +36 + t.intRow("BFHQ_STATS_PERSONAL_loss", rec->loss); // +40 + t.strRow("BFHQ_PROFILES_PLAYERINFO_enlisted", rec->jond); // +44 + t.strRow("BFHQ_PROFILES_PLAYERINFO_lastbattle", rec->lbtl); // +72 total = 5; break; case 4: // global scores - t.intRow("BFHQ_globalscore", 32); - t.intRow("BFHQ_wins", 36); - t.intRow("BFHQ_losses", 40); - t.intRow("BFHQ_teamworkscore", 100); - t.intRow("BFHQ_combatscore", 168); - t.intRow("BFHQ_commanderscore", 156); + t.intRow("BFHQ_globalscore", rec->scor); // +32 + t.intRow("BFHQ_wins", rec->wins); // +36 + t.intRow("BFHQ_losses", rec->loss); // +40 + t.intRow("BFHQ_teamworkscore", rec->twsc); // +100 + t.intRow("BFHQ_combatscore", rec->cmsc); // +168 + t.intRow("BFHQ_commanderscore", rec->cdsc); // +156 total = 6; break; - case 7: // weapons, 68-byte entries at +528 + case 7: // weapons, 68-byte retail entries at +528 for (int k = 0; k < 13; ++k) { - const int w = 528 + 68 * k; + const PlayerStatsRecord::Weapon& w = rec->weapons[k]; t.label(k, kFavouriteWeaponKeys[k]); - r.pushInt(t.i(w + 28)); // kills - r.pushInt(t.i(w + 32)); // deaths + r.pushInt(w.kills); // kills + r.pushInt(w.deaths); // deaths char accuracy[24]; // sub_10003320("%d") + "%" (sub_10001AA0) - ::_snprintf(accuracy, sizeof(accuracy) - 1, "%d%%", t.i(w + 36)); + ::_snprintf(accuracy, sizeof(accuracy) - 1, "%d%%", w.accuracy); accuracy[sizeof(accuracy) - 1] = 0; r.pushNarrow(accuracy); - r.pushNarrow(t.s(w + 40)); // kill/death ratio - r.pushNarrow(t.s(w)); // time + r.pushNarrow(w.kd.c_str()); // kill/death ratio + r.pushNarrow(w.time.c_str()); // time } total = 9; break; - case 8: // vehicles, 68-byte entries at +2676 + case 8: // vehicles, 68-byte retail entries at +2676 for (int k = 0; k < 7; ++k) { if (k == 5) // `cmp esi, 8Ch` - the sixth is skipped, its id kept continue; - const int v = 2676 + 68 * k; + const PlayerStatsRecord::Vehicle& v = rec->vehicles[k]; t.label(k, kFavouriteVehicleKeys[k]); - r.pushInt(t.i(v + 28)); // kills - r.pushInt(t.i(v + 64)); // road kills - r.pushInt(t.i(v + 32)); // deaths - r.pushNarrow(t.s(v + 36)); // kill/death ratio - r.pushNarrow(t.s(v)); // time + r.pushInt(v.kills); // kills + r.pushInt(v.roadKills); // road kills + r.pushInt(v.deaths); // deaths + r.pushNarrow(v.kd.c_str()); // kill/death ratio + r.pushNarrow(v.time.c_str()); // time } total = 6; break; - case 9: // kits, 64-byte entries at +2224 + case 9: // kits, 64-byte retail entries at +2224 for (int k = 0; k < 7; ++k) { - const int kit = 2224 + 64 * k; + const PlayerStatsRecord::Kit& kit = rec->kits[k]; t.label(k, kFavouriteKitKeys[k]); - r.pushInt(t.i(kit + 28)); // kills - r.pushInt(t.i(kit + 32)); // deaths - r.pushNarrow(t.s(kit + 36)); // kill/death ratio - r.pushNarrow(t.s(kit)); // time + r.pushInt(kit.kills); // kills + r.pushInt(kit.deaths); // deaths + r.pushNarrow(kit.kd.c_str()); // kill/death ratio + r.pushNarrow(kit.time.c_str()); // time } total = 7; break; case 10: // armies, per MenuTeamManager team { - // The count is asked once (var_5C); per team: getTeam, the army's 40-byte entry at + // The count is asked once (var_5C); per team: getTeam, the army's 40-byte retail entry at // 1820 + 40 * teamId (unchecked), the row keyed by the team id, localise("") (an empty key // never reaches the host), host +0x124 getModDirectorySetting asked and dropped, the flag // image, localise("") again, the team's name (+8) localised, then time / wins / losses. @@ -4854,7 +5201,7 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost { const MenuTeam* team = tm->getTeam(k); // +0x30 const int teamId = team->teamId; - const int army = 1820 + 40 * teamId; + const PlayerStatsRecord::Army& army = rec->armies[teamId]; r.beginRow(teamId); { HostWide w; hostLocalise(h, "", w); r.pushWide(w.c_str(), (int) w.size()); } (void) h->getModDirectorySetting(); // +0x124 @@ -4864,42 +5211,42 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost r.pushNarrow(flag); { HostWide w; hostLocalise(h, "", w); r.pushWide(w.c_str(), (int) w.size()); } { HostWide w; hostLocalise(h, team->name.c_str(), w); r.pushWide(w.c_str(), (int) w.size()); } - r.pushNarrow(t.s(army)); - r.pushInt(t.i(army + 28)); - r.pushInt(t.i(army + 32)); + r.pushNarrow(army.time.c_str()); + r.pushInt(army.wins); + r.pushInt(army.losses); } total = (int) teams; break; } case 11: // current and next rank { - vc71::string key; + std::string key; t.label(0, "PROFILE_currentrank"); - hostRankKey(h, t.i(160), key); // +0x1B4 with the record's rank + hostRankKey(h, rec->rank, key); // +0x1B4 with the record's rank (+160) r.pushNarrow(key.c_str()); t.label(0, "PROFILE_nextrank"); - hostRankKey(h, t.i(160) + 1, key); + hostRankKey(h, rec->rank + 1, key); r.pushNarrow(key.c_str()); total = 2; break; } - case 12: t.favouriteRow("kit_%d", 3560, 3564); total = 1; break; - case 13: t.favouriteRow("vehicle_%d", 3592, 3596); total = 1; break; - case 14: t.favouriteRow("weapon_%d", 3624, 3628); total = 1; break; - case 15: t.favouriteRow("map_%d", 3656, 3660); total = 1; break; + case 12: t.favouriteRow("kit_%d", rec->fkit, rec->fkitTime); total = 1; break; // +3560 / +3564 + case 13: t.favouriteRow("vehicle_%d", rec->fveh, rec->fvehTime); total = 1; break; // +3592 / +3596 + case 14: t.favouriteRow("weapon_%d", rec->fwea, rec->fweaTime); total = 1; break; // +3624 / +3628 + case 15: t.favouriteRow("map_%d", rec->fmap, rec->fmapTime); total = 1; break; // +3656 / +3660 case 16: // the record's map rows { - // Per 40-byte row {id, wins, losses, time} of the vector at +3688 (its size re-read every + // Per row {id, wins, losses, time} of the vector at +3688 (its size re-read every // pass): host +0x120 getModInfo asked again each time, +0x34 getMapFromGameSpyId(id); rows // whose map the mod does not know are skipped uncounted. A known map inside the window // gives id = the map's gsid (+0x9C), its name (+0x1C), wins, losses, time - and every known // map counts toward totalCount whether shown or not. - const Vc71Vector* rows = reinterpret_cast(rec->bytes + 3688); + const std::vector& rows = rec->maps; unsigned int known = 0; - for (unsigned int k = 0; rows->first && k < (unsigned int) ((rows->last - rows->first) / 40); ++k) + for (unsigned int k = 0; k < (unsigned int) rows.size(); ++k) { - const char* row = rows->first + 40 * k; - const int mapId = *reinterpret_cast(row); + const PlayerStatsRecord::MapRow& row = rows[k]; + const int mapId = row.id; IModInfo* mi = static_cast(h->getModInfo()); const IModInfo::Map* map = mi->getMapFromGameSpyId(mapId); if (!map) @@ -4908,9 +5255,9 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost { r.beginRow(map->gameSpyId); r.pushNarrow(map->name.c_str()); - r.pushInt(*reinterpret_cast(row + 4)); - r.pushInt(*reinterpret_cast(row + 8)); - r.pushNarrow(reinterpret_cast(row + 12)->c_str()); + r.pushInt(row.wins); + r.pushInt(row.losses); + r.pushNarrow(row.time.c_str()); } ++total; ++known; @@ -4918,13 +5265,13 @@ static void listPlayerStats(const gameswf::fn_call& fn, ListResult& r, ListHost break; } case 17: // the summary strip - t.intRow("BFHQ_globalscore", 32); - t.strRow("BFHQ_enlisted", 44); - t.strRow("BFHQ_lastbattle", 72); - t.strRow("BFHQ_timeascommander", 344); - t.strRow("BFHQ_timeassquadleader", 372); - t.strRow("BFHQ_timeassquadmember", 400); - t.strRow("BFHQ_timeaslonewolf", 428); + t.intRow("BFHQ_globalscore", rec->scor); // +32 + t.strRow("BFHQ_enlisted", rec->jond); // +44 + t.strRow("BFHQ_lastbattle", rec->lbtl); // +72 + t.strRow("BFHQ_timeascommander", rec->tcdr); // +344 + t.strRow("BFHQ_timeassquadleader", rec->tsql); // +372 + t.strRow("BFHQ_timeassquadmember", rec->tsqm); // +400 + t.strRow("BFHQ_timeaslonewolf", rec->tlwf); // +428 total = 7; break; default: // 5, 6 and out of range: empty @@ -5137,10 +5484,9 @@ static void listUnlockEquipment(const gameswf::fn_call& fn, ListResult& r, ListH TeamManager tm = teamManager(); UnlockRecord rec; rec.now = (int) ::time(0); rec.a = 0; rec.count = 0; rec.b = 0; - rec.unlocks.alloc = 0; rec.unlocks.first = rec.unlocks.last = rec.unlocks.end = 0; const int teamIdentifier = ::atoi(word1); const int kitPosition = ::atoi(word2); - struct NameId { vc71::string name; int id; }; + struct NameId { std::string name; int id; }; NameId* names = 0; unsigned int nameCount = 0; { @@ -5160,7 +5506,7 @@ static void listUnlockEquipment(const gameswf::fn_call& fn, ListResult& r, ListH names = new NameId[items.size()]; for (std::size_t k = 0; k < items.size(); ++k) { - vc71::string key; + std::string key; shippedLowercase(items[k].name.c_str(), key); unsigned int slot = 0; while (slot < nameCount && ::strcmp(names[slot].name.c_str(), key.c_str()) != 0) ++slot; @@ -5177,7 +5523,7 @@ static void listUnlockEquipment(const gameswf::fn_call& fn, ListResult& r, ListH continue; if (k >= (unsigned int) start && k < (unsigned int) end) { - vc71::string key; + std::string key; shippedLowercase(equipmentTemplate(e), key); r.beginRowStr(key.c_str()); pushLocalised(r, h, equipmentDisplay(e)); @@ -5221,7 +5567,7 @@ static void listWeaponStats(const gameswf::fn_call& fn, ListResult& r, const tu_ { (void) teamManager(); // asked and dropped r.begin(); - vc71::string name(s_selectedEquipment.c_str()); + std::string name(s_selectedEquipment.c_str()); if (which == "wpunlockstats") name = s_selectedUnlockEquipment.c_str(); else if (which == "wpuunlockstats") @@ -5300,7 +5646,11 @@ void as_playerstats_unlock(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_unlock"); void* h = asHost(); +#if defined(__APPLE__) + const int unlockId = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int unlockId = (int) fn.arg(0).to_number(); +#endif const int pid = hostPlayerId(); IBase* unlocks = static_cast(h)->getPlayerUnlocks(); const bool result = static_cast(unlocks)->setUnlocks(pid, unlockId); @@ -5469,12 +5819,20 @@ static void setGeneralBoolArgumentFirst(const gameswf::fn_call& fn, GsBoolSetter static void setGeneralIntOwnerFirst(const gameswf::fn_call& fn, GsIntSetter setter) { IGeneralSettings* gs = generalSettingsOf(generalSettingsSingleton()); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (gs->*setter)(value); } static void setGeneralIntArgumentFirst(const gameswf::fn_call& fn, GsIntSetter setter) { +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (generalSettingsOf(generalSettingsSingleton())->*setter)(value); } @@ -5567,10 +5925,26 @@ void as_generalsettings_setCrosshairColor(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_generalsettings_setCrosshairColor"); IGeneralSettings* gs = generalSettingsOf(generalSettingsSingleton()); +#if defined(__APPLE__) + const int red = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int red = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int green = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int green = static_cast(fn.arg(1).to_number()); +#endif +#if defined(__APPLE__) + const int blue = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int blue = static_cast(fn.arg(2).to_number()); +#endif +#if defined(__APPLE__) + const int alpha = bf2x87::toIntTruncate(fn.arg(3).to_number()); +#else const int alpha = static_cast(fn.arg(3).to_number()); +#endif gs->setCrosshairColor(red, green, blue, alpha); // +0x54 } @@ -5594,9 +5968,21 @@ void as_generalsettings_getSquadtagColor(const gameswf::fn_call& fn) { SWF_AS_TR static void setGeneralRgb(const gameswf::fn_call& fn, int offset) { IGeneralSettings* gs = generalSettingsOf(generalSettingsSingleton()); +#if defined(__APPLE__) + const int red = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int red = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int green = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int green = static_cast(fn.arg(1).to_number()); +#endif +#if defined(__APPLE__) + const int blue = bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const int blue = static_cast(fn.arg(2).to_number()); +#endif if (offset == 0x5C) gs->setBuddytagColor(red, green, blue); // +0x5C else gs->setSquadtagColor(red, green, blue); // +0x64 } @@ -5705,8 +6091,7 @@ void as_generalsettings_removeServer(const gameswf::fn_call& fn) // Control settings edit backup maps and restore the prior engine selection afterward. -// mapInput remains unregistered until input capture and its integer status contract are -// implemented; publishing the current Boolean stub would report ineffective rebindings. +// mapInput (sub_1000EDA0) is registered by registerRecoveredNatives (SwiffNativesRecovered.inl). static IBase* controlSettingsSingleton() { @@ -5815,7 +6200,11 @@ void as_controlsettings_setActiveControlMap(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_controlsettings_setActiveControlMap"); (void) g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = static_cast(fn.arg(0).to_number()); +#endif s_editedControlMap = kEditedControlMapNames[index]; } @@ -5853,7 +6242,11 @@ void as_controlsettings_resetDefault(const gameswf::fn_call& fn) { SWF_AS_TRACE( void as_controlsettings_getMappedString(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_controlsettings_getMappedString"); +#if defined(__APPLE__) + const int input = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int input = static_cast(fn.arg(0).to_number()); +#endif const bool alternate = fn.arg(1).to_bool(); const bool second = fn.arg(2).to_bool(); renddx9abi::HostString key; @@ -5873,11 +6266,11 @@ void as_controlsettings_getMappedString(const gameswf::fn_call& fn) { HostWide localised; (void) g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(localised, key); // +0xA8 - gameswf::assign_dice_string_object_wide(object, reinterpret_cast(localised.c_str())); + gameswf::assign_dice_string_object_wide(object, BF2_DICE_UTF16(localised.c_str())); } } else - gameswf::assign_dice_string_object_wide(object, reinterpret_cast(text.c_str())); + gameswf::assign_dice_string_object_wide(object, BF2_DICE_UTF16(text.c_str())); restoreControlMapSelection(); } fn.result->set_as_object_interface(object); @@ -6159,7 +6552,11 @@ static void publishServerInt(const gameswf::fn_call& fn, GssIntGetter getter) static void setServerInt(const gameswf::fn_call& fn, GssIntSetter setter) { IGameServerSettings* gss = gameServerSettings(); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif (gss->*setter)(value); } @@ -6202,7 +6599,11 @@ void as_serversettings_setMaxPlayers(const gameswf::fn_call& fn) SWF_AS_TRACE("as_serversettings_setMaxPlayers"); (void) g_swiffPlayerInstance->getSwiffHost(); IGameServerSettings* gss = gameServerSettings(); +#if defined(__APPLE__) + const int value = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int value = static_cast(fn.arg(0).to_number()); +#endif gss->setMaxPlayers(value); // +0x44 (void) gss->apply(); // +0x18 } @@ -6245,12 +6646,20 @@ void as_serversettings_setCoopBotCount(const gameswf::fn_call& fn) IBase* gss = gameServerSettingsSingleton(); if (gs) { +#if defined(__APPLE__) + const int count = bf2x87::toIntTruncate(value); +#else const int count = static_cast(value); +#endif static_cast(gs)->setMaxBots(count); // +0xB4 static_cast(gs)->setCoopBotCount(count); // +0xF4 } if (gss) +#if defined(__APPLE__) + static_cast(gss)->setCoopBotCount(bf2x87::toIntTruncate(value)); // +0x1A4 +#else static_cast(gss)->setCoopBotCount(static_cast(value)); // +0x1A4 +#endif } // AS_ServerSettings_setCoopBotDiff (0x10063AA0): argument zero as a float first; the two lookups; @@ -6572,7 +6981,11 @@ void as_multiplay_addMapToMapList(const gameswf::fn_call& fn) if (!path.empty()) { const std::string mode(fn.arg(1).to_string()); +#if defined(__APPLE__) + const unsigned int size = (unsigned int) bf2x87::toIntTruncate(fn.arg(2).to_number()); +#else const unsigned int size = (unsigned int) (int) fn.arg(2).to_number(); +#endif IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); if (static_cast(static_cast(gs))->getUseBots()) { @@ -6662,7 +7075,11 @@ void as_multiplay_removeMapfromMapList(const gameswf::fn_call& fn) BusyHost busy = busyOpen(); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); (void) classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = static_cast(fn.arg(0).to_number()); +#endif (void) h->removeServerEntry(static_cast(index)); // +0x12C busyClose(busy); } @@ -6676,7 +7093,11 @@ void as_multiplay_moveMapInList(const gameswf::fn_call& fn) SWF_AS_TRACE("as_multiplay_moveMapInList"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); (void) classManager->getSingleton(renddx9abi::HostString("LocalProfileManager")); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = static_cast(fn.arg(0).to_number()); +#endif const bool up = fn.arg(1).to_bool(); (void) h->moveServerEntry(static_cast(index), up); // +0x130 fn.result->set_bool(true); @@ -6847,7 +7268,7 @@ void as_multiplay_getMapDescriptionFromId(const gameswf::fn_call& fn) std::wstring out; g_swiffPlayerInstance->getSwiffHost()->getLocalizedString(out, key); // +0xA8 gameswf::as_object_interface* text = gameswf::create_dice_string_object(nullptr, 0); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(out.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(out.c_str())); fn.result->set_as_object_interface(text); return; } @@ -7054,7 +7475,11 @@ void as_multiplay_downloadServerLogo(const gameswf::fn_call& fn) void as_multiplay_getTeamName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_getTeamName"); +#if defined(__APPLE__) + const int index = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int index = (int) fn.arg(0).to_number(); +#endif const renddx9abi::HostString name(s_teamNames[index]); fn.result->set_tu_string(tu_string(name.c_str())); } @@ -7159,7 +7584,7 @@ void as_mod_getCurrentModName(const gameswf::fn_call& fn) void as_playerstats_getCurrentUnlockDescription(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getCurrentUnlockDescription"); - vc71::string name(s_selectedUnlock.c_str()); + std::string name(s_selectedUnlock.c_str()); EquipmentKeys rec; if (!findEquipmentByName(name.c_str(), rec)) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } setLocalisedStringObject(fn, rec.descriptionKey); @@ -7175,13 +7600,13 @@ void as_profile_getCurrentRankString(const gameswf::fn_call& fn) if (!h) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) fetchPlayerStats(h, *rec); - const int rankId = *reinterpret_cast(rec->bytes + 160); + const int rankId = rec->rank; delete rec; - vc71::string key; + std::string key; hostRankKey(h, rankId, key); - vc71::wstring text; + std::wstring text; hostLocaliseKey(h, key, text); - fn.result->set_as_object_interface(gameswf::create_dice_string_object(reinterpret_cast(text.c_str()), (int) text.size())); + fn.result->set_as_object_interface(gameswf::create_dice_string_object(BF2_DICE_UTF16(text.c_str()), (int) text.size())); } // dice.bf2.Logic.beginWaitState(flag), and promoted. @@ -7195,7 +7620,11 @@ void as_logic_beginWaitState(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_logic_beginWaitState"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + (void) h->setBusy(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x2B0 +#else (void) h->setBusy(static_cast(fn.arg(0).to_number())); // +0x2B0 +#endif } // dice.bf2.Logic.endWaitState(), and promoted. No @@ -7222,7 +7651,11 @@ void as_logic_getTeamsConId(const gameswf::fn_call& fn) SWF_AS_TRACE("as_logic_getTeamsConId"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); IMenuTeamManager* tm = static_cast(h->getMenuTeamManager()); // +0x50 +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = (int) fn.arg(0).to_number(); +#endif const MenuTeam* team = tm->findTeamById(id); // +0x34 fn.result->set_double((double) team->teamId); } @@ -7231,12 +7664,13 @@ void as_logic_getTeamsConId(const gameswf::fn_call& fn) // keyed by the same bit mask the checkboxes use. setToggleFilter below writes it; its reader is // Multiplay.updateFilter (PE 10056020 -> 10055700). The shipped map // is constructed and destroyed by the DLL's own static initialiser pair at 100D6290 / 100D6A21. -// The retained vc71::string values are internal storage; this map never crosses the DLL boundary. -static std::map s_filterValues; +// The retained std::string values are internal storage; this map never crosses the DLL boundary. +static std::map s_filterValues; // unk_100F8810 - the DLL-global free-text filter clause, written by Multiplay.setFilter // (PE 100519C0, still unregistered here) and read - and rewritten in place - by the builder below. -static vc71::string s_textFilter; +static std::string s_textFilter; + // Publishes whether any bit in the supplied filter mask is enabled. // Requires GeneralSettings and one numeric argument. @@ -7245,7 +7679,11 @@ void as_multiplay_getToggleFilter(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_getToggleFilter"); IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); +#if defined(__APPLE__) + const int mask = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int mask = (int) fn.arg(0).to_number(); +#endif fn.result->set_bool(static_cast(static_cast(gs))->getToggleFilter(mask)); } // Sets a browser filter bit and its query clause from (mask, on, clause); publishes no result. @@ -7256,9 +7694,13 @@ void as_multiplay_setToggleFilter(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setToggleFilter"); IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); +#if defined(__APPLE__) + const int mask = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int mask = (int) fn.arg(0).to_number(); +#endif const bool on = fn.arg(1).to_bool(); - vc71::string clause(fn.arg(2).to_string()); + std::string clause(fn.arg(2).to_string()); const bool blank = clause.c_str()[0] == 0 || ::strcmp(clause.c_str(), "%%") == 0; static_cast(static_cast(gs))->setToggleFilter(mask, blank ? false : on); if (blank) @@ -7283,12 +7725,12 @@ static bool isMapSizeFilter(int mask) { return mask == 2048 || mask == 4096 || mask == 8192; } -static void buildFilterString(vc71::string& out) +static void buildFilterString(std::string& out) { IBase* gs = classManager->getSingleton(renddx9abi::HostString("GeneralSettings")); - vc71::string filter; + std::string filter; - typedef std::map::const_iterator Entry; + typedef std::map::const_iterator Entry; unsigned int mapSizeArmed = 0; for (Entry it = s_filterValues.begin(); it != s_filterValues.end(); ++it) if (filterBitOn(gs, it->first) && it->second.c_str()[0] != 0 && isMapSizeFilter(it->first)) @@ -7299,7 +7741,7 @@ static void buildFilterString(vc71::string& out) for (Entry it = s_filterValues.begin(); it != s_filterValues.end(); ++it) { const int mask = it->first; - const vc71::string& clause = it->second; + const std::string& clause = it->second; if (!filterBitOn(gs, mask) || clause.c_str()[0] == 0) continue; if (filter.c_str()[0] == 0) @@ -7349,9 +7791,9 @@ static void buildFilterString(vc71::string& out) // would be a wild copy rather than a throw, so the length tests stop one character // short of that boundary. Every other input is byte-for-byte the shipped result. if (s_textFilter.size() > 4 && ::strncmp(s_textFilter.c_str(), "and", 3) == 0) - s_textFilter = vc71::string(s_textFilter.c_str() + 4, s_textFilter.size() - 4); + s_textFilter = std::string(s_textFilter.c_str() + 4, s_textFilter.size() - 4); if (s_textFilter.size() > 5 && ::strncmp(s_textFilter.c_str(), " and", 4) == 0) - s_textFilter = vc71::string(s_textFilter.c_str() + 5, s_textFilter.size() - 5); + s_textFilter = std::string(s_textFilter.c_str() + 5, s_textFilter.size() - 5); filter = s_textFilter; } else @@ -7371,7 +7813,7 @@ void as_multiplay_updateFilter(const gameswf::fn_call& fn) ISwiffHost* cursorHost = static_cast(cursorBase); if (cursorHost) { SetCursor(cursorHost->getCursor(1)); cursorHost->setBusy(1); } ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); - vc71::string filter; // declared first, so it dies last + std::string filter; // declared first, so it dies last buildFilterString(filter); const std::string kind = h->getServerListKind(); // +0x134 IServerBrowser* list = h->getServerList(kind); // +0x7C @@ -7594,10 +8036,10 @@ static void awardText(const gameswf::fn_call& fn, bool description) AwardView award; if (findAward(id, level, award)) { - vc71::wstring wide; + std::wstring wide; hostLocaliseKey(static_cast(g_swiffPlayerInstance->getSwiffHost()), - vc71::string((description ? award.description : award.name).c_str()), wide); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + std::string((description ? award.description : award.name).c_str()), wide); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); } else { @@ -7997,7 +8439,11 @@ void as_multiplay_setLeaderboardId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setLeaderboardId"); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + hostSetLeaderboardId(h, bf2x87::toIntTruncate(fn.arg(0).to_number())); +#else hostSetLeaderboardId(h, static_cast(fn.arg(0).to_number())); +#endif } // Multiplay.getLeaderboardName() / getLeaderboardDescription(), inside the @@ -8015,10 +8461,10 @@ static void leaderboardText(const gameswf::fn_call& fn, bool description) const char* entry = (category >= 0 && category <= 3) ? leaderboardKey(category, board) : 0; if (entry) key = description ? std::string(entry) + "_desc" : std::string(entry); - vc71::wstring wide; - hostLocaliseKey(static_cast(g_swiffPlayerInstance->getSwiffHost()), vc71::string(key.c_str()), wide); + std::wstring wide; + hostLocaliseKey(static_cast(g_swiffPlayerInstance->getSwiffHost()), std::string(key.c_str()), wide); gameswf::as_object_interface* text = gameswf::create_dice_string_object(nullptr, 0); - gameswf::assign_dice_string_object_wide(text, reinterpret_cast(wide.c_str())); + gameswf::assign_dice_string_object_wide(text, BF2_DICE_UTF16(wide.c_str())); fn.result->set_as_object_interface(text); busyClose(busy); } @@ -8075,7 +8521,11 @@ void as_multiplay_goLeaderboardPlayer(const gameswf::fn_call& fn) SWF_AS_TRACE("as_multiplay_goLeaderboardPlayer"); BusyHost busy = busyOpen(); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + hostGoLeaderboardPlayer(h, bf2x87::toIntTruncate(fn.arg(0).to_number())); +#else hostGoLeaderboardPlayer(h, static_cast(fn.arg(0).to_number())); +#endif busyClose(busy); } @@ -8087,8 +8537,16 @@ void as_playerstats_getLeaderBoard(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getLeaderBoard"); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int request = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int request = static_cast(fn.arg(1).to_number()); +#endif HostLeaderboard cache; const bool ok = id ? hostGetLeaderboardPlayer(h, id, cache, request) : hostGetLeaderboard(h, cache, request, 0); fn.result->set_bool(ok); @@ -8098,8 +8556,16 @@ void as_playerstats_refreshLeaderBoard(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_refreshLeaderBoard"); void* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + const int id = bf2x87::toIntTruncate(fn.arg(0).to_number()); +#else const int id = static_cast(fn.arg(0).to_number()); +#endif +#if defined(__APPLE__) + const int request = bf2x87::toIntTruncate(fn.arg(1).to_number()); +#else const int request = static_cast(fn.arg(1).to_number()); +#endif fn.result->set_bool(hostFetchLeaderboard(h, id, request, 0)); } @@ -8387,7 +8853,11 @@ void as_multiplay_setLeaderboardCategoryId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_setLeaderboardCategoryId"); ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); +#if defined(__APPLE__) + h->setLeaderboardCategory(bf2x87::toIntTruncate(fn.arg(0).to_number())); // +0x140 +#else h->setLeaderboardCategory(static_cast(fn.arg(0).to_number())); // +0x140 +#endif } // Returns the first current-mod game mode's display name, or empty for no modes. @@ -8418,8 +8888,8 @@ void as_multiplay_getSelectedLeaderboardCategoryId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_multiplay_getSelectedLeaderboardCategoryId"); (void) g_swiffPlayerInstance->getSwiffHost(); - const vc71::string key("BFHQ_leaderboardscores"); - vc71::wstring text; + const std::string key("BFHQ_leaderboardscores"); + std::wstring text; ISwiffHost* h = g_swiffPlayerInstance->getSwiffHost(); std::wstring wide; (void) h->getLocalizedString(wide, std::string(key.c_str())); // +0xA8 @@ -8427,7 +8897,7 @@ void as_multiplay_getSelectedLeaderboardCategoryId(const gameswf::fn_call& fn) // The String's wide side is assigned from the copy's c_str() (10052647..1005264E), so it ends // at the first NUL whatever length the host wrote. fn.result->set_as_object_interface(gameswf::create_dice_string_object( - reinterpret_cast(text.c_str()), (int) ::wcslen(text.c_str()))); + BF2_DICE_UTF16(text.c_str()), (int) ::wcslen(text.c_str()))); } // sub_1005D7A0 - dice.bf2.Profile.getRankProgress(): SwiffHost +716() as a double - a number. @@ -8448,14 +8918,14 @@ void as_profile_getNextRankString(const gameswf::fn_call& fn) if (!h) { fn.result->set_as_object_interface(gameswf::create_dice_string_object(0, 0)); return; } PlayerStatsRecord* rec = new PlayerStatsRecord(); (void) fetchPlayerStats(h, *rec); - const int rankId = *reinterpret_cast(rec->bytes + 160); + const int rankId = rec->rank; delete rec; const int next = hostNextRank(h, rankId); - vc71::string key; + std::string key; hostRankKey(h, next, key); - vc71::wstring text; + std::wstring text; hostLocaliseKey(h, key, text); - fn.result->set_as_object_interface(gameswf::create_dice_string_object(reinterpret_cast(text.c_str()), (int) text.size())); + fn.result->set_as_object_interface(gameswf::create_dice_string_object(BF2_DICE_UTF16(text.c_str()), (int) text.size())); } // sub_1005BA20 - dice.bf2.PlayerStats.getKitAccuracy(): the stats record's int at +2220 as a number @@ -8465,7 +8935,7 @@ void as_playerstats_getKitAccuracy(const gameswf::fn_call& fn) SWF_AS_TRACE("as_playerstats_getKitAccuracy"); PlayerStatsRecord* rec = new PlayerStatsRecord(); const bool ok = fetchPlayerStats(asHost(), *rec); - const double v = ok ? (double) *reinterpret_cast(rec->bytes + 2220) : 0.0; + const double v = ok ? (double) rec->osaa : 0.0; delete rec; fn.result->set_double(v); } @@ -8473,37 +8943,41 @@ void as_playerstats_getKitAccuracy(const gameswf::fn_call& fn) // sub_1005AC60 / sub_1005ADB0 - dice.bf2.PlayerStats.getOpponentName() / getVictimName(): the stats // record's std::string at +492 / +456; empty or a single space becomes "-", and so does a record that // could not be fetched. string. -static void statsNameAt(const gameswf::fn_call& fn, int offset) +static void statsNameAt(const gameswf::fn_call& fn, std::string PlayerStatsRecord::* field) { PlayerStatsRecord* rec = new PlayerStatsRecord(); - vc71::string out("-"); + std::string out("-"); if (fetchPlayerStats(asHost(), *rec)) { - const vc71::string* name = reinterpret_cast(rec->bytes + offset); + const std::string* name = &(rec->*field); if (name->size() != 0 && ::strcmp(name->c_str(), " ") != 0) out = *name; } delete rec; fn.result->set_tu_string(tu_string(out.c_str())); } -void as_playerstats_getOpponentName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentName"); statsNameAt(fn, 492); } -void as_playerstats_getVictimName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimName"); statsNameAt(fn, 456); } +void as_playerstats_getOpponentName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentName"); statsNameAt(fn, &PlayerStatsRecord::vmns); } +void as_playerstats_getVictimName(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimName"); statsNameAt(fn, &PlayerStatsRecord::mvns); } // sub_1005AF00 / sub_1005AFF0 - getOpponentRankId() / getVictimRankId(): the int beside the name // (+524 / +488) as a number; a single-space name or an unfetched record answers -1. -static void statsRankIdAt(const gameswf::fn_call& fn, int nameOffset, int idOffset) +static void statsRankIdAt(const gameswf::fn_call& fn, std::string PlayerStatsRecord::* nameField, + int PlayerStatsRecord::* idField) { PlayerStatsRecord* rec = new PlayerStatsRecord(); double v = -1.0; if (fetchPlayerStats(asHost(), *rec)) { - const vc71::string* name = reinterpret_cast(rec->bytes + nameOffset); - if (::strcmp(name->c_str(), " ") != 0) v = (double) *reinterpret_cast(rec->bytes + idOffset); + const std::string* name = &(rec->*nameField); + if (::strcmp(name->c_str(), " ") != 0) v = (double) (rec->*idField); } delete rec; fn.result->set_double(v); } -void as_playerstats_getOpponentRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentRankId"); statsRankIdAt(fn, 492, 524); } -void as_playerstats_getVictimRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimRankId"); statsRankIdAt(fn, 456, 488); } +void as_playerstats_getOpponentRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getOpponentRankId"); statsRankIdAt(fn, &PlayerStatsRecord::vmns, &PlayerStatsRecord::vmrs); } +void as_playerstats_getVictimRankId(const gameswf::fn_call& fn) { SWF_AS_TRACE("as_playerstats_getVictimRankId"); statsRankIdAt(fn, &PlayerStatsRecord::mvns, &PlayerStatsRecord::mvrs); } + +// The retail natives recovered by c-swiff-natives (docs/macos-c-swiff-natives.md). +#include "SwiffNativesRecovered.inl" static void registerAsMethods(SwiffAsNamespace* general, SwiffAsNamespace** ns, const char* const* names, int count) @@ -8673,7 +9147,7 @@ static void registerAsMethods(SwiffAsNamespace* general, SwiffAsNamespace** ns, else if (::strcmp(n, "ControlSettings") == 0) { // Twenty-one of the shipped registrar 1000F090's twenty-two rows, in its order. - // mapInput (1000EDA0) is withheld on purpose: see the section comment above its siblings. + // mapInput (1000EDA0) is registered by registerRecoveredNatives. ns[i]->registerNativeCompatibleMethod("setActiveControlMap"); ns[i]->registerNativeCompatibleMethod("getMappedString"); ns[i]->registerNativeCompatibleMethod("cancel"); @@ -8999,6 +9473,8 @@ static void registerAsMethods(SwiffAsNamespace* general, SwiffAsNamespace** ns, ns[i]->registerNativeCompatibleMethod("endWaitState"); ns[i]->registerNativeCompatibleMethod("setFrameLabel"); ns[i]->registerNativeCompatibleMethod("enableScroller"); + ns[i]->registerNativeCompatibleMethod("eraseStorageString"); // sub_1004D170, registered at 1004E3E3 + ns[i]->registerNativeCompatibleMethod("getDefaultLevel"); // sub_1004D5B0, registered at 1004E43B ns[i]->registerNativeCompatibleMethod("getIsLoading"); ns[i]->registerNativeCompatibleMethod("setIsLoading"); ns[i]->registerNativeCompatibleMethod("readyToPlay"); @@ -9098,6 +9574,8 @@ static void buildAsGraph() built[i] = addNs(bf2, kNamespaces[i], dotted); } registerAsMethods(general, built, kNamespaces, nsCount); + registerRecoveredNatives(built, kNamespaces, nsCount); // c-swiff-natives: the rows the port lacked + registerHapticNatives(built, kNamespaces, nsCount); ::renddx9abi::logf("[SwiffPlayer] buildAsGraph: _global.dice + dice.bf2.<%d namespaces> built", nsCount); } @@ -9110,6 +9588,9 @@ namespace { inline void** rcVtbl(void* rc) { return *reinterpret_cast(rc); } +#if !defined(_MSC_VER) +using namespace ::dice::hfe::ui::native_render; +#else // bitmap creators (return an int texture handle) inline int rcCreateEmpty(void* rc) // +0x18 slot 6 { return reinterpret_cast(rcVtbl(rc)[0x18/4])(rc); } @@ -9169,9 +9650,9 @@ inline void rcTextSet(void* rc, void* line, const wchar_t* text) { re inline void rcTextDetach(void* rc, void* line) { reinterpret_cast(rcVtbl(rc)[0x74/4])(rc, line); } // +0x74 slot 29 inline void rcTextDraw(void* rc, void* line, const void* m, unsigned c, int f) { reinterpret_cast(rcVtbl(rc)[0x78/4])(rc, line, m, c, f); } // +0x78 slot 30 drawText inline char rcTextExtent(void* rc, void* line, int n, float* w, float* h) { return reinterpret_cast(rcVtbl(rc)[0x7C/4])(rc, line, n, w, h); } // +0x7C slot 31 -inline char rcTextHit(void* rc, void* line, int* pos, int x, int y) { return reinterpret_cast(rcVtbl(rc)[0x80/4])(rc, line, pos, x, y); } // +0x80 slot 32 +inline char rcTextHit(void* rc, void* line, int* pos, float x, float y) { return reinterpret_cast(rcVtbl(rc)[0x80/4])(rc, line, pos, x, y); } // +0x80 slot 32 - RendDX9 0x10152FF0 fld/fmul's x, y inline int rcTextSelection(void* rc, void* line, int* a, int* b) { return reinterpret_cast(rcVtbl(rc)[0x84/4])(rc, line, a, b); } // +0x84 slot 33 - AL answers "a selection exists" (sub_1009A910 -> sub_10088D60) -inline char rcTextSetSelection(void* rc, void* line, int a, int b, int c, int d) { return reinterpret_cast(rcVtbl(rc)[0x88/4])(rc, line, a, b, c, d); } // +0x88 slot 34 +inline char rcTextSetSelection(void* rc, void* line, float a, float b, float c, float d) { return reinterpret_cast(rcVtbl(rc)[0x88/4])(rc, line, a, b, c, d); } // +0x88 slot 34 - RendDX9 0x10153060 fld/fmul's all four inline void rcTextBlur(void* rc, void* line) { reinterpret_cast(rcVtbl(rc)[0x8C/4])(rc, line); } // +0x8C slot 35 inline void rcTextSetSize(void* rc, void* line, float size, int flag) { reinterpret_cast(rcVtbl(rc)[0x90/4])(rc, line, size, flag); } // +0x90 slot 36 inline void rcTextCaret(void* rc, void* line, int pos) { reinterpret_cast(rcVtbl(rc)[0x94/4])(rc, line, pos); } // +0x94 slot 37 @@ -9182,14 +9663,25 @@ inline void rcSetMovieHeight(void* rc, int h) { reinterpret_cast(rcVtbl(rc)[0xB0/4])(rc, sx, sy); } // +0xB0 slot 44 inline void rcSetBackgroundColor(void* rc, unsigned rgb) { reinterpret_cast(rcVtbl(rc)[0xB4/4])(rc, rgb); } // +0xB4 slot 45 inline void rcSetMouseState(void* rc, int x, int y, int b) { reinterpret_cast(rcVtbl(rc)[0xB8/4])(rc, x, y, b); } // +0xB8 slot 46 -inline char rcCapability0(void* rc, int a) { return reinterpret_cast(rcVtbl(rc)[0xC4/4])(rc, a); } // +0xC4 slot 49 -inline char rcCapability1(void* rc, int a) { return reinterpret_cast(rcVtbl(rc)[0xC8/4])(rc, a); } // +0xC8 slot 50 -inline void rcSetPairState(void* rc, int a, int b) { reinterpret_cast(rcVtbl(rc)[0xD4/4])(rc, a, b); } // +0xD4 slot 53 +inline char rcCapability0(void* rc, intptr_t a) { return reinterpret_cast(rcVtbl(rc)[0xC4/4])(rc, a); } // +0xC4 slot 49 +inline char rcCapability1(void* rc, intptr_t a) { return reinterpret_cast(rcVtbl(rc)[0xC8/4])(rc, a); } // +0xC8 slot 50 +inline void rcSetPairState(void* rc, intptr_t a, int b) { reinterpret_cast(rcVtbl(rc)[0xD4/4])(rc, a, b); } // +0xD4 slot 53 inline void rcUpdateTime(void* rc, unsigned t, float dt) { reinterpret_cast(rcVtbl(rc)[0xD8/4])(rc, t, dt); } // +0xD8 slot 54 +#endif // Movie objects belong to this gameswf build and require its typed API; compatibility // offsets from the older movie interface do not apply. // Host callbacks below retain the separate ISwiffHost ABI. +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] These are the four raw helpers still used by the +// lifecycle. ActionScript already uses typed ISwiffHost calls. Keep obsolete +// PE-only helpers out of the native image, including their manual sret shapes. +inline void hostPreLoad10(void* h) { static_cast(h)->init(); } +inline void hostPreLoad50(void* h) { static_cast(h)->getMenuTeamManager(); } +inline void hostUpdate(void* h) { static_cast(h)->update(); } +inline void hostGetViewportSize(void* h, unsigned* w, unsigned* height) +{ static_cast(h)->getViewportSize(w, height); } +#else inline void hostPreLoad10(void* h) { reinterpret_cast(rcVtbl(h)[0x10/4])(h); } // +0x10 inline void hostPreLoad50(void* h) { reinterpret_cast(rcVtbl(h)[0x50/4])(h); } // +0x50 inline void hostUpdate(void* h) { reinterpret_cast(rcVtbl(h)[0x20/4])(h); } // +0x20 @@ -9240,9 +9732,7 @@ inline void hostSetJoinPassword(void* h, const void* str) { reinterpret_cast(rcVtbl(pm)[88/4])(pm, stdStringOut); } // +0x58 inline void pmClear(void* pm) { reinterpret_cast(rcVtbl(pm)[72/4])(pm); } // +0x48 - -// A queued mouse sample - 12 bytes, the element of the +1104 vc71-shaped vector. -struct MouseState { int x; int y; int buttons; }; +#endif // Reinterpret a float's bits as a dword (updateTime/line_style_width pass floats through dword slots). inline unsigned floatBits(float f) { unsigned d; ::memcpy(&d, &f, 4); return d; } @@ -9284,9 +9774,9 @@ SwiffPlayer::SwiffPlayer() swiff_host = 0; elapsed_time = 0.0f; pad_44d[0] = pad_44d[1] = pad_44d[2] = 0; - queued_mouse_aux = queued_mouse_begin = queued_mouse_end = queued_mouse_capacity = 0; g_swiffPlayerInstance = this; + ++s_livePlayers; // [CHOSEN, not recovered] issue #7, see releaseMovie // The shipped ctor's sub_1006F100(0) sets a gameswf file-scope byte to 0 [UNRESOLVED: which // gameswf setter]. That byte is zero-initialised anyway, so omitting the call is a no-op @@ -9299,7 +9789,8 @@ SwiffPlayer::SwiffPlayer() gameswf::register_fscommand_callback(swiffFsCommand); gameswf::set_render_handler(&render_handler); - // Off unless BF2_SWIFFPLAYER_ASLOG=1 - see asLogEnabled(). Retail registers no log callback. + // Retail registers no log callback. Preserve full AS tracing when explicitly selected; + // the separate input diagnostic admits only mouse-prefixed messages. if (asLogEnabled()) gameswf::register_log_callback(swiffAsLogCb); @@ -9312,18 +9803,53 @@ SwiffPlayer::SwiffPlayer() } -// Releases movie state, gameswf globals, and queued mouse storage. +// Releases the loaded movie with every script object it created and resets _global, so the next +// player starts from fresh script state, as a freshly mapped SwiffPlayer.dll does. Safe to call +// with no movie loaded. The movie library is kept: later players share its parsed definitions, +// which reference each other and would never be freed once dropped from it. The global steps run +// only when this is the only live player, so no other player's clips or _global are cleared. +// [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7): gameswf replaces the +// shipped player, and this teardown is ours. Script values form reference cycles between a movie's +// clips and objects, so dropping the instance alone frees nothing; release_script_objects breaks +// them first. +void SwiffPlayer::releaseMovie() +{ + gameswf::movie_interface* inst = static_cast(movie_instance); + gameswf::movie_definition* def = static_cast(movie_definition); + movie_instance = 0; + movie_definition = 0; + const bool onlyPlayer = s_livePlayers == 1; + if (onlyPlayer) + gameswf::release_script_objects(); + if (inst) + inst->drop_ref(); + if (def) + def->drop_ref(); + if (onlyPlayer) + { + gameswf::action_clear(); + ::renddx9abi::logf("[SwiffPlayer] movie released (script objects and globals cleared)"); + } + else + { + std::fprintf(stderr, "SwiffPlayer: other player alive, globals kept (%d live)\n", s_livePlayers); + std::fflush(stderr); + ::renddx9abi::logf("SwiffPlayer: other player alive, globals kept (%d live)", s_livePlayers); + } +} + +// Releases movie state and gameswf globals; the queued mouse vector is destroyed as a member. SwiffPlayer::~SwiffPlayer() { // Shipped dtor also: sub_10071710 gameswf-global check, drops movie_definition/movie_instance // via sub_1006F2A0, sub_10077700 gameswf AS/GC teardown, and a LocalProfileManager voip-volume - // save. All are movie/voip-state teardown; with both null here they are no-ops. [Stage 3] + // save. The voip-volume save stays out [Stage 3]; releaseMovie() is this build's movie and + // global teardown ([CHOSEN, not recovered], issue #7). + releaseMovie(); + --s_livePlayers; // [CHOSEN, not recovered] issue #7, see releaseMovie voip_update_flag = 0; - if (queued_mouse_begin) - ::renddx9abi::engineFree(queued_mouse_begin); - queued_mouse_begin = queued_mouse_end = queued_mouse_capacity = 0; if (g_swiffPlayerInstance == this) g_swiffPlayerInstance = 0; @@ -9560,6 +10086,7 @@ bool SwiffPlayer::loadMovie(const char* movieName) buildAsGraph(); ::renddx9abi::logf("[SwiffPlayer::loadMovie] returning true"); + SWF_LIST_TRACE("loadMovie '%s'", movieName ? movieName : ""); // [TEMP] c-swf-disconnect return true; } @@ -9603,7 +10130,7 @@ void SwiffPlayer::update(float deltaTime) // bridge consults before queuing a mouse press (sub_4A2D60/sub_4A2DD0 in BF2.exe); interactive run // drive10 lost every click after the multiplayer tab while mouse moves kept arriving. Logged on // change only, with the display count, so the AS lines around the flip name what set it. - if (swiff_host && asLogEnabled()) + if (swiff_host && mouseLogEnabled()) { static int s_busy = -1; const int busy = reinterpret_cast(rcVtbl(swiff_host)[696/4])(swiff_host); @@ -9620,8 +10147,7 @@ void SwiffPlayer::update(float deltaTime) // Mouse flush: the queued path if there is queued input or the deferred sample is already spent; // otherwise apply the deferred position once and mark it spent. - const bool haveQueued = queued_mouse_begin && - ((static_cast(queued_mouse_end) - static_cast(queued_mouse_begin)) / (int)sizeof(MouseState)) > 0; + const bool haveQueued = !queued_mouse.empty(); if (haveQueued || !deferred_mouse_dirty) { processQueuedMouseState(); // virtual, exactly as the shipped update dispatches it @@ -9679,25 +10205,30 @@ void SwiffPlayer::display() s_streamCounts[7]); } -// push a mouse sample onto the +1104 vc71-shaped vector (grows on the engine heap). +// push a mouse sample onto the queued-mouse vector (+1104 in retail). void SwiffPlayer::queueMouseState(int x, int y, int buttons) { // [TEMP] RW-89 queue tracer (BF2_SWIFFPLAYER_ASLOG): every button change the engine queues and the // queue depth then, plus a depth line every 2000th sample - drive12 showed the host's input-block // flag flat at 0 while no press reached the movie after the multiplayer tab; this says whether the // engine still queues presses (starvation in our drain) or stopped calling (engine-side routing). - if (asLogEnabled()) + if (mouseLogEnabled()) { static int s_lastButtons = 0; static unsigned s_samples = 0; - const int depth = queued_mouse_begin ? (int)((static_cast(queued_mouse_end) - static_cast(queued_mouse_begin)) / (int)sizeof(MouseState)) : 0; + const int depth = (int) queued_mouse.size(); ++s_samples; if (buttons != s_lastButtons || (s_samples % 2000) == 0) - ::renddx9abi::logf("[mouse] queued buttons %d -> %d at (%d,%d) depth=%d sample#%u", s_lastButtons, buttons, x, y, depth, s_samples); + { + unsigned width = 0, height = 0; + if (swiff_host) + hostGetViewportSize(swiff_host, &width, &height); + ::renddx9abi::logf("[mouse] queued buttons %d -> %d at (%d,%d) depth=%d sample#%u hostViewport=%ux%u movie=%dx%d", + s_lastButtons, buttons, x, y, depth, s_samples, width, height, movie_width, movie_height); + } s_lastButtons = buttons; } MouseState ms; ms.x = x; ms.y = y; ms.buttons = buttons; - vc71::vectorRef q(&queued_mouse_aux); - q.push_back(ms); + queued_mouse.push_back(ms); } // text input (Stage 5): these dispatch through the host IME handler + write into a host std::string. @@ -9782,15 +10313,26 @@ void SwiffPlayer::getTextInput1(void* outStdString) } // render capability queries, guarded. -char SwiffPlayer::renderCapability0(int a) { return render_context ? rcCapability0(render_context, a) : 0; } -char SwiffPlayer::renderCapability1(int a) { return render_context ? rcCapability1(render_context, a) : 0; } +char SwiffPlayer::renderCapability0(intptr_t a) { return render_context ? rcCapability0(render_context, a) : 0; } +char SwiffPlayer::renderCapability1(intptr_t a) { return render_context ? rcCapability1(render_context, a) : 0; } // render pair-state, guarded. -void SwiffPlayer::renderSetPairState(int a, int b) +#if defined(_MSC_VER) +void SwiffPlayer::renderSetPairState(intptr_t a, int b) { if (render_context) rcSetPairState(render_context, a, b); } +#else +// [CHOSEN, not recovered] Native spelling of 0x10005F50: `cmp [ecx+0xC],0; je ret 8` else +// `jmp [vtbl+0xD4]` with the caller's two stack arguments, i.e. SwiffRender 0x10154E60 +// setTextureTechnique(const std::string&, int). See docs/macos-c-swiff-re.md. +void SwiffPlayer::renderSetPairState(const std::string& textureName, int techniqueIndex) +{ + if (render_context) + rcSetPairState(render_context, textureName, techniqueIndex); +} +#endif // notify_mouse. Scales the raw (x,y) from the SwiffHost viewport into movie space, // clamps, feeds the movie and the renderer. @@ -9815,8 +10357,9 @@ void SwiffPlayer::notifyMouse(int x, int y, int buttons) // [TEMP] RW-89 mouse tracer (BF2_SWIFFPLAYER_ASLOG): every button transition the host delivers, // raw and in movie space - interactive run drive6 had an OK click that reached no handler and // the logs could not say whether the press ever arrived. [RETIRE-WHEN: RW-89] - if (asLogEnabled() && buttons != mouse_buttons) - ::renddx9abi::logf("[mouse] buttons %d -> %d at raw=(%d,%d) movie=(%d,%d)", mouse_buttons, buttons, x, y, mx, my); + if (mouseLogEnabled() && buttons != mouse_buttons) + ::renddx9abi::logf("[mouse] buttons %d -> %d at raw=(%d,%d) movie=(%d,%d) hostViewport=%ux%u movieSize=%dx%d", + mouse_buttons, buttons, x, y, mx, my, vpW, vpH, movie_width, movie_height); { // [TEMP] stream tracer: the host viewport the mouse scale is derived from (first 3 + full frames) static int s_n = 0; if (streamLogEnabled() && (++s_n <= 3 || s_streamVerbose)) @@ -9834,19 +10377,12 @@ void SwiffPlayer::notifyMouse(int x, int y, int buttons) // pop the front queued sample and deliver it. No-op when the queue is empty. void SwiffPlayer::processQueuedMouseState() { - if (!queued_mouse_begin) - return; - MouseState* begin = static_cast(queued_mouse_begin); - MouseState* end = static_cast(queued_mouse_end); - const int count = static_cast(end - begin); - if (count <= 0) + if (queued_mouse.empty()) return; - const MouseState front = begin[0]; + const MouseState front = queued_mouse.front(); // erase-front: shift the rest down one and retract end (the shipped sub_10007370). - for (int i = 1; i < count; ++i) - begin[i - 1] = begin[i]; - queued_mouse_end = static_cast(queued_mouse_end) - sizeof(MouseState); + queued_mouse.erase(queued_mouse.begin()); notifyMouse(front.x, front.y, front.buttons); } @@ -9855,9 +10391,17 @@ void SwiffPlayer::processQueuedMouseState() // Forwards gameswf rendering callbacks to the matching SwiffRender operations. // setRender and loadMovie must supply render_context before any callback; no null guards. +// The handler is always SwiffPlayer::render_handler, so its owner sits that member's offset below it. +ISwiffRender* SwiffRenderHandler::renderContext() +{ + SwiffPlayer* const owner = reinterpret_cast( + reinterpret_cast(this) - offsetof(SwiffPlayer, render_handler)); + return owner->render_context; +} + namespace { inline void* rhRc(SwiffRenderHandler* self) -{ return *reinterpret_cast(reinterpret_cast(self) + 8); } +{ return self->renderContext(); } inline unsigned rgbaDword(const gameswf::rgba& c) { unsigned d; ::memcpy(&d, &c, 4); return d; } } // anonymous namespace @@ -9875,11 +10419,16 @@ gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_alpha(int w, int h, bi->m_original_height = h; return bi; } +// 0x10005AE0: a NULL image answers NULL before anything is allocated (0x10005AED..0x10005AFE); +// otherwise the dimensions are stored before the renderer call (0x10005B42..0x10005B4E). gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_rgb(image::rgb* im) { + if (!im) + return 0; gameswf::bitmap_info* bi = new gameswf::bitmap_info(); + bi->m_original_width = im->m_width; + bi->m_original_height = im->m_height; bi->m_texture_id = static_cast(rcCreateRgb(rhRc(this), im)); - if (im) { bi->m_original_width = im->m_width; bi->m_original_height = im->m_height; } return bi; } gameswf::bitmap_info* SwiffRenderHandler::create_bitmap_info_rgba(image::rgba* im) @@ -10066,9 +10615,14 @@ bool SwiffRenderHandler::text_extent(void* line, int count, float* w, float* h) SPLA("[stream] text_extent(%p, %d) -> %d w=%.1f h=%.1f", line, count, ok ? 1 : 0, w ? *w : -1.f, h ? *h : -1.f); // [TEMP] RW-89 return ok; } -bool SwiffRenderHandler::text_hit(void* line, int* outPos, int x, int y) +// 0x10005E20: the out slot is the forwarder's own y argument slot (`lea edx,[ebp+0x14]`), so +// it starts as y's bit pattern and is copied to *outPos unconditionally after SwiffRender +0x80 +// (0x10005E3E..0x10005E44). gameswf reads it only on a hit (0x100887DC). +bool SwiffRenderHandler::text_hit(void* line, int* outPos, float x, float y) { - int pos = y; // the shipped forwarder's stack copy of the last argument + int pos; + static_assert(sizeof(pos) == sizeof(y), "the shipped out slot is y's 32-bit stack slot"); + ::memcpy(&pos, &y, sizeof(pos)); const bool hit = rcTextHit(rhRc(this), line, &pos, x, y) != 0; if (outPos) *outPos = pos; return hit; @@ -10083,8 +10637,9 @@ bool SwiffRenderHandler::text_selection(void* line, int* a, int* b) // before it deletes [start, end): with "no selection" the outs are meaningless. [DICE-MOD #46] return has; } -bool SwiffRenderHandler::text_set_selection(void* line, int a, int b, int c, int d) -{ return rcTextSetSelection(rhRc(this), line, a, b, c, d) != 0; } +// 0x10005E90 (`jmp [vtbl+0x88]`): the four float dwords pass through unchanged. +bool SwiffRenderHandler::text_set_selection(void* line, float x1, float y1, float x2, float y2) +{ return rcTextSetSelection(rhRc(this), line, x1, y1, x2, y2) != 0; } void SwiffRenderHandler::text_blur(void* line) { rcTextBlur(rhRc(this), line); } void SwiffRenderHandler::text_set_size(void* line, float size, int flag) { diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h index 1a608292b..dbe3a8323 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayer.h @@ -13,6 +13,13 @@ #include "gameswf/gameswf_types.h" #include "../../../../RendDX9Abi/HfeAbi.h" // dice::hfe::IBase #include "../../../../RendDX9Abi/Frontier.h" +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] One native declaration for host and plugin dispatch. +#include "../../../Menu/ISwiffPlayer.h" +#endif + +#include +#include namespace dice { namespace hfe { @@ -46,10 +53,13 @@ struct SwiffRenderHandler : public gameswf::render_handler { SwiffRenderHandler() {} - // NO data members - the subobject is exactly 4 bytes (its vtable ptr), matching the shipped - // layout (object is 1120 bytes). A Stage-3 forwarder reaches render_context the way the shipped - // code does: this subobject sits at object+4 and render_context at object+12, so the owner is - // reinterpret_cast((char*)this - 4). No back-pointer member is stored. + // NO data members - the subobject is only its vtable ptr, as in the shipped layout. The handler + // is always SwiffPlayer::render_handler (retail: this subobject at object+4, render_context at + // object+12), so a forwarder reaches render_context through its owner, recovered from this + // member's offset by renderContext(). No back-pointer member is stored. + + // The owning SwiffPlayer's render_context. + ISwiffRender* renderContext(); virtual gameswf::bitmap_info* create_bitmap_info_empty(); virtual gameswf::bitmap_info* create_bitmap_info_alpha(int w, int h, unsigned char* data); @@ -93,9 +103,9 @@ struct SwiffRenderHandler : public gameswf::render_handler virtual void text_detach(void* line); // 24 -> +0x74 virtual void text_draw(void* line, const gameswf::matrix* m, unsigned color, int flags); // 25 -> +0x78 virtual bool text_extent(void* line, int count, float* w, float* h); // 26 -> +0x7C - virtual bool text_hit(void* line, int* outPos, int x, int y); // 27 -> +0x80 + virtual bool text_hit(void* line, int* outPos, float x, float y); // 27 -> +0x80 (0x10005E20: float x/y) virtual bool text_selection(void* line, int* a, int* b); // 28 -> +0x84 (AL = has selection) - virtual bool text_set_selection(void* line, int a, int b, int c, int d); // 29 -> +0x88 + virtual bool text_set_selection(void* line, float x1, float y1, float x2, float y2); // 29 -> +0x88 (0x10005E90: jmp, floats) virtual void text_blur(void* line); // 30 -> +0x8C virtual void text_set_size(void* line, float size, int flag); // 31 -> +0x90 virtual void text_caret(void* line, int pos); // 32 -> +0x94 @@ -107,6 +117,7 @@ struct SwiffRenderHandler : public gameswf::render_handler // BF2.exe dispatches into it by raw byte offset (initMainMenuSwiff), so the declaration order here // must never change. +#if defined(_MSC_VER) class ISwiffPlayer : public IBase { public: @@ -152,15 +163,15 @@ class ISwiffPlayer : public IBase // 23 +0x5C virtual ISwiffHost* getSwiffHost() = 0; // 24 +0x60 - virtual char renderCapability0(int a) = 0; + virtual char renderCapability0(intptr_t a) = 0; // 25 +0x64 - virtual char renderCapability1(int a) = 0; + virtual char renderCapability1(intptr_t a) = 0; // 26 +0x68 virtual int getMovieWidth() = 0; // 27 +0x6C virtual int getMovieHeight() = 0; // 28 +0x70 - virtual void renderSetPairState(int a, int b) = 0; + virtual void renderSetPairState(intptr_t a, int b) = 0; // a: the texture name's address // 29 +0x74 virtual void legacyModeOff() = 0; // 30 +0x78 @@ -181,12 +192,13 @@ class ISwiffPlayer : public IBase protected: ~ISwiffPlayer() {} }; +#endif -// SwiffPlayer - the 1120-byte object. Member order and offsets match the IDB local type -// dice_hfe_SwiffPlayer_BF2 exactly; static_asserts in the .cpp hold the size and the load-bearing -// offsets. The ISwiffPlayer base supplies the +0 vtable; the SwiffRenderHandler member supplies the -// +4 one. +// SwiffPlayer - member order matches the IDB local type dice_hfe_SwiffPlayer_BF2 (the retail object +// is 1120 bytes; the +N comments are its offsets). The queued-mouse storage is a std::vector +// (https://github.com/B2BF/OpenBF2/issues/7), so the native object's size differs from retail. The +// ISwiffPlayer base supplies the +0 vtable; the SwiffRenderHandler member supplies the +4 one. class SwiffPlayer : public ISwiffPlayer { @@ -217,15 +229,28 @@ class SwiffPlayer : public ISwiffPlayer virtual void notifyKeyState(int code, int down); virtual void resetModifierState(); virtual void setTextInput(const char* text); +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] Native images share the host declaration. The + // clipboard bodies keep their opaque storage helpers behind these adapters. + virtual void getTextInput0(std::string& out) override { getTextInput0(static_cast(&out)); } + virtual void getTextInput1(std::string& out) override { getTextInput1(static_cast(&out)); } + void getTextInput0(void* outStdString); + void getTextInput1(void* outStdString); +#else virtual void getTextInput0(void* outStdString); virtual void getTextInput1(void* outStdString); +#endif virtual void setSwiffHost(ISwiffHost* host); virtual ISwiffHost* getSwiffHost(); - virtual char renderCapability0(int a); - virtual char renderCapability1(int a); + virtual char renderCapability0(intptr_t a); + virtual char renderCapability1(intptr_t a); virtual int getMovieWidth(); virtual int getMovieHeight(); - virtual void renderSetPairState(int a, int b); +#if defined(_MSC_VER) + virtual void renderSetPairState(intptr_t a, int b); +#else + virtual void renderSetPairState(const std::string& textureName, int techniqueIndex); +#endif virtual void legacyModeOff(); virtual void legacyModeOn(); virtual char getModeFlag(); @@ -236,7 +261,13 @@ class SwiffPlayer : public ISwiffPlayer virtual void setVoipUpdateFlag(char v); private: + // A queued mouse sample (12 bytes), the element of the queued-mouse vector. + struct MouseState { int x; int y; int buttons; }; + void initKeyTranslation(); // SwiffPlayer_initKeyTranslation 0x10005410 + // Drops the movie instance and definition, every script object and _global. + // [CHOSEN, not recovered] issue #7; see the definition. + void releaseMovie(); // +4 - the embedded render handler. gameswf holds a pointer to it via set_render_handler. SwiffRenderHandler render_handler; @@ -281,12 +312,10 @@ class SwiffPlayer : public ISwiffPlayer // +1100 (+3 pad) unsigned char legacy_flag_44c; unsigned char pad_44d[3]; - // +1104..+1116 - the queued-mouse vector (aux/begin/end/capacity), grown on the engine heap. - void* queued_mouse_aux; - void* queued_mouse_begin; - void* queued_mouse_end; - void* queued_mouse_capacity; + // +1104 - the queued mouse samples (retail: a 16-byte VC7.1 vector). + std::vector queued_mouse; + friend struct SwiffRenderHandler; // renderContext() reaches render_context friend IBase* __fastcall RefFactory_ui_SwiffPlayer(unsigned int iid, IBase* parent); }; diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp index 9edcb912a..1019252c0 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.cpp @@ -9,7 +9,6 @@ #include "../../../../RendDX9Abi/HfeAbi.h" #include "../../../../RendDX9Abi/BfMemory.h" -#include "../../../../RendDX9Abi/Vc71Vector.h" namespace dice { namespace hfe { @@ -75,20 +74,39 @@ void SwiffModule::getSingletonList(RD9_HOST_VECTOR_PARAMETER(SingletonRegInfo, / // static_cast(this) yields. namespace { +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] These two ordinals precede EventManager's destructor; +// tools/macos/vtable_audit.py checks them against Clang's provider table. +constexpr unsigned nativeEventRegisterSlot = 11; +constexpr unsigned nativeEventUnregisterSlot = 12; +typedef bool (*EmRegisterFn)(void*, EventCategory, IEventListener*, int); +typedef bool (*EmUnregisterFn)(void*, EventCategory, IEventListener*); +#else typedef int (__thiscall* EmRegisterFn) (void* self, int category, void* handler, int priority); typedef int (__thiscall* EmUnregisterFn)(void* self, int category, void* handler); +#endif inline void eventManagerRegister(int category, void* handler, int priority) { void* em = eventManager; void** vtbl = *reinterpret_cast(em); +#if !defined(_MSC_VER) + reinterpret_cast(vtbl[nativeEventRegisterSlot])( + em, static_cast(category), static_cast(handler), priority); +#else reinterpret_cast(vtbl[0x2C / 4])(em, category, handler, priority); +#endif } inline void eventManagerUnregister(int category, void* handler) { void* em = eventManager; void** vtbl = *reinterpret_cast(em); +#if !defined(_MSC_VER) + reinterpret_cast(vtbl[nativeEventUnregisterSlot])( + em, static_cast(category), static_cast(handler)); +#else reinterpret_cast(vtbl[0x30 / 4])(em, category, handler); +#endif } } // anonymous namespace @@ -142,6 +160,18 @@ IModule* dllmodules[] = 0 }; +#if defined(BF2_STATIC_PLUGINS) +// [CHOSEN, not recovered] The statically linked image's "reload" (Code/StaticPlugins/StaticPlugins.h): +// deinitDll released the module and nulled its slot; a fresh SwiffPlayer.dll mapping would run the +// table's initializer again, so the slot gets a new module before the next initDll. The other image +// statics (gameswf globals, the key-state bytes) are not reset; see docs/macos-c-menu-interact.md. +extern "C" void bf2_swiffplayer_reloadImage() +{ + if (!dllmodules[0]) + dllmodules[0] = new ui::SwiffModule(); +} +#endif + } // namespace hfe } // namespace dice diff --git a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h index 67c91d11b..6a5b8e8a5 100644 --- a/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h +++ b/Code/BF2/External/gameswf/SwiffPlayer/SwiffPlayerModule.h @@ -11,6 +11,10 @@ #ifdef BF2_IMAGE_SWIFFPLAYER #include "../../../../RendDX9Abi/HfeAbi.h" +#if !defined(_MSC_VER) +// [CHOSEN, not recovered] Native callbacks use the host's pointer-sized event arguments. +#include "../../../Game/IEventListener.h" +#endif namespace dice { namespace hfe { @@ -19,9 +23,21 @@ namespace ui { // The one-slot event interface, the same shape RendDX9's ModuleGeom carries (PluginModules.h): the // EventManager pushes four dwords, the handler tests the first two - (category, id). A local copy // rather than a shared one so the SwiffPlayer image does not depend on the RendDX9 module headers. +#if !defined(_MSC_VER) +class ECCoreEventHandler : public ::dice::hfe::IEventListener +#else class ECCoreEventHandler +#endif { public: +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] Both module bodies inspect only category and id. + // Preserve their recovered helper while publishing the actual host callback. + void handleEvent(EventCategory category, unsigned int id, EventNode*, void*) override + { + handleCoreModuleEvent(static_cast(category), static_cast(id), 0, 0); + } +#endif virtual void handleCoreModuleEvent(int category, int id, int a3, int a4) = 0; // +0x00 protected: diff --git a/Code/BF2/External/gameswf/gameswf.h b/Code/BF2/External/gameswf/gameswf.h index 148aca28c..5baf71693 100644 --- a/Code/BF2/External/gameswf/gameswf.h +++ b/Code/BF2/External/gameswf/gameswf.h @@ -149,12 +149,27 @@ namespace gameswf struct as_object; + struct as_object_interface; + + // The registry of live script objects, kept by as_object_interface's constructors and + // destructor so the movie teardown (release_script_objects) also reaches objects that only + // reference each other. [CHOSEN, not recovered] issue #7 + // (https://github.com/B2BF/OpenBF2/issues/7). + void register_script_object(as_object_interface* obj); + void unregister_script_object(as_object_interface* obj); // This is the base class for all ActionScript-able objects // ("as_" stands for ActionScript). struct as_object_interface : public resource { - virtual ~as_object_interface() {} + // [CHOSEN, not recovered] issue #7: registration, see register_script_object. + as_object_interface() { register_script_object(this); } + as_object_interface(const as_object_interface& other) : resource(other) { register_script_object(this); } + virtual ~as_object_interface() { unregister_script_object(this); } + + // [CHOSEN, not recovered] issue #7: a safe downcast for the movie teardown; character + // answers itself. movie declares the same slot (gameswf_impl.h). + virtual character* cast_to_character() { return 0; } // [DICE-MOD SwiffPlayer: a SAFE downcast to as_object, following the cast_to_font / // cast_to_character_def pattern above. Needed by the AS2 `addProperty` builtin, whose @@ -890,9 +905,10 @@ namespace gameswf virtual void text_detach(void* /*line*/) {} virtual void text_draw(void* /*line*/, const matrix* /*m*/, unsigned /*color*/, int /*flags*/) {} virtual bool text_extent(void* /*line*/, int /*count*/, float* /*w*/, float* /*h*/) { return false; } - virtual bool text_hit(void* /*line*/, int* /*out_pos*/, int /*x*/, int /*y*/) { return false; } + // [DICE-MOD SwiffPlayer] float coordinates: SwiffPlayer.dll 0x100887A5..0x100887D7 / 0x10088823..0x1008883B + virtual bool text_hit(void* /*line*/, int* /*out_pos*/, float /*x*/, float /*y*/) { return false; } virtual bool text_selection(void* /*line*/, int* a, int* b) { if (a) *a = 0; if (b) *b = 0; return false; } // [DICE-MOD SwiffPlayer #46] true = a selection exists - virtual bool text_set_selection(void* /*line*/, int, int, int, int) { return false; } + virtual bool text_set_selection(void* /*line*/, float, float, float, float) { return false; } virtual void text_blur(void* /*line*/) {} virtual void text_set_size(void* /*line*/, float /*size*/, int /*flag*/) {} virtual void text_caret(void* /*line*/, int /*pos*/) {} diff --git a/Code/BF2/External/gameswf/gameswf_action.cpp b/Code/BF2/External/gameswf/gameswf_action.cpp index ea848e5bf..8a9147af9 100644 --- a/Code/BF2/External/gameswf/gameswf_action.cpp +++ b/Code/BF2/External/gameswf/gameswf_action.cpp @@ -6,6 +6,10 @@ // Implementation and helpers for SWF actions. +// [CHOSEN, not recovered] issue #7: the script-object registry. Included before the gameswf headers: +// MSVC's pulls in , whose isfinite template the fake isfinite() macro of +// base/tu_math.h would otherwise rename. +#include #include "gameswf_action.h" // [TEMP] RW-89 diagnostic: the last member name ActionGetMember read, so the two 'invalid object' // errors below can say WHICH member came back undefined. Remove with the tracers. @@ -4263,8 +4267,11 @@ namespace gameswf // "[object Object]" - which is what makes the shipped operator== tell two clips // apart. The function arms format "" / "" the // same way there; they are not on any measured path and stay stock here. + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): %zX prints the + // whole address, so two objects never alias through their low 32 bits; on x86 it is + // the shipped %X of the 32-bit address. The three function/object arms share this. char buf[52]; - _snprintf(buf, 50, "", (unsigned int) (uintptr_t) m_object_value); + _snprintf(buf, 50, "", (size_t) (uintptr_t) m_object_value); buf[50] = 0; m_string_value = buf; } @@ -4272,13 +4279,13 @@ namespace gameswf else if (m_type == C_FUNCTION) { char buffer[50]; - snprintf(buffer, 50, "", (unsigned) m_c_function_value); + snprintf(buffer, 50, "", (size_t) (uintptr_t) m_c_function_value); m_string_value = buffer; } else if (m_type == AS_FUNCTION) { char buffer[50]; - snprintf(buffer, 50, "", (unsigned) m_as_function_value); + snprintf(buffer, 50, "", (size_t) (uintptr_t) m_as_function_value); m_string_value = buffer; } else @@ -4906,6 +4913,101 @@ namespace gameswf } + void as_environment::release_values(array* held) + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Only this + // environment's own storage is emptied; m_target, m_this_object, m_super_ctor and + // m_register_env hold no references. + { + for (int i = 0; i < m_stack.size(); i++) + { + hold_script_value(held, m_stack[i]); + } + m_stack.resize(0); + for (int i = 0; i < m_registers.size(); i++) + { + hold_script_value(held, m_registers[i]); + } + m_registers.resize(0); + for (stringi_hash::iterator it = m_variables.begin(); it != m_variables.end(); ++it) + { + hold_script_value(held, it->second); + } + m_variables.clear(); + for (int i = 0; i < m_local_frames.size(); i++) + { + hold_script_value(held, m_local_frames[i].m_value); + } + m_local_frames.resize(0); + } + + + // [CHOSEN, not recovered] issue #7: the live script objects, by address. Allocated on first + // use and never freed, so objects destroyed during static destruction still find it. + static std::unordered_set* s_script_objects = NULL; + + void register_script_object(as_object_interface* obj) + { + if (s_script_objects == NULL) + { + s_script_objects = new std::unordered_set; + } + s_script_objects->insert(obj); + } + + void unregister_script_object(as_object_interface* obj) + { + if (s_script_objects != NULL) + { + s_script_objects->erase(obj); + } + } + + + void release_script_objects() + // [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7). A movie's clips + // and objects reference each other from script state - `this` and `_parent` left in a register + // bank, a clip stored in another clip's variable or in a class's static property, a prototype + // and its constructor, a clip removed from its parent while its own scripts still reference + // it - so dropping the movie's last reference freed nothing. `held` keeps every registered + // object alive while the edges are cleared, so the registry does not change under the loop; + // its destruction then drops the last references to objects that no longer reference each + // other. Objects nobody counts (a zero reference count: s_sprite_builtins, stack temporaries) + // are left alone. + { + release_library_classes(); + if (s_script_objects == NULL) + { + return; + } + array held; + for (std::unordered_set::iterator it = s_script_objects->begin(); it != s_script_objects->end(); ++it) + { + if ((*it)->get_ref_count() > 0) + { + held.push_back(as_value(*it)); + } + } + for (int i = 0, n = held.size(); i < n; i++) + { + as_object_interface* obj = held[i].to_object(); + if (obj == NULL) + { + continue; + } + if (character* ch = obj->cast_to_character()) + { + ch->release_script_values(&held); + } + else if (as_object* ao = obj->cast_to_as_object()) + { + ao->clear(); + ao->m_getters.clear(); + ao->m_setters.clear(); + } + } + } + + int as_environment::find_local(const tu_string& varname) const // Search the active frame for the named var; return its index // in the m_local_frames stack if found. @@ -5229,6 +5331,18 @@ namespace gameswf // onDoublePress. const tu_string& event_id::get_function_name() const { + // Bind the DICE events by enum value: the retained upstream socket-event + // enum has an extra entry absent from its positional name table below. + if (m_id == CONSTRUCT) + { + static const tu_string name("onConstruct"); + return name; + } + if (m_id == DOUBLE_PRESS) + { + static const tu_string name("onDoublePress"); + return name; + } static tu_string s_function_names[EVENT_COUNT] = { "INVALID", // INVALID diff --git a/Code/BF2/External/gameswf/gameswf_action.h b/Code/BF2/External/gameswf/gameswf_action.h index b0c101dbd..b40d97bd6 100644 --- a/Code/BF2/External/gameswf/gameswf_action.h +++ b/Code/BF2/External/gameswf/gameswf_action.h @@ -11,6 +11,9 @@ #include "gameswf.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] bf2x87::lowUInt32 +#endif #include "gameswf_types.h" #include @@ -37,6 +40,46 @@ namespace gameswf // [DICE-MOD SwiffPlayer #38] the narrow twin: Mod.getCurrentModName (sub_1004F950) assigns the // +44 tu_string from a plain host string and CLEARS the +60 wide side, the mirror of the above. void assign_dice_string_object_narrow(as_object_interface* object, const char* text); + +#if !defined(_WIN32) + // [CHOSEN, not recovered] gameswf and DICE's String object keep text as 16-bit Windows + // wchar_t units (Uint16). The host's std::wstring/wchar_t is 32 bits on POSIX, so the + // shipped `reinterpret_cast(wide)` handed over 'W',0,'e',0,... and every + // localized menu string ended after its first character. dice_utf16 converts one wchar_t + // to one Uint16 (count-preserving; above U+FFFF becomes U+FFFD). The temporary lives to + // the end of the full expression that names it (docs/macos-c-asan-heap.md). + struct dice_utf16 + { + explicit dice_utf16(const wchar_t* wide) + { + if (!wide) { m_null = true; return; } + for (; *wide; ++wide) m_units.push_back(unit(*wide)); + m_units.push_back(0); + } + operator const Uint16*() const { return m_null ? 0 : &m_units[0]; } + private: + static Uint16 unit(wchar_t c) { return (unsigned int) c > 0xFFFFu ? (Uint16) 0xFFFD : (Uint16) c; } + array m_units; + bool m_null = false; + }; + // The opposite boundary: Uint16 text to the renderer's native wchar_t (text_set). + struct dice_wide + { + explicit dice_wide(const Uint16* units) + { + if (units) for (; *units; ++units) m_chars.push_back((wchar_t) *units); + m_chars.push_back(0); + } + operator const wchar_t*() const { return &m_chars[0]; } + private: + array m_chars; + }; +#define BF2_DICE_UTF16(wide) ((const Uint16*) ::gameswf::dice_utf16(wide)) +#define BF2_DICE_WIDE(units) ((const wchar_t*) ::gameswf::dice_wide(units)) +#else +#define BF2_DICE_UTF16(wide) (reinterpret_cast(wide)) +#define BF2_DICE_WIDE(units) ((const wchar_t*) (units)) +#endif void array_object_push(as_object* arr, const as_value& v); @@ -275,7 +318,11 @@ namespace gameswf // way to do it. Everything else just // continues to work. -#if (WCHAR_MAX != MAXINT) +#if !defined(_WIN32) && (WCHAR_MAX > 0xFFFF) + // [CHOSEN, not recovered] MAXINT is undefined here, so the stock test below picked + // the 16-bit decoder for the 32-bit POSIX wchar_t. Decode native characters. + tu_string::encode_utf8_from_wchar(&m_string_value, (const uint32 *)wstr); +#elif (WCHAR_MAX != MAXINT) tu_string::encode_utf8_from_wchar(&m_string_value, (const uint16 *)wstr); #else # if (WCHAR_MAX != MAXSHORT) @@ -394,7 +441,12 @@ namespace gameswf void operator^=(const as_value& v) { set_int(int(this->to_number()) ^ int(v.to_number())); } void shl(const as_value& v) { set_int(int(this->to_number()) << int(v.to_number())); } void asr(const as_value& v) { set_int(int(this->to_number()) >> int(v.to_number())); } +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + void lsr(const as_value& v) { set_int((bf2x87::lowUInt32(this->to_number()) >> int(v.to_number()))); } +#else void lsr(const as_value& v) { set_int((Uint32(this->to_number()) >> int(v.to_number()))); } +#endif void string_concat(const tu_string& str); @@ -773,6 +825,17 @@ namespace gameswf assert(m_action_buffer); } + // Releases the property object lazy_create_properties took a reference on (stock 2006 had + // no destructor and leaked it with every function used as an object). + // [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7). + ~as_as_function() + { + if (m_properties) + { + m_properties->drop_ref(); + } + } + void set_is_function2() { m_is_function2 = true; } void set_local_register_count(uint8 ct) { assert(m_is_function2); m_local_register_count = ct; } void set_function2_flags(uint16 flags) { assert(m_is_function2); m_function2_flags = flags; } @@ -954,9 +1017,42 @@ namespace gameswf // [DICE-MOD SwiffPlayer: dotted-path resolution through OBJECT members, with the shipped // _global fallback - the resolver get_variable/set_variable use. See the .cpp.] as_object_interface* find_object_path(const tu_string& path, as_object_interface* start) const; + + // Movie teardown: appends every object or function held on the stack, in the registers, + // the variables and the local frames to *held, then empties them. + // [CHOSEN, not recovered] issue #7; see release_script_objects. + void release_values(array* held); }; + // Appends v to *held when it is an object or an ActionScript function, the only values that + // can keep another object alive. A helper of the movie teardown (release_script_objects). + // [CHOSEN, not recovered] issue #7. + inline void hold_script_value(array* held, const as_value& v) + { + if (v.get_type() == as_value::OBJECT || v.get_type() == as_value::AS_FUNCTION) + { + held->push_back(v); + } + } + + // Breaks every script reference cycle between the live script objects, so plain reference + // counting can free them once their owners let go. Every registered clip and object (see + // register_script_object), reachable from the movie or not, is cleared: a clip's environment, + // event handlers and children (without UNLOAD events), an object's members, accessors and + // prototype. Runs no ActionScript. Afterwards every script object is unusable and _global is + // empty: call it only when the whole player is going away, right before its movie's last + // reference is dropped and _global is reset, and only when no other player is alive + // (SwiffPlayer::releaseMovie counts them), so nothing still in use is cleared. + // [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7): our gameswf + // replaces the shipped player, whose own teardown is not recovered. + void release_script_objects(); + + // Drops the Object.registerClass bindings of every library definition (gameswf_impl.cpp). + // Part of release_script_objects. [CHOSEN, not recovered] issue #7. + void release_library_classes(); + + // Parameters/environment for C functions callable from ActionScript. struct fn_call { diff --git a/Code/BF2/External/gameswf/gameswf_button.cpp b/Code/BF2/External/gameswf/gameswf_button.cpp index 1389c03a4..1c829fd8c 100644 --- a/Code/BF2/External/gameswf/gameswf_button.cpp +++ b/Code/BF2/External/gameswf/gameswf_button.cpp @@ -7,6 +7,7 @@ #include "gameswf_button.h" +#include "gameswf_log.h" #include "gameswf_action.h" #include "gameswf_render.h" @@ -144,6 +145,9 @@ frame loop: namespace gameswf { +#if !defined(_MSC_VER) + const char* swf_list_trace_path(character* ch); // [TEMP] gameswf_impl.cpp +#endif // [DICE-MOD SwiffPlayer #51] generate_mouse_button_events (and the RW-89 tracer that lived in it) // are gone: the shipped player has no root-level dispatcher, every character runs its own mouse // pass - for buttons, button_character_instance::mouse_update below. @@ -177,6 +181,20 @@ namespace gameswf bool m_first_mouse_frame; bool m_mouse_pressed; + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. The state + // characters are walked too; the button keeps owning them. + virtual void release_script_values(array* held) + { + character::release_script_values(held); + for (int i = 0; i < m_record_character.size(); i++) + { + if (m_record_character[i] != NULL) + { + held->push_back(as_value(m_record_character[i].get_ptr())); + } + } + } + button_character_instance(button_character_definition* def, movie* parent, int id) : character(parent, id), @@ -464,6 +482,14 @@ namespace gameswf // [UNRESOLVED: whether that ordering is observable]. void fire_transition(int c) { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: a button transition (its actions queue on the parent). + if (swf_list_trace_on()) + { + SWF_LIST_TRACE("button cond=0x%x on '%s' (%d action records)", c, swf_list_trace_path(this), + m_def->m_button_actions.size()); + } +#endif if (m_def->m_sound != NULL) { sound_handler* s = get_sound_handler(); diff --git a/Code/BF2/External/gameswf/gameswf_dlist.cpp b/Code/BF2/External/gameswf/gameswf_dlist.cpp index 7f3615e3b..2b0715c90 100644 --- a/Code/BF2/External/gameswf/gameswf_dlist.cpp +++ b/Code/BF2/External/gameswf/gameswf_dlist.cpp @@ -189,6 +189,12 @@ namespace gameswf if (dobj.m_character->get_depth() == depth) { +#if !defined(_MSC_VER) + if (g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("replace at depth %d in list %p (size %d)", depth, (void*) this, size); + } +#endif dobj.set_character(NULL); m_display_object_array.remove(index); } @@ -328,6 +334,10 @@ namespace gameswf smart_ptr old_ch = di.m_character; + // [DICE-MOD SwiffPlayer #58] 0x100A8080 releases the root's mouse capture held by the + // outgoing character or anything beneath it (see remove_display_object below). + old_ch->release_mouse_capture_within(); + // Put the new character in its place. assert(ch); ch->set_depth(depth); @@ -416,6 +426,16 @@ namespace gameswf // Remove reference only. di.m_ref = false; + // [DICE-MOD SwiffPlayer #58] 0x100A7A20 (0x100A7A67..0x100A7AAA): a removed character that + // holds the root's mouse capture, or contains its holder, releases it. The holder took it on + // its press (#51) and gives it back only in its own release transition, which a character + // off the list never runs again; every other state machine stays gated off. mainMenu.swf's + // CREATE ACCOUNT button: its onPress runs createOffline, which on success jumps the root + // from the account page (frame 19) to the main menu (49) and removes the pressed button, so + // after an SP account creation no click reached the menu. The shipped body then clears the + // removed character's parent (+0x64); the port keeps the parent for its dead reference (#42) + // [CHOSEN, not recovered]. + if (di.m_character.get_ptr()) di.m_character->release_mouse_capture_within(); if (di.m_character.get_ptr()) di.m_character->mark_dead(); // [DICE-MOD SwiffPlayer #42] dead from the removal on } @@ -423,6 +443,12 @@ namespace gameswf void display_list::clear() // clear the display list. { +#if !defined(_MSC_VER) + if (g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("clear list %p (size %d, sprite destroyed)", (void*) this, m_display_object_array.size()); + } +#endif int i, n = m_display_object_array.size(); for (i = 0; i < n; i++) { @@ -433,8 +459,24 @@ namespace gameswf m_display_object_array.clear(); } - - + + + void display_list::release_characters(array* held) + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Unlike clear(), + // no UNLOAD: the movie is being destroyed with its scripts already disconnected. + { + for (int i = 0, n = m_display_object_array.size(); i < n; i++) + { + character* ch = m_display_object_array[i].m_character.get_ptr(); + if (ch != NULL) + { + held->push_back(as_value(ch)); + } + } + m_display_object_array.clear(); + } + + void display_list::reset() // reset the references to the display list. { @@ -466,6 +508,14 @@ namespace gameswf r++; } } +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: a sweep inside a mouse pass (the owner is named by the goto line). + if (r > 0 && g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("sweep list %p removed %d, %d left%s", (void*) this, r, m_display_object_array.size(), + m_display_object_array.size() == 0 ? " - EMPTY (buffer freed)" : ""); + } +#endif //printf("### removed characters: %4d active characters: %4d\n", r, m_display_object_array.size()); } diff --git a/Code/BF2/External/gameswf/gameswf_dlist.h b/Code/BF2/External/gameswf/gameswf_dlist.h index eecb2e9f8..01a91accf 100644 --- a/Code/BF2/External/gameswf/gameswf_dlist.h +++ b/Code/BF2/External/gameswf/gameswf_dlist.h @@ -97,6 +97,11 @@ namespace gameswf // reset the references to the display list. void reset(); + // Movie teardown (release_script_objects): appends every character, removed ones included, to + // *held and empties the list without sending UNLOAD, so no ActionScript runs. + // [CHOSEN, not recovered] issue #7. + void release_characters(array* held); + // remove unreferenced objects. void update(); diff --git a/Code/BF2/External/gameswf/gameswf_impl.cpp b/Code/BF2/External/gameswf/gameswf_impl.cpp index 79d582c23..d3303f143 100644 --- a/Code/BF2/External/gameswf/gameswf_impl.cpp +++ b/Code/BF2/External/gameswf/gameswf_impl.cpp @@ -14,6 +14,7 @@ #include "base/tu_file.h" +#include "../../Core/MsvcCrtCompat.h" // [CHOSEN, not recovered] _snprintf_s/_TRUNCATE outside MSVC #include "base/utility.h" #include "gameswf_action.h" #include "gameswf_button.h" @@ -501,6 +502,20 @@ namespace gameswf return res; } + virtual void release_registered_classes() + // [CHOSEN, not recovered] issue #7: Object.registerClass binds through the exports only. + { + for (stringi_hash >::iterator it = m_exports.begin(); it != m_exports.end(); ++it) + { + character_def* cdef = it->second != NULL ? it->second->cast_to_character_def() : NULL; + if (cdef != NULL && cdef->m_registered_class != NULL) + { + cdef->m_registered_class->drop_ref(); + cdef->m_registered_class = NULL; + } + } + } + virtual void add_import(const char* source_url, int id, const char* symbol) // Adds an entry to a table of resources that need to // be imported from other movies. Client code must @@ -1066,7 +1081,7 @@ namespace gameswf // Recompute pixel scale. float scale_x = m_viewport_width / TWIPS_TO_PIXELS(m_def->m_frame_size.width()); float scale_y = m_viewport_height / TWIPS_TO_PIXELS(m_def->m_frame_size.height()); - m_pixel_scale = fmax(scale_x, scale_y); + m_pixel_scale = tu_util::fmax(scale_x, scale_y); } @@ -1591,6 +1606,20 @@ namespace gameswf static tu_string s_workdir; + void release_library_classes() + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. The library + // keeps its definitions for the next player; their class bindings belong to the released + // movie, and a stale class's constructor would run in an environment that no longer exists. + { + for (stringi_hash< smart_ptr >::iterator it = s_movie_library.begin(); it != s_movie_library.end(); ++it) + { + if (it->second != NULL) + { + it->second->release_registered_classes(); + } + } + } + void save_extern_movie(movie_interface* m) { s_extern_sprites.push_back(m); @@ -3153,11 +3182,38 @@ namespace gameswf // [TEMP] RW-89 mouse tracer: the press/release lines the interactive drives read, in the format // of the stock-era tracer that lived beside generate_mouse_button_events. [RETIRE-WHEN: RW-89] +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: BF2_SWF_EMPTY_LIST_GUARD=1 ends a sprite's mouse child pass when a + // handler emptied its list (off by default; not shipped behaviour, see the mouse_update loop). + static bool swf_empty_list_guard() + { + static int s_on = -1; + if (s_on < 0) + { + const char* v = getenv("BF2_SWF_EMPTY_LIST_GUARD"); + s_on = (v && v[0] == '1') ? 1 : 0; + } + return s_on != 0; + } + + // [TEMP] c-swf-disconnect: the tracer's path, for the other gameswf files. + const char* swf_list_trace_path(character* ch) { return swf_trace_path(ch); } +#endif + static void swf_trace_mouse(const char* what, character* ch) { log_error("[mouse] %s -> %s\n", what, swf_trace_path(ch)); } + // [TEMP] [CHOSEN, not recovered] Input-only diagnostics never inspect script values. + // [RETIRE-WHEN: ea-popup-input] Remove after live login/Close input is verified. + static bool swf_trace_input_enabled() + { + const char* value = ::getenv("BF2_SWIFFPLAYER_INPUTLOG"); + return value && value[0] == '1' && value[1] == '\0'; + } + static bool s_trace_mouse_pass = false; + struct sprite_instance : public character { smart_ptr m_def; @@ -3298,6 +3354,20 @@ namespace gameswf bool m_dead; // [DICE-MOD SwiffPlayer #42] see character::mark_dead virtual void mark_dead() { m_dead = true; } + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Adds the + // environment, the class prototype and every child to the base character's values. + virtual void release_script_values(array* held) + { + character::release_script_values(held); + m_as_environment.release_values(held); + if (m_class_proto != NULL) + { + held->push_back(as_value(m_class_proto.get_ptr())); + m_class_proto = NULL; + } + m_display_list.release_characters(held); + } + // [DICE-MOD SwiffPlayer #53] frame 0's DoAction tags, queued by on_event_load's // execute_frame_tags(0), are NOT run at placement: the shipped on_event_load // (sub_10081870) frees the action list (+224) right after the tags, and the script runs @@ -3509,8 +3579,8 @@ namespace gameswf // // The shipped pass, per frame, per sprite: // - // 1. its own state machine runs only while nobody holds the pointer or this sprite does (the - // root's active entity). `consumed` - a sibling above already claimed the point - leaves + // 1. its own state machine runs while this sprite holds the pointer, or while nobody does + // and this is not the root movie. `consumed` - a sibling above claimed the point - leaves // both state bits clear, so the sprite sees "up, outside"; otherwise bit 1 is a button // down and bit 0 is point_test_world on the pointer in world twips; // 2. the first frame only latches, and nothing fires unless m_mouse_enabled; @@ -3530,9 +3600,25 @@ namespace gameswf { // Keep this (particularly m_as_environment) alive during any method calls! smart_ptr this_ptr(this); +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: nesting of mouse passes for the [swf-list] tracer. + struct pass_depth { pass_depth() { g_swf_mouse_pass_depth++; } ~pass_depth() { g_swf_mouse_pass_depth--; } } depth_scope; +#endif movie* active = m_root->get_active_entity(); - if (active == this || active == NULL) + const bool trace_root = this == m_root->get_root_movie() && swf_trace_input_enabled(); + if (trace_root) + { + static int previous_buttons = -1; + int x, y, buttons; + m_root->get_mouse_state(&x, &y, &buttons); + s_trace_mouse_pass = buttons != previous_buttons; + previous_buttons = buttons; + if (s_trace_mouse_pass) + log_error("[mouse] dispatch at=(%d,%d) buttons=%d capture=%s\n", x, y, buttons, + active ? swf_trace_path(active->cast_to_character()) : "none"); + } + if (active == this || (active == NULL && this != m_root->get_root_movie())) { m_prev_mouse_flags = m_mouse_flags; m_mouse_flags = 0; @@ -3554,6 +3640,10 @@ namespace gameswf m_prev_mouse_flags = m_mouse_flags; m_first_mouse_frame = false; } + if (s_trace_mouse_pass && (m_mouse_flags & 1) && m_mouse_enabled) + log_error("[mouse] hit %s id=%d depth=%d frame=%d flags=%u previous=%u dead=%d\n", + swf_trace_path(this), get_id(), get_depth(), get_current_frame(), + m_mouse_flags, m_prev_mouse_flags, m_dead); if (m_mouse_enabled && m_mouse_flags != m_prev_mouse_flags) { switch (m_mouse_flags | (m_prev_mouse_flags << 2)) @@ -3621,14 +3711,48 @@ namespace gameswf { for (int i = m_display_list.get_character_count() - 1; i >= 0; i--) { +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: the shipped loop (0x10080265..0x100802A2) caches the + // count and re-reads the buffer; an emptied list leaves the buffer NULL and the + // next read faults, in the shipped DLL as well. BF2_SWF_EMPTY_LIST_GUARD=1 (off by + // default; not shipped behaviour) ends the pass there instead. + if (m_display_list.get_character_count() <= i) + { + SWF_LIST_TRACE("loop '%s' i=%d past size %d%s", swf_trace_path(this), i, + m_display_list.get_character_count(), + m_display_list.get_character_count() == 0 ? " - EMPTY, buffer freed, next read faults" : " (stale slot)"); + if (m_display_list.get_character_count() == 0 && swf_empty_list_guard()) + { + break; + } + } +#endif const display_object_info& dobj = m_display_list.get_display_object(i); character* ch = dobj.m_ref ? dobj.m_character.get_ptr() : NULL; if (ch != NULL && ch->get_visible()) { +#if !defined(_MSC_VER) + const int trace_before = m_display_list.get_character_count(); +#endif + const bool was_consumed = consumed; consumed = ch->mouse_update(consumed) || consumed; + if (s_trace_mouse_pass && consumed && !was_consumed) + log_error("[mouse] consumed by %s id=%d depth=%d\n", + swf_trace_path(ch), ch->get_id(), ch->get_depth()); +#if !defined(_MSC_VER) + if (m_display_list.get_character_count() != trace_before && swf_list_trace_on()) + { + char child_name[96]; + snprintf(child_name, sizeof(child_name), "%s", ch->get_name().c_str()); + SWF_LIST_TRACE("dlist CHANGED '%s' %d -> %d inside the child pass, after child #%d '%s'", + swf_trace_path(this), trace_before, + m_display_list.get_character_count(), i, child_name); + } +#endif } } } + if (trace_root) s_trace_mouse_pass = false; return consumed || ((m_mouse_flags & 1) != 0 && m_mouse_enabled); } @@ -3914,6 +4038,12 @@ namespace gameswf // the pass with a zero delta. The label form (goto_labeled_frame, vtable +28) applies // at once. Stock 2006 replayed the timeline inline here. m_pending_goto_frames.push_back(target_frame_number); +#if !defined(_MSC_VER) + if (g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("gotoFrame queued '%s' -> %d", swf_trace_path(this), target_frame_number); + } +#endif // goto_frame stops by default. m_play_state = STOP; @@ -3983,6 +4113,19 @@ namespace gameswf { // Keep this (particularly m_as_environment) alive during execution! smart_ptr this_ptr(this); +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: gotos inside a mouse pass, or any that change the list size. + const int trace_dl0 = m_display_list.get_character_count(); + const int trace_from = m_current_frame; +#define SWF_TRACE_GOTO_SWEPT() \ + if (swf_list_trace_on() && (g_swf_mouse_pass_depth > 0 || m_display_list.get_character_count() != trace_dl0)) \ + { \ + SWF_LIST_TRACE("goto '%s' frame %d -> %d dlist %d -> %d", swf_trace_path(this), trace_from, \ + target_frame_number, trace_dl0, m_display_list.get_character_count()); \ + } +#else +#define SWF_TRACE_GOTO_SWEPT() +#endif // [DICE-MOD SwiffPlayer #53] a goto applied before the first pass takes the owed // frame-0 script with it: the target frame's actions are what runs from here on. @@ -4031,6 +4174,7 @@ namespace gameswf m_time_remainder = 0; m_update_frame = false; m_display_list.update(); + SWF_TRACE_GOTO_SWEPT(); on_event(event_id::ENTER_FRAME); do_actions(); return; @@ -4156,6 +4300,7 @@ namespace gameswf m_time_remainder = 0; m_update_frame = false; m_display_list.update(); + SWF_TRACE_GOTO_SWEPT(); on_event(event_id::ENTER_FRAME); do_actions(); } @@ -4170,6 +4315,12 @@ namespace gameswf // [DICE-MOD SwiffPlayer #45] applied at once, as the shipped +28 (0x100802E0) // dispatches straight to +24; the 2006 stop-by-default is kept for the callers // that rely on it (the AS methods set their own state right after). +#if !defined(_MSC_VER) + if (g_swf_mouse_pass_depth > 0) + { + SWF_LIST_TRACE("gotoLabel '%s' -> '%s'", swf_trace_path(this), label); + } +#endif apply_goto_frame(target_frame); m_play_state = STOP; return true; @@ -5199,6 +5350,14 @@ namespace gameswf smart_ptr this_ptr(this); bool called = false; +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect: the events a mouse pass fires (press, release, roll over/out). + if (g_swf_mouse_pass_depth > 0 && swf_list_trace_on()) + { + SWF_LIST_TRACE("event %d/%s on '%s' dlist=%d", (int) id.m_id, id.get_function_name().c_str(), + swf_trace_path(this), m_display_list.get_character_count()); + } +#endif // [DICE-MOD SwiffPlayer #51] sub_10081620: the clip-event handler when there is one, ELSE // the member of that name, and only a defined one. Stock 2006 called both when both existed. @@ -5225,6 +5384,13 @@ namespace gameswf } } } +#if !defined(_MSC_VER) + if (called && g_swf_mouse_pass_depth > 0 && swf_list_trace_on()) + { + SWF_LIST_TRACE("event %d/%s done on '%s' dlist=%d", (int) id.m_id, id.get_function_name().c_str(), + swf_trace_path(this), m_display_list.get_character_count()); + } +#endif return called; } @@ -5538,6 +5704,7 @@ namespace gameswf movie* parent = sprite->get_parent(); log_error("[removeMovieClip] '%s' depth=%d parent=%p\n", // [TEMP] RW-88 nav tracer swf_trace_path(sprite), sprite->get_depth(), parent); + SWF_LIST_TRACE("removeMovieClip '%s' depth=%d", swf_trace_path(sprite), sprite->get_depth()); if (parent) { // Keep the instance alive across its own removal - the caller may still be running diff --git a/Code/BF2/External/gameswf/gameswf_impl.h b/Code/BF2/External/gameswf/gameswf_impl.h index 3774b155d..084febe74 100644 --- a/Code/BF2/External/gameswf/gameswf_impl.h +++ b/Code/BF2/External/gameswf/gameswf_impl.h @@ -57,6 +57,10 @@ namespace gameswf // body is not located; the rule reproduces the golden.] False when no exported font matches.] virtual bool get_exported_font_name(const font* f, tu_string* out) { return false; } virtual character_def* get_character_def(int id) = 0; + // Movie teardown: drops the classes Object.registerClass bound to this definition's + // exports, so a definition kept in the library for the next player holds no function of + // the released movie. [CHOSEN, not recovered] issue #7; see release_script_objects. + virtual void release_registered_classes() {} virtual bool get_labeled_frame(const char* label, int* frame_number) = 0; @@ -427,6 +431,25 @@ namespace gameswf // generic_character::m_def_owner); a sprite already owns its definition through m_def. virtual void hold_definition(character_def* /*def*/) {} + // Movie teardown (release_script_objects): appends every object or function this character + // references from script state (event handlers, the mask; overrides add their environment + // and children) to *held, then clears its own references, so clips of a released movie no + // longer keep each other alive. Runs no ActionScript. + // [CHOSEN, not recovered] issue #7 (https://github.com/B2BF/OpenBF2/issues/7). + virtual void release_script_values(array* held) + { + for (hash::iterator it = m_event_handlers.begin(); it != m_event_handlers.end(); ++it) + { + hold_script_value(held, it->second); + } + m_event_handlers.clear(); + if (m_mask != NULL) + { + held->push_back(as_value(m_mask.get_ptr())); + m_mask = NULL; + } + } + character(movie* parent, int id) : m_id(id), @@ -595,6 +618,16 @@ namespace gameswf { return; } + release_mouse_capture_within(); + } + + // The capture walk set_visible ends with (sub_1007F030), also inlined by the display list's + // remove_display_object (0x100A7A20: 0x100A7A67..0x100A7AAA) and replace_display_object + // (0x100A8080: 0x100A80B3..0x100A80ED) for the character leaving the list: when the root's + // active entity is this character or lies beneath it, the capture is dropped. Both list + // bodies fetch the root through sub_10071710 (the global root, see the [CHOSEN] note above). + void release_mouse_capture_within() + { movie* owner = this; // the nearest sprite: only a sprite answers get_root() while (owner != NULL && owner->get_root() == NULL) { diff --git a/Code/BF2/External/gameswf/gameswf_log.cpp b/Code/BF2/External/gameswf/gameswf_log.cpp index 58c8556ff..fe07c9a58 100644 --- a/Code/BF2/External/gameswf/gameswf_log.cpp +++ b/Code/BF2/External/gameswf/gameswf_log.cpp @@ -11,6 +11,12 @@ #include #include +#if !defined(_MSC_VER) +#include +#include +#include +#include +#endif namespace gameswf @@ -69,6 +75,51 @@ namespace gameswf s_log_callback(true, s_buffer); } + +#if !defined(_MSC_VER) + int g_swf_mouse_pass_depth = 0; + + bool swf_list_trace_on() + { + static int s_on = -1; + if (s_on < 0) + { + const char* v = getenv("BF2_SWF_LIST_TRACE"); + s_on = (v && v[0] >= '1' && v[0] <= '9') ? 1 : 0; + } + return s_on != 0; + } + + void swf_list_trace(const char* fmt, ...) + { + static char s_last[512]; + static int s_repeats = 0; + char line[512]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + if (strcmp(line, s_last) == 0) + { + s_repeats++; + return; + } + struct timeval tv; + gettimeofday(&tv, NULL); + struct tm tmv; + localtime_r(&tv.tv_sec, &tmv); + if (s_repeats > 0) + { + fprintf(stderr, "[swf-list] (previous line x%d more)\n", s_repeats); + } + fprintf(stderr, "%02d:%02d:%02d.%03d [swf-list] %s%s\n", tmv.tm_hour, tmv.tm_min, tmv.tm_sec, + (int) (tv.tv_usec / 1000), g_swf_mouse_pass_depth > 0 ? "[mouse] " : "", line); + fflush(stderr); + strncpy(s_last, line, sizeof(s_last) - 1); + s_last[sizeof(s_last) - 1] = '\0'; + s_repeats = 0; + } +#endif } diff --git a/Code/BF2/External/gameswf/gameswf_log.h b/Code/BF2/External/gameswf/gameswf_log.h index 2037ea4fe..88a23026d 100644 --- a/Code/BF2/External/gameswf/gameswf_log.h +++ b/Code/BF2/External/gameswf/gameswf_log.h @@ -23,6 +23,19 @@ namespace gameswf void log_error(const char* fmt, ...); #endif // not __GNUC__ + +#if !defined(_MSC_VER) + // [TEMP] c-swf-disconnect display-list tracer (docs/macos-c-swf-disconnect.md), off unless + // BF2_SWF_LIST_TRACE=1. One flushed stderr line per event, prefixed "[swf-list]"; a line + // identical to the previous one is counted, not repeated. g_swf_mouse_pass_depth is the + // nesting of sprite mouse passes, so a line can say whether it ran inside one. + bool swf_list_trace_on(); + void swf_list_trace(const char* fmt, ...) __attribute__((format (printf, 1, 2))); + extern int g_swf_mouse_pass_depth; +#define SWF_LIST_TRACE(...) do { if (gameswf::swf_list_trace_on()) gameswf::swf_list_trace(__VA_ARGS__); } while (0) +#else +#define SWF_LIST_TRACE(...) do { } while (0) +#endif } diff --git a/Code/BF2/External/gameswf/gameswf_render.cpp b/Code/BF2/External/gameswf/gameswf_render.cpp index 286893305..df8b9bb2a 100644 --- a/Code/BF2/External/gameswf/gameswf_render.cpp +++ b/Code/BF2/External/gameswf/gameswf_render.cpp @@ -209,7 +209,8 @@ namespace gameswf { return s_render_handler ? s_render_handler->text_extent(line, count, w, h) : false; } - bool text_hit(void* line, int* out_pos, int x, int y) + // 0x1009A8E0: ecx = line, edx = out_pos, the two float dwords passed on to handler +0x6C. + bool text_hit(void* line, int* out_pos, float x, float y) { return s_render_handler ? s_render_handler->text_hit(line, out_pos, x, y) : false; } @@ -222,9 +223,10 @@ namespace gameswf if (b) *b = 0; return false; } - bool text_set_selection(void* line, int a, int b, int c, int d) + // 0x1009A940: the four float dwords passed on to handler +0x74. + bool text_set_selection(void* line, float x1, float y1, float x2, float y2) { - return s_render_handler ? s_render_handler->text_set_selection(line, a, b, c, d) : false; + return s_render_handler ? s_render_handler->text_set_selection(line, x1, y1, x2, y2) : false; } void text_blur(void* line) { diff --git a/Code/BF2/External/gameswf/gameswf_render.h b/Code/BF2/External/gameswf/gameswf_render.h index 77b08a460..03276fdee 100644 --- a/Code/BF2/External/gameswf/gameswf_render.h +++ b/Code/BF2/External/gameswf/gameswf_render.h @@ -77,9 +77,10 @@ namespace gameswf void text_detach(void* line); void text_draw(void* line, const matrix* m, unsigned color, int flags); bool text_extent(void* line, int count, float* w, float* h); - bool text_hit(void* line, int* out_pos, int x, int y); + // [DICE-MOD SwiffPlayer] float coordinates: SwiffPlayer.dll 0x100887A5..0x100887D7 / 0x10088823..0x1008883B + bool text_hit(void* line, int* out_pos, float x, float y); bool text_selection(void* line, int* a, int* b); // [DICE-MOD SwiffPlayer #46] true = a selection exists - bool text_set_selection(void* line, int a, int b, int c, int d); + bool text_set_selection(void* line, float x1, float y1, float x2, float y2); void text_blur(void* line); void text_set_size(void* line, float size, int flag); void text_caret(void* line, int pos); diff --git a/Code/BF2/External/gameswf/gameswf_string.cpp b/Code/BF2/External/gameswf/gameswf_string.cpp index 8502147b3..317e832ce 100644 --- a/Code/BF2/External/gameswf/gameswf_string.cpp +++ b/Code/BF2/External/gameswf/gameswf_string.cpp @@ -9,6 +9,9 @@ #include "base/tu_config.h" #include "gameswf_string.h" #include "gameswf_log.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] bf2x87::lowUInt32 +#endif #include "base/smart_ptr.h" @@ -52,7 +55,12 @@ namespace gameswf for (int i = 0; i < fn.nargs; i++) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + uint32 c = bf2x87::lowUInt32(fn.arg(i).to_number()); +#else uint32 c = (uint32) fn.arg(i).to_number(); +#endif result.append_wide_char(c); } @@ -261,7 +269,14 @@ namespace gameswf // built from wide text keeps its narrow copy EMPTY (the shipped Locale.getString never fills // it), so string contexts see "" for a translation - a shipped quirk, preserved. virtual const char* get_text_value() const { return m_string.c_str(); } - virtual const Uint16* get_wide_text_value() const { return m_wide.size() > 1 ? &m_wide[0] : 0; } + // [#38] Never null for a String object: the shipped text setter (sub_10089440, 0x10089553) + // takes the object's std::wstring c_str(), which MSVC never returns null, so a String object + // always goes through the wide setter (vslot +0x110), an empty one included. + virtual const Uint16* get_wide_text_value() const + { + static const Uint16 s_empty = 0; + return m_wide.size() > 1 ? &m_wide[0] : &s_empty; + } }; // [DICE-MOD SwiffPlayer #31] the forwarders for the methods the shipped String object registers. diff --git a/Code/BF2/External/gameswf/gameswf_text.cpp b/Code/BF2/External/gameswf/gameswf_text.cpp index 73cfbc5f5..34d344e98 100644 --- a/Code/BF2/External/gameswf/gameswf_text.cpp +++ b/Code/BF2/External/gameswf/gameswf_text.cpp @@ -7,6 +7,9 @@ #include "base/utf8.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] bf2x87::lowUInt32 +#endif #include "base/utility.h" #include "gameswf_impl.h" #include "gameswf_shape.h" @@ -602,6 +605,11 @@ namespace gameswf bool m_password; // +345 int m_tab_index; // +348 int m_max_chars; // +352 + // [DICE-MOD SwiffPlayer #53] +368 (0x170): the last height sub_10084DE0 was asked for + // (0x10084E01 stores its int argument before the scale test), i.e. formatText's laid-out + // height in pixels. `textHeight` answers it (vslot 0x10C = 0x10087A90, `mov eax,[ecx+170h]`); + // the constructor seeds 666 (0x1008772C). + int m_text_height_px; tu_string m_restrict; // +356/+360 as_value m_on_changed; // +376 as_value m_on_set_focus; // +408 @@ -626,7 +634,8 @@ namespace gameswf m_lines_dirty(false), m_password(false), m_tab_index(-1), - m_max_chars(0) + m_max_chars(0), + m_text_height_px(666) { assert(parent); assert(m_def); @@ -686,6 +695,18 @@ namespace gameswf } } + // [CHOSEN, not recovered] issue #7: movie teardown, see release_script_objects. Adds the + // field's environment and its two handler values to the base character's values. + virtual void release_script_values(array* held) + { + character::release_script_values(held); + m_as_environment.release_values(held); + hold_script_value(held, m_on_changed); + m_on_changed.set_undefined(); + hold_script_value(held, m_on_set_focus); + m_on_set_focus.set_undefined(); + } + void set_tab_index(int index) // sub_10087B50 { if (m_tab_index >= 0 && m_tab_index < s_tab_table.size() && s_tab_table[m_tab_index] == this) @@ -845,7 +866,12 @@ namespace gameswf //else if (name == "textColor") { // The arg is 0xRRGGBB format. +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + Uint32 rgb = bf2x87::lowUInt32(val.to_number()); +#else Uint32 rgb = (Uint32) val.to_number(); +#endif cxform cx = get_cxform(); cx.m_[0][0] = fclamp(((rgb >> 16) & 255) / 255.0f, 0, 1); @@ -1025,7 +1051,7 @@ namespace gameswf render::text_set_size(line, width_px, (int) m_def->m_alignment); if (!m_password) { - render::text_set(line, (const wchar_t*) &text[0]); + render::text_set(line, BF2_DICE_WIDE(&text[0])); // [CHOSEN, not recovered] POSIX: widen, see dice_wide return; } // A password field shows one asterisk per character (the shipped fills a 512-wide buffer). @@ -1038,12 +1064,13 @@ namespace gameswf int n = 0; while (text[n]) n++; if (n > 511) n = 511; - render::text_set(line, (const wchar_t*) &s_asterisks[511 - n]); + render::text_set(line, BF2_DICE_WIDE(&s_asterisks[511 - n])); } // sub_10084DE0: grow the field's y scale so at least `height_px` is visible (auto-size). void set_height_at_least(float height_px) { + m_text_height_px = (int) height_px; // 0x10084E01, before the test matrix m = get_matrix(); const float h = TWIPS_TO_PIXELS(get_height()); if (h * m.m_[1][1] < height_px && h > 0) @@ -1242,7 +1269,7 @@ namespace gameswf text_glyph_record rec; // one to work on rec.m_style.m_font = m_def->m_font; rec.m_style.m_color = m_def->m_color; - rec.m_style.m_x_offset = fmax(0, m_def->m_left_margin + m_def->m_indent); + rec.m_style.m_x_offset = tu_util::fmax(0, m_def->m_left_margin + m_def->m_indent); rec.m_style.m_y_offset = m_def->m_text_height + (m_def->m_font->get_leading() - m_def->m_font->get_descent()) * scale; rec.m_style.m_text_height = m_def->m_text_height; @@ -1297,7 +1324,7 @@ namespace gameswf m_text_glyph_records.push_back(rec); align_line(m_def->m_alignment, last_line_start_record, x); - x = fmax(0, m_def->m_left_margin + m_def->m_indent); // new paragraphs get the indent. + x = tu_util::fmax(0, m_def->m_left_margin + m_def->m_indent); // new paragraphs get the indent. y += m_def->m_text_height + leading; // Start a new record on the next line. @@ -1655,14 +1682,16 @@ namespace gameswf float x1 = m_drag_x * 0.05f, y1 = m_drag_y * 0.05f; float x2 = p.m_x * 0.05f, y2 = p.m_y * 0.05f; int pos = 0; - if (render::text_hit(m_lines[0], &pos, (int) x2, (int) y2)) + // 0x100887A5..0x100887D7: x2/y2 are fstp'd floats pushed unconverted (no fistp). + if (render::text_hit(m_lines[0], &pos, x2, y2)) { m_caret = (Uint16) pos; } m_blink_time = 0; if (x1 > x2) { float t = x1; x1 = x2; x2 = t; } if (y1 > y2) { float t = y1; y1 = y2; y2 = t; } - render::text_set_selection(m_lines[0], (int) x1, (int) y1, (int) x2, (int) y2); + // 0x10088823..0x1008883B: the sorted floats are pushed as raw dwords. + render::text_set_selection(m_lines[0], x1, y1, x2, y2); } const bool result = (m_mouse_state & 1) != 0; if (m_mouse_state == m_prev_mouse_state) @@ -1925,9 +1954,9 @@ namespace gameswf { if (name == "text") { - // sub_10089440: a value that is an object goes by its payload - the wide text when - // it carries one (DICE's String object from Locale.getString), else its narrow text - // value; a plain value goes narrow through to_string(). + // sub_10089440: a DICE String object always goes through the wide setter with its + // wide text, empty when it carries none (the shipped narrow arm at 0x10089599 is + // unreachable: it needs a null std::wstring c_str()); any other value goes narrow. as_object_interface* obj = val.to_object(); if (obj) { @@ -1950,7 +1979,12 @@ namespace gameswf } if (name == "textColor") { +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + const Uint32 rgb = bf2x87::lowUInt32(val.to_number()); +#else const Uint32 rgb = (Uint32) val.to_number(); +#endif const Uint32 cur = ((Uint32) m_text_color.m_r << 16) | ((Uint32) m_text_color.m_g << 8) | m_text_color.m_b; if (rgb != cur) { @@ -1973,9 +2007,19 @@ namespace gameswf return true; } if (name == "border") { m_border = val.to_bool(); return true; } +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + if (name == "borderColor") { const Uint32 c = bf2x87::lowUInt32(val.to_number()); m_border_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } +#else if (name == "borderColor") { const Uint32 c = (Uint32) val.to_number(); m_border_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } +#endif if (name == "background") { m_background = val.to_bool(); return true; } +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + if (name == "backgroundColor") { const Uint32 c = bf2x87::lowUInt32(val.to_number()); m_background_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } +#else if (name == "backgroundColor") { const Uint32 c = (Uint32) val.to_number(); m_background_color = rgba((c >> 16) & 255, (c >> 8) & 255, c & 255, 255); return true; } +#endif if (name == "password") { m_password = val.to_bool(); return true; } if (name == "tabIndex") { set_tab_index((int) val.to_number()); return true; } if (name == "onChanged") { m_on_changed = val; return true; } @@ -2028,7 +2072,11 @@ namespace gameswf } if (name == "_width") { val->set_double(TWIPS_TO_PIXELS(get_width())); return true; } if (name == "_height") { val->set_double(TWIPS_TO_PIXELS(get_height())); return true; } - if (name == "textHeight") { val->set_double((double) (int) (m_def->m_text_height * 0.05f)); return true; } + // [DICE-MOD #53] sub_10087C60: `textHeight` is vslot 0x10C, the laid-out height formatText + // last requested (m_text_height_px), not the font size. The loading screen's label + // component sets `_height = textHeight`; with the font size every multi-line field shrank + // to one line and the next formatText stopped after the first wrap. + if (name == "textHeight") { val->set_double((double) m_text_height_px); return true; } if (name == "border") { val->set_bool(m_border); return true; } if (name == "borderColor") { val->set_double((double) (int) (((Uint32) m_border_color.m_a << 24) | ((Uint32) m_border_color.m_r << 16) | ((Uint32) m_border_color.m_g << 8) | m_border_color.m_b)); return true; } if (name == "background") { val->set_bool(m_background); return true; } diff --git a/Code/BF2/External/gameswf/gameswf_textformat.cpp b/Code/BF2/External/gameswf/gameswf_textformat.cpp index 4c4066859..e5a3f1477 100644 --- a/Code/BF2/External/gameswf/gameswf_textformat.cpp +++ b/Code/BF2/External/gameswf/gameswf_textformat.cpp @@ -5,6 +5,9 @@ #include "gameswf_log.h" #include "gameswf_textformat.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] bf2x87::lowUInt32 +#endif namespace gameswf { @@ -156,7 +159,12 @@ void textformat_setformat(const fn_call& fn) if (obj->get_member("color", &method)) { //log_msg("Color exists and is set to %f\n", method.to_number()); +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative number (arm64 saturates to 0). + obj->obj.colorSet(bf2x87::lowUInt32(method.to_number())); +#else obj->obj.colorSet((uint32)method.to_number()); +#endif } if (obj->get_member("indent", &method)) { diff --git a/Code/BF2/External/gameswf/gameswf_types.cpp b/Code/BF2/External/gameswf/gameswf_types.cpp index 2d80d2d4b..2eb2551c9 100644 --- a/Code/BF2/External/gameswf/gameswf_types.cpp +++ b/Code/BF2/External/gameswf/gameswf_types.cpp @@ -254,7 +254,7 @@ namespace gameswf // length of the two basis vectors. float basis0_length2 = m_[0][0] * m_[0][0] + m_[0][1] * m_[0][1]; float basis1_length2 = m_[1][0] * m_[1][0] + m_[1][1] * m_[1][1]; - float max_length2 = fmax(basis0_length2, basis1_length2); + float max_length2 = tu_util::fmax(basis0_length2, basis1_length2); return sqrtf(max_length2); } @@ -523,10 +523,10 @@ namespace gameswf void rect::expand_to_point(float x, float y) // Expand this rectangle to enclose the given point. { - m_x_min = fmin(m_x_min, x); - m_y_min = fmin(m_y_min, y); - m_x_max = fmax(m_x_max, x); - m_y_max = fmax(m_y_max, y); + m_x_min = tu_util::fmin(m_x_min, x); + m_y_min = tu_util::fmin(m_y_min, y); + m_x_max = tu_util::fmax(m_x_max, x); + m_y_max = tu_util::fmax(m_y_max, y); } diff --git a/Code/BF2/External/python-embedded/linux/CMakeLists.txt b/Code/BF2/External/python-embedded/linux/CMakeLists.txt index 85cc6b212..dfa5812e1 100644 --- a/Code/BF2/External/python-embedded/linux/CMakeLists.txt +++ b/Code/BF2/External/python-embedded/linux/CMakeLists.txt @@ -28,18 +28,34 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) project(dice_py LANGUAGES C CXX) endif() -if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") +# [CHOSEN, not recovered] The same description also builds libdice_py.dylib for the macOS port. +# Only the configure output differs: ../macos/pyconfig.h is the vendored configure's answer on +# Darwin (see ../macos/README.md); config.c, the source list and every flag are shared. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + set(DICE_PY_MACOS OFF) + set(DICE_PY_PYCONFIG_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8 OR NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") + message(FATAL_ERROR + "dice_py/linux: pyconfig.h here is configure's output for Linux x86-64 (LP64, " + "little-endian, 16-byte fpos_t); this is ${CMAKE_SYSTEM_PROCESSOR} with " + "${CMAKE_SIZEOF_VOID_P}-byte pointers. Regenerate pyconfig.h for the platform first - " + "README.md says how.") + endif() +elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + set(DICE_PY_MACOS ON) + get_filename_component(DICE_PY_PYCONFIG_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../macos" ABSOLUTE) + # The Darwin pyconfig.h holds for both x86_64 and arm64 (LP64, little-endian, same libSystem + # sizes); see ../macos/README.md. [CHOSEN, not recovered] Universal builds use the + # compiler's per-slice architecture macros for the va_list override, not the CMake host. + if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) + message(FATAL_ERROR "dice_py/macos: only 64-bit macOS is supported.") + endif() +else() message(FATAL_ERROR - "dice_py/linux: this directory builds libdice_py.so for Linux only (this is " - "${CMAKE_SYSTEM_NAME}). The Windows dice_py.dll is built by " + "dice_py/linux: this directory builds libdice_py.so for Linux and libdice_py.dylib for " + "macOS only (this is ${CMAKE_SYSTEM_NAME}). The Windows dice_py.dll is built by " "Code/Build/python/build_python.cmd.") endif() -if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8 OR NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") - message(FATAL_ERROR - "dice_py/linux: pyconfig.h here is configure's output for Linux x86-64 (LP64, little-endian, " - "16-byte fpos_t); this is ${CMAKE_SYSTEM_PROCESSOR} with ${CMAKE_SIZEOF_VOID_P}-byte " - "pointers. Regenerate pyconfig.h for the platform first - README.md says how.") -endif() # Where libdice_py.so and dice_py_check land. The root project points this at the `bf2` directory. if(NOT DEFINED BF2_DICE_PY_OUTPUT_DIR) @@ -163,7 +179,7 @@ set_target_properties(dice_py PROPERTIES ) target_include_directories(dice_py PUBLIC - "${CMAKE_CURRENT_SOURCE_DIR}" # pyconfig.h (configure's output, see README.md) + "${DICE_PY_PYCONFIG_DIR}" # pyconfig.h (configure's output, see README.md) "${DICE_PY_SRC}/Include" PRIVATE "${DICE_PY_ZLIB}" # zlib.h for Modules/zlibmodule.c @@ -211,11 +227,24 @@ endforeach() # build never is. PYTHONPATH/PLATFORM say linux2 where this kernel's configure says linux6: # [CHOSEN, not recovered] sys.platform is the retail-era value, the only one 2004 scripts could # have tested; see README.md. +# [CHOSEN, not recovered] macOS keeps "linux2" too: the game's Python scripts were only ever run +# on win32 and linux2, so reporting the retail Linux value keeps their platform tests on the +# path the retail Linux server took. See ../macos/README.md. set_source_files_properties("${DICE_PY_SRC}/Modules/getpath.c" PROPERTIES COMPILE_DEFINITIONS "PREFIX=\"/usr/local\";EXEC_PREFIX=\"/usr/local\";VERSION=\"2.3\";VPATH=\"\";PYTHONPATH=\":plat-linux2:lib-tk\"") set_source_files_properties("${DICE_PY_SRC}/Python/getplatform.c" PROPERTIES COMPILE_DEFINITIONS "PLATFORM=\"linux2\"") +# [CHOSEN, not recovered] macOS: Modules/_localemodule.c's __APPLE__ branch includes Mac/Include's +# macglue.h and calls PyMac_getscript from Python/mactoolboxglue.c, the Carbon toolbox glue that +# upstream links only into a framework build. That glue is not part of this build, so the unit is +# compiled as the generic POSIX module it is on Linux: setlocale/localeconv/nl_langinfo, and no +# _getdefaultlocale (locale.py then reads the LANG/LC_* environment, as on the Linux server). +if(DICE_PY_MACOS) + set_property(SOURCE "${DICE_PY_SRC}/Modules/_localemodule.c" APPEND PROPERTY COMPILE_OPTIONS + "-U__APPLE__") +endif() + # System libraries: libm (mathmodule, timemodule), libdl (dynload_shlib), pthreads (thread.c) and, # where glibc still ships it separately (before 2.34), libutil for posixmodule's openpty/forkpty. set(THREADS_PREFER_PTHREAD_FLAG ON) @@ -229,7 +258,10 @@ if(NOT DICE_PY_OPENPTY_IN_LIBC) endif() # A shared object links even with unresolved symbols; refuse that, so a missing system library or # a module compiled without its dependency fails HERE rather than when `bf2` first dlopens it. -target_link_options(dice_py PRIVATE -Wl,--no-undefined) +# ld64 (macOS) already rejects undefined symbols in a dylib by default and has no --no-undefined. +if(NOT DICE_PY_MACOS) + target_link_options(dice_py PRIVATE -Wl,--no-undefined) +endif() # ------------------------------------------------------------------------------------------------- # The runtime check: the same pycheck.cpp the Windows build runs, linked against libdice_py.so and @@ -239,10 +271,15 @@ add_executable(dice_py_check "${DICE_PY_CHECK_SOURCE}") target_link_libraries(dice_py_check PRIVATE dice_py) target_compile_definitions(dice_py_check PRIVATE DEDICATED=1) target_compile_options(dice_py_check PRIVATE "-include${DICE_PY_BUILDCONFIG_H}") +if(DICE_PY_MACOS) + set(DICE_PY_RPATH "@loader_path") # the Mach-O spelling of $ORIGIN +else() + set(DICE_PY_RPATH "\$ORIGIN") +endif() set_target_properties(dice_py_check PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${BF2_DICE_PY_OUTPUT_DIR}" - BUILD_RPATH "\$ORIGIN" - INSTALL_RPATH "\$ORIGIN" + BUILD_RPATH "${DICE_PY_RPATH}" + INSTALL_RPATH "${DICE_PY_RPATH}" BUILD_WITH_INSTALL_RPATH TRUE CXX_STANDARD 14 # the engine's standard; Python.h is consumed from C++14 CXX_STANDARD_REQUIRED ON diff --git a/Code/BF2/External/python-embedded/linux/README.md b/Code/BF2/External/python-embedded/linux/README.md index dd0bbd4f6..054594467 100644 --- a/Code/BF2/External/python-embedded/linux/README.md +++ b/Code/BF2/External/python-embedded/linux/README.md @@ -2,7 +2,8 @@ This directory builds CPython 2.3.4 and the vendored zlib 1.2.3 as `libdice_py.so` for Linux x86-64. It supports a standalone interpreter check and -the root engine build. See the public +the root engine build. The same description builds `libdice_py.dylib` for the +macOS port with the Darwin `pyconfig.h` from [../macos](../macos/README.md). See the public [build guide](../../../../../docs/building.md#linux-and-wsl) for the engine targets. ## Build and check @@ -85,3 +86,9 @@ upstream release. Keep the [upstream Python license](../py-src-2.3.4/LICENSE) and source notices with the interpreter. + +[CHOSEN, not recovered] The owner-requested macOS N1 fix bounds +`Modules/socketmodule.c:socket_inet_ntop`'s POSIX buffer initialization to +`sizeof(ip)`, removing the one-byte stack overwrite from `sizeof(ip) + 1`. +The Windows branch stays unchanged. Preserve this correction on source updates; +see [N1 validation](../../../../../docs/macos-n1-posix-net.md). diff --git a/Code/BF2/External/python-embedded/macos/README.md b/Code/BF2/External/python-embedded/macos/README.md new file mode 100644 index 000000000..0e6b90c14 --- /dev/null +++ b/Code/BF2/External/python-embedded/macos/README.md @@ -0,0 +1,66 @@ +# macOS embedded Python + +This directory holds the Darwin `pyconfig.h` for `libdice_py.dylib`, the embedded +CPython 2.3.4 of the macOS dedicated-server port. The port is an intentional, +owner-requested platform change, `[CHOSEN, not recovered]`: there was no retail +macOS server. The build description itself is shared with Linux and lives in +[../linux/CMakeLists.txt](../linux/CMakeLists.txt); it selects this directory's +`pyconfig.h` when CMake runs on Darwin. See +[docs/macos-port.md](../../../../../docs/macos-port.md) for the port as a whole. + +## Build and check + +From the repository root, the root project builds the library beside `bf2`: + +```sh +cmake --preset macos-x64 +cmake --build out/build/macos-x64 --target dice_py dice_py_check_run +``` + +For both slices, use `cmake --preset macos-universal` and build +`out/build/macos-universal` instead. This `[CHOSEN, not recovered]` preset passes +`CMAKE_OSX_ARCHITECTURES="arm64;x86_64"`. The `VA_LIST_IS_ARRAY` override is selected +by compiler architecture macros separately for each slice; it does not depend on +the configure host. Native arm64 execution still requires the owner's M2 run. + +Standalone, as on Linux: + +```sh +cmake -S Code/BF2/External/python-embedded/linux -B out/build/dice_py-macos \ + -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_OSX_SYSROOT=macosx +cmake --build out/build/dice_py-macos --target dice_py_check_run +``` + +The library's install name is `@rpath/libdice_py.dylib`; `bf2` and `dice_py_check` +carry an `@loader_path` runtime search path, the Mach-O equivalent of `$ORIGIN`. + +## Differences from the Linux build + +| Item | macOS | Reason | +| --- | --- | --- | +| `pyconfig.h` | Vendored configure output for Darwin x86_64, plus two marked overrides | See the provenance block at the top of `pyconfig.h`. | +| `HAVE_BROKEN_POSIX_SEMAPHORES` | Defined by hand | Darwin defines `_POSIX_SEMAPHORES` as `-1` and `sem_init` fails with `ENOSYS`; the 2.3 thread module would otherwise build every lock on it. | +| `VA_LIST_IS_ARRAY` | Undefined on arm64 only | arm64 Darwin's `va_list` is a pointer. Untested: the reference machine is x86_64. | +| `Modules/_localemodule.c` | Compiled with `-U__APPLE__` | Its Apple branch needs `macglue.h` and the Carbon toolbox glue from a framework build. Without it the module is the generic POSIX one used on Linux. | +| `sys.platform` | `linux2`, as on Linux | The game's scripts were written for `win32` and `linux2`; keeping the Linux value keeps them on the retail Linux server's paths. | +| `--no-undefined` | Not passed | `ld64` already rejects undefined symbols in a dylib. | +| SDK sysroot | `CMAKE_OSX_SYSROOT=macosx` in the preset | Apple clang otherwise searches `/usr/local/include` (Homebrew) first; configure was run with the same sysroot. | + +`dice_py_check_run` passes on macOS 15.7 x86_64: initialization, 64-bit pointer +round trip, 40 builtin modules, zlib and loopback UDP. Prefix-search warnings appear +as on Linux, because the engine sets `sys.path` itself. + +## POSIX publication (S2.10) + +[CHOSEN, not recovered] `Python/ceval.c` uses C11 atomics for pending-call queue indices, +the work flag and its producer try-lock. A failed try-lock returns the existing refusal (-1), +including in a nested signal handler. Sequential consistency publishes the queue entries +before the consumer reads them and retires an entry before a producer reuses it. +Every POSIX `_Py_Ticker` access in `ceval.c` and `Objects/longobject.c` uses `__atomic`; +its exported scalar declaration stays intact. `Objects/obmalloc.c` publishes the arena +vector before its count using C11 atomics; old vectors remain deliberately retained as +upstream requires. These changes apply on Linux too. Windows branches remain unchanged. + +The focused check in `Code/Tests/s2_10_threads` drives four concurrent producers and +40,000 callbacks against the real library. See [S2.10 results](../../../../../docs/macos-s2-10-threads.md) +for coverage and the owner-run server TSan bundle. diff --git a/Code/BF2/External/python-embedded/macos/pyconfig.h b/Code/BF2/External/python-embedded/macos/pyconfig.h new file mode 100644 index 000000000..5cd00489d --- /dev/null +++ b/Code/BF2/External/python-embedded/macos/pyconfig.h @@ -0,0 +1,974 @@ +/* ================================================================================================= + * BF2Rebuilt: pyconfig.h for libdice_py.dylib - the macOS build of the embedded CPython 2.3.4. + * [CHOSEN, not recovered]: there was no retail macOS server; this file serves the macOS port. + * + * PROVENANCE. Everything between this comment block and the "macOS overrides" block at the end of + * the file is the VERBATIM output of the vendored py-src-2.3.4/configure (GNU Autoconf 2.57), run in a scratch + * copy of py-src-2.3.4 on macOS 15.7.7 (Darwin 24.6.0, x86_64) with Apple clang 17.0.0 (Command + * Line Tools) on 2026-10-21 as + * + * CC="clang -std=gnu89 -isysroot $(xcrun --show-sdk-path) \ + * -Wno-error=implicit-function-declaration -Wno-error=implicit-int \ + * -Wno-error=int-conversion -Wno-error=incompatible-function-pointer-types" ./configure + * + * with no other option, matching ../linux/pyconfig.h's upstream default configuration (UCS-2 + * unicode, pymalloc, threads, IPv6). Why the extra flags: + * -std=gnu89 and the -Wno-error= set: Apple clang turns implicit function declarations into + * errors even in gnu89 mode, and Autoconf 2.57's probes call exit() without . Without + * the demotions every AC_TRY_RUN probe fails and configure silently reports SIZEOF_OFF_T 0, + * WORDS_BIGENDIAN and SIGNED_RIGHT_SHIFT_ZERO_FILLS - the same failure ../linux/pyconfig.h + * records for GCC 14. + * -isysroot: Apple clang otherwise searches /usr/local/include first, so Homebrew headers + * (libintl.h from gettext, GNU readline) leak into the probes. CMake passes the same SDK + * sysroot to every compile, so configure and build now see the same headers. + * + * The configure part is NOT HAND-EDITED. Differences from the Linux configure output are configure's honest answers on + * Darwin, for example: SIZEOF_FPOS_T 8 (Darwin's fpos_t is an off_t), HAVE_SOCKADDR_SA_LEN, + * no HAVE_STAT_TV_NSEC (Darwin spells it st_mtimespec), no HAVE_GETHOSTBYNAME_R, no + * HAVE_LIBINTL_H. USE_TOOLBOX_OBJECT_GLUE and WITH_DYLD are set by configure's Darwin case; the + * units that read them (Python/mactoolboxglue.c, Python/dynload_next.c) are not in the build - + * dynload_shlib.c (dlopen) is the loader on both POSIX ports. A few probes (chroot, flock, + * getpagesize, inet_aton, hstrerror, setgroups, fdatasync) report absent because their 2003 + * probe programs do not compile against the current SDK; posixmodule then simply omits those + * functions, which the game's scripts do not call. + * MACHDEP is darwin; ../linux/CMakeLists.txt passes the retail-era "linux2" platform string on + * macOS too (documented there and in README.md beside this file). + * + * To regenerate: copy py-src-2.3.4 somewhere scratch (never configure the vendored tree), run the + * command above there, copy its pyconfig.h over the configure part of this file, and keep this + * block and the macOS overrides block. + * ============================================================================================= */ +/* pyconfig.h. Generated by configure. */ +/* pyconfig.h.in. Generated from configure.in by autoheader. */ + + +#ifndef Py_PYCONFIG_H +#define Py_PYCONFIG_H + + +/* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want + support for AIX C++ shared extension modules. */ +/* #undef AIX_GENUINE_CPLUSPLUS */ + +/* Define this if you have AtheOS threads. */ +/* #undef ATHEOS_THREADS */ + +/* Define if your contains bad prototypes for exec*() (as it does + on SGI IRIX 4.x) */ +/* #undef BAD_EXEC_PROTOTYPES */ + +/* Define this if you have BeOS threads. */ +/* #undef BEOS_THREADS */ + +/* Define if you have the Mach cthreads package */ +/* #undef C_THREADS */ + +/* Define if --enable-ipv6 is specified */ +#define ENABLE_IPV6 1 + +/* Define if getpgrp() must be called as getpgrp(0). */ +/* #undef GETPGRP_HAVE_ARG */ + +/* Define if gettimeofday() does not have second (timezone) argument This is + the case on Motorola V4 (R40V4.2) */ +/* #undef GETTIMEOFDAY_NO_TZ */ + +/* struct addrinfo (netdb.h) */ +#define HAVE_ADDRINFO 1 + +/* Define to 1 if you have the `alarm' function. */ +#define HAVE_ALARM 1 + +/* Define this if your time.h defines altzone. */ +/* #undef HAVE_ALTZONE */ + +/* Define if nice() returns success/failure instead of the new priority. */ +/* #undef HAVE_BROKEN_NICE */ + +/* Define if poll() sets errno on invalid file descriptors. */ +/* #undef HAVE_BROKEN_POLL */ + +/* Define if the Posix semaphores do not work on your system */ +/* #undef HAVE_BROKEN_POSIX_SEMAPHORES */ + +/* Define if pthread_sigmask() does not work on your system. */ +/* #undef HAVE_BROKEN_PTHREAD_SIGMASK */ + +/* Define to 1 if you have the `chown' function. */ +#define HAVE_CHOWN 1 + +/* Define if you have the 'chroot' function. */ +/* #undef HAVE_CHROOT */ + +/* Define to 1 if you have the `clock' function. */ +#define HAVE_CLOCK 1 + +/* Define to 1 if you have the `confstr' function. */ +#define HAVE_CONFSTR 1 + +/* Define to 1 if you have the `ctermid' function. */ +#define HAVE_CTERMID 1 + +/* Define if you have the 'ctermid_r' function. */ +/* #undef HAVE_CTERMID_R */ + +/* Define to 1 if you have the device macros. */ +/* #undef HAVE_DEVICE_MACROS */ + +/* Define if we have /dev/ptc. */ +/* #undef HAVE_DEV_PTC */ + +/* Define if we have /dev/ptmx. */ +#define HAVE_DEV_PTMX 1 + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the `dlopen' function. */ +#define HAVE_DLOPEN 1 + +/* Define to 1 if you have the `dup2' function. */ +#define HAVE_DUP2 1 + +/* Defined when any dynamic module loading is enabled. */ +#define HAVE_DYNAMIC_LOADING 1 + +/* Define to 1 if you have the `execv' function. */ +#define HAVE_EXECV 1 + +/* Define if you have the 'fchdir' function. */ +#define HAVE_FCHDIR 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define if you have the 'fdatasync' function. */ +/* #undef HAVE_FDATASYNC */ + +/* Define if you have the 'flock' function. */ +/* #undef HAVE_FLOCK */ + +/* Define to 1 if you have the `fork' function. */ +#define HAVE_FORK 1 + +/* Define to 1 if you have the `forkpty' function. */ +#define HAVE_FORKPTY 1 + +/* Define to 1 if you have the `fpathconf' function. */ +#define HAVE_FPATHCONF 1 + +/* Define to 1 if you have the `fseek64' function. */ +/* #undef HAVE_FSEEK64 */ + +/* Define to 1 if you have the `fseeko' function. */ +#define HAVE_FSEEKO 1 + +/* Define to 1 if you have the `fstatvfs' function. */ +#define HAVE_FSTATVFS 1 + +/* Define if you have the 'fsync' function. */ +#define HAVE_FSYNC 1 + +/* Define to 1 if you have the `ftell64' function. */ +/* #undef HAVE_FTELL64 */ + +/* Define to 1 if you have the `ftello' function. */ +#define HAVE_FTELLO 1 + +/* Define to 1 if you have the `ftime' function. */ +#define HAVE_FTIME 1 + +/* Define to 1 if you have the `ftruncate' function. */ +#define HAVE_FTRUNCATE 1 + +/* Define to 1 if you have the `gai_strerror' function. */ +#define HAVE_GAI_STRERROR 1 + +/* Define if you have the getaddrinfo function. */ +#define HAVE_GETADDRINFO 1 + +/* Define to 1 if you have the `getcwd' function. */ +#define HAVE_GETCWD 1 + +/* Define this if you have flockfile(), getc_unlocked(), and funlockfile() */ +#define HAVE_GETC_UNLOCKED 1 + +/* Define to 1 if you have the `getgroups' function. */ +#define HAVE_GETGROUPS 1 + +/* Define to 1 if you have the `gethostbyname' function. */ +#define HAVE_GETHOSTBYNAME 1 + +/* Define this if you have some version of gethostbyname_r() */ +/* #undef HAVE_GETHOSTBYNAME_R */ + +/* Define this if you have the 3-arg version of gethostbyname_r(). */ +/* #undef HAVE_GETHOSTBYNAME_R_3_ARG */ + +/* Define this if you have the 5-arg version of gethostbyname_r(). */ +/* #undef HAVE_GETHOSTBYNAME_R_5_ARG */ + +/* Define this if you have the 6-arg version of gethostbyname_r(). */ +/* #undef HAVE_GETHOSTBYNAME_R_6_ARG */ + +/* Define to 1 if you have the `getloadavg' function. */ +#define HAVE_GETLOADAVG 1 + +/* Define to 1 if you have the `getlogin' function. */ +#define HAVE_GETLOGIN 1 + +/* Define to 1 if you have the `getnameinfo' function. */ +#define HAVE_GETNAMEINFO 1 + +/* Define if you have the 'getpagesize' function. */ +/* #undef HAVE_GETPAGESIZE */ + +/* Define to 1 if you have the `getpeername' function. */ +#define HAVE_GETPEERNAME 1 + +/* Define to 1 if you have the `getpgid' function. */ +#define HAVE_GETPGID 1 + +/* Define to 1 if you have the `getpgrp' function. */ +#define HAVE_GETPGRP 1 + +/* Define to 1 if you have the `getpid' function. */ +#define HAVE_GETPID 1 + +/* Define to 1 if you have the `getpriority' function. */ +#define HAVE_GETPRIORITY 1 + +/* Define to 1 if you have the `getpwent' function. */ +#define HAVE_GETPWENT 1 + +/* Define to 1 if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY 1 + +/* Define to 1 if you have the `getwd' function. */ +#define HAVE_GETWD 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_GRP_H 1 + +/* Define if you have the 'hstrerror' function. */ +/* #undef HAVE_HSTRERROR */ + +/* Define to 1 if you have the `hypot' function. */ +#define HAVE_HYPOT 1 + +/* Define if you have the 'inet_aton' function. */ +/* #undef HAVE_INET_ATON */ + +/* Define if you have the 'inet_pton' function. */ +#define HAVE_INET_PTON 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `kill' function. */ +#define HAVE_KILL 1 + +/* Define to 1 if you have the `killpg' function. */ +#define HAVE_KILLPG 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_LANGINFO_H 1 + +/* Defined to enable large file support when an off_t is bigger than a long + and long long is available and at least as big as an off_t. You may need to + add some flags for configuration and compilation to enable this mode. (For + Solaris and Linux, the necessary defines are already defined.) */ +/* #undef HAVE_LARGEFILE_SUPPORT */ + +/* Define to 1 if you have the `lchown' function. */ +#define HAVE_LCHOWN 1 + +/* Define to 1 if you have the `dl' library (-ldl). */ +#define HAVE_LIBDL 1 + +/* Define to 1 if you have the `dld' library (-ldld). */ +/* #undef HAVE_LIBDLD */ + +/* Define to 1 if you have the `ieee' library (-lieee). */ +/* #undef HAVE_LIBIEEE */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_LIBINTL_H */ + +/* Define to 1 if you have the `resolv' library (-lresolv). */ +/* #undef HAVE_LIBRESOLV */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_LIBUTIL_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define if you have the 'link' function. */ +#define HAVE_LINK 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define this if you have the type long long. */ +#define HAVE_LONG_LONG 1 + +/* Define to 1 if you have the `lstat' function. */ +#define HAVE_LSTAT 1 + +/* Define this if you have the makedev macro. */ +/* #undef HAVE_MAKEDEV */ + +/* Define to 1 if you have the `memmove' function. */ +#define HAVE_MEMMOVE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `mkfifo' function. */ +#define HAVE_MKFIFO 1 + +/* Define to 1 if you have the `mknod' function. */ +#define HAVE_MKNOD 1 + +/* Define to 1 if you have the `mktime' function. */ +#define HAVE_MKTIME 1 + +/* Define to 1 if you have the `mremap' function. */ +/* #undef HAVE_MREMAP */ + +/* Define to 1 if you have the header file. */ +#define HAVE_NCURSES_H 1 + +/* Define to 1 if you have the header file, and it defines `DIR'. */ +/* #undef HAVE_NDIR_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_NETPACKET_PACKET_H */ + +/* Define to 1 if you have the `nice' function. */ +#define HAVE_NICE 1 + +/* Define to 1 if you have the `openpty' function. */ +#define HAVE_OPENPTY 1 + +/* Define to 1 if you have the `pathconf' function. */ +#define HAVE_PATHCONF 1 + +/* Define to 1 if you have the `pause' function. */ +#define HAVE_PAUSE 1 + +/* Define to 1 if you have the `plock' function. */ +/* #undef HAVE_PLOCK */ + +/* Define to 1 if you have the `poll' function. */ +#define HAVE_POLL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_POLL_H 1 + +/* Define if your compiler supports function prototype */ +#define HAVE_PROTOTYPES 1 + +/* Define if you have GNU PTH threads. */ +/* #undef HAVE_PTH */ + +/* Defined for Solaris 2.6 bug in pthread header. */ +/* #undef HAVE_PTHREAD_DESTRUCTOR */ + +/* Define to 1 if you have the header file. */ +#define HAVE_PTHREAD_H 1 + +/* Define to 1 if you have the `pthread_init' function. */ +/* #undef HAVE_PTHREAD_INIT */ + +/* Define to 1 if you have the `pthread_sigmask' function. */ +#define HAVE_PTHREAD_SIGMASK 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_PTY_H */ + +/* Define to 1 if you have the `putenv' function. */ +#define HAVE_PUTENV 1 + +/* Define to 1 if you have the `readlink' function. */ +#define HAVE_READLINK 1 + +/* Define to 1 if you have the `realpath' function. */ +#define HAVE_REALPATH 1 + +/* Define if you have readline 2.2 */ +#define HAVE_RL_COMPLETION_APPEND_CHARACTER 1 + +/* Define if you have readline 4.2 */ +#define HAVE_RL_COMPLETION_MATCHES 1 + +/* Define if you have readline 4.0 */ +#define HAVE_RL_PRE_INPUT_HOOK 1 + +/* Define to 1 if you have the `select' function. */ +#define HAVE_SELECT 1 + +/* Define to 1 if you have the `setegid' function. */ +#define HAVE_SETEGID 1 + +/* Define to 1 if you have the `seteuid' function. */ +#define HAVE_SETEUID 1 + +/* Define to 1 if you have the `setgid' function. */ +#define HAVE_SETGID 1 + +/* Define if you have the 'setgroups' function. */ +/* #undef HAVE_SETGROUPS */ + +/* Define to 1 if you have the `setlocale' function. */ +#define HAVE_SETLOCALE 1 + +/* Define to 1 if you have the `setpgid' function. */ +#define HAVE_SETPGID 1 + +/* Define to 1 if you have the `setpgrp' function. */ +#define HAVE_SETPGRP 1 + +/* Define to 1 if you have the `setregid' function. */ +#define HAVE_SETREGID 1 + +/* Define to 1 if you have the `setreuid' function. */ +#define HAVE_SETREUID 1 + +/* Define to 1 if you have the `setsid' function. */ +#define HAVE_SETSID 1 + +/* Define to 1 if you have the `setuid' function. */ +#define HAVE_SETUID 1 + +/* Define to 1 if you have the `setvbuf' function. */ +#define HAVE_SETVBUF 1 + +/* Define to 1 if you have the `sigaction' function. */ +#define HAVE_SIGACTION 1 + +/* Define to 1 if you have the `siginterrupt' function. */ +#define HAVE_SIGINTERRUPT 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SIGNAL_H 1 + +/* Define to 1 if you have the `sigrelse' function. */ +#define HAVE_SIGRELSE 1 + +/* Define to 1 if you have the `snprintf' function. */ +#define HAVE_SNPRINTF 1 + +/* Define if sockaddr has sa_len member */ +#define HAVE_SOCKADDR_SA_LEN 1 + +/* struct sockaddr_storage (sys/socket.h) */ +#define HAVE_SOCKADDR_STORAGE 1 + +/* Define to 1 if you have the `statvfs' function. */ +#define HAVE_STATVFS 1 + +/* Define if you have struct stat.st_mtim.tv_nsec */ +/* #undef HAVE_STAT_TV_NSEC */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDARG_H 1 + +/* Define if your compiler supports variable length function prototypes (e.g. + void fprintf(FILE *, char *, ...);) *and* */ +#define HAVE_STDARG_PROTOTYPES 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDDEF_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strdup' function. */ +#define HAVE_STRDUP 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the `strftime' function. */ +#define HAVE_STRFTIME 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_STROPTS_H */ + +/* Define to 1 if you have the `strptime' function. */ +#define HAVE_STRPTIME 1 + +/* Define to 1 if `st_blksize' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BLKSIZE 1 + +/* Define to 1 if `st_blocks' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_BLOCKS 1 + +/* Define to 1 if `st_rdev' is member of `struct stat'. */ +#define HAVE_STRUCT_STAT_ST_RDEV 1 + +/* Define to 1 if `tm_zone' is member of `struct tm'. */ +#define HAVE_STRUCT_TM_TM_ZONE 1 + +/* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use + `HAVE_STRUCT_STAT_ST_BLOCKS' instead. */ +#define HAVE_ST_BLOCKS 1 + +/* Define if you have the 'symlink' function. */ +#define HAVE_SYMLINK 1 + +/* Define to 1 if you have the `sysconf' function. */ +#define HAVE_SYSCONF 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYSEXITS_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_AUDIOIO_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_BSDTTY_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_DIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_FILE_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_LOCK_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MKDEV_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_SYS_MODEM_H */ + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +/* #undef HAVE_SYS_NDIR_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_POLL_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_RESOURCE_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SELECT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SOCKET_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIMES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UTSNAME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_WAIT_H 1 + +/* Define to 1 if you have the `tcgetpgrp' function. */ +#define HAVE_TCGETPGRP 1 + +/* Define to 1 if you have the `tcsetpgrp' function. */ +#define HAVE_TCSETPGRP 1 + +/* Define to 1 if you have the `tempnam' function. */ +#define HAVE_TEMPNAM 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TERMIOS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TERM_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_THREAD_H */ + +/* Define to 1 if you have the `timegm' function. */ +#define HAVE_TIMEGM 1 + +/* Define to 1 if you have the `times' function. */ +#define HAVE_TIMES 1 + +/* Define to 1 if you have the `tmpfile' function. */ +#define HAVE_TMPFILE 1 + +/* Define to 1 if you have the `tmpnam' function. */ +#define HAVE_TMPNAM 1 + +/* Define to 1 if you have the `tmpnam_r' function. */ +/* #undef HAVE_TMPNAM_R */ + +/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use + `HAVE_STRUCT_TM_TM_ZONE' instead. */ +#define HAVE_TM_ZONE 1 + +/* Define to 1 if you have the `truncate' function. */ +#define HAVE_TRUNCATE 1 + +/* Define to 1 if you don't have `tm_zone' but do have the external array + `tzname'. */ +/* #undef HAVE_TZNAME */ + +/* Define this if you have tcl and TCL_UTF_MAX==6 */ +/* #undef HAVE_UCS4_TCL */ + +/* Define this if you have the type uintptr_t. */ +/* #undef HAVE_UINTPTR_T */ + +/* Define to 1 if you have the `uname' function. */ +#define HAVE_UNAME 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `unsetenv' function. */ +#define HAVE_UNSETENV 1 + +/* Define if you have a useable wchar_t type defined in wchar.h; useable means + wchar_t must be 16-bit unsigned type. (see Include/unicodeobject.h). */ +/* #undef HAVE_USABLE_WCHAR_T */ + +/* Define to 1 if you have the `utimes' function. */ +#define HAVE_UTIMES 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UTIME_H 1 + +/* Define to 1 if you have the `waitpid' function. */ +#define HAVE_WAITPID 1 + +/* Define if the compiler provides a wchar.h header file. */ +#define HAVE_WCHAR_H 1 + +/* Define to 1 if you have the `wcscoll' function. */ +#define HAVE_WCSCOLL 1 + +/* Define if tzset() actually switches the local timezone in a meaningful way. + */ +#define HAVE_WORKING_TZSET 1 + +/* Define to 1 if you have the `_getpty' function. */ +/* #undef HAVE__GETPTY */ + +/* Define if you are using Mach cthreads directly under /include */ +/* #undef HURD_C_THREADS */ + +/* Define if you are using Mach cthreads under mach / */ +/* #undef MACH_C_THREADS */ + +/* Define to 1 if `major', `minor', and `makedev' are declared in . + */ +/* #undef MAJOR_IN_MKDEV */ + +/* Define to 1 if `major', `minor', and `makedev' are declared in + . */ +/* #undef MAJOR_IN_SYSMACROS */ + +/* Define if mvwdelch in curses.h is an expression. */ +#define MVWDELCH_IS_EXPRESSION 1 + +/* Define to the address where bug reports for this package should be sent. */ +/* #undef PACKAGE_BUGREPORT */ + +/* Define to the full name of this package. */ +/* #undef PACKAGE_NAME */ + +/* Define to the full name and version of this package. */ +/* #undef PACKAGE_STRING */ + +/* Define to the one symbol short name of this package. */ +/* #undef PACKAGE_TARNAME */ + +/* Define to the version of this package. */ +/* #undef PACKAGE_VERSION */ + +/* Defined if PTHREAD_SCOPE_SYSTEM supported. */ +#define PTHREAD_SYSTEM_SCHED_SUPPORTED 1 + +/* Define as the integral type used for Unicode representation. */ +#define PY_UNICODE_TYPE unsigned short + +/* Define if you want to build an interpreter with many run-time checks. */ +/* #undef Py_DEBUG */ + +/* Defined if Python is built as a shared library. */ +/* #undef Py_ENABLE_SHARED */ + +/* Define as the size of the unicode type. */ +#define Py_UNICODE_SIZE 2 + +/* Define if you want to have a Unicode type. */ +#define Py_USING_UNICODE 1 + +/* Define as the return type of signal handlers (`int' or `void'). */ +#define RETSIGTYPE void + +/* Define if setpgrp() must be called as setpgrp(0, 0). */ +/* #undef SETPGRP_HAVE_ARG */ + +/* Define if i>>j for signed int i does not extend the sign bit when i < 0 */ +/* #undef SIGNED_RIGHT_SHIFT_ZERO_FILLS */ + +/* The size of a `char', as computed by sizeof. */ +#define SIZEOF_CHAR 1 + +/* The size of a `double', as computed by sizeof. */ +#define SIZEOF_DOUBLE 8 + +/* The size of a `float', as computed by sizeof. */ +#define SIZEOF_FLOAT 4 + +/* The size of a `fpos_t', as computed by sizeof. */ +#define SIZEOF_FPOS_T 8 + +/* The size of a `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* The size of a `long', as computed by sizeof. */ +#define SIZEOF_LONG 8 + +/* The size of a `long long', as computed by sizeof. */ +#define SIZEOF_LONG_LONG 8 + +/* The number of bytes in an off_t. */ +#define SIZEOF_OFF_T 8 + +/* The number of bytes in a pthread_t. */ +#define SIZEOF_PTHREAD_T 8 + +/* The size of a `short', as computed by sizeof. */ +#define SIZEOF_SHORT 2 + +/* The number of bytes in a time_t. */ +#define SIZEOF_TIME_T 8 + +/* The size of a `uintptr_t', as computed by sizeof. */ +/* #undef SIZEOF_UINTPTR_T */ + +/* The size of a `void *', as computed by sizeof. */ +#define SIZEOF_VOID_P 8 + +/* The size of a `wchar_t', as computed by sizeof. */ +#define SIZEOF_WCHAR_T 4 + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if you can safely include both and + (which you can't on SCO ODT 3.0). */ +#define SYS_SELECT_WITH_SYS_TIME 1 + +/* Define to 1 if you can safely include both and . */ +#define TIME_WITH_SYS_TIME 1 + +/* Define to 1 if your declares `struct tm'. */ +/* #undef TM_IN_SYS_TIME */ + +/* Define if you want to use MacPython modules on MacOSX in unix-Python. */ +#define USE_TOOLBOX_OBJECT_GLUE 1 + +/* Define if a va_list is an array of some kind */ +#define VA_LIST_IS_ARRAY 1 + +/* Define if you want SIGFPE handled (see Include/pyfpe.h). */ +/* #undef WANT_SIGFPE_HANDLER */ + +/* Define if you want wctype.h functions to be used instead of the one + supplied by Python itself. (see Include/unicodectype.h). */ +/* #undef WANT_WCTYPE_FUNCTIONS */ + +/* Define if WINDOW in curses.h offers a field _flags. */ +/* #undef WINDOW_HAS_FLAGS */ + +/* Define if you want to emulate SGI (IRIX 4) dynamic linking. This is + rumoured to work on VAX (Ultrix), Sun3 (SunOS 3.4), Sequent Symmetry + (Dynix), and Atari ST. This requires the 'dl-dld' library, + ftp://ftp.cwi.nl/pub/dynload/dl-dld-1.1.tar.Z, as well as the 'GNU dld' + library, ftp://ftp.cwi.nl/pub/dynload/dld-3.2.3.tar.Z. Do not bother on + SunOS 4 or 5, they already have dynamic linking using shared libraries. */ +/* #undef WITH_DL_DLD */ + +/* Define if you want documentation strings in extension modules */ +#define WITH_DOC_STRINGS 1 + +/* Define if you want to use the new-style (Openstep, Rhapsody, MacOS) dynamic + linker (dyld) instead of the old-style (NextStep) dynamic linker (rld). + Dyld is necessary to support frameworks. */ +#define WITH_DYLD 1 + +/* Define to 1 if libintl is needed for locale functions. */ +/* #undef WITH_LIBINTL */ + +/* Define if you want to produce an OpenStep/Rhapsody framework (shared + library plus accessory files). */ +/* #undef WITH_NEXT_FRAMEWORK */ + +/* Define if you want to compile in Python-specific mallocs */ +#define WITH_PYMALLOC 1 + +/* Define if you want to use SGI (IRIX 4) dynamic linking. This requires the + "dl" library by Jack Jansen, ftp://ftp.cwi.nl/pub/dynload/dl-1.6.tar.Z. Do + not bother on IRIX 5, it already has dynamic linking using SunOS style + shared libraries */ +/* #undef WITH_SGI_DL */ + +/* Define if you want to compile in rudimentary thread support */ +#define WITH_THREAD 1 + +/* Define if you want to read files with foreign newlines. */ +#define WITH_UNIVERSAL_NEWLINES 1 + +/* Define to 1 if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ +/* #undef WORDS_BIGENDIAN */ + +/* Define to 1 if on AIX 3. + System headers sometimes define this. + We just want to avoid a redefinition error message. */ +#ifndef _ALL_SOURCE +/* # undef _ALL_SOURCE */ +#endif + +/* This must be set to 64 on some systems to enable large file support. */ +#define _FILE_OFFSET_BITS 64 + +/* Define on Linux to activate all library features */ +#define _GNU_SOURCE 1 + +/* This must be defined on some systems to enable large file support. */ +#define _LARGEFILE_SOURCE 1 + +/* Define to 1 if on MINIX. */ +/* #undef _MINIX */ + +/* Define on NetBSD to activate all library features */ +#define _NETBSD_SOURCE 1 + +/* Define _OSF_SOURCE to get the makedev macro. */ +/* #undef _OSF_SOURCE */ + +/* Define to 2 if the system does not provide POSIX.1 features except with + this defined. */ +/* #undef _POSIX_1_SOURCE */ + +/* Define to activate features from IEEE Stds 1003.1-2001 */ +#define _POSIX_C_SOURCE 200112L + +/* Define to 1 if you need to in order for `stat' and other things to work. */ +/* #undef _POSIX_SOURCE */ + +/* Define if you have POSIX threads, and your system does not define that. */ +/* #undef _POSIX_THREADS */ + +/* Define to force use of thread-safe errno, h_errno, and other functions */ +#define _REENTRANT 1 + +/* Define to the level of X/Open that your system supports */ +#define _XOPEN_SOURCE 600 + +/* Define to activate Unix95-and-earlier features */ +#define _XOPEN_SOURCE_EXTENDED 1 + +/* Define on FreeBSD to activate all library features */ +#define __BSD_VISIBLE 1 + +/* Define to 1 if type `char' is unsigned and you are not using gcc. */ +#ifndef __CHAR_UNSIGNED__ +/* # undef __CHAR_UNSIGNED__ */ +#endif + +/* Defined on Solaris to see additional function prototypes. */ +/* #undef __EXTENSIONS__ */ + +/* Define to 'long' if doesn't define. */ +/* #undef clock_t */ + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `int' if doesn't define. */ +/* #undef gid_t */ + +/* Define to `int' if does not define. */ +/* #undef mode_t */ + +/* Define to `long' if does not define. */ +/* #undef off_t */ + +/* Define to `int' if does not define. */ +/* #undef pid_t */ + +/* Define to empty if the keyword does not work. */ +/* #undef signed */ + +/* Define to `unsigned' if does not define. */ +/* #undef size_t */ + +/* Define to `int' if does not define. */ +/* #undef socklen_t */ + +/* Define to `int' if doesn't define. */ +/* #undef uid_t */ + +/* Define to empty if the keyword does not work. */ +/* #undef volatile */ + + +/* Define the macros needed if on a UnixWare 7.x system. */ +#if defined(__USLC__) && defined(__SCO_VERSION__) +#define STRICT_SYSV_CURSES /* Don't use ncurses extensions */ +#endif + +/* ---- macOS overrides: the only hand-written lines in this file. ---- */ + +/* [CHOSEN, not recovered] Darwin's defines _POSIX_SEMAPHORES as -1 ("not supported"): + * sem_init/sem_destroy fail with ENOSYS and only named semaphores exist. Python/thread_pthread.h + * tests the macro with #ifdef, so without this it builds every lock on sem_init and every lock + * operation fails. HAVE_BROKEN_POSIX_SEMAPHORES is the switch upstream already provides for such + * platforms (configure.in sets it for SunOS 5.8); it selects the mutex + condition-variable locks. */ +#define HAVE_BROKEN_POSIX_SEMAPHORES 1 + +/* [CHOSEN, not recovered] arm64 (Apple silicon). The configure run above was x86_64, where va_list + * is an array type. On arm64 Darwin va_list is a plain char*, so Py_VA_COPY must assign rather than + * memcpy through it. Every other value above holds for arm64 macOS too (LP64, little-endian, the + * same libSystem). This override is untested: the port's reference machine is x86_64. */ +#if defined(__arm64__) || defined(__aarch64__) +#undef VA_LIST_IS_ARRAY +#endif + +#endif /*Py_PYCONFIG_H*/ diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c index e9375faa9..98865aa7c 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Modules/socketmodule.c @@ -3024,7 +3024,12 @@ socket_inet_ntop(PyObject *self, PyObject *args) #endif /* Guarantee NUL-termination for PyString_FromString() below */ +#ifdef MS_WINDOWS memset((void *) &ip[0], '\0', sizeof(ip) + 1); +#else + /* [CHOSEN, not recovered] Bound initialization to the actual POSIX buffer. */ + memset((void *) &ip[0], '\0', sizeof(ip)); +#endif if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) { return NULL; diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c index f246bd232..7f36161f5 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/longobject.c @@ -28,11 +28,20 @@ static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit); static PyLongObject *divrem1(PyLongObject *, digit, digit *); static PyObject *long_format(PyObject *aa, int base, int addL); +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) +/* [CHOSEN, not recovered] Match ceval.c's atomic ticker accesses on POSIX. */ +#define SIGCHECK(PyTryBlock) \ + if (__atomic_sub_fetch(&_Py_Ticker, 1, __ATOMIC_SEQ_CST) < 0) { \ + __atomic_store_n(&_Py_Ticker, _Py_CheckInterval, __ATOMIC_SEQ_CST); \ + if (PyErr_CheckSignals()) { PyTryBlock; } \ + } +#else #define SIGCHECK(PyTryBlock) \ if (--_Py_Ticker < 0) { \ _Py_Ticker = _Py_CheckInterval; \ if (PyErr_CheckSignals()) { PyTryBlock; } \ } +#endif /* Normalize (remove leading zeros from) a long int object. Doesn't attempt to free the storage--in most cases, due to the nature diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c index 7e5fd4a8e..7ad6e18b2 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Objects/obmalloc.c @@ -409,8 +409,15 @@ static poolp freepools = NULL; /* free list for cached pools */ * and only grows by appending at the end. For now we never return an arena * to the OS. */ +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) +/* [CHOSEN, not recovered] POSIX: publish the vector before its count, including to + frees without the GIL (see new_arena). C11 implicit accesses are sequentially consistent. */ +static _Atomic(uptr *) arenas = NULL; +static _Atomic uint narenas = 0; +#else static uptr *volatile arenas = NULL; /* the pointer itself is volatile */ static volatile uint narenas = 0; +#endif static uint maxarenas = 0; /* Number of pools still available to be allocated in the current arena. */ diff --git a/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c b/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c index 035520a59..03abb7f00 100644 --- a/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c +++ b/Code/BF2/External/python-embedded/py-src-2.3.4/Python/ceval.c @@ -429,21 +429,40 @@ static struct { int (*func)(void *); void *arg; } pendingcalls[NPENDINGCALLS]; +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) +#include +/* [CHOSEN, not recovered] POSIX pending-call publication must order the queue slots. + C11 atomics are used in this C runtime; the Windows implementation is retained below. */ +static _Atomic int pendingfirst = 0; +static _Atomic int pendinglast = 0; +static _Atomic int things_to_do = 0; +#else static volatile int pendingfirst = 0; static volatile int pendinglast = 0; static volatile int things_to_do = 0; +#endif int Py_AddPendingCall(int (*func)(void *), void *arg) { +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + /* A failed try-lock refuses nested/simultaneous producers without blocking a signal handler. */ + static _Atomic int busy = 0; +#else static int busy = 0; +#endif int i, j; /* XXX Begin critical section */ /* XXX If you want this to be safe against nested XXX asynchronous calls, you'll have to work harder! */ +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + if (atomic_exchange_explicit(&busy, 1, memory_order_seq_cst)) + return -1; +#else if (busy) return -1; busy = 1; +#endif i = pendinglast; j = (i + 1) % NPENDINGCALLS; if (j == pendingfirst) { @@ -454,7 +473,11 @@ Py_AddPendingCall(int (*func)(void *), void *arg) pendingcalls[i].arg = arg; pendinglast = j; +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + __atomic_store_n(&_Py_Ticker, 0, __ATOMIC_SEQ_CST); +#else _Py_Ticker = 0; +#endif things_to_do = 1; /* Signal main loop */ busy = 0; /* XXX End critical section */ @@ -772,13 +795,22 @@ eval_frame(PyFrameObject *f) async I/O handler); see Py_AddPendingCall() and Py_MakePendingCalls() above. */ +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + /* [CHOSEN, not recovered] May be reset by Py_AddPendingCall without the GIL. */ + if (__atomic_sub_fetch(&_Py_Ticker, 1, __ATOMIC_SEQ_CST) < 0) { +#else if (--_Py_Ticker < 0) { +#endif if (*next_instr == SETUP_FINALLY) { /* Make the last opcode before a try: finally: block uninterruptable. */ goto fast_next_opcode; } +#if !defined(MS_WINDOWS) && (defined(__APPLE__) || defined(__linux__)) + __atomic_store_n(&_Py_Ticker, _Py_CheckInterval, __ATOMIC_SEQ_CST); +#else _Py_Ticker = _Py_CheckInterval; +#endif tstate->tick_counter++; if (things_to_do) { if (Py_MakePendingCalls() < 0) { diff --git a/Code/BF2/Game/AudioSettings.cpp b/Code/BF2/Game/AudioSettings.cpp index c3ef6fd66..24e9fbb43 100644 --- a/Code/BF2/Game/AudioSettings.cpp +++ b/Code/BF2/Game/AudioSettings.cpp @@ -7,7 +7,14 @@ #include "../Core/Ids.h" #include "../Core/SmartItf.h" // classManager #include "../Sound/BfSound.h" +#if defined(_WIN32) #include +#else +#include // [CHOSEN, not recovered] hw.memsize for the GlobalMemoryStatus arm +#include +#endif +#include +#include #include #include #include @@ -19,9 +26,23 @@ namespace { int physicalMemoryMegabytes() { try { +#if defined(_WIN32) MEMORYSTATUS status; GlobalMemoryStatus(&status); int megabytes = static_cast((status.dwTotalPhys + 0x7FFFFu) >> 20); +#else + // [CHOSEN, not recovered] GlobalMemoryStatus for the large-address-aware 32-bit BF2.exe: + // dwTotalPhys is a 32-bit DWORD saturated at 0xFFFFFFFF above 4 GB. The same DWORD + // arithmetic follows, so a machine with 4 GB or more wraps to 0 MB and selects "Low", as + // the retail client does on such a machine. + std::uint64_t physical = 0; + std::size_t length = sizeof(physical); + if (sysctlbyname("hw.memsize", &physical, &length, 0, 0) != 0) + physical = 0; + const std::uint32_t totalPhys = physical > 0xFFFFFFFFull ? 0xFFFFFFFFu + : static_cast(physical); + int megabytes = static_cast(static_cast(totalPhys + 0x7FFFFu) >> 20); +#endif const int remainder = megabytes % 4; if (remainder) megabytes += 4 - remainder; return megabytes; @@ -314,6 +335,19 @@ bool AudioSettings::apply(bool reportErrors) applyRecord(m_current, reportErrors); g_bfSound->engine()->playMusic(); } + // [TEMP] [CHOSEN, not recovered] BF2_AUDIO_TRACE=1: what an apply left in the sound + // facade, for unattended option runs. [RETIRE-WHEN: macos-options-validated] + const char* trace = std::getenv("BF2_AUDIO_TRACE"); + if (trace && trace[0] == '1') + { + std::fprintf(stderr, "[TEMP] [AUDIO] apply result=%d status=%d provider=\"%s\" eax=%d quality=\"%s\" " + "groups effects=%.3f music=%.3f voice=%.3f effects3=%.3f\n", + result ? 1 : 0, m_status, m_current.provider.c_str(), m_current.enableEAX ? 1 : 0, + m_current.soundQuality.c_str(), g_bfSound->getVolumeForGroup(0), + g_bfSound->getVolumeForGroup(1), g_bfSound->getVolumeForGroup(2), + g_bfSound->getVolumeForGroup(3)); + std::fflush(stderr); + } } return result; } diff --git a/Code/BF2/Game/Common/ClientConnection.cpp b/Code/BF2/Game/Common/ClientConnection.cpp index b5bf1af30..3cf7d4959 100644 --- a/Code/BF2/Game/Common/ClientConnection.cpp +++ b/Code/BF2/Game/Common/ClientConnection.cpp @@ -23,6 +23,7 @@ #include "../../IO/Network/NetworkManager.h" // io::networkManager - transmitMsgs' local-latency arm #include "../../Physics/LatencyCompensation.h" // world::LatencyCompensation::getLocalLatency (local only) #include "../GameServer/ServerSettings.h" // sv.demoQuality - demoQualityFromSettings' single read +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -243,7 +244,7 @@ const char* ClientConnection::initChallengeString(const char* fixed) else { for (int j = 0; j <= 9; ++j) - m_challengeString[j] = static_cast(rand() % 26 + 97); + m_challengeString[j] = static_cast(bf2crt::rand() % 26 + 97); m_challengeString[9] = 0; // the tenth byte becomes the terminator } return m_challengeString; diff --git a/Code/BF2/Game/Common/GhostManager.cpp b/Code/BF2/Game/Common/GhostManager.cpp index 83274b203..b043f7439 100644 --- a/Code/BF2/Game/Common/GhostManager.cpp +++ b/Code/BF2/Game/Common/GhostManager.cpp @@ -37,6 +37,7 @@ #include "../../Core/ClassManager.h" // getClassName +0x28 - debugShowActiveGhosts #include "../../Core/SettingsRepostitory.h" // GSDebugGhostManager, boolGet +0x50 +#include // offsetof - the retail layout checks below #include // memset - the 4 KB ghost table #include // debugShowActiveGhosts' two locals @@ -45,6 +46,12 @@ namespace hfe { extern ClassManager* classManager; // Core/Globals.cpp - the per-TU extern convention +#if defined(_M_IX86) +// readData's remove and update arms read these two fields at their retail offsets. +static_assert(offsetof(io::INetworkableObject, m_ownerId) == 0x04, "retail owner id"); +static_assert(offsetof(io::INetworkableObject, m_object) == 0x08, "retail replicated object"); +#endif + // Initialize per-connection ghost queues and baseline storage. Ghost ids are seeded // lazily on first assignment. State masks and the control-object id are deliberately // left uninitialized until their owning paths set them. @@ -1722,13 +1729,12 @@ bool GhostManager::readData(io::BitStream& stream) io::INetworkableObject* const objEntry = networkable->m_networkableObject; bool disable = true; - if (objEntry && *reinterpret_cast( - reinterpret_cast(objEntry) + 4) >= 0) + // The retail reads are the low word of m_ownerId (+0x04 on x86), sign-extended. + if (objEntry && static_cast(objEntry->m_ownerId) >= 0) { // the object belongs to a player - only disable it if that player is gone // or local, and only if it is not parented to something else. - const short playerId = *reinterpret_cast( - reinterpret_cast(objEntry) + 4); + const short playerId = static_cast(objEntry->m_ownerId); world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId); if (!player || !player->getIsRemote() || object->getParent()) disable = false; @@ -1782,10 +1788,10 @@ bool GhostManager::readData(io::BitStream& stream) io::INetworkable* const n = desc ? desc->properties[0].networkables[0] : 0; if (n && n->m_networkableObject) { - const unsigned char* const info = - *reinterpret_cast( - reinterpret_cast(n->m_networkableObject) + 8); - if (info && (info[4] & 0x20)) + // The retail reads [netobj +0x08] (m_object) and tests the low byte of that object's + // +0x04 flag word, the same bit sendData skips on. + const world::IObject* const info = n->m_networkableObject->m_object; + if (info && (static_cast(info->getFlags()) & 0x20)) desc = 0; // treat it as unknown: skip the payload } } diff --git a/Code/BF2/Game/Common/PlayerActionManager.cpp b/Code/BF2/Game/Common/PlayerActionManager.cpp index cd54f3011..c705a0c2d 100644 --- a/Code/BF2/Game/Common/PlayerActionManager.cpp +++ b/Code/BF2/Game/Common/PlayerActionManager.cpp @@ -32,6 +32,9 @@ PlayerActionManager::PlayerActionManager() std::memset(&zeroInput, 0, sizeof(zeroInput)); PlayerAction zeroAction; + // set() does not write m_inputIndex, so the index is cleared first. transmit sends slot 0's + // index as the packet's base index while add() is still sliding these placeholders out. + zeroAction.m_inputIndex = 0; zeroAction.set(zeroInput); for (int i = 0; i < 3; ++i) diff --git a/Code/BF2/Game/Common/ServerConnection.cpp b/Code/BF2/Game/Common/ServerConnection.cpp index c1095b771..62b1a2405 100644 --- a/Code/BF2/Game/Common/ServerConnection.cpp +++ b/Code/BF2/Game/Common/ServerConnection.cpp @@ -39,6 +39,7 @@ #include "../../IO/Network/NetworkableInfo.h" // getForceNetworkableId - the phase-A replication gate #include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" // getDefaultTeam - the object's team #include "../Objects/ObjectLayoutAccess.h" // physicsNode (+0x44) / objectTemplate (+0x14) +#include "../Objects/RemoteControlledObjectTemplate.h" // rcType - getSpecialCommanderObjects #include "../../Physics/IPhysicsNode.h" // getPositionalSpeed (+0x60) - the priority speed factor #include "../../IO/Network/INetworkableObject.h" // m_ownerId / m_object - the scope pass reads both #include "../../Core/Debug.h" // the attested line-98 "Control object not found" @@ -75,15 +76,6 @@ int remoteControlledObjectTeam(world::IObject* object) return 0; } -// Returns the template's remote-control type, despite the helper's State name. -// [UNRESOLVED] Meanings of the selected type values. -int remoteControlledObjectState(world::IObject* object) -{ - const char* const templ = reinterpret_cast( - world::object_detail::LayoutAccess::objectTemplate(object)); // IObject +0x14 - return *reinterpret_cast(templ + 0x180); // ...Template::rcType -} - // ICameraObject's transform - both updateGhostManager call sites inline `vtable +0x10 with a 0 // argument` and copy the 64-byte result; that slot is getTransformation(float). void cameraTransform(world::ICameraObject* camera, Mat4& out) @@ -213,7 +205,11 @@ void ServerConnection::getSpecialCommanderObjects(int team) it != rcObjects.end(); ++it) { world::IObject* const object = it->second; - const int state = remoteControlledObjectState(object); // the template's rcType + // Registry objects carry a RemoteControlledObjectTemplate; the PE reads its rcType at + // retail +0x180. The named member, because this build's template layout is not retail's + // (rcType sits at +0x208 on x86 here). [UNRESOLVED] Meanings of the selected type values. + const int state = static_cast( + world::object_detail::LayoutAccess::objectTemplate(object))->rcType; // IObject +0x14 if (remoteControlledObjectTeam(object) != team) continue; if (state != 1 && state != 2 && state != 3) diff --git a/Code/BF2/Game/ControlSettings.cpp b/Code/BF2/Game/ControlSettings.cpp index 1703ef526..aaa70d91f 100644 --- a/Code/BF2/Game/ControlSettings.cpp +++ b/Code/BF2/Game/ControlSettings.cpp @@ -218,7 +218,7 @@ void ControlSettings::updateInputDevices() // it is a game input, the output name is emptied, the manager captures into it, and the frame // event manager is asked to post event (10, 12) - the engine's EnableEscapeKeyMapping handler, // which clears the flag - two seconds later (40000000h). The third argument is never read. -bool ControlSettings::mapNextInput(int input, bool alternate, int /*unused*/, bool second, bool gameInput) +int ControlSettings::mapNextInput(int input, bool alternate, int /*unused*/, bool second, bool gameInput) { m_mappingInput = true; bool isAxis = false; @@ -229,7 +229,7 @@ bool ControlSettings::mapNextInput(int input, bool alternate, int /*unused*/, bo } } m_mappedInputName = ""; - const bool result = mapManager()->mapNextInput(m_map, input, alternate, isAxis, second, !gameInput, m_mappedInputName); + const int result = mapManager()->mapNextInput(m_map, input, alternate, isAxis, second, !gameInput, m_mappedInputName); frameEventManager->postEvent(static_cast(10), 12u, nullptr, 2.0f); return result; } diff --git a/Code/BF2/Game/ControlSettings.h b/Code/BF2/Game/ControlSettings.h index 8268d6ea2..7a1880a67 100644 --- a/Code/BF2/Game/ControlSettings.h +++ b/Code/BF2/Game/ControlSettings.h @@ -21,7 +21,7 @@ class IControlSettings : public IBase { virtual bool setDefaults() = 0; //+24 4B3230: reset, re-run Settings/Controls.con, back up; true virtual void resetControlMaps() = 0; //+28 4B2BE0: reset() on every live map virtual void updateInputDevices() = 0; //+2C 4B2C70: device manager update(-1.0f) then update(0.1f) - virtual bool mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) = 0; + virtual int mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) = 0; //+30 4B2CA0: the manager's full EAX (int status) virtual bool selectControlMap(const std::string& name) = 0; //+34 4B38A0: the map the feel accessors forward to; true virtual bool getBindingDescription(io::IControlMap* map, int input, bool alternate, bool second, bool gameInput, std::string& key, std::wstring& text) = 0; @@ -72,7 +72,7 @@ class ControlSettings final : public IControlSettings { bool setDefaults() override; void resetControlMaps() override; void updateInputDevices() override; - bool mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) override; + int mapNextInput(int input, bool alternate, int unused, bool second, bool gameInput) override; bool selectControlMap(const std::string& name) override; bool getBindingDescription(io::IControlMap* map, int input, bool alternate, bool second, bool gameInput, std::string& key, std::wstring& text) override; diff --git a/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp b/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp index 2c284150f..e09eca44b 100644 --- a/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp +++ b/Code/BF2/Game/DemoRecorder/DemoLibrary.cpp @@ -1,7 +1,7 @@ // [INFERRED] path. Full client PE410742/4C2510/4C25D0/4C2590/479830/4C3030/4C2A60/4C1D90/4C1FF0/ -// /4C1B90/689430/4C1BA0/4C1BB0/4C1BC0/4B3AB0/4B1C80/4C1C00/4C1DB0 read; the HTTP-side -// bodies 4C2DF0/4C1B70/4C1B80/4C1BD0 read and left as diagnostic stops at their first use of the -// withheld HTTPRequest base. +// /4C1B90/689430/4C1BA0/4C1BB0/4C1BC0/4B3AB0/4B1C80/4C1C00/4C1DB0 read. The HTTP side +// (4C1B70/4C1B80/4C1BD0 and the callbacks 4C1EC0/4C2D70/4B3A90) is recovered on the HTTPRequest +// base (Game/Persistence/HTTPRequest.cpp); 4C2DF0 (download) remains a stop - docs/macos-c-demolib-re.md. #include "DemoLibrary.h" #if !DEDICATED #include "DemoHeader.h" @@ -22,7 +22,7 @@ extern ClassManager* classManager; DemoLibraryEntry::DemoLibraryEntry() : version(0) {} // constructs the five strings; the int is written by refresh -// (124 B): the withheld base's constructor (59C390) runs first in retail; then the table, +// 4C2510 (124 B): the HTTPRequest base's constructor (59C390) runs first; then the table, // refcount 1, the empty entry vector, the four strings, progress 0, the two flags clear and the // pending bookmark -1. DemoLibrary::DemoLibrary() @@ -30,8 +30,8 @@ DemoLibrary::DemoLibrary() { } -// (131 B): the four strings in reverse order, the entry rows and their storage, then the -// withheld base's destructor (59C3C0). +// 4C25D0 (131 B): the four strings in reverse order, the entry rows and their storage, then the +// HTTPRequest base's destructor (59C3C0). DemoLibrary::~DemoLibrary() {} // (66 B): the settings-factory shape - aggregation refused, 176 retail bytes, construction @@ -114,11 +114,15 @@ bool DemoLibrary::refreshEntries() return true; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: demo-library-http-request] -// Stops until the HTTP request base and transfer lifecycle are recovered. +// [TEMP] [RETIRE-WHEN: demo-library-download-name] 4C2DF0 is read (cancel a busy transfer, +// store name/url/description, progress 0, require a current profile, create and delete +// \\profiles\\Default\\demos\\dummy.txt, build <4C26E0()>.bf2demo, getFile(url, path, true), +// on refusal "Unable to download demo file"), but its target-name helper 4C26E0 (a scan of the +// demos directory for the first free formatted name) is not recovered. Reached only from a user +// demo-download action, never per frame. bool DemoLibrary::download(const std::string&, const std::string&, const std::string&) { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::download: the HTTPRequest base (Game/Persistence/HTTPRequest.cpp, PE59C390) that PE4C2DF0 tests first is unrecovered\n"); + std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::download: PE4C2DF0's target-name helper PE4C26E0 is unrecovered\n"); std::fflush(stderr); std::abort(); } @@ -147,27 +151,54 @@ bool DemoLibrary::removeEntry(unsigned int index) return true; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: demo-library-http-request] -// / 4C1B80 / 4C1BD0 forward to the withheld base (59C420 think, 59C400 busy, 59C440 cancel -// followed by the target file's deletion). +// 4C1B70: `add ecx,4; jmp 59C420` - the base's think (no SDK call while both handles are -1). +// The tail jump leaves no defined answer in EAX; the only caller (SwiffHost::update) drops it. int DemoLibrary::update() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::update: HTTPRequest 59C420 (PE4C1B70) is unrecovered\n"); - std::fflush(stderr); - std::abort(); + HTTPRequest::update(); + return 0; } +// 4C1B80: `add ecx,4; jmp 59C400` - the base's pending-transfer test. bool DemoLibrary::isDownloading() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::isDownloading: HTTPRequest 59C400 (PE4C1B80) is unrecovered\n"); - std::fflush(stderr); - std::abort(); + return HTTPRequest::isUpdating(); } +// 4C1BD0: through the table's +28 (isDownloading); when busy, the base's cancel (59C440), then +// fileManager +20 deletes the target file (+30), and true. Idle answers the +28 false. bool DemoLibrary::cancelDownload() { - std::fprintf(stderr, "[FRONTIER] dice::hfe::DemoLibrary::cancelDownload: HTTPRequest 59C440 (PE4C1BD0) is unrecovered\n"); - std::fflush(stderr); - std::abort(); + if (!isDownloading()) + return false; + HTTPRequest::cancel(); + io::fileManager->deleteFile(m_downloadPath); // +20 + return true; +} +// 4C1EC0 (this = base +4): failed flag (+AC) set, the base failure (59C640), the message posted +// when it is not "" (operator!= 87F324 against 87FB54), then the partial target (+30) deleted. +void DemoLibrary::onGetFailure(const std::string& message) +{ + m_downloadFailed = true; + HTTPRequest::onGetFailure(message); + if (message != "") + reportError(message); + io::fileManager->deleteFile(m_downloadPath); // +20 +} +// 4C2D70: failed flag cleared, the base completion (59C660); a pending bookmark (+A8 != -1) goes +// to LocalProfileManager +B0 when that singleton exists, then is reset to -1; then the rescan 4C2A60. +void DemoLibrary::onGetFileComplete() +{ + m_downloadFailed = false; + HTTPRequest::onGetFileComplete(); + if (m_pendingBookmark != -1) { + IBase* manager = classManager->getSingleton(std::string("LocalProfileManager")); + if (manager) + static_cast(manager)->removeDemoBookmark(static_cast(m_pendingBookmark)); // +B0 + m_pendingBookmark = -1; + } + refreshEntries(); } +// 4B3A90 (ICF-shared): the progress float is stored at +A0. +void DemoLibrary::onProgress(float progress) { m_downloadProgress = progress; } const std::string& DemoLibrary::getDownloadName() { return m_downloadName; } const std::string& DemoLibrary::getDownloadUrl() { return m_downloadUrl; } diff --git a/Code/BF2/Game/DemoRecorder/DemoLibrary.h b/Code/BF2/Game/DemoRecorder/DemoLibrary.h index 381897ac3..755f65404 100644 --- a/Code/BF2/Game/DemoRecorder/DemoLibrary.h +++ b/Code/BF2/Game/DemoRecorder/DemoLibrary.h @@ -1,10 +1,11 @@ // Lists profile demos and exposes download controls. [INFERRED] Names and placement. -// [FRONTIER] [RETIRE-WHEN: demo-library-http-request] Implement the HTTPRequest base, -// callbacks, and download/update/status/cancel slots before enabling HTTP use; -// remaining calls stop with diagnostics. +// The HTTPRequest base sits at +4 (ctor 4C2510 calls 59C390 on [esi+4] and stores its table +// 8A90E8 there). update/isDownloading/cancelDownload and the three callbacks are recovered; +// download (4C2DF0) still stops: its target-name helper 4C26E0 is unrecovered. #ifndef GAME_DEMORECORDER_DEMOLIBRARY_H #define GAME_DEMORECORDER_DEMOLIBRARY_H #include "../../Core/IBase.h" +#include "../Persistence/HTTPRequest.h" #include #include #if !DEDICATED @@ -30,27 +31,27 @@ struct DemoLibraryEntry class IDemoLibrary : public IBase { public: virtual bool refresh() = 0; //+10 4C3030: 4C2A60, then true; LocalProfileManager::login 4AA4CD - virtual bool download(const std::string& name, const std::string& url, const std::string& description) = 0; //+14 4C2DF0 [FRONTIER] + virtual bool download(const std::string& name, const std::string& url, const std::string& description) = 0; //+14 4C2DF0 [FRONTIER] (4C26E0) virtual unsigned int getNumEntries() = 0; virtual DemoLibraryEntry* getEntry(unsigned int index) = 0; //+1C 4C1FF0: null past the count (through the virtual count) virtual bool removeEntry(unsigned int index) = 0; //+20 4C2660: deletes the file, erases the row - virtual int update() = 0; //+24 4C1B70 -> HTTPRequest 59C420 [FRONTIER] - virtual bool isDownloading() = 0; //+28 4C1B80 -> HTTPRequest 59C400 [FRONTIER] + virtual int update() = 0; //+24 4C1B70 -> HTTPRequest 59C420 + virtual bool isDownloading() = 0; //+28 4C1B80 -> HTTPRequest 59C400 virtual const std::string& getDownloadName() = 0; //+2C 4C1B90 +4C virtual const std::string& getDownloadUrl() = 0; virtual const std::string& getDownloadDescription() = 0; virtual float getDownloadProgress() = 0; //+38 4C1BB0 +A0 - virtual bool cancelDownload() = 0; //+3C 4C1BD0 [FRONTIER] + virtual bool cancelDownload() = 0; //+3C 4C1BD0 virtual bool getFlagA4() = 0; //+40 4C1BC0 +A4 [UNRESOLVED role] virtual void setFlagA4(bool value) = 0; //+44 4B3AB0 (ICF-shared setter) virtual void setPendingBookmark(int index) = 0; //+48 4B1C80 +A8; the download-complete callback hands it to LocalProfileManager +B0 virtual bool hasDownloadFailed() = 0; //+4C 4C1C00 +AC, raised by the failure callback }; -class DemoLibrary final : public IDemoLibrary { +class DemoLibrary final : public IDemoLibrary, public HTTPRequest { public: - DemoLibrary(); // retail 176 bytes (24 of them the withheld base) - ~DemoLibrary(); // body; the slot sits in the withheld base's table + DemoLibrary(); // 4C2510, retail 176 bytes (24 of them the base at +4) + ~DemoLibrary(); // 4C25D0; its slot is the base table's 4C25C0 thunk static IBase* create(unsigned int iid, IBase* outer); void addRef() override; // shared int getRef() override; // shared @@ -72,6 +73,10 @@ class DemoLibrary final : public IDemoLibrary { void setFlagA4(bool value) override; void setPendingBookmark(int index) override; bool hasDownloadFailed() override; + // The HTTPRequest table 8A90E8: +8 4C1EC0, +C 4C2D70, +18 4B3A90 (the rest are the base's). + void onGetFailure(const std::string& message) override; + void onGetFileComplete() override; + void onProgress(float progress) override; private: friend struct DemoLibraryFixture; diff --git a/Code/BF2/Game/GameClient/GameClient.cpp b/Code/BF2/Game/GameClient/GameClient.cpp index 53dea96d9..7c19ddb68 100644 --- a/Code/BF2/Game/GameClient/GameClient.cpp +++ b/Code/BF2/Game/GameClient/GameClient.cpp @@ -5,6 +5,7 @@ #include "GameClient.h" #if !DEDICATED +#include #include #include #include @@ -2115,6 +2116,18 @@ bool GameClient::getPause() { return m_paused; } / bool GameClient::getDisconnectRequested() { return m_disconnectRequested; } // : +0x120 bool GameClient::getIsReady() { return m_isReady; } // : +0x158 +namespace { +// The payload pointer a PostRemoteEvent stores in its notification node (PE node +0x2C). The named +// member keeps the retail x86 offset and follows the native layout elsewhere. +#if defined(_M_IX86) +static_assert(offsetof(NotificationEventNode, m_data) == 0x2C, "retail PE notification payload"); +#endif +inline void* remoteEventPayload(EventNode* node) +{ + return static_cast(node)->m_data; +} +} // namespace + // Dispatches client core/network events for join progress, player state, chat and object removal. // Database acknowledgements preserve network-ID regression order; mismatched IDs are fatal. // Event-specific node and data payloads must match the selected ID. @@ -2177,7 +2190,7 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* // Rewind the id allocator before comparing the highest used network id with the // server's watermark. The rewind result is discarded; the separate query can return -1. io::networkManager->regressNetworkableIds(); // discarded - const int theirs = **reinterpret_cast(reinterpret_cast(node) + 0x2C); + const int theirs = *static_cast(remoteEventPayload(node)); // node +0x2C const int ours = io::networkManager->getHighestUsedNetID(); if (theirs != ours) Debug(DEBUGTYPE_7, GAMECLIENT_FILE, 1404, "") @@ -2194,7 +2207,7 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* break; case 9: { - const int playerId = **reinterpret_cast(reinterpret_cast(node) + 0x2C); + const int playerId = *static_cast(remoteEventPayload(node)); // node +0x2C if (world::IPlayer* player = world::playerManager->getPlayerFromId(playerId)) { player->setIsAlive(true); // PE +0x64 @@ -2204,7 +2217,7 @@ void GameClient::handleEvent(EventCategory category, unsigned int id, EventNode* } case 10: { - const char* const payload = *reinterpret_cast(reinterpret_cast(node) + 0x2C); + const char* const payload = static_cast(remoteEventPayload(node)); // node +0x2C const int playerId = *reinterpret_cast(payload); const bool flag = payload[4] != 0; world::IPlayer* const player = world::playerManager->getPlayerFromId(playerId); diff --git a/Code/BF2/Game/GameLogic/GameLogic.cpp b/Code/BF2/Game/GameLogic/GameLogic.cpp index d3dc96e35..f8d9dfe85 100644 --- a/Code/BF2/Game/GameLogic/GameLogic.cpp +++ b/Code/BF2/Game/GameLogic/GameLogic.cpp @@ -1231,9 +1231,9 @@ void GameLogic::setFogStartEndAndBase(const Vec4& value) IBase* const framework = classManager->getSingleton("PostProductionFrameWork"); if (framework) { - typedef void (__fastcall* SetStateVec4Fn)(void* self, void* edx, const Vec4* value); + typedef void (__thiscall* SetStateVec4Fn)(void* self, const Vec4* value); void** const vtbl = *reinterpret_cast(framework); - reinterpret_cast(vtbl[0x24 / sizeof(void*)])(framework, 0, &value); + reinterpret_cast(vtbl[0x24 / 4])(framework, &value); } } diff --git a/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp b/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp index 77d15ef2c..700f61b98 100644 --- a/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp +++ b/Code/BF2/Game/GameLogic/GameLogicExplosion.cpp @@ -37,6 +37,7 @@ #include "../../Scene/Object/PlayerManager.h" #include "../../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" #include "../../Sound/BfSound.h" +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) #include "../../AI/AIInterface/BFKnowledge/BFCollisionHandler.h" #include "../../AI/AIDLL/AI/Main/CommonSingletonServer.h" // m_iBFCollisionHandler @@ -554,7 +555,7 @@ bool GameLogicExplosion::handleExplosionForceOnObject( if (isSoldier) { radial.y += *g_explosionSoldierForceYMod; - strength *= static_cast(std::rand() % 100) / 200.0f + 0.8f; + strength *= static_cast(bf2crt::rand() % 100) / 200.0f + 0.8f; } const float existingForce = length(node->getPositionalAcceleration()); diff --git a/Code/BF2/Game/GameLogic/Player.cpp b/Code/BF2/Game/GameLogic/Player.cpp index f2e2087e2..43120de4d 100644 --- a/Code/BF2/Game/GameLogic/Player.cpp +++ b/Code/BF2/Game/GameLogic/Player.cpp @@ -1945,21 +1945,13 @@ void Player::handleGasClouds(float deltaTime) if (!particleSystemManager) return; - // [PLATFORM] This plugin boundary uses RendDX9's MSVC 7.1 vector carrier: allocator at +0, - // begin at +4, end at +8. Do not cast it to a native std::vector; the ELF container differs. + // The renderer's active-instance vector, shared by reference (issue #7). const geom::ParticleSystemInstanceList* const systems = particleSystemManager->getInstances(); - // The PE re-reads the vector words on every iteration and breaks on a null begin; retain - // those repeated reads rather than snapshotting a container that instance calls may mutate. - for (unsigned int i = 0; ; ++i) + // The PE re-reads the vector's size on every iteration; retain that rather than snapshotting + // a container that instance calls may mutate. + for (unsigned int i = 0; i < static_cast(systems->size()); ++i) { - geom::IParticleSystemInstance* const* const first = systems->begin(); - if (!first) - break; - geom::IParticleSystemInstance* const* const last = systems->end(); - if (i >= static_cast(last - first)) - break; - - geom::IParticleSystemInstance* const system = systems->begin()[i]; + geom::IParticleSystemInstance* const system = (*systems)[i]; if (!system->getTemplate()->getGasCloudType()) continue; diff --git a/Code/BF2/Game/GameLogic/ServerGameLogic.cpp b/Code/BF2/Game/GameLogic/ServerGameLogic.cpp index 65f84edea..2e9b5f3ca 100644 --- a/Code/BF2/Game/GameLogic/ServerGameLogic.cpp +++ b/Code/BF2/Game/GameLogic/ServerGameLogic.cpp @@ -3,6 +3,9 @@ // Keep the retail event order and unchecked assumptions at each call site. #include "ServerGameLogic.h" +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include #include @@ -545,6 +548,33 @@ void ServerGameLogic::uPlaying(float deltaTime) if (getBeginRoundState() == 3 && m_shouldUpdateTicketSystem) // +0x28C uPlayingTicketSystem(deltaTime); + +#if !defined(_WIN32) + // [TEMP] [CHOSEN, not recovered] BF2_ROUND_TRACE=1: one stderr line per BeginRoundState + // change and every 30 s of play (tickets, alive humans, players), so loopback runs can + // confirm the round start from the server log. Off by default; reads only. + // [RETIRE-WHEN: the macOS loopback round checks move to a query tool] + static const bool roundTrace = std::getenv("BF2_ROUND_TRACE") != 0; + if (roundTrace) + { + static int lastState = -1; + static unsigned int lastTick = 0; + const int now = static_cast(getBeginRoundState()); + const unsigned int tick = static_cast(WorldPref::getTickCount()); + if (now != lastState || (now == 3 && tick - lastTick >= 900)) + { + std::fprintf(stderr, + "[round] state %d -> %d tick %u aliveHumans %d players %d needed %d " + "tickets %u/%u ai %d\n", + lastState, now, tick, world::playerManager->getNumberOfAliveHumanPlayers(), + world::playerManager->getNumberOfPlayers(), + serverSettings->getNumPlayersNeededToStart(), getNumberOfTickets(1), + getNumberOfTickets(2), ai::g_aiInstance != 0 ? 1 : 0); + lastState = now; + lastTick = tick; + } + } +#endif } @@ -1324,6 +1354,20 @@ void ServerGameLogic::checkSpecialForcesTriggers(world::IPlayer* player, world:: soldier->handleMessage(static_cast(26), player, false); } +#if !defined(_WIN32) +// [TEMP] BF2_ENTRY_TRACE=1: which step of the vehicle entry refuses (diagnosis only, no behaviour). +// [RETIRE-WHEN: vehicle-entry-diagnosed] +static bool entryTraceArmed() +{ + static const bool armed = std::getenv("BF2_ENTRY_TRACE") != 0; + return armed; +} +#define BF2_ENTRY_TRACE(...) do { if (entryTraceArmed()) { std::fprintf(stderr, "[ENTRY] " __VA_ARGS__); \ + std::fputc('\n', stderr); std::fflush(stderr); } } while (0) +#else +#define BF2_ENTRY_TRACE(...) do { } while (0) +#endif + // Processes a player's per-tick fire, vehicle, seat, device and camera input. // Dead players proceed only while using their free camera. The drop-key path requires a vehicle. // Entering or leaving rereads the current vehicle for later actions; repeated queries are intentional. @@ -1340,6 +1384,8 @@ void ServerGameLogic::checkPlayerTriggers(world::IPlayer* player, world::IObject // 2. PIUse - the enter / exit key if (inputPressed(input, io::PIUse)) { + BF2_ENTRY_TRACE("PIUse p%d holdsSelectable=%d", player->getId(), + playerHoldsSelectableWeapon(effectiveControlObject(player)) ? 1 : 0); if (!playerHoldsSelectableWeapon(effectiveControlObject(player))) { toggleEntryPoint(player, true); @@ -1589,9 +1635,13 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::IPlayer* const player = getPlayer(playerArg); // the identity + BF2_ENTRY_TRACE("toggle p%d enter=%d", player->getId(), enter ? 1 : 0); // gate 1: a spectator toggles nothing if (player->getVehicle() == player->getFreeCamera()) // +0x48 / +0xA8 + { + BF2_ENTRY_TRACE("refused: free camera"); return; + } // gate 2: a dead or wrecked body // the template is read raw (+0x14) and dereferenced with NO null check, unlike the enter half. @@ -1602,18 +1652,28 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::IArmorGLComp* const armor = static_cast( world::object_detail::LayoutAccess::armorComponent(player->getVehicle())); // +0x3C if (armor && armor->getStatus()) // +0x5C: 0 alive, 1 wreck, 2 gone + { + BF2_ENTRY_TRACE("refused: armor status %d", (int) armor->getStatus()); return; + } } // gate 3: the one-second world-time cooldown if (WorldPref::getWorldTime() - static_cast(player)->m_worldTime < 1.0f) // +0xE4 + { + BF2_ENTRY_TRACE("refused: cooldown (now %.2f last %.2f)", (double) WorldPref::getWorldTime(), + (double) static_cast(player)->m_worldTime); return; + } world::IObject* vehicle = player->getVehicle(); // +0x48 world::IPlayerControlObject* const pco = static_cast( vehicle->queryInterface(world::IID_IPlayerControlObject)); // +0x0C if (!pco) + { + BF2_ENTRY_TRACE("refused: vehicle has no PCO"); return; + } // `proceed` is decided before the exit half runs and is not recomputed afterwards: a player // whose seat forbids entering another vehicle still gets to leave it, they just do not get the @@ -1694,6 +1754,7 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) } } + BF2_ENTRY_TRACE("inVehicle=%d proceed=%d", inVehicle ? 1 : 0, proceed ? 1 : 0); if (!proceed) return; @@ -1704,7 +1765,10 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::object_detail::LayoutAccess::objectTemplate(vehicle); // +0x14 if (vt && vt->getClassID() == world::CID_SoldierTemplate && !static_cast(vehicle)->isNotFireingOrHaveRecoil()) // +0x298 + { + BF2_ENTRY_TRACE("refused: soldier firing or recoiling"); return; + } } const float radius = enter ? 3.0f : 5.0f; // cmovnz flt_888E6B8 (3.0) over 0x40A00000 (5.0) @@ -1736,6 +1800,8 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) entry = world::BFfindEntryPoint(position, radius, player->getTeam(), // +0xE8 player, enter, true, true); } + BF2_ENTRY_TRACE("search at %.1f/%.1f/%.1f r=%.1f team=%d -> entry=%p", (double) position.x, + (double) position.y, (double) position.z, (double) radius, player->getTeam(), (void*) entry); if (entry) { @@ -1746,7 +1812,9 @@ void ServerGameLogic::toggleEntryPoint(world::IPlayer* playerArg, bool enter) world::IObject* const target = static_cast( entry->queryInterface(world::IID_IObject)); // +0x0C - if (game->enterVehicle(player, target, false)) // +0xA4 + const bool entered = game->enterVehicle(player, target, false); // +0xA4 + BF2_ENTRY_TRACE("enterVehicle -> %d", entered ? 1 : 0); + if (entered) static_cast(player)->m_worldTime = static_cast(WorldPref::getWorldTime()); } else @@ -1933,6 +2001,14 @@ void ServerGameLogic::spawnPlayer(world::IPlayer* playerArg, std::pairboolGet(std::string("UseAI"), false) == 1) refuseBecauseAI = (player->getIsAIPlayer() == 1); // +0x64 +#if !defined(_WIN32) + // [TEMP] [CHOSEN, not recovered] AI test aid: BF2_AI_SPAWN_WITHOUT_HUMAN=1 lets bots + // take the first spawn wave without a human, so AI runs need no client (server-only + // loopback). Off by default; the shipped rule above is unchanged. + // [RETIRE-WHEN: AI recovery reaches G6] + if (refuseBecauseAI && std::getenv("BF2_AI_SPAWN_WITHOUT_HUMAN")) + refuseBecauseAI = false; +#endif } if (refuseBecauseAI) return; @@ -2434,7 +2510,12 @@ PyObject* sgl_setParam(PyObject*, PyObject* args) // four keys to the game logic, five to the score manager - and each narrows the double // differently. See the note above. if (key.compare("tickets") == 0) +#if defined(__APPLE__) + // [CHOSEN, not recovered] Keep the x86 wrap of a negative value (arm64 saturates): docs/macos-c-arm64-client.md. + sgl->setNumberOfTickets(team, bf2x87::lowUInt32(value)); +#else sgl->setNumberOfTickets(team, static_cast(value)); +#endif else if (key.compare("ticketLimit") == 0) // GameLogic.py passes (team, limitId, threshold) here: the generic `value` is // the limit ID and the generic `id` argument is its threshold. Keep their order. diff --git a/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp b/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp index 9a3cc5a1f..750b30a0b 100644 --- a/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp +++ b/Code/BF2/Game/GameLogic/SpawnSystem/SpawnGroup.cpp @@ -2,6 +2,9 @@ #include "SpawnGroup.h" +#include // [TEMP] BF2_SPAWNGROUP_TRACE +#include + #include "../../../Core/Ids.h" #include "../../../Core/SettingsRepostitory.h" // settings - GLSWorldSizeX/Z #include "../../../Core/System.h" // WorldPref::getTickCount @@ -15,6 +18,7 @@ #include // rand - getSpawnPoint's pick +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -147,7 +151,7 @@ ISpawnPoint* SpawnGroup::getSpawnPoint(bool isAI) const } ISpawnPoint* picked = 0; if (!candidates.empty()) - picked = candidates[static_cast(std::rand()) % candidates.size()]; + picked = candidates[static_cast(bf2crt::rand()) % candidates.size()]; return picked; } @@ -364,7 +368,7 @@ bool SpawnGroup::getNetUpdate(io::BitStream& stream, io::BaseLineData* /*baselin } // Reads changed spawn-group fields into the next baseline, carrying forward unsent values. -// Position and squad are both decoded, but a position change takes precedence when applying them. +// Position and squad are both decoded and both applied (position first). // Decoded positions have zero Y. World-size settings are reread for each update; // odd world sizes retain the writer/reader quantization difference. void SpawnGroup::setNetUpdate(io::BitStream& stream, float /*time*/, bool ghostActive, @@ -433,7 +437,7 @@ void SpawnGroup::setNetUpdate(io::BitStream& stream, float /*time*/, bool ghostA if (stateMask == 0) // nothing changed - no apply return; - // 6: the apply. A second pass, AND NOT IN THE read'S order - see the note. + // 6: the apply. A second pass, AND NOT IN THE read'S order. const int worldSizeX = settings->intGet(std::string("GLSWorldSizeX"), 0); const int worldSizeZ = settings->intGet(std::string("GLSWorldSizeZ"), 0); @@ -456,10 +460,24 @@ void SpawnGroup::setNetUpdate(io::BitStream& stream, float /*time*/, bool ghostA - static_cast(worldSizeZ / 2); setPos(position); // +0x30, BY value } - else if (stateMask & 0x20) // else, not a second if - see the note + // A second if, not an else: retail lays the setPos block out of line and returns from it to + // the squad test (0x811222D call +0x30, 0x8112230 jmp 0x811211C `and edi, 0x20`). An else + // dropped the squad of every group whose first update also carried its position, leaving the + // constructor's -1 ("no squad", offered to the whole team): squad-leader spawn points appeared + // for players outside the squad (docs/macos-c-handplay-1.md). + if (stateMask & 0x20) { setSquad(record.squad); // +0x20 } +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: squad-spawn-filter-validated] + // BF2_SPAWNGROUP_TRACE=1: each applied client spawn-group update (docs/macos-c-handplay-1.md). + static const bool trace = std::getenv("BF2_SPAWNGROUP_TRACE") != 0; + if (trace) + std::fprintf(stderr, "[SPAWNGROUP] %p mask=0x%02x team=%d squad=%d active=%d points=%d aiOnly=%d\n", + (void*) this, stateMask, getTeam(), getSquad(), m_active ? 1 : 0, m_hasSpawnPoints ? 1 : 0, + m_onlyForAI ? 1 : 0); +#endif } } // namespace hfe diff --git a/Code/BF2/Game/GameLogic/VoiceMessages.cpp b/Code/BF2/Game/GameLogic/VoiceMessages.cpp index 7f7c7b927..62b420f18 100644 --- a/Code/BF2/Game/GameLogic/VoiceMessages.cpp +++ b/Code/BF2/Game/GameLogic/VoiceMessages.cpp @@ -11,6 +11,7 @@ #include // sqrt - playSoldierVO's range test #include // rand - getSpeechId #include // memset - the speech table +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -386,7 +387,7 @@ int VoiceMessages::getSpeechId(int message, int voice) if (cell.first < 0 || cell.count <= 0) return -1; if (cell.count > 1) - return cell.first + std::rand() % cell.count; + return cell.first + bf2crt::rand() % cell.count; return cell.first; } diff --git a/Code/BF2/Game/GameServer/AutoRecorder.h b/Code/BF2/Game/GameServer/AutoRecorder.h index 1227e39f0..f96f0973b 100644 --- a/Code/BF2/Game/GameServer/AutoRecorder.h +++ b/Code/BF2/Game/GameServer/AutoRecorder.h @@ -6,6 +6,9 @@ #define GAME_GAMESERVER_AUTORECORDER_H #include +#if !defined(_WIN32) +#include +#endif #include "../IEventListener.h" #include "../../Core/Mutex.h" @@ -41,7 +44,12 @@ class AutoRecorderHookThread : public Thread /* +0x10 */ std::string m_hookCommand; // sv.autoDemoHook, copied by init /* +0x14 */ AutoRecorder* m_owner; // hookCompleted's receiver /* +0x18 */ Mutex* m_mutex; // the owner'S mutex, not one of its own +#if defined(_WIN32) /* +0x1C */ bool m_quit; // set by ~AutoRecorder before Thread::stop +#else + // [CHOSEN, not recovered] POSIX: run also reads this flag while the owner mutex is unlocked. + std::atomic m_quit; +#endif }; // AutoRecorder - ELF ctor 0x809FD20 (C1, 298 B), dtor 0x809FF90 (D1) / 0x80A00D0 (D0), diff --git a/Code/BF2/Game/GameServer/GameServer.cpp b/Code/BF2/Game/GameServer/GameServer.cpp index b869c638a..c9185cb76 100644 --- a/Code/BF2/Game/GameServer/GameServer.cpp +++ b/Code/BF2/Game/GameServer/GameServer.cpp @@ -12,7 +12,11 @@ #include "../GameLogic/SquadManager/ISquadManager.h" #if !DEDICATED #include "../GeneralSettings.h" // limitCoopPlayers' two client-only bot-count pushes +#include "../../Sound/BfSound.h" +#include "../Main/BF2ClientSeams.h" // hudManager - the radio spam notice of a hosted game +#include "../../Menu/BF2HudManager.h" #endif +#include "ServerInfo.h" // radioBlockedDuration - the spam notice's seconds #include "../Common/GameEventManager.h" // onNewConnection queues the ChallengeEvent #include "../Common/GhostManager.h" // the per-connection ghost update #include "../../Core/System.h" // WorldPref::getTickCount @@ -122,6 +126,7 @@ #include // the empty-maplist refusal writes to std::cout #include #include "../../Scene/Object/WorldObjTemplPortal/PortalManager.h" // IPortalManager::update, +0x40 +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -504,7 +509,13 @@ bool GameServer::startServer(const std::string& a1, int port, int /* dead - neve if (m_netServer) { // NetServer initialization returns zero on success; other results destroy the listener and fail startup. - if (m_netServer->init(a1, port, true) != 0) // +0x10 + const int netInit = m_netServer->init(a1, port, true); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] + if (std::getenv("BF2_HOST_TRACE")) + std::fprintf(stderr, "[host] NetServer::init(%s, %d) -> %d\n", a1.c_str(), port, netInit); +#endif + if (netInit != 0) // +0x10 { if (m_netServer) delete m_netServer; @@ -563,7 +574,13 @@ bool GameServer::startServer(const std::string& a1, int port, int /* dead - neve if (!levelName.empty()) { - if (!game->loadPath(levelName)) // IGame vtable +0x24 - THE handoff + const bool loaded = game->loadPath(levelName); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] + if (std::getenv("BF2_HOST_TRACE")) + std::fprintf(stderr, "[host] loadPath(%s) -> %d\n", levelName.c_str(), loaded ? 1 : 0); +#endif + if (!loaded) // IGame vtable +0x24 - THE handoff { #if !DEDICATED // [PLATFORM] A listen server's failed map load disables the required profiler and fails startup without quitting the engine. @@ -587,6 +604,11 @@ bool GameServer::startServer(const std::string& a1, int port, int /* dead - neve if (!isDedicated()) { const int localPlayer = createPlayer(settings->stringGet("GSPlayerName", "player"), false); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] + if (std::getenv("BF2_HOST_TRACE")) + std::fprintf(stderr, "[host] createPlayer -> %d\n", localPlayer); +#endif if (localPlayer == -1) return false; } @@ -615,8 +637,8 @@ bool GameServer::loadPath(const std::string& levelName) limitCoopPlayers(); // The challenge ordinal is random 0..9, seeded from the wall clock in milliseconds. - srand((int)(g_system->getWallClockTime() * 1000.0)); // System +0x1C; flt_888B168 = 1000.0f - m_mapInfo.setChallengeOrdinal(rand() % 10); // MapInfo at +0x04, by value + bf2crt::srand((int)(g_system->getWallClockTime() * 1000.0)); // System +0x1C; flt_888B168 = 1000.0f + m_mapInfo.setChallengeOrdinal(bf2crt::rand() % 10); // MapInfo at +0x04, by value if (m_loadState) // +0xA0 nonzero = something is loaded unload(); // virtual, IGame slot +0x28 @@ -1461,38 +1483,88 @@ bool GameServer::destroyObject(world::IObject* object) return Game::destroyObject(object); } +namespace { +// The spam notice a hosted game shows its own human player when the radio filter refuses one of +// their messages: the shared "spam" game-info line, then the localized seconds-left chat line. +// The same arm as GameClient::radioMessage; in BF2.exe it is inlined into GameServer::radioMessage +// (0x4C523E..0x4C5348) and radioMessageFromPlayer (0x4C4FCC..0x4C50D6). A dedicated server has no +// HUD; the Linux dedicated image omits the arm. +void showRadioSpamNotice(Game* game, world::IPlayer* player) +{ +#if !DEDICATED + game->localGameInfoMessage(static_cast(14), std::string("spam")); // PE +0x60 + if (!hudManager) + return; + const int blockedDuration = serverInfo->m_block.radioBlockedDuration; + const int seconds = static_cast( + player->getRadioSpamFilterFlagTimer() // PE +0x320 + + blockedDuration + 1.0f + - WorldPref::getWorldTime()); + const std::wstring text = hudManager->replaceWideTokenFromInt( // +0x44 + hudManager->getLocalizedString( // +0x38 + std::string("HUD_HUD_MENU_CHAT_SPAM_MESSAGE")), + std::string("#SEC#"), seconds); + hudManager->addServerChat(text, player->getTeam()); // +0x130, team read last +#else + (void)game; + (void)player; +#endif +} +} // namespace + +// Sends a radio message from a player through the server's own radio relay. A hosted game (the +// client image running the server) also plays the message back for its local human player and +// shows them the spam notice; the client image tests isDedicated() at run time for both arms +// (BF2.exe 0x4C5180), while the Linux dedicated image has neither (ELF 0x080AD3E0 keeps only the +// discarded local-player query). localPlayback is cleared for anyone but the local human player. bool GameServer::radioMessage(TargetChannel channel, const std::string& message, world::IPlayer* player, unsigned int extra, - bool /*unused*/, bool bypassSpamCheck) + bool localPlayback, bool bypassSpamCheck) { if (!player) return true; - // Retail performs this virtual call even though it discards the result. - world::playerManager->getLocalHumanPlayer(); + if (player != world::playerManager->getLocalHumanPlayer()) // +0x30 + localPlayback = false; int messageId; const std::string empty1; const std::string empty2; - if (static_cast(gameLogic)->getVoiceMessages()->namesToIds( - &messageId, 0, 0, message, empty1, empty2) && - (bypassSpamCheck || !player->getIsThisASpam(true))) - { - EventNode* node = createRadioMessageReceivedEvent( - -1, - static_cast(messageId), - static_cast(player->getId()), - static_cast(player->getTeam()), - static_cast(extra), - static_cast(channel), 3); - eventManager->postEvent(ECNetwork, node, 0.0f); + if (!static_cast(gameLogic)->getVoiceMessages()->namesToIds( + &messageId, 0, 0, message, empty1, empty2)) + return true; + + if (!bypassSpamCheck && player->getIsThisASpam(true)) // PE +0x308 = ELF +0x30C + { + if (!isDedicated() && localPlayback && !player->getIsAIPlayer()) // 0x440510, PE +0x60 + showRadioSpamNotice(this, player); + return true; + } + + EventNode* node = createRadioMessageReceivedEvent( + -1, + static_cast(messageId), + static_cast(player->getId()), + static_cast(player->getTeam()), + static_cast(extra), + static_cast(channel), 3); + eventManager->postEvent(ECNetwork, node, 0.0f); + + if (!isDedicated() && localPlayback) // BF2.exe 0x4C53B2..0x4C53E0 + { + const int id = player->getId(); // getId first in this arm + const int team = player->getTeam(); + playbackRadioMessage(channel, static_cast(3), team, id, messageId); } return true; } +// As radioMessage, for a player named by id. AI senders keep their id as the relay connection, +// everyone else is relayed as the server (-1). The hosted-game arms are those of radioMessage +// (BF2.exe 0x4C4F10; ELF 0x080AD1F0 has neither), but localPlayback is not narrowed here. bool GameServer::radioMessageFromPlayer(TargetChannel channel, const std::string& message, unsigned int playerId, unsigned int extra, - bool /*unused*/, bool bypassSpamCheck) + bool localPlayback, bool bypassSpamCheck) { world::IPlayer* player = world::playerManager->getPlayerFromId(static_cast(playerId)); if (!player) @@ -1501,43 +1573,64 @@ bool GameServer::radioMessageFromPlayer(TargetChannel channel, const std::string int messageId; const std::string empty1; const std::string empty2; - if (static_cast(gameLogic)->getVoiceMessages()->namesToIds( - &messageId, 0, 0, message, empty1, empty2) && - (bypassSpamCheck || !player->getIsThisASpam(true))) - { - const int connectionId = player->getIsAIPlayer() - ? static_cast(playerId) - : 0xFF; - EventNode* node = createRadioMessageReceivedEvent( - connectionId, - static_cast(messageId), - static_cast(playerId), - static_cast(player->getTeam()), - static_cast(extra), - static_cast(channel), 3); - eventManager->postEvent(ECNetwork, node, 0.0f); + if (!static_cast(gameLogic)->getVoiceMessages()->namesToIds( + &messageId, 0, 0, message, empty1, empty2)) + return true; + + if (!bypassSpamCheck && player->getIsThisASpam(true)) + { + if (!isDedicated() && localPlayback && !player->getIsAIPlayer()) + showRadioSpamNotice(this, player); + return true; + } + + const int connectionId = player->getIsAIPlayer() + ? static_cast(playerId) + : 0xFF; + EventNode* node = createRadioMessageReceivedEvent( + connectionId, + static_cast(messageId), + static_cast(playerId), + static_cast(player->getTeam()), + static_cast(extra), + static_cast(channel), 3); + eventManager->postEvent(ECNetwork, node, 0.0f); + + if (!isDedicated() && localPlayback) // BF2.exe 0x4C5133..0x4C5161 + { + // The player's own getId, not the argument (GameClient's overload passes the argument). + const int id = player->getId(); + const int team = player->getTeam(); + playbackRadioMessage(channel, static_cast(3), team, id, messageId); } return true; } +// Sends a server game-info line (type 0). A hosted game plays it back locally as well +// (BF2.exe 0x4C53F0; not in the Linux dedicated image), with a in the team and b in the sender +// position, as GameClient::gameInfoMessage does. bool GameServer::gameInfoMessage(TargetChannel channel, const std::string& message, - unsigned int a, unsigned int b, bool /*unused*/) + unsigned int a, unsigned int b, bool localPlayback) { int messageId; const std::string empty1; const std::string empty2; - if (static_cast(gameLogic)->getVoiceMessages()->namesToIds( + if (!static_cast(gameLogic)->getVoiceMessages()->namesToIds( &messageId, 0, 0, message, empty1, empty2)) - { - EventNode* node = createRadioMessageReceivedEvent( - -1, - static_cast(messageId), - static_cast(a), - static_cast(b), - static_cast(b), - static_cast(channel), 0); - eventManager->postEvent(ECNetwork, node, 0.0f); - } + return true; + + EventNode* node = createRadioMessageReceivedEvent( + -1, + static_cast(messageId), + static_cast(a), + static_cast(b), + static_cast(b), + static_cast(channel), 0); + eventManager->postEvent(ECNetwork, node, 0.0f); + + if (!isDedicated() && localPlayback) // BF2.exe 0x4C54AA..0x4C54C7 + playbackRadioMessage(channel, static_cast(0), + static_cast(a), static_cast(b), messageId); return true; } @@ -2394,9 +2487,13 @@ bool GameServer::update(int steps, float dt) updateConnections(elapsed); processGameStateAndSendPackets(elapsed); } - // [PLATFORM] NOT - BF2.exe 0x4D1138..0x4D1151, a listen-server arm the dedicated ELF - // folded away: `if (!isDedicated() && i == steps - 1)` the sound owner (ds:0xA23DC0) vslot - // +0x18(steps). Its identity is unread. +#if !DEDICATED + // A listen server updates the local listener and mixer once, after the last simulation step. + // BF2.exe 0x4D1138..0x4D1151: isDedicated (0x440510), then ds:0xA23DC0 (the BfSound that + // 0x7E1774 stores after its 0x148-byte construction) vslot +0x18(steps). + if (!isDedicated() && i == steps - 1) + g_bfSound->update(steps); +#endif } // [PLATFORM] NOT - BF2.exe 0x4D1162..0x4D1173: `if (isLightmapRenderingNode())` // (0x440530) ds:0x987350 vslot +0x28() - a lightmap-farm tool arm the dedicated ELF folded away. diff --git a/Code/BF2/Game/GameServer/VoipServerConnection.cpp b/Code/BF2/Game/GameServer/VoipServerConnection.cpp index df469599c..e4c2dc7d5 100644 --- a/Code/BF2/Game/GameServer/VoipServerConnection.cpp +++ b/Code/BF2/Game/GameServer/VoipServerConnection.cpp @@ -33,6 +33,7 @@ #include #include #include +#include "../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -311,10 +312,10 @@ bool VoipServerConnection::InitEnabledVoip() // m_sharedSecret, and the in-process server must expect the same bytes. The PE stores it in the // shared-secret field (this+0x43FC) rather than a temporary, then hands that same string to the // server's Start. - const int letterCount = rand() % 10 + 8; + const int letterCount = bf2crt::rand() % 10 + 8; m_sharedSecret = static_cast(118); // leading 'v' for (int i = 0; i < letterCount; ++i) - m_sharedSecret += static_cast(rand() % 26 + 'a'); + m_sharedSecret += static_cast(bf2crt::rand() % 26 + 'a'); m_localVoipServer440C->Start(m_sharedSecret, static_cast(m_infoWord4400)); return true; } @@ -632,7 +633,7 @@ int VoipServerConnection::CreateClientSessionId(int playerId) return 0; const int range = (int)powf(256.0f, 2.0f); // 65536, computed not folded - int id = rand() % range; + int id = bf2crt::rand() % range; const std::list& players = world::playerManager->getPlayers(); @@ -645,7 +646,7 @@ int VoipServerConnection::CreateClientSessionId(int playerId) { if ((*it)->getVoipSessionId() == id) // vslot 624 = +0x270 { - id += 1 + (rand() % 500); // random bump, not +1 + id += 1 + (bf2crt::rand() % 500); // random bump, not +1 clash = true; // and rescan from the head break; } diff --git a/Code/BF2/Game/GeneralSettings.cpp b/Code/BF2/Game/GeneralSettings.cpp index fc316a1de..1f23702e5 100644 --- a/Code/BF2/Game/GeneralSettings.cpp +++ b/Code/BF2/Game/GeneralSettings.cpp @@ -5,6 +5,7 @@ #include "../Core/SmartItf.h" #include "../Menu/ISwiffHost.h" #include "../Menu/IServerBrowser.h" +#include "../Core/MsvcCrtCompat.h" // [CHOSEN, not recovered] __time32_t/_time32 outside MSVC #if !DEDICATED #include "Main/BF2ClientSeams.h" // hudManager (ds:0xA10890) #include "../Scene/Object/PlayerManager.h" // world::playerManager (ds:0xA08F60), +0x30 getLocalHumanPlayer diff --git a/Code/BF2/Game/HudInformationLayer.cpp b/Code/BF2/Game/HudInformationLayer.cpp index 2908cc96f..ceef90d4b 100644 --- a/Code/BF2/Game/HudInformationLayer.cpp +++ b/Code/BF2/Game/HudInformationLayer.cpp @@ -817,7 +817,9 @@ void HudInformationLayer::update(float dt) HudInformationLayer::HudInformationLayer() : m_refCount(1), m_nextId(0) { +#if defined(_M_IX86) static_assert(sizeof(State) == 0x518, "Non-STL x86 suffix changed"); +#endif m_state.field88 = false; m_state.FriendlyTicketBleed = 0; m_state.field90 = false; @@ -995,9 +997,14 @@ HudInformationLayer::HudInformationLayer() : m_refCount(1), m_nextId(0) // The last two overwrite eight bytes of adjacent HUD flags. Copy their // representation without inventing a larger source array or correcting // the shipped overrun. The destructor frees only the ten real pointers. + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the overrun stays + // the same eight flag bytes (+0x234..+0x23B), one 8-byte pointer instead of two 4-byte ones, + // so PlayerTeam and kitSelected are untouched as on x86. On x86 every write passes the test. const char* initial = emptyString; - std::memcpy(reinterpret_cast(&m_state) + offsetof(State, optionIcons) + i * sizeof(initial), - &initial, sizeof(initial)); + const size_t overrunEnd = offsetof(State, optionIcons) + sizeof(m_state.optionIcons) + 8; + const size_t at = offsetof(State, optionIcons) + i * sizeof(initial); + if (at + sizeof(initial) <= overrunEnd) + std::memcpy(reinterpret_cast(&m_state) + at, &initial, sizeof(initial)); m_state.radioNames[i] = emptyWideString; m_state.radioVehicleNames[i] = emptyWideString; m_state.squadNames[i] = emptyWideString; diff --git a/Code/BF2/Game/LocalProfileManager.h b/Code/BF2/Game/LocalProfileManager.h index 4b2074bf4..284ca1065 100644 --- a/Code/BF2/Game/LocalProfileManager.h +++ b/Code/BF2/Game/LocalProfileManager.h @@ -83,10 +83,15 @@ class ILocalProfileManager : public IBase { virtual bool quickLogin(const std::string& name, const std::string& password) = 0; // PE+C0 4AAD00 virtual bool saveGlobalSettings() = 0; // PE+C4 4A9440 virtual bool validateProfileFiles(const std::string& directory) = 0; // PE+C8 4A8580 + // PE+CC 619360 `mov eax,[ecx+34h]; ret` and PE+D0 4A7DB0 (sret copy of this+38h, RET 4): + // the profile index and password the last login stored. [INFERRED] names. The only known + // caller is BF2Engine's activateMod pair (0x403E40 / 0x404010). + virtual int getLoginProfileIndex() = 0; // PE+CC 619360 (ICF-shared one-load getter) + virtual std::string getLoginPassword() = 0; // PE+D0 4A7DB0 // [INFERRED] +A8/+AC/+B0 use unsigned indices/count and a borrowed pointer. // Full PE bodies/callers prove the x86 widths, arity and return conventions; // int-vs-unsigned and pointer-vs-reference source spelling are not attested. - // [FRONTIER] PE+CC..+D4 remain absent; no additional opaque slot is filled. + // PE+D4 4ABD10 is the scalar deleting destructor; no destructor slot is declared (see below). }; struct LocalProfileFixture; @@ -150,6 +155,8 @@ class LocalProfileManager final : public ILocalProfileManager, public IEventList bool quickLogin(const std::string& name, const std::string& password) override; bool saveGlobalSettings() override; bool validateProfileFiles(const std::string& directory) override; + int getLoginProfileIndex() override; + std::string getLoginPassword() override; void handleEvent(EventCategory, unsigned int, EventNode*, void*) override; // actual5B74B0 RET16 private: friend struct LocalProfileFixture; @@ -163,8 +170,8 @@ class LocalProfileManager final : public ILocalProfileManager, public IEventList bool m_profilesDirty; // retail+21 bool m_filterValidProfiles; // retail+22 std::vector m_profiles; // retail+24 - int m_field34; - std::string m_field38; + int m_field34; // retail+34 login's profile index (+CC) + std::string m_field38; // retail+38 login's password (+D0) bool m_field54; }; diff --git a/Code/BF2/Game/LocalProfileManagerOperations.cpp b/Code/BF2/Game/LocalProfileManagerOperations.cpp index a39383b19..70d9221c7 100644 --- a/Code/BF2/Game/LocalProfileManagerOperations.cpp +++ b/Code/BF2/Game/LocalProfileManagerOperations.cpp @@ -22,6 +22,7 @@ #include "DemoRecorder/DemoLibrary.h" // IDemoLibrary::refresh - login's demo-directory rescan #include "../Core/ClassManager.h" #include "../Core/EventManager.h" +#include "../IO/File/FileManager.h" // deleteProfile: io::fileManager +0x48 / +0x20 #include #include #include @@ -29,17 +30,6 @@ namespace dice { namespace hfe { extern ClassManager* classManager; -namespace { -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: local-profile-operation-calls] -// These stops belong to known callers; no suffix slot or payload ABI is invented. -[[noreturn]] void deleteSelectedProfileFrontier() -{ - std::fprintf(stderr, "[FRONTIER] dice::hfe::LocalProfileManager::deleteProfile: the default-user comparison at PE4AB01D and the directory removal that follows are unrecovered\n"); - std::fflush(stderr); - std::abort(); -} -} - // Loads and applies a profile; the middle argument is unused. // Online profiles must pass presence login. Requires current-profile, ProfileManager, and DemoLibrary objects. bool LocalProfileManager::login(int profileIndex, const std::string&, const std::string& password) @@ -157,7 +147,21 @@ bool LocalProfileManager::deleteProfile(int profileIndex) getLocalProfiles(profiles, true); // Unlike login, PE4AAFEC uses a signed comparison and has no negative guard. if (profileIndex >= static_cast(profiles.size())) return false; - deleteSelectedProfileFrontier(); + // PE4AB003..4AB10C. A deleted default user is forgotten first (Global.con's +0x20/+0x24, + // the empty string by value). + IGlobalSettings* global = static_cast(g_globalSettings); + if (profiles[profileIndex].name == global->getDefaultUser()) + global->setDefaultUser(std::string("")); + saveGlobalSettings(); // +C4 4AB05F; result discarded + // The profile directory under the file manager's own home substitution (+0x48 on + // io::fileManager itself, not its base system), with the shipped backslashes. + std::string path = std::string(io::fileManager->getHomeSubstitution()) + "\\Profiles\\"; + std::string directory = path + profiles[profileIndex].name; + // PE4AB0D1: erase(size(), 1) - a no-op the shipped body performs. + directory.erase(directory.size(), 1); + io::fileManager->deleteFile(directory); // +0x20; result discarded + m_profilesDirty = true; // +0x21 + return true; } // Creates an online account only for a current profile without a GameSpy nickname. diff --git a/Code/BF2/Game/LocalProfileManagerSuffix.cpp b/Code/BF2/Game/LocalProfileManagerSuffix.cpp index 783a494be..1c35682b8 100644 --- a/Code/BF2/Game/LocalProfileManagerSuffix.cpp +++ b/Code/BF2/Game/LocalProfileManagerSuffix.cpp @@ -255,6 +255,18 @@ bool LocalProfileManager::quickLogin(const std::string& name, const std::string& // PE4A9440 (80 B): the GlobalSettings file name, then its script, through the profile writer // (whose constant true is returned). +// PE 619360: one load of +34h (the body is shared by identical-code folding). +int LocalProfileManager::getLoginProfileIndex() +{ + return m_field34; +} + +// PE 4A7DB0: a copy of +38h into the caller's return string. +std::string LocalProfileManager::getLoginPassword() +{ + return m_field38; +} + bool LocalProfileManager::saveGlobalSettings() { IGlobalSettings* global = static_cast(g_globalSettings); diff --git a/Code/BF2/Game/Main/BF2.cpp b/Code/BF2/Game/Main/BF2.cpp index 10b8c2f75..b7fb4c283 100644 --- a/Code/BF2/Game/Main/BF2.cpp +++ b/Code/BF2/Game/Main/BF2.cpp @@ -40,7 +40,20 @@ namespace memory { void memory_update_modules(const char*) { } } # include "../../Sound/NullSound.h" // ISoundEngine::setMasterVolume # include "../../Menu/IMenuLogic.h" // menuLogic - the active menu # include "BF2Console.h" // IMenuLogic::getConsole()->getConsoleActive() +# include "../../Platform/Windows/WinInputScript.h" // [TEMP] BF2_INPUT_SCRIPT host # endif +#elif defined(__APPLE__) && !DEDICATED +// [CHOSEN, not recovered] macOS client: the Cocoa host stands in for the Win32 message pump and +// entry chain (docs/macos-s2-4.md). The headers mirror the Win32 client list above. +# include // exit(0) on a posted quit +# include "../../IO/Input/Input.h" // IInputManager::setHasFocus +# include "../Utility/Vars.h" // Vars::enableProfiling around the main loop +# include "BF2Window.h" // the game window at BF2Engine+0x10 +# include "../../Sound/BfSound.h" // g_bfSound - the focus-loss mute +# include "../../Sound/NullSound.h" // ISoundEngine::setMasterVolume +# include "../../Menu/IMenuLogic.h" // menuLogic - the active menu +# include "BF2Console.h" // IMenuLogic::getConsole()->getConsoleActive() +# include "../../Platform/macOS/CocoaHost.h" #endif // Rebuilds the single command-line string the engine expects. The C runtime has already stripped the @@ -88,10 +101,24 @@ namespace io { extern IBase* inputManager; } // ds:0x8AC8CA4 - Core/Globa static void allowAccessibilityShortcutKeys(bool allow); static void restoreDesktopSettings(); # if !DEDICATED -static BOOL CALLBACK lockLoadedModule(PCSTR moduleName, ULONG moduleBase, ULONG moduleSize, PVOID userContext); +# if defined(_M_IX86) +typedef ULONG LoadedModuleBase; +# else +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): dbghelp maps +// EnumerateLoadedModules to EnumerateLoadedModules64, whose callback takes a 64-bit base. +typedef DWORD64 LoadedModuleBase; +# endif +static BOOL CALLBACK lockLoadedModule(PCSTR moduleName, LoadedModuleBase moduleBase, ULONG moduleSize, PVOID userContext); static void trimOtherProcessesAndFileCache(); static int bf2MessageHandler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); # endif +#elif defined(__APPLE__) && !DEDICATED +class IBase; +namespace io { extern IBase* inputManager; } // Core/Globals.cpp defines it as IBase* + +// [CHOSEN, not recovered] The macOS counterparts of the Win32 pieces above (bottom of this file). +static void restoreDesktopSettings(); +static int bf2MessageHandler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); #endif BF2::BF2() @@ -153,6 +180,10 @@ bool BF2::init(const std::string& commandLine) // when BF2Engine::init ran with isDedicated() false; `+dedicated 1` leaves it null. if (Window* window = m_engine->getWindow()) window->addMessageHandler(bf2MessageHandler); +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The same registration for the macOS window. + if (Window* window = m_engine->getWindow()) + window->addMessageHandler(bf2MessageHandler); #endif return true; } @@ -190,6 +221,12 @@ void BF2::handleInGameWinMessages() restoreDesktopSettings(); // the same five calls bf2WinMain makes on exit exit(0); // no engine shutdown at all, as shipped } +# if !DEDICATED + // [TEMP] [CHOSEN, not recovered] A BF2_INPUT_SCRIPT run ignores the real keyboard and mouse + // (Platform/Windows/WinInputScript.h). [RETIRE-WHEN: client-test-automation-replaced] + if (inputscript::winInputScriptActive() && inputscript::winInputScriptIsRealInput(msg.message)) + continue; +# endif TranslateMessage(&msg); DispatchMessageA(&msg); } @@ -198,6 +235,9 @@ void BF2::handleInGameWinMessages() # if !DEDICATED if (menuLogic) deviceMask = static_cast(-2); // every device but bit 0 while a menu is up + // [TEMP] [CHOSEN, not recovered] One BF2_INPUT_SCRIPT tick per pump; nothing without the variable. + if (inputscript::winInputScriptActive() && m_engine && m_engine->getWindow()) + inputscript::winInputScriptPump(m_engine->getWindow()->getHwnd(), menuLogic != 0); # endif if (m_engine) { @@ -217,6 +257,33 @@ void BF2::handleInGameWinMessages() # endif } } +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The Cocoa pump in place of PeekMessage/DispatchMessage: it drains + // every pending event and reports a posted quit as WM_QUIT does. The focus and mute logic + // below repeats the Win32 arm above unchanged. + if (macos::CocoaHost::instance().pumpEvents()) + { + restoreDesktopSettings(); + exit(0); // no engine shutdown, as on Win32 + } + + unsigned int deviceMask = static_cast(-1); + if (menuLogic) + deviceMask = static_cast(-2); + if (m_engine) + { + if (Window* window = m_engine->getWindow()) + { + const bool hasFocus = window->getHasFocus(); + if (io::inputManager) + static_cast(io::inputManager)->setHasFocus(hasFocus, deviceMask); + if (!settings->boolGet("GSDeveloper", false) && g_bfSound && g_bfSound->engine()) + { + ISoundEngine* engine = g_bfSound->engine(); + engine->setMasterVolume(hasFocus ? 1.0f : 0.0f); + } + } + } #endif } @@ -224,6 +291,193 @@ void BF2::handleInGameWinMessages() } // namespace dice +#if defined(__APPLE__) && !DEDICATED + +// [CHOSEN, not recovered] macOS client: the desktop-state and window-message pieces of the +// Win32 chain below, on the Cocoa host. There was no retail macOS image; see docs/macos-s2-4.md. + +namespace dice { +namespace hfe { + +using namespace hostmsg; + +// Win32 restores accessibility keys, mouse trails and the screensaver; macOS has no counterpart +// for the first two, and the display-sleep assertion stands for the screensaver switch. The +// cursor is released in case a relative-mode mouse still held it. +static void restoreDesktopSettings() +{ + macos::CocoaHost& host = macos::CocoaHost::instance(); + host.setRelativeMouseMode(false); + host.preventDisplaySleep(false); +} + +// The menu key ring (declared in BF2.h); the console ring is defined in BF2Console.cpp. +char menuKeyBuffer[256]; +int menuKeyCount = 0; +int menuKeyRead = 0; +int menuKeyWrite = 0; + +// The Win32 ring writers, unchanged: the write index wraps at 256 and the count wraps to 0. +static int pushConsoleChar(char c) +{ + int index = consoleCharWrite; + if (consoleCharWrite > 255) + index = 0; + consoleCharBuffer[index] = c; + consoleCharWrite = index + 1; + if (++consoleCharCount > 255) + consoleCharCount = 0; + return 0; +} + +static int pushMenuKey(char key) +{ + int index = menuKeyWrite; + if (menuKeyWrite > 255) + index = 0; + menuKeyBuffer[index] = key; + menuKeyWrite = index + 1; + if (++menuKeyCount > 255) + menuKeyCount = 0; + return 0; +} + +// GetAsyncKeyState(VK_CONTROL) / (VK_MENU). [CHOSEN] Command counts as Ctrl, so Command-C/V/X +// work as the Mac shortcuts; BF2Window_macos.cpp turns Command+letter into the control character. +static bool controlKeyDown() +{ + return (macos::CocoaHost::instance().modifierFlags() & + (macos::HostModControl | macos::HostModCommand)) != 0; +} + +static bool altKeyDown() +{ + return (macos::CocoaHost::instance().modifierFlags() & macos::HostModOption) != 0; +} + +// The Win32 bf2MessageHandler with the same arms. Omitted: the Caps Lock switch-off on +// WM_ACTIVATEAPP and on an in-game Caps Lock press (SendInput of VK_CAPITAL), which macOS offers +// no supported counterpart for; Caps Lock stays as the user set it. WM_INPUTLANGCHANGEREQUEST +// does not occur on macOS. +static int bf2MessageHandler(HWND /*hwnd*/, UINT message, WPARAM wParam, LPARAM lParam) +{ + if (message > WM_LBUTTONDOWN) + { + if (message == WM_LBUTTONUP) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + { + menuLogic->onMouseButtonUp(); + return 0; + } + } + else if (message == WM_LBUTTONDBLCLK) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + { + menuLogic->onMouseDoubleClick(); + return 0; + } + } + return 0; + } + if (message == WM_LBUTTONDOWN) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + menuLogic->onMouseButtonDown(); + return 0; + } + if (message == WM_MOUSEMOVE) + { + if (settings && !settings->boolGet("GSDedicated", false) && menuLogic) + menuLogic->onMouseMove(static_cast(lParam & 0xFFFF), + static_cast((lParam >> 16) & 0xFFFF)); + return 0; + } + + switch (message) + { + case WM_KEYDOWN: + if (!settings) + return 0; + if (settings->boolGet("GSDedicated", false)) + return 0; + if (!menuLogic || wParam != VK_DELETE) + return 0; + pushMenuKey(127); // DEL reaches the menu as 127 + return 0; + + case WM_CHAR: + if (!settings) + return 0; + if (settings->boolGet("GSDedicated", false)) + return 0; + pushConsoleChar(static_cast(wParam)); + if (!menuLogic || (menuLogic->getConsole() && menuLogic->getConsole()->getConsoleActive())) + return 0; + if (!controlKeyDown() || (controlKeyDown() && altKeyDown())) + { + if (wParam == 27) + menuLogic->onEscape(); + else + pushMenuKey(static_cast(wParam)); + return 0; + } + { + const char key = static_cast(wParam | 0x60); + if (key == 'v' || key == 'c' || key == 'x') + pushMenuKey(key); + } + return 0; + + default: + return 0; + } +} + +// The bf2Main/bf2WinMain shape of the Win32 client entry: desktop state saved, BF2 created, the +// pump-and-mainLoop loop, the handler removed, BF2 deleted, desktop state restored. +static int bf2MacMain(const std::string& commandLine) +{ + macos::CocoaHost& host = macos::CocoaHost::instance(); + host.initApplication(); // NSApplication before any window exists + host.preventDisplaySleep(true); // SPI_SETSCREENSAVEACTIVE 0 counterpart + + g_system->restoreFPUExceptions(); + BF2* bf2 = new BF2(); + if (!bf2->init(commandLine)) + { + restoreDesktopSettings(); + return 42; + } + + Vars::enableProfiling(true); + const std::string demo = settings->stringGet("GSDemo", std::string()); + if (!demo.empty() && bf2Engine) + bf2Engine->playDemo(true, demo); + + do + { + g_system->restoreFPUExceptions(); + bf2->handleInGameWinMessages(); + } + while (bf2Engine->mainLoop()); + + Vars::enableProfiling(false); + if (Window* window = bf2Engine->getWindow()) + window->removeMessageHandler(bf2MessageHandler); + + delete bf2; + g_system->storeAndTurnOffFPUExceptions(); + restoreDesktopSettings(); + return 0; +} + +} // namespace hfe +} // namespace dice + +#endif // __APPLE__ && !DEDICATED + #if defined(_WIN32) // Windows GUI entry and desktop-state handling shared by both images. The dedicated @@ -295,9 +549,9 @@ static void restoreDesktopSettings() // the memory-locking trio of BF2::init (client only) // . The IDB named it after its use: every loaded module's pages get locked. -static BOOL CALLBACK lockLoadedModule(PCSTR /*moduleName*/, ULONG moduleBase, ULONG moduleSize, PVOID /*userContext*/) +static BOOL CALLBACK lockLoadedModule(PCSTR /*moduleName*/, LoadedModuleBase moduleBase, ULONG moduleSize, PVOID /*userContext*/) { - VirtualLock(reinterpret_cast(moduleBase), moduleSize); + VirtualLock(reinterpret_cast(static_cast(moduleBase)), moduleSize); return TRUE; } @@ -692,6 +946,60 @@ int main(int argc, char** argv) #endif // dedicated - the headless console entry +#elif defined(__APPLE__) && !DEDICATED +#include +#include +#include +#include + +// [CHOSEN, not recovered] The macOS client entry point: the argv join of the POSIX main, then +// the Win32 client's entry chain (bf2MacMain above). +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-startup-stable] Coordinator diagnostic: +// with BF2_EXIT_TRACE set, print the stack of whoever calls exit(). lldb cannot attach through +// the sandbox-exec run harness. Registered first, so it runs last, still inside exit(). +static void bf2MacExitTrace() +{ + void* frames[64]; + const int count = backtrace(frames, 64); + std::fprintf(stderr, "[exit-trace] exit() reached from:\n"); + backtrace_symbols_fd(frames, count, 2); +} + +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-startup-stable] Coordinator diagnostic: +// with BF2_ABORT_TRACE set, stdout is unbuffered (the harness redirects it to client.log, and a +// fully buffered stdout loses its last lines at abort()) and SIGABRT prints the aborting stack. +static void bf2MacAbortTrace(int) +{ + void* frames[64]; + const int count = backtrace(frames, 64); + std::fprintf(stderr, "[abort-trace] SIGABRT raised from:\n"); + backtrace_symbols_fd(frames, count, 2); + std::signal(SIGABRT, SIG_DFL); +} + +int main(int argc, const char** argv) +{ + if (std::getenv("BF2_EXIT_TRACE")) + std::atexit(bf2MacExitTrace); + if (std::getenv("BF2_ABORT_TRACE")) + { + std::setvbuf(stdout, 0, _IONBF, 0); + std::signal(SIGABRT, bf2MacAbortTrace); + } + dice::hfe::g_system = new dice::hfe::System(); + + std::string commandLine; + for (int i = 1; i < argc; ++i) + appendCommandLineArg(commandLine, argv[i], i == 1); + + const int result = dice::hfe::bf2MacMain(commandLine); + if (result == 42) + std::cerr << "fatal error: argument parsing failed" << std::endl; + if (dice::hfe::g_system) + delete dice::hfe::g_system; + return result; +} + #else // [PLATFORM] The ELF entry point. ELF 0x8052ab0. diff --git a/Code/BF2/Game/Main/BF2.h b/Code/BF2/Game/Main/BF2.h index 57c8c2f86..9f7fb8efd 100644 --- a/Code/BF2/Game/Main/BF2.h +++ b/Code/BF2/Game/Main/BF2.h @@ -38,12 +38,16 @@ class BF2 BF2Engine* m_engine; // offset 0 - the only member }; -#if defined(_WIN32) && !DEDICATED +#if !DEDICATED // Keyboard rings filled by window messages and consumed by menu/console text input. -// Toggling either UI flushes its ring. [INFERRED] Global names. +// Toggling either UI flushes its ring. [INFERRED] Global names. The console ring is defined in +// BF2Console.cpp on every platform; the menu ring beside the Win32 window procedure in BF2.cpp. extern char consoleCharBuffer[256]; -extern char menuKeyBuffer[256]; extern int consoleCharCount, consoleCharRead, consoleCharWrite; +#endif +// [CHOSEN, not recovered] The macOS client fills the menu ring too (BF2.cpp, __APPLE__ arm). +#if (defined(_WIN32) || defined(__APPLE__)) && !DEDICATED +extern char menuKeyBuffer[256]; extern int menuKeyCount, menuKeyRead, menuKeyWrite; #endif diff --git a/Code/BF2/Game/Main/BF2ClientFrontiers.cpp b/Code/BF2/Game/Main/BF2ClientFrontiers.cpp index d2d2659ee..68542d6c5 100644 --- a/Code/BF2/Game/Main/BF2ClientFrontiers.cpp +++ b/Code/BF2/Game/Main/BF2ClientFrontiers.cpp @@ -5,19 +5,6 @@ #include namespace dice { namespace hfe { -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: local-profile-client-callers] -// The native manager publishes through +C8, with two approved abort-only positions. -// The remaining activateMod caller chain first stops at untyped +D0. These signatures -// describe the engine callers, not a recovered LocalProfileManager vtable. -#define BF2_LOCAL_PROFILE_FRONTIER(method) \ - std::fprintf(stderr, "[FRONTIER] dice::hfe::" #method ": LocalProfileManager suffix is unrecovered\n"); \ - std::fflush(stderr); \ - std::abort() - -void localProfileManager_vslot0x70(IBase*, const std::string&) { BF2_LOCAL_PROFILE_FRONTIER(localProfileManager_vslot0x70); } -const std::string& localProfileManager_vslot0xD0(IBase*, std::string&, int) { BF2_LOCAL_PROFILE_FRONTIER(localProfileManager_vslot0xD0); } -#undef BF2_LOCAL_PROFILE_FRONTIER - // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: swiff-host-server-browser] // Haptic targets remain null until their implementations exist; menu initialization // checks for null before dispatching to them. diff --git a/Code/BF2/Game/Main/BF2ClientSeams.h b/Code/BF2/Game/Main/BF2ClientSeams.h index 0826b02e0..806af9d02 100644 --- a/Code/BF2/Game/Main/BF2ClientSeams.h +++ b/Code/BF2/Game/Main/BF2ClientSeams.h @@ -103,8 +103,8 @@ extern BF2VoipClient* bf2VoipClient; // ds:0x9A4DA0 - the "Bf2Vo extern BF2Render* g_bf2Render; // ds:0x9A5580 - published by BF2Render ctor extern IBase* g_geometryTemplateManager;// ds:0x9A5578 - 20 PE readers after init extern IBase* g_renderer; // BF2.exe `g_Renderer` - [UNRESOLVED] symbol name -extern IBase* unresolvedGlobalA33C08; // ds:0xA33C08; bf2_w32ded ds:0x8B25B0, written by - // ai::AIInstanceServer::updateInstance - [UNRESOLVED] identity +extern IBase*& unresolvedGlobalA33C08; // ds:0xA33C08 = ai::g_aiInstance (BF2.exe 0x801030, + // AIInstanceServer::updateInstance); bf2_w32ded ds:0x8B25B0 // The client's singleton slots (BF2.exe 0x4301A9 registers them; ds:0x987340..0x987398). The // first two rows pass IID 1 and flags 1, transcribed as-is in Core/ModuleRegistry.cpp. @@ -136,11 +136,9 @@ extern IBase* g_serverLogoManager; // ds:0x987340 "ServerLogo // Remaining client seams use role-based names where known and vslot names where // [UNRESOLVED]. Slot comments describe the PE ABI; typed interfaces own other services. -bool modInfo_vslot0x30(IBase* modInfo, const std::string& modName); // IModInfo +0x30 startGame join result 8 - [UNRESOLVED] role -void localProfileManager_vslot0x70(IBase* lpm, const std::string& value); // +0x70 activateMod* -const std::string& localProfileManager_vslot0xD0(IBase* lpm, std::string& scratch, int arg); // +0xD0 activateMod* +bool modInfo_vslot0x30(IBase* modInfo, const std::string& modName); // IModInfo +0x30 startGame join result 8: getModFromPath != null void bf2VoipClient_update(BF2VoipClient* voip); // +0x9C mainLoop [INFERRED] role -bool unresolvedGlobalA33C08_vslot0x18(); // +0x18 mainLoop (ragdoll viewer), 0x4038A0 +bool unresolvedGlobalA33C08_vslot0x18(); // +0x18 mainLoop (ragdoll viewer), 0x40D227: IAIInstance::isInitialized // Optional haptic force targets; the declared seam requires their actual interfaces. extern IBase* g_hapticForceTargets[6]; // ds:0x9EBEC8, 0x9EBECC, 0x9EBF00, 0x9EBF04, 0x9EBF08, 0x9EBF0C [UNRESOLVED] identity; null in this image void hapticTarget_vslot0x4C(IBase* target, const double* force3); // +0x4C a NovintHFX::Vect3 built from three doubles diff --git a/Code/BF2/Game/Main/BF2Engine.cpp b/Code/BF2/Game/Main/BF2Engine.cpp index 6c3bc007b..d9abd8bd9 100644 --- a/Code/BF2/Game/Main/BF2Engine.cpp +++ b/Code/BF2/Game/Main/BF2Engine.cpp @@ -54,6 +54,7 @@ #include "Demo.h" // [INFERRED] header path; demo.cpp itself is attested #include "../../Scene/Object/PlayerManager.h" // the real PlayerManager - replaces the local shim #include "../Objects/IPlayer.h" // per-player handleFrameUpdate loop +#include "../Objects/IObjectTemplate.h" // [TEMP] BF2_PLAY_TRACE: the vehicle template name #include "../Objects/ICameraObject.h" // mainLoop's held camera: getCamera / setInterpolatedMode #include @@ -74,17 +75,26 @@ #include "../HudInformationLayer.h" #include "../Objects/Fx/PersistentExplosionEffectManager.h" #endif -#include "../../Sound/BfSound.h" // IBfSound* g_bfSound - the client's menu/movie arms +#include "../../Sound/BfSound.h" +#if defined(__APPLE__) && !DEDICATED +#include "../../Sound/SoundEngine/BfSoundEngine.h" // [TEMP] SoundStats for BF2_PLAY_TRACE +#endif // IBfSound* g_bfSound - the client's menu/movie arms #include "../../IO/Input/Input.h" // io::IInputManager / IInputDeviceManager - the client's input arms #include // time / difftime - sessionStartTime +#include // [TEMP] std::tolower - the input-script query +#include #include // memcpy - updateInput's sample copy #include // std::fprintf - the [FRONTIER] stop in startGame's client branch #include // std::abort - the same stop #if !DEDICATED #include "BF2ClientSeams.h" // [FRONTIER] client collaborators without recovered classes +#include "../../AI/AIInterface/AIInstance.h" // ai::g_aiInstance, IAIInstance (ds:0xA33C08 in the client) #include "../LocalProfileManager.h" // native client startup interface #include "../ProfileManager.h" // renderMenu case 14 clears the pending transition #include "../../Menu/BF2HudManager.h" // constructor and established virtual prefix; publication gated +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) +#include "../../Geom/GeometryTemplateManager.h" // shutdown: the client arm's template clear (+0x28) +#endif #include #include #include "../../Core/Ids.h" // the menu CIDs / IID_IMenuLogic / IID_IFSMoviePlayer @@ -92,7 +102,22 @@ #include "../../Menu/IMenuLogic.h" // menuLogic #include "../../Sound/BfSound/MusicPlayer.h" #include "../../IO/Input/PlayerInput.h" // updateInput's per-tick copy +#if defined(_WIN32) #include // ShellExecuteA - restartBF2 / activateMod / browseModHomepage +#elif defined(__APPLE__) +// [CHOSEN, not recovered] macOS: the cursor, minimize, URL and relaunch counterparts. +#include "../../Platform/macOS/CocoaHost.h" +#include "../../Platform/macOS/MacSystem.h" +#include "../../Platform/macOS/ClientPaths.h" +#include +#endif +#endif + +#if !DEDICATED && (defined(_WIN32) || defined(__APPLE__)) +#include "../../Platform/InputScript.h" // [TEMP] aim / walk-to query (BF2_INPUT_SCRIPT) +#include +#include +#include #endif // Middleware attribution functions have global scope. Preserve their startup call order. @@ -137,6 +162,11 @@ bool BF2Engine::getMenuActive() const // [CHOSEN] accessor with getMenuActive's shape: the movie player is a client-only member, and // mainLoop tests it in four places that must fold to nothing in a dedicated build. +#if DEDICATED +// [TEMP] the dedicated image has no BF2_HOST_TRACE (the helper below is client-only). +#define BF2_HOST_TRACE_SITE(step, value) ((void)0) +#endif + bool BF2Engine::isMoviePlaying() const { #if DEDICATED @@ -247,6 +277,217 @@ void musicTraceSite(const char* site) if (armed < 0) armed = std::getenv("BF2_TRACE_MUSIC") ? 1 : 0; if (armed) { std::fprintf(stderr, "[MUSIC] event 0 from %s\n", site); std::fflush(stderr); } } +#if defined(__APPLE__) +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] +// BF2_HOST_TRACE=1: one read-only stderr line per startMission/startGame exit, naming the step +// (docs/macos-c-singleplayer.md: the client-hosted instant battle that sometimes never loads). +void hostTrace(const char* step, int value) +{ + static int armed = -1; + if (armed < 0) armed = std::getenv("BF2_HOST_TRACE") ? 1 : 0; + if (armed) { std::fprintf(stderr, "[host] %s %d\n", step, value); std::fflush(stderr); } +} +#define BF2_HOST_TRACE_SITE(step, value) hostTrace(step, static_cast(value)) +#else +#define BF2_HOST_TRACE_SITE(step, value) ((void)0) +#endif +#if defined(__APPLE__) +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-ingame-play-validated] +// BF2_PLAY_TRACE=1: once a second, one read-only stderr line about the local player (alive, +// vehicle template and seat root, position, view direction), the players alive per team, and +// the sound engine (initialized, provider, playing samples, allocated/max voices). Judging +// scripted playthroughs from the log (docs/macos-c-ingame-play.md). Nothing is written. +void playTraceTick() +{ + static int armed = -1; + if (armed < 0) armed = std::getenv("BF2_PLAY_TRACE") ? 1 : 0; + if (!armed || !world::playerManager) + return; + static double last = 0.0; + const double now = static_cast(std::clock()) / CLOCKS_PER_SEC; + if (now - last < 1.0 && last != 0.0) + return; + last = now; + int alive[3] = { 0, 0, 0 }, total[3] = { 0, 0, 0 }; + const std::list& players = world::playerManager->getPlayers(); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + const int team = (*it)->getTeam(); + if (team < 0 || team > 2) continue; + ++total[team]; + if ((*it)->getIsAlive()) ++alive[team]; + } + char sound[256] = "sound=none"; + if (g_soundEngine && g_soundEngine->isInitialized()) + { + const SoundStats* st = static_cast(g_soundEngine->getStats()); + if (st) + std::snprintf(sound, sizeof sound, "sound=on provider=\"%s\" playing=%d waiting=%d sources=%d maxVoices=%d", + st->providerInfo ? st->providerInfo : "", st->playing, st->waiting, st->sources, st->maxVoices); + } + else if (g_soundEngine) + std::snprintf(sound, sizeof sound, "sound=not-initialized"); + world::IPlayer* player = world::playerManager->getLocalHumanPlayer(); + if (!player) + { + std::fprintf(stderr, "[PLAY] no local player; players t1 %d/%d t2 %d/%d; %s\n", + alive[1], total[1], alive[2], total[2], sound); + std::fflush(stderr); + return; + } + const char* vehicleName = "-"; + float pos[3] = { 0, 0, 0 }; + if (world::IObject* vehicle = player->getVehicle()) + { + world::IObject* root = world::getRootParent(vehicle); + if (vehicle->getTemplate()) vehicleName = vehicle->getTemplate()->getName().c_str(); + const Vec3& p = (root ? root : vehicle)->getAbsolutePosition(); + pos[0] = p.x; pos[1] = p.y; pos[2] = p.z; + } + float fwd[3] = { 0, 0, 0 }; + if (world::ICameraObject* camera = player->getCamera()) + { + const Mat4& m = camera->getTransformation(0.0f); + fwd[0] = m.m[8]; fwd[1] = m.m[9]; fwd[2] = m.m[10]; + } + std::fprintf(stderr, "[PLAY] alive=%d manDown=%d team=%d vehicle=%s pos=%.1f/%.1f/%.1f fwd=%.2f/%.2f/%.2f " + "players t1 %d/%d t2 %d/%d; %s\n", + player->getIsAlive() ? 1 : 0, player->getIsManDown() ? 1 : 0, player->getTeam(), vehicleName, + pos[0], pos[1], pos[2], fwd[0], fwd[1], fwd[2], alive[1], total[1], alive[2], total[2], sound); + std::fflush(stderr); +} + +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-client-perf-understood] +// BF2_FRAME_TRACE=1: once a second (wall clock), one stderr line with the frame count, the mean and +// worst frame time, and the mean wall time of each mainLoop section (docs/macos-c-handplay-1.md). +// Measurement only: off by default, nothing in the loop changes. +namespace frametrace { +enum Section { Pre, Update, Script, Objects, Render, Tail, Count }; +static int s_armed = -1; +static std::chrono::steady_clock::time_point s_mark, s_frameStart, s_windowStart; +static double s_sum[Count], s_frameMax, s_frameSum; +static int s_frames, s_ticks; +inline bool armed() +{ + if (s_armed < 0) s_armed = std::getenv("BF2_FRAME_TRACE") ? 1 : 0; + return s_armed != 0; +} +inline void begin() +{ + if (!armed()) return; + s_frameStart = s_mark = std::chrono::steady_clock::now(); + if (s_windowStart.time_since_epoch().count() == 0) s_windowStart = s_frameStart; +} +inline void mark(Section s) +{ + if (!armed()) return; + const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); + s_sum[s] += std::chrono::duration(now - s_mark).count(); + s_mark = now; +} +inline void end(int ticks, bool inGame) +{ + if (!armed()) return; + mark(Tail); + const double ms = std::chrono::duration(s_mark - s_frameStart).count(); + s_frameSum += ms; + if (ms > s_frameMax) s_frameMax = ms; + ++s_frames; + s_ticks += ticks; + const double window = std::chrono::duration(s_mark - s_windowStart).count(); + if (window < 1.0) return; + const double n = s_frames ? s_frames : 1; + std::fprintf(stderr, "[FRAME] %s fps=%.1f mean=%.1fms max=%.1fms ticks=%d | pre %.1f update %.1f script %.1f " + "objects %.1f render %.1f tail %.1f\n", + inGame ? "game" : "menu", s_frames / window, s_frameSum / n, s_frameMax, s_ticks, + s_sum[Pre] / n, s_sum[Update] / n, s_sum[Script] / n, s_sum[Objects] / n, s_sum[Render] / n, + s_sum[Tail] / n); + std::fflush(stderr); + for (int i = 0; i < Count; ++i) s_sum[i] = 0.0; + s_frameMax = s_frameSum = 0.0; + s_frames = s_ticks = 0; + s_windowStart = s_mark; +} +} // namespace frametrace +#define BF2_FRAME_MARK(s) frametrace::mark(frametrace::s) +#endif +#if !DEDICATED && (defined(_WIN32) || defined(__APPLE__)) +// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: client-test-automation-replaced] +// The input script's aim / face / walk-to query (Platform/InputScript.h): read-only. +bool scriptQuery(const char* target, float viewPos[3], float viewFwd[3], float targetPos[3]) +{ + if (!world::playerManager) + return false; + world::IPlayer* self = world::playerManager->getLocalHumanPlayer(); + if (!self || !self->getIsAlive()) + return false; + world::ICameraObject* camera = self->getCamera(); + if (!camera) + return false; + const Mat4& m = camera->getTransformation(0.0f); + for (int i = 0; i < 3; ++i) { viewPos[i] = m.m[12 + i]; viewFwd[i] = m.m[8 + i]; } + float x, y, z; + if (std::sscanf(target, "%f/%f/%f", &x, &y, &z) == 3) + { + targetPos[0] = x; targetPos[1] = y; targetPos[2] = z; + return true; + } + const std::string kind(target); + if (kind.compare(0, 5, "tmpl:") == 0 && world::objectManager) + { + // Nearest root object whose template name is one of the comma-separated names. + std::string names = "," + kind.substr(5) + ","; + for (char& c : names) c = static_cast(std::tolower(static_cast(c))); + float bestT = 1e30f; + bool foundT = false; + std::map& all = world::objectManager->getAllObjectsFromGrid(); + for (std::map::iterator it = all.begin(); it != all.end(); ++it) + { + world::IObject* o = it->second; + if (!o || o->getParent() || !o->getTemplate()) + continue; + std::string n = "," + o->getTemplate()->getName() + ","; + for (char& c : n) c = static_cast(std::tolower(static_cast(c))); + if (names.find(n) == std::string::npos) + continue; + const Vec3& pos = o->getAbsolutePosition(); + const float dx = pos.x - viewPos[0], dy = pos.y - viewPos[1], dz = pos.z - viewPos[2]; + const float d = dx * dx + dy * dy + dz * dz; + if (d < bestT) + { + bestT = d; foundT = true; + targetPos[0] = pos.x; targetPos[1] = pos.y + 1.0f; targetPos[2] = pos.z; + } + } + return foundT; + } + const int team = self->getTeam(); + float best = 1e30f; + bool found = false; + const std::list& players = world::playerManager->getPlayers(); + for (std::list::const_iterator it = players.begin(); it != players.end(); ++it) + { + world::IPlayer* p = *it; + if (p == self || !p->getIsAlive() || !p->getVehicle()) + continue; + if ((kind == "enemy" && p->getTeam() == team) || (kind == "friend" && p->getTeam() != team)) + continue; + if (kind != "enemy" && kind != "friend" && kind != "player") + return false; + world::IObject* root = world::getRootParent(p->getVehicle()); + const Vec3& pos = (root ? root : p->getVehicle())->getAbsolutePosition(); + const float dx = pos.x - viewPos[0], dy = pos.y - viewPos[1], dz = pos.z - viewPos[2]; + const float d = dx * dx + dy * dy + dz * dz; + if (d < best) + { + best = d; found = true; + targetPos[0] = pos.x; targetPos[1] = pos.y + 1.2f; targetPos[2] = pos.z; // chest height + } + } + return found; +} +const bool s_scriptQueryRegistered = (inputscript::setScriptQuery(&scriptQuery), true); +#endif bool s_menuMusicHold = true; // byte_96E340: activateMenu skips the menu-music start once bool s_cursorShown = true; // byte_96E3A3: mainLoop hides the cursor once, when a movie starts bool s_activateMenuOnFrame1 = true; // byte_96E3A4: mainLoop's first-frame login + activateMenu @@ -355,6 +596,10 @@ SingleInstanceGuard::SingleInstanceGuard() #elif defined(_WIN32) && !DEDICATED handle = 0; // the editor: no guard, never a second instance isFirstInstance = true; +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] Same first/second-instance gate, using a per-user advisory lock. + lockFd = macos::acquireClientInstanceLock(); + isFirstInstance = lockFd >= 0; #endif } @@ -362,6 +607,10 @@ SingleInstanceGuard::~SingleInstanceGuard() { #if BF2_ENGINE_INSTANCE_MUTEX ReleaseMutex(handle); // not CloseHandle - as shipped (0x4083F0) +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] Keep the inode so contenders always lock the same file. + if (lockFd >= 0) + close(lockFd); #endif } #undef BF2_ENGINE_INSTANCE_MUTEX @@ -603,6 +852,27 @@ bool BF2Engine::init(const std::string& commandLine) return true; } +#if !DEDICATED +namespace { +// GeometryTemplateManager +0x28 (clear) on the client's ds:0x9A5578 slot, through the typed +// interface that the renderer-linked client builds carry. +void shutdownGeometryTemplates(IBase* manager) +{ +#if defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS) + static_cast(manager)->clear(); +#else + // [FRONTIER] [TEMP] [CHOSEN, not recovered] Client builds without the typed renderer interface + // (neither MSVC nor the statically linked plugins) have no reviewed dispatch for this slot. + // [RETIRE-WHEN: posix-client-geometry-interface] Such a client carries the typed manager header. + (void)manager; + std::fprintf(stderr, "[FRONTIER] dice::hfe::BF2Engine::shutdown GeometryTemplateManager::clear reached\n"); + std::fflush(stderr); + std::abort(); +#endif +} +} // namespace +#endif + // Shuts down the game and engine services. // [INFERRED] Boolean return type; current callers discard the always-true result. bool BF2Engine::shutdown() @@ -653,6 +923,14 @@ bool BF2Engine::shutdown() shutdownGame(true); // the bool argument is 1 (0x8131d2c-0x8131d31) +#if !DEDICATED + // Client arm (BF2.exe 0x408E32..0x408ECF; absent from the server ELF). The music player that + // initEngine created: its nonvirtual destructor (0x7E1900) unregisters the ECMenu handler. + // The member is cleared whether or not it was set (0x408E54). + delete musicPlayer; + musicPlayer = 0; +#endif + // 6. World teardown. None of this has a counterpart in init() or initEngine(): mainTerrain and // the object templates are created by level loading, so shutdown() is doing double duty as // an engine teardown and a world teardown. @@ -663,11 +941,33 @@ bool BF2Engine::shutdown() world::objectTemplateManager->deleteAll(false); // vtable +0x38, argument 0 +#if !DEDICATED + // BF2.exe 0x408E91: drop every geometry template the level loaded (GeometryTemplateManager + // +0x28) before the renderer goes away. + if (g_geometryTemplateManager) + shutdownGeometryTemplates(g_geometryTemplateManager); +#endif + // Instance() is called and its result discarded, purely to force the singleton into existence // so that Release() has something to tear down. Faithful to the binary, odd as it reads. world::SupplyDropManager::Instance(); world::SupplyDropManager::Release(); +#if !DEDICATED + // BF2.exe 0x408EAA: delete the HUD manager through its deleting destructor (slot 0, flag 1) + // and clear the "HudManager" singleton slot. Its widgets, Ref2System and HUD fonts hold renderer + // resources, so this must precede shutdownEngine, which unloads the renderer. + if (hudManager) + { + delete hudManager; + hudManager = 0; + } + + // [CHOSEN, not recovered] BF2.exe 0x408EC0 then calls Bf2VoipClient +0x68 when the voice client + // exists. This tree never constructs one (see initEngine), so the call is omitted. + // [RETIRE-WHEN: client-voip-optional] Restore the call with the voice client's class. +#endif + shutdownSettingsRepostitory(); // mirrors init()'s initSettingsRepostitory() shutdownEngine(); @@ -1169,6 +1469,29 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro swiffHost->setPage(2); } activateMenu(0); +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] c-loopback harness switch, off unless + // BF2_MAC_COMMANDLINE_JOIN=1 is set. Shipped, the menu's ActionScript reads this page + // (dice.bf2.Logic.getCommandLine) and calls dice.bf2.Logic.joinCommandlineServer on its + // own; the macOS menu does not run that script yet. This makes the same host call + // as_logic_joinCommandlineServer makes (port +0x0E4, address +0x0DC, joinServer +0x100, + // query port 0), so the join event reaches renderMenu's case 3 as it would from the + // menu. [RETIRE-WHEN: macos-menu-actionscript] the menu script issues the join itself. + if (!settings->boolGet("GSIsServer", false)) + { + const char* commandLineJoin = std::getenv("BF2_MAC_COMMANDLINE_JOIN"); + if (commandLineJoin && commandLineJoin[0] == '1') + { + const int page = swiffHost->getPage(); + const int port = swiffHost->getPortSetting(); + const std::string address = swiffHost->getJoinAddressSetting(); + const bool queued = swiffHost->joinServer(address, port, 0); + std::fprintf(stderr, "[TEMP] BF2_MAC_COMMANDLINE_JOIN: page %d, joinServer(%s, %d, 0) -> %d\n", + page, address.c_str(), port, queued ? 1 : 0); + std::fflush(stderr); + } + } +#endif return true; } } @@ -1181,7 +1504,9 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro SingletonRegInfo sri = { std::string("Game"), reinterpret_cast(&game), IID_IGame, CID_GameServer, 2 }; classManager->registerSingleton(sri); // ClassManager vtable +0x44, 0x81383c8 - if (!game->init()) // IGame vtable +0x18, 0x81383ff + const bool gameInit = game->init(); + BF2_HOST_TRACE_SITE("server game->init", gameInit); + if (!gameInit) // IGame vtable +0x18, 0x81383ff return false; // > edx=0, return 0 // renameAndReOpenPureLog composes "Logs/" + arg1 + arg2 + ".log" (verified from the string @@ -1197,7 +1522,9 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro setGameLogic(CID_ServerGameLogic); // releases the old gameLogic and // createInstance2(cid, IID_IGameLogic) - if (!gameLogic->init()) // IGameLogic vtable +0x10, 0x81384d0 + const bool logicInit = gameLogic->init(); + BF2_HOST_TRACE_SITE("server gameLogic->init", logicInit); + if (!logicInit) // IGameLogic vtable +0x10, 0x81384d0 return false; int port = serverSettings->m_serverPort; // ServerSettings +0x20 @@ -1205,6 +1532,7 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro port = settings->intGet("GSPort", 16567); // queried a second time; intGet // [UNRESOLVED] The third startServer argument's meaning; this caller passes zero. ok = gameServer->startServer(serverSettings->m_serverIP, port, 0); + BF2_HOST_TRACE_SITE("server startServer", ok); } else { @@ -1266,7 +1594,7 @@ bool BF2Engine::startGame(bool noAutoJoin, bool startFromMenu) // 2nd bool fro { std::string mod = host->getServerMod(); // the server's mod IBase* modInfo = classManager->getSingleton("ModInfo"); - if (!modInfo_vslot0x30(modInfo, mod)) // IModInfo +0x30 - [UNRESOLVED] role + if (!modInfo_vslot0x30(modInfo, mod)) // IModInfo +0x30, getModFromPath { if (compareIgnoreCase(mod, "mods/xpack") == 0) // both images host->setMessageId(26); @@ -1438,7 +1766,7 @@ bool BF2Engine::initEngine() return false; SingletonServer::init(); // genuinely static - 0x813907E pushes nothing #if !DEDICATED - musicPlayer = new MusicPlayer(); // operator new(8), 0x7E1B40 - client only; never deleted + musicPlayer = new MusicPlayer(); // operator new(8), 0x7E1B40 - client only; shutdown deletes it #endif return true; } @@ -1547,11 +1875,17 @@ static double s_prevWallClockTime = 0.0; // [INFERRED] na static float* const s_sleepOverheadTime = // [INFERRED] name Vars::getFloat("server-sleep-overhead-time", 0.005f); // default bits 0x3BA3D70A +#ifndef BF2_FRAME_MARK +#define BF2_FRAME_MARK(s) ((void)0) // [TEMP] BF2_FRAME_TRACE: client only +#endif bool BF2Engine::mainLoop() { // Runs one frame per call. A pending quit returns false before any frame work. if (quitNextFrameFlag) return false; +#if defined(__APPLE__) && !DEDICATED + frametrace::begin(); // [TEMP] BF2_FRAME_TRACE +#endif // : the idle throttle. The binary does `if (!byte52) usleep(100000);` - a flat 100 ms // (imm 0x186A0 at 0x8137A80), NOT derived from a getter. byte52 (+0x52) is set from a handleEvent @@ -1695,7 +2029,11 @@ bool BF2Engine::mainLoop() { if (s_cursorShown) { +#if defined(__APPLE__) + macos::CocoaHost::instance().showCursor(false); // [CHOSEN, not recovered] ShowCursor(FALSE) +#else ShowCursor(FALSE); +#endif s_cursorShown = false; } byte70 = true; @@ -1723,8 +2061,14 @@ bool BF2Engine::mainLoop() { if (byte70) { +#if defined(__APPLE__) + // [CHOSEN, not recovered] the host's counter has ShowCursor's semantics. + if (macos::CocoaHost::instance().showCursor(true) == 1) + macos::CocoaHost::instance().showCursor(false); +#else if (ShowCursor(TRUE) == 1) ShowCursor(FALSE); +#endif if (musicPlayer) { musicTraceSite("mainLoop byte70"); // [TEMP] BF2_TRACE_MUSIC @@ -1751,6 +2095,10 @@ bool BF2Engine::mainLoop() if ((!isDedicated() && ticks > 0 && !game) || g_bfSound->getForceUpdate()) g_bfSound->update(ticks); // IBfSound: the one-int update (PE slot +0x18) } +#if defined(__APPLE__) + if (game && !isDedicated()) + playTraceTick(); // [TEMP] BF2_PLAY_TRACE +#endif if (game && gameLogic && !isDedicated() && renderTicks > 0) // The HUD information-layer singleton is required on this client path. static_cast(g_hudInformationLayer)->update(static_cast(renderTicks) * renderDt); @@ -1759,6 +2107,7 @@ bool BF2Engine::mainLoop() // Step simulation only with ticks and both game owners present; use the // simulation-rate sample already taken for this frame. + BF2_FRAME_MARK(Pre); // [TEMP] BF2_FRAME_TRACE if (!isMoviePlaying() && ticks > 0 && game && gameLogic) // 0x813752E; BF2.exe adds the movie gate { #if !DEDICATED @@ -1775,6 +2124,7 @@ bool BF2Engine::mainLoop() // Python updates require render ticks and an initialized host, independent of // game presence and simulation rate. + BF2_FRAME_MARK(Update); // [TEMP] BF2_FRAME_TRACE if (renderTicks > 0) { if (python::pythonHost()->isInitialized()) @@ -1789,6 +2139,7 @@ bool BF2Engine::mainLoop() // Advance the separate frame-event manager by a duration, not a timestamp. // Its processEvents result is discarded. frameEventManager->processEvents(frameTime); + BF2_FRAME_MARK(Script); // [TEMP] BF2_FRAME_TRACE // Advance the world only outside movies, with a game and nonzero simulation rate. if (!isMoviePlaying() && game && !simRateZero) // / 0x813758A; BF2.exe adds the movie gate @@ -1807,7 +2158,7 @@ bool BF2Engine::mainLoop() // BF2.exe 0x40CA80: the viewer comes from BF2Render::getRenderView when the AI global // says so or the game logic is a client's. The view transform is fetched twice, as shipped. The // dedicated PE still makes the AI global's +0x18 call with bf2Render null (result - // unused) - [UNRESOLVED] identity of ds:0xA33C08 / ds:0x8B25B0; not called on a server here. + // unused). ds:0xA33C08 / ds:0x8B25B0 is ai::g_aiInstance; not called on a server here. const bool aiViewer = unresolvedGlobalA33C08 && unresolvedGlobalA33C08_vslot0x18(); if (bf2Render && (aiViewer || (gameLogic && !gameLogic->isServer()))) { @@ -1835,6 +2186,7 @@ bool BF2Engine::mainLoop() } } + BF2_FRAME_MARK(Objects); // [TEMP] BF2_FRAME_TRACE #if !DEDICATED // THE frame - BF2.exe 0x40CA80. Never in a dedicated image: isDedicated() gates it and every // object it touches is client-only. @@ -1878,6 +2230,7 @@ bool BF2Engine::mainLoop() bf2Render->update(frameTime); // vslot +0x14, 0x4530D0 #endif + BF2_FRAME_MARK(Render); // [TEMP] BF2_FRAME_TRACE bf2Console->updateConsole(); #if !DEDICATED if (hudManager) @@ -1942,6 +2295,9 @@ bool BF2Engine::mainLoop() // externally detectable. CheckServerAliveThread is the producer side. if (isDedicated()) // BF2.exe 0x40CA80: `if (sub_440510() && sub_440510())` - markAsStillRunning(); // the call site's test and the inlined body's own +#if defined(__APPLE__) && !DEDICATED + frametrace::end(ticks, game != 0 && menuLogic == 0); // [TEMP] BF2_FRAME_TRACE +#endif // [CHOSEN, not recovered] The per-frame PunkBuster SDK pump is omitted. // A queued quit makes this the final frame. @@ -2087,7 +2443,7 @@ bool BF2Engine::filterGameInput(io::GameInput& input) menuLogic->handleInput(input); // IMenuLogic +0x38 return false; } -#if defined(_WIN32) +#if defined(_WIN32) || defined(__APPLE__) // [CHOSEN, not recovered] macOS fills the ring too menuKeyCount = 0; // the WM_KEYDOWN ring (Game/Main/BF2.cpp) is dropped menuKeyRead = menuKeyWrite; // every frame the menu is down #endif @@ -2371,6 +2727,7 @@ bool BF2Engine::startMission(const std::string& map, const std::string& /*mode - #endif const bool started = startGame(false, false); + BF2_HOST_TRACE_SITE("startMission startGame", started); if (!started) { activateMenu(0); @@ -2702,9 +3059,16 @@ void BF2Engine::playSound(const std::string&) {} void BF2Engine::browseModHomepage(const std::string& url) { #if !DEDICATED +#if defined(__APPLE__) + // [CHOSEN, not recovered] ShowWindow(SW_MINIMIZE) and ShellExecuteA("open", url). + macos::CocoaHost::instance().minimize(); + if (!macos::CocoaHost::instance().openURL(url)) + return; +#else ShowWindow(window->getHwnd(), SW_MINIMIZE); // Window vslot +0x2C if (reinterpret_cast(ShellExecuteA(0, "open", url.c_str(), 0, 0, SW_SHOWNORMAL)) <= 32) return; +#endif quitNextFrameFlag = true; #else (void)url; @@ -2716,10 +3080,16 @@ void BF2Engine::browseModHomepage(const std::string& url) void BF2Engine::restartBF2() { #if !DEDICATED +#if defined(__APPLE__) + // [CHOSEN, not recovered] GetModuleFileNameA + ShellExecuteA(exe, commandLine). + if (!macos::relaunchExecutable(commandLine)) + return; +#else char fileName[MAX_PATH]; GetModuleFileNameA(0, fileName, MAX_PATH); if (reinterpret_cast(ShellExecuteA(0, "open", fileName, commandLine.c_str(), 0, SW_SHOWNORMAL)) <= 32) return; +#endif quitNextFrameFlag = true; #endif } @@ -2741,14 +3111,16 @@ void BF2Engine::buildRestartCommandLine(const std::string& modPath, const std::s } if (IBase* lpm = classManager->getSingleton("LocalProfileManager")) { - if (static_cast(lpm)->getCurrentProfile()) + ILocalProfileManager* profiles = static_cast(lpm); + if (LocalProfile* profile = profiles->getCurrentProfile()) // +0x44 { - std::string scratch; - localProfileManager_vslot0x70(lpm, localProfileManager_vslot0xD0(lpm, scratch, 1)); - std::string password; - password = static_cast(lpm)->getPassword(); - commandLine += std::string(" +playerName ") + scratch; // [UNRESOLVED] which string each += takes: - commandLine += std::string(" +playerPassword ") + password; // the decompiler drops the operands + // 0x403F34..0x403FE8: the login password goes back into the record encoded (+0x70 with + // `true`, pushed before +0xD0's return slot), then the record's encoded password (+0x88) + // and its GameSpy nick (record +0x54) go on the command line. + profiles->setPassword(profiles->getLoginPassword(), true); // +0xD0, +0x70 + std::string password = profiles->getPassword(); // +0x88 + commandLine += std::string(" +playerName ") + profile->gamespyNick; + commandLine += std::string(" +playerPassword ") + password; } } } @@ -2790,7 +3162,24 @@ IMenuLogic* menuLogic = 0; // dword_987358 - the active menu; s hud::BF2HudManager* hudManager = 0; // dword_A10890 - zeroed again by the client ctor (0x408190) BF2VoipClient* bf2VoipClient = 0; // dword_9A4DA0 IBase* g_renderer = 0; // BF2.exe g_Renderer - [UNRESOLVED] symbol; set by the renderer bring-up, not by this TU -IBase* unresolvedGlobalA33C08 = 0; // ds:0xA33C08 / bf2_w32ded ds:0x8B25B0 +// ds:0xA33C08 is ai::g_aiInstance: its only writer, 0x801030, stores getSimpleSingleton("AI") as +// ai::AIInstanceServer::updateInstance does. The alias keeps one object for both names. +IBase*& unresolvedGlobalA33C08 = ai::g_aiInstance; + +// startGame join result 8 (0x40543F..0x40544F): ModInfo +0x30 with the server's mod path and a full +// 32-bit test of the result. The client ModInfo table 0x8A1230 holds 0x47E590 there, which matches +// each 0x154-byte Mod on its first string (path): IModInfo::getModFromPath. +bool modInfo_vslot0x30(IBase* modInfo, const std::string& modName) +{ + return static_cast(modInfo)->getModFromPath(modName) != 0; +} + +// mainLoop's ragdoll viewer (0x40D1ED..0x40D22A) calls the AI instance's +0x18 after its null test: +// IAIInstance::isInitialized. +bool unresolvedGlobalA33C08_vslot0x18() +{ + return ai::aiInstance()->isInitialized(); +} // The client singleton slots BF2.exe 0x4301A9 registers (Core/ModuleRegistry.cpp). [CHOSEN] placement: // their .data addresses 0x987340..0x987398 surround menuLogic (0x987358) and s_prevWallClockTime // (0x987330), i.e. this TU's statics. diff --git a/Code/BF2/Game/Main/BF2Engine.h b/Code/BF2/Game/Main/BF2Engine.h index 3ac24719b..7ee85fc96 100644 --- a/Code/BF2/Game/Main/BF2Engine.h +++ b/Code/BF2/Game/Main/BF2Engine.h @@ -188,7 +188,7 @@ class BF2Engine : public io::IInputFilter, /* 164 */ int dwordA4; // [UNRESOLVED] Constructor sets -1; shutdown does not reset it. /* 168 */ Demo* demo; // Owned demo controller. - /* 172 */ MusicPlayer* musicPlayer; // Client-only allocation; original shutdown does not delete it. + /* 172 */ MusicPlayer* musicPlayer; // Client-only allocation; the client shutdown arm deletes it. #if !DEDICATED struct MovieEntry // Client-only movie queue payload. { @@ -217,6 +217,9 @@ struct SingleInstanceGuard { #if defined(_WIN32) && !DEDICATED /* +0x00 */ void* handle; // Win32 handle without including windows.h. +#elif defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] Owned flock descriptor; closed on destruction or exec. + int lockFd; #endif /* +0x04 (client) / +0x00 */ bool isFirstInstance; SingleInstanceGuard(); diff --git a/Code/BF2/Game/Main/BF2Render.cpp b/Code/BF2/Game/Main/BF2Render.cpp index c70a10fb2..62ccaab90 100644 --- a/Code/BF2/Game/Main/BF2Render.cpp +++ b/Code/BF2/Game/Main/BF2Render.cpp @@ -39,7 +39,11 @@ #include #include #include +#if defined(_WIN32) #include +#else +#include // [CHOSEN, not recovered] getpid for the title +#endif namespace dice { namespace hfe { @@ -88,79 +92,52 @@ void notifyCollisionManagerRendererShutdown(IBase* manager) const char kSourcePath[] = "C:\\dice\\Projects\\BF2Branches\\Patch_1_50\\Code\\BF2\\Game\\Main\\BF2Render.cpp"; -// View of RendDX9's plugin-owned display modes. Both plugin flavors retain the -// VC7.1 container layout and 40-byte records; this is not a host-owned exchange -// container. The retail display-mode carrier embeds one record at offset 4. -struct RendererDisplayMode -{ - /* +0x00 */ unsigned short width; - /* +0x02 */ unsigned short height; - /* +0x04 */ unsigned short refreshHz; - /* +0x06 */ unsigned char bpp; - /* +0x07 */ unsigned char pad07; // never copied by 0x4547F0 - /* +0x08 */ vc71::vector_layout depthFormats; // D3DFORMAT dwords - /* +0x18 */ vc71::vector_layout multiSamples; // renddx9abi::DisplayModeMultiSample -}; -static_assert(sizeof(RendererDisplayMode) == 40, "Renderer +0x3C hands back 40-byte records"); - -// size() with VC7.1's own arithmetic: 0 while _First is null, else (_Last - _First) / 40 as a signed -// pointer difference - the imul / sar / shr-add sequence at 0x453849 and 0x454970 is a signed divide. -int rendererModeCount(const vc71::vector_layout& modes) +// RendDX9's plugin-owned display modes: the std::vector of display-mode records Renderer +0x3C +// returns (DisplayModeAbi.h; retail: a VC7.1 vector of 40-byte records). Both images share the STL +// (issue #7). The retail display-mode carrier embeds one record at offset 4. +typedef renddx9abi::DisplayModeRecord RendererDisplayMode; +typedef std::vector RendererDisplayModes; + +// size(). Retail open-codes it with VC7.1's arithmetic (0 while _First is null, else a signed +// pointer difference over 40 - the imul / sar / shr-add sequence at 0x453849 and 0x454970). +int rendererModeCount(const RendererDisplayModes& modes) { - if (!modes.first) - return 0; - return static_cast(modes.last - modes.first) / static_cast(sizeof(RendererDisplayMode)); + return static_cast(modes.size()); } -const RendererDisplayMode& rendererModeAt(const vc71::vector_layout& modes, unsigned int index) +const RendererDisplayMode& rendererModeAt(const RendererDisplayModes& modes, unsigned int index) { - return reinterpret_cast(modes.first)[index]; + return modes[index]; } // Requests modes with all three filter flags enabled. Renderer caching means // an earlier VideoOptions query can already have populated the list with its filter. -const vc71::vector_layout& rendererDisplayModes(dx9rend::IRenderer* renderer) +const RendererDisplayModes& rendererDisplayModes(dx9rend::IRenderer* renderer) { dx9rend::DisplayModeFilter filter; filter.aspect4by3 = true; // [ebp-4] filter.crossCheckDisplaySettings = true; // [ebp-3] filter.minimumResolution = true; // [ebp-2] - return *static_cast(renderer->slot_0x3C(&filter)); + return *static_cast(renderer->slot_0x3C(&filter)); } // Requires a nonempty depth-format list; init and setDisplayMode retain one entry. -// Returns a borrowed reference. Native and compatibility empty-list behavior differs. +// Returns a borrowed reference. const unsigned int& carrierDepthFront(const renddx9abi::HostDisplayMode& carrier) { return *renddx9abi::hostDepthFirst(carrier); } -// Copies display-mode scalars and assigns both owned lists. -// [PLATFORM] The native carrier flattens the fields; compatibility uses the ABI -// carrier's owned-range assignment. +// Copies display-mode scalars (0x4547F0 skips the pad byte) and assigns both lists. void assignDisplayMode(renddx9abi::HostDisplayMode& carrier, const RendererDisplayMode& mode) { carrier.width = mode.width; carrier.height = mode.height; - carrier.refreshHz = mode.refreshHz; + carrier.refreshHz = mode.refresh; carrier.bpp = mode.bpp; - const unsigned int* depthFirst = - reinterpret_cast(mode.depthFormats.first); - const unsigned int* depthLast = - reinterpret_cast(mode.depthFormats.last); - const renddx9abi::DisplayModeMultiSample* sampleFirst = - reinterpret_cast(mode.multiSamples.first); - const renddx9abi::DisplayModeMultiSample* sampleLast = - reinterpret_cast(mode.multiSamples.last); -#if BF2_PLUGIN_ABI_NATIVE - carrier.depthFormats.assign(depthFirst, depthLast); - carrier.multiSamples.assign(sampleFirst, sampleLast); -#else - renddx9abi::assignOwnedDisplayVector(carrier.depthFormats, depthFirst, depthLast); - renddx9abi::assignOwnedDisplayVector( - carrier.multiSamples, sampleFirst, sampleLast); -#endif + carrier.depthFormats.assign(mode.depthFormats.begin(), mode.depthFormats.end()); + carrier.multiSamples.assign(mode.multiSample.begin(), mode.multiSample.end()); } } // anonymous namespace @@ -219,7 +196,11 @@ bool BF2Render::init() // A window title reaches nothing but the taskbar. std::ostringstream title; title << "BF2 (v" << BuildNrUtil::getBuildNrString() << "-LC" +#if defined(_WIN32) << ", pid: " << ::GetCurrentProcessId() << ")"; +#else + << ", pid: " << static_cast(::getpid()) << ")"; +#endif const bool fullscreen = settings->boolGet("GSFullScreen", false); const int width = settings->intGet("GSWindowSizeX", 800); @@ -241,15 +222,9 @@ bool BF2Render::init() m_displayModeCarrier->bpp = 32; m_displayModeCarrier->vsync = 0; -#if BF2_PLUGIN_ABI_NATIVE m_displayModeCarrier->depthFormats.push_back(75u); // D3DFMT_D24S8 m_displayModeCarrier->windows.push_back( reinterpret_cast(m_window->getHwnd())); -#else - vc71::vectorRef(&m_displayModeCarrier->depthFormats).push_back(75u); - void* hwnd = reinterpret_cast(m_window->getHwnd()); - vc71::vectorRef(&m_displayModeCarrier->windows).push_back(hwnd); -#endif if (fullscreen) m_window->toggleFullscreenStyle(); @@ -296,15 +271,6 @@ void BF2Render::shutdown() { if (m_displayModeCarrier) { -#if !BF2_PLUGIN_ABI_NATIVE - // The rebuilt client uses native mode. Keep the retail branch complete for isolated - // ABI compilation: its POD carrier has no automatic vector destructors. - renddx9abi::clearOwnedDisplayVector(m_displayModeCarrier->windows); - renddx9abi::clearOwnedDisplayVector( - m_displayModeCarrier->multiSamples); - renddx9abi::clearOwnedDisplayVector( - m_displayModeCarrier->depthFormats); -#endif delete m_displayModeCarrier; } @@ -430,13 +396,12 @@ unsigned int BF2Render::toggleFullscreen() // listing because the original print path is absent. [INFERRED] Method spelling. void BF2Render::listScreenModes() { - const vc71::vector_layout& modes = rendererDisplayModes(m_renderer); // +0x3C + const RendererDisplayModes& modes = rendererDisplayModes(m_renderer); // +0x3C for (unsigned int i = 0; i < static_cast(rendererModeCount(modes)); ++i) { const RendererDisplayMode& mode = rendererModeAt(modes, i); - const unsigned int* first = reinterpret_cast(mode.depthFormats.first); - const unsigned int* last = reinterpret_cast(mode.depthFormats.last); - (void)std::find(first, last, carrierDepthFront(*m_displayModeCarrier)); // discarded + (void)std::find(mode.depthFormats.begin(), mode.depthFormats.end(), + carrierDepthFront(*m_displayModeCarrier)); // discarded } } @@ -447,7 +412,7 @@ void BF2Render::listScreenModes() // [PLATFORM] Native vector operations retain their own allocation semantics. void BF2Render::setDisplayMode(int index) { - const vc71::vector_layout& modes = rendererDisplayModes(m_renderer); // +0x3C + const RendererDisplayModes& modes = rendererDisplayModes(m_renderer); // +0x3C if (index < 0 || index >= rendererModeCount(modes)) { Debug(DebugTypeError, kSourcePath, 460, "") << "ScreenMode out of range"; @@ -456,16 +421,9 @@ void BF2Render::setDisplayMode(int index) const unsigned int depthFormat = carrierDepthFront(*m_displayModeCarrier); assignDisplayMode(*m_displayModeCarrier, rendererModeAt(modes, index)); -#if BF2_PLUGIN_ABI_NATIVE m_displayModeCarrier->depthFormats.clear(); m_displayModeCarrier->depthFormats.push_back(depthFormat); m_displayModeCarrier->multiSamples.clear(); -#else - renddx9abi::clearOwnedDisplayVector(m_displayModeCarrier->depthFormats); - vc71::vectorRef(&m_displayModeCarrier->depthFormats).push_back(depthFormat); - renddx9abi::clearOwnedDisplayVector( - m_displayModeCarrier->multiSamples); -#endif m_window->resizeClient(m_displayModeCarrier->width, // +0x44 m_displayModeCarrier->height); diff --git a/Code/BF2/Game/Main/BF2Window.cpp b/Code/BF2/Game/Main/BF2Window.cpp index 76b981c0e..db48b060a 100644 --- a/Code/BF2/Game/Main/BF2Window.cpp +++ b/Code/BF2/Game/Main/BF2Window.cpp @@ -2,12 +2,14 @@ #include "BF2Window.h" -#if !DEDICATED +// [CHOSEN, not recovered] The macOS client uses BF2Window_macos.cpp instead. +#if !DEDICATED && defined(_WIN32) #include "BF2Engine.h" // menuLogic - the active menu (Window::wndProc) #include "../../Core/EventManager.h" // eventManager->postEvent on WM_ACTIVATEAPP #include "../IEventListener.h" // EventCategory #include "../Utility/Vars.h" // opt-window-x / opt-window-y +#include "../../Platform/Windows/WinInputScript.h" // [TEMP] BF2_INPUT_SCRIPT focus #include namespace dice { @@ -117,7 +119,9 @@ bool Window::create(const std::string& title, int width, int height, bool fullsc } bool Window::isCreated() const { return m_hwnd != 0; } -bool Window::getHasFocus() const { return m_hasFocus; } +// [TEMP] [CHOSEN, not recovered] A BF2_INPUT_SCRIPT run reports focus (WinInputScript.h). +// [RETIRE-WHEN: client-test-automation-replaced] +bool Window::getHasFocus() const { return m_hasFocus || inputscript::winInputScriptActive(); } const std::string& Window::getTitle() const { return m_title; } int Window::getWidth() const { return m_width; } int Window::getHeight() const { return m_height; } @@ -317,4 +321,4 @@ void BF2Window::toggleFullscreenStyle() } // namespace hfe } // namespace dice -#endif // !dedicated +#endif // !dedicated && _WIN32 diff --git a/Code/BF2/Game/Main/BF2Window.h b/Code/BF2/Game/Main/BF2Window.h index d9412204f..40310299c 100644 --- a/Code/BF2/Game/Main/BF2Window.h +++ b/Code/BF2/Game/Main/BF2Window.h @@ -6,7 +6,13 @@ #ifndef GAME_MAIN_BF2WINDOW_H // [INFERRED] guard style #define GAME_MAIN_BF2WINDOW_H +#if defined(_WIN32) #include +#elif defined(__APPLE__) +// [CHOSEN, not recovered] macOS port: HWND/UINT/WPARAM/LPARAM/LRESULT in dice::hfe, and the +// Win32 message ids BF2Window_macos.mm synthesizes from Cocoa events. +#include "../../Platform/macOS/HostWindowTypes.h" +#endif #include #include @@ -45,7 +51,12 @@ class Window // [INFERRED] name - base, TU [UNRE // the wndproc create() registers. Static: it reaches the window through // `mainWindow`, not through GWL_USERDATA (the `this` passed as lpParam to CreateWindowExA is // never read back). +#if defined(_WIN32) static LRESULT CALLBACK wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); +#else + // [CHOSEN, not recovered] macOS: called by BF2Window_macos.mm with synthesized messages. + static LRESULT wndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); +#endif friend class SwiffHost; // clears m_hideCursor directly protected: diff --git a/Code/BF2/Game/Main/IVideoOptions.h b/Code/BF2/Game/Main/IVideoOptions.h index 97e8a2f88..75bd88e42 100644 --- a/Code/BF2/Game/Main/IVideoOptions.h +++ b/Code/BF2/Game/Main/IVideoOptions.h @@ -1,6 +1,5 @@ // Host view of renderer video options. Virtual order is fixed and has no destructor slot. -// Native plugins share host STL types; retail-compatible plugins convert VC7.1 strings/vectors -// at the boundary. Do not pass native STL objects through a retail-layout interface. +// The renderer shares the host's STL types (issue #7), so strings and vectors cross directly. // [INFERRED] Interface/member names. [UNRESOLVED] Unnamed option slots retain provisional roles. #ifndef GAME_MAIN_IVIDEOOPTIONS_H #define GAME_MAIN_IVIDEOOPTIONS_H diff --git a/Code/BF2/Game/Main/OpenBF2Console.cpp b/Code/BF2/Game/Main/OpenBF2Console.cpp index c9ef81083..e657059cd 100644 --- a/Code/BF2/Game/Main/OpenBF2Console.cpp +++ b/Code/BF2/Game/Main/OpenBF2Console.cpp @@ -126,15 +126,26 @@ std::vector resolveModuleCandidates(const std::string& name) out.push_back(name); return out; } + // [CHOSEN, not recovered] macOS uses .dylib for the same lib convention; a typed .so or + // .dll is still stripped so one config line keeps working on every build. +#if defined(__APPLE__) + const char* const suffix = ".dylib"; +#else + const char* const suffix = ".so"; +#endif std::string base = name; if (endsWithNoCase(base, ".so")) base.erase(base.size() - 3); +#if defined(__APPLE__) + else if (endsWithNoCase(base, ".dylib")) + base.erase(base.size() - 6); +#endif else if (endsWithNoCase(base, ".dll")) base.erase(base.size() - 4); const std::string stem = (base.compare(0, 3, "lib") == 0) ? base.substr(3) : base; - out.push_back(std::string("lib") + stem + ".so"); + out.push_back(std::string("lib") + stem + suffix); if (base != std::string("lib") + stem) // skip the duplicate when the name already had lib - out.push_back(base + ".so"); + out.push_back(base + suffix); #endif return out; } diff --git a/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp b/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp index b1fca4b38..e658d4b58 100644 --- a/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp +++ b/Code/BF2/Game/MatchMaking/Client/CdKeyStore.cpp @@ -6,8 +6,14 @@ #include "CdKeyStore.h" #if !DEDICATED +#if defined(_WIN32) #include #include +#else +// [CHOSEN, not recovered] macOS: the DPAPI counterpart (docs/macos-port.md, "Protected profile +// data (DPAPI)"). The flow below is the shipped one; only the API calls differ. +#include "../../../Platform/macOS/ProtectedData.h" +#endif #include // malloc / free - the 402CF0 / 402D10 pair #include // memcmp / strlen @@ -74,7 +80,11 @@ void ProtectedData::release() { if (m_blob) { +#if defined(_WIN32) ::LocalFree(m_blob->pbData); +#else + macos::freeProtectedData(m_blob->pbData); +#endif delete m_blob; m_blob = 0; } @@ -86,8 +96,13 @@ bool ProtectedData::protect(const std::string& plainText) { DATA_BLOB in; const char* const text = plainText.c_str(); +#if defined(_WIN32) in.pbData = reinterpret_cast(const_cast(text)); in.cbData = static_cast(std::strlen(text) + 1); +#else + in.pbData = reinterpret_cast(const_cast(text)); + in.cbData = static_cast(std::strlen(text) + 1); +#endif if (plainText.empty()) return false; @@ -95,21 +110,32 @@ bool ProtectedData::protect(const std::string& plainText) release(); m_blob = new DATA_BLOB; // : operator new(8) +#if defined(_WIN32) return ::CryptProtectData(&in, L"This is the description string.", 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, m_blob) != FALSE; +#else + // A failed protect leaves the blob empty, as a failed CryptProtectData does. + m_blob->cbData = 0; + m_blob->pbData = 0; + return macos::protectData(in.pbData, in.cbData, m_blob); +#endif } // Decodes a dpapi-protected hexadecimal value in place. Assigns plaintext only on // success; failure preserves the original text and leaks the temporary decode buffer. bool ProtectedData::unprotect(std::string& hexText) { +#if defined(_WIN32) const DWORD count = static_cast(hexText.size() >> 1); LPWSTR description = 0; +#else + const std::uint32_t count = static_cast(hexText.size() >> 1); +#endif if (!count) return false; - BYTE* const bytes = static_cast(std::malloc(count)); // : the engine malloc + unsigned char* const bytes = static_cast(std::malloc(count)); // : the engine malloc hexToBytes(hexText, bytes); DATA_BLOB in; @@ -117,6 +143,7 @@ bool ProtectedData::unprotect(std::string& hexText) in.cbData = count; DATA_BLOB out; +#if defined(_WIN32) if (::CryptUnprotectData(&in, &description, 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &out)) { hexText = std::string(reinterpret_cast(out.pbData)); @@ -125,6 +152,23 @@ bool ProtectedData::unprotect(std::string& hexText) ::LocalFree(out.pbData); return true; } +#else + out.cbData = 0; + out.pbData = 0; + // The plain text carries its terminator (protect includes it), so it is read as a C string. + if (macos::unprotectData(in.pbData, in.cbData, &out) && out.cbData && out.pbData[out.cbData - 1] == 0) + { + hexText = std::string(reinterpret_cast(out.pbData)); + std::free(bytes); + macos::freeProtectedData(out.pbData); + return true; + } + if (out.pbData) + macos::freeProtectedData(out.pbData); + // As shipped, `bytes` is not freed on failure; there is no system message to format. + return false; +#endif +#if defined(_WIN32) char* message = 0; if (::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | @@ -133,6 +177,7 @@ bool ProtectedData::unprotect(std::string& hexText) reinterpret_cast(&message), 0, 0)) ::LocalFree(message); return false; +#endif } // Writes the encrypted blob as hex. Requires a non-null blob from successful protection. diff --git a/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp b/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp index 0b5757fcb..e2d361d5f 100644 --- a/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp +++ b/Code/BF2/Game/MatchMaking/Server/MatchMakingServer.cpp @@ -14,6 +14,7 @@ extern "C" { #include "MMBackend.h" #include "GameSpyBackend.h" #include "ServerQueryCache.h" // serverQueryCache - MatchMakingServer::update ticks it +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -78,7 +79,7 @@ const char* GameSpyCDKeyAuthenticator::getChallengeString() if (!challenge[0]) { for (unsigned int i = 0; i < 8; ++i) - challenge[i] = alphabet[std::rand() % (sizeof(alphabet) - 1)]; + challenge[i] = alphabet[bf2crt::rand() % (sizeof(alphabet) - 1)]; challenge[8] = 0; } return challenge; diff --git a/Code/BF2/Game/Objects/Base/Bundle.cpp b/Code/BF2/Game/Objects/Base/Bundle.cpp index abeafd805..ed8f823ab 100644 --- a/Code/BF2/Game/Objects/Base/Bundle.cpp +++ b/Code/BF2/Game/Objects/Base/Bundle.cpp @@ -2,6 +2,7 @@ // Contents: recovered Bundle construction and composite child propagation. #include "Bundle.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "BundleTemplate.h" #include "../../../Core/Debug.h" #include "../../../Core/Ids.h" @@ -25,11 +26,13 @@ namespace { # define BF2_BUNDLE_VCALL #endif +#if defined(_MSC_VER) template inline Fn bundleVslot(void* object, unsigned int byteOffset) { return reinterpret_cast((*reinterpret_cast(object))[byteOffset / 4]); } +#endif // The renderer geometry interface is not otherwise present in the server source tree. Both ports // pin this one operation: PE +0x4C / ELF +0x54, taking an absolute transform and a part number. @@ -38,11 +41,11 @@ void setGeometryPartTransformation(geom::IGeometry* geometry, { #if defined(_MSC_VER) const unsigned int slot = 0x4C; -#else - const unsigned int slot = 0x54; -#endif typedef void (BF2_BUNDLE_VCALL* Fn)(void*, const Mat4&, int); bundleVslot(geometry, slot)(geometry, transformation, part); +#else + geometry_part::setTransform(geometry, &transformation, part); // ELF +0x54 +#endif } // Leaves nearly unit vectors unchanged and collapses nearly zero vectors to zero. diff --git a/Code/BF2/Game/Objects/Base/Camera.cpp b/Code/BF2/Game/Objects/Base/Camera.cpp index 6c858a0fd..5a530c195 100644 --- a/Code/BF2/Game/Objects/Base/Camera.cpp +++ b/Code/BF2/Game/Objects/Base/Camera.cpp @@ -5,6 +5,7 @@ // Keep request/force position paths and the separate general/near-vehicle shake behavior. #include "Camera.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../../../Core/System.h" #include "../../../Core/Ids.h" #include "../../../Core/Debug.h" // setViewMode's attested line 1171 @@ -109,11 +110,13 @@ inline IHeightmapCluster* cameraHeightmapCluster() # define BF2_VCALL #endif +#if defined(_MSC_VER) template inline Fn vslot(void* object, unsigned int byteOffset) { return reinterpret_cast((*reinterpret_cast(object))[byteOffset / 4]); } +#endif typedef int (BF2_VCALL* VFn_geomCount)(void*); typedef void (BF2_VCALL* VFn_geomSet)(void*, int); @@ -124,15 +127,16 @@ typedef void (BF2_VCALL* VFn_geomSet)(void*, int); const unsigned int kGeomSetSubGeometrySlot = 0x6C; const unsigned int kGeomSubGeometryCountSlot = 0x74; const unsigned int kGeomSetLodSlot = 0x78; -#else -const unsigned int kGeomSetSubGeometrySlot = 0x70; -const unsigned int kGeomSubGeometryCountSlot = 0x78; -const unsigned int kGeomSetLodSlot = 0x7C; -#endif inline int geomSubGeometryCount(void* g) { return vslot(g, kGeomSubGeometryCountSlot)(g); } inline void geomSetSubGeometry(void* g, int i){ vslot(g, kGeomSetSubGeometrySlot)(g, i); } inline void geomSetLod(void* g, int i) { vslot(g, kGeomSetLodSlot)(g, i); } +#else +// Non-MSVC: the named geometry_part operations (ELF +0x70 / +0x78 / +0x7C). +inline int geomSubGeometryCount(void* g) { return geometry_part::getSubgeomCount(g); } +inline void geomSetSubGeometry(void* g, int i){ geometry_part::setSubgeom(g, i); } +inline void geomSetLod(void* g, int i) { geometry_part::setLod(g, i); } +#endif #if !DEDICATED && defined(_MSC_VER) // [TEMP] [CHOSEN, not recovered] Optional BF2_TRACE_VEHICLE_GEOM diagnostics for geometry switches and local camera roots. @@ -766,10 +770,11 @@ const Mat4& Camera::getTransformationCVMChase(float deltaTime, bool frontChase) float radius = root->getPhysicBoundingRadius(); if (radius <= 2.0f) radius = 2.0f; -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) else // [PLATFORM] PE 0x5F0A36/0x5F0A56 repeats this virtual call on the >2 or unordered // arm. ELF 0x81DCAD0 caches its sole call, so the non-Win32 source path does too. + // Every Windows image (x86 and the native x64, issue #7) takes the PE arm. radius = root->getPhysicBoundingRadius(); #endif desiredDistance = radius * s_chaseDistanceScale; @@ -788,9 +793,9 @@ const Mat4& Camera::getTransformationCVMChase(float deltaTime, bool frontChase) desiredDirection.x, desiredDirection.y, desiredDirection.z, 1.0f }; float blend = deltaTime * cameraTemplate->getFollowStiffness(); -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) // [PLATFORM] PE's clamp helper returns zero for unordered/NaN; the ELF's inlined comparisons - // leave NaN untouched. + // leave NaN untouched. Every Windows image (x86 and the native x64, issue #7) takes the PE arm. if (!(blend >= 0.0f)) blend = 0.0f; #else diff --git a/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp b/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp index f20fc9112..1931532bb 100644 --- a/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp +++ b/Code/BF2/Game/Objects/Base/ModuleWorldObjTemplBase.cpp @@ -89,6 +89,52 @@ struct BaseTemplateConsoleAccess static const std::string& getAiTemplate() { return simpleObject()->m_aiTemplate; } // +296 static void setAiTemplate(const std::string& value) { simpleObject()->m_aiTemplate = value; } + // The animated-UV block (offsets ELF / PE). Every executor stores the parsed value straight + // into the field; the PE Vec2 setters of Size, Max and RotationScale go through a small + // non-inlined helper that copies the two floats (PE 0x553857, 0x5539CB, 0x553F95), which + // the ELF executors inline. + static bool getAnimatedUVTranslation() { return simpleObject()->m_animatedUVTranslation; } // 228 / 0x118 + static void setAnimatedUVTranslation(bool value) { simpleObject()->m_animatedUVTranslation = value; } + static const Math::Vec2& getAnimatedUVTranslationSpeed() // 232 / 0x11C + { return simpleObject()->m_animatedUVTranslationSpeed; } + static void setAnimatedUVTranslationSpeed(const Math::Vec2& value) + { simpleObject()->m_animatedUVTranslationSpeed = value; } + static const Math::Vec2& getAnimatedUVTranslationSize() // 248 / 0x12C + { return simpleObject()->m_animatedUVTranslationSize; } + static void setAnimatedUVTranslationSize(const Math::Vec2& value) + { simpleObject()->m_animatedUVTranslationSize = value; } + static const Math::Vec2& getAnimatedUVTranslationMax() // 240 / 0x124 + { return simpleObject()->m_animatedUVTranslationMax; } + static void setAnimatedUVTranslationMax(const Math::Vec2& value) + { simpleObject()->m_animatedUVTranslationMax = value; } + static int getAnimatedUVTranslationIndex() { return simpleObject()->m_animatedUVTranslationIndex; } // 256 / 0x134 + static void setAnimatedUVTranslationIndex(int value) { simpleObject()->m_animatedUVTranslationIndex = value; } + static bool getAnimatedUVTranslationReverse() // 260 / 0x138 + { return simpleObject()->m_animatedUVTranslationReverse; } + static void setAnimatedUVTranslationReverse(bool value) + { simpleObject()->m_animatedUVTranslationReverse = value; } + // The one int-typed flag: GET zero-extends the byte, SET stores `value != 0`. + static int getAnimatedUVRotation() { return simpleObject()->m_animatedUVRotation ? 1 : 0; } // 261 / 0x139 + static void setAnimatedUVRotation(int value) { simpleObject()->m_animatedUVRotation = value != 0; } + static int getAnimatedUVRotationIndex() { return simpleObject()->m_animatedUVRotationIndex; } // 272 / 0x144 + static void setAnimatedUVRotationIndex(int value) { simpleObject()->m_animatedUVRotationIndex = value; } + static const Math::Vec2& getAnimatedUVRotationScale() // 264 / 0x13C + { return simpleObject()->m_animatedUVRotationScale; } + static void setAnimatedUVRotationScale(const Math::Vec2& value) + { simpleObject()->m_animatedUVRotationScale = value; } + static float getAnimatedUVRotationRadius() { return simpleObject()->m_animatedUVRotationRadius; } // 276 / 0x148 + static void setAnimatedUVRotationRadius(float value) { simpleObject()->m_animatedUVRotationRadius = value; } + static bool getAnimatedUVRotationReverse() { return simpleObject()->m_animatedUVRotationReverse; } // 280 / 0x14C + static void setAnimatedUVRotationReverse(bool value) { simpleObject()->m_animatedUVRotationReverse = value; } + static bool getRotateAsAnimatedUV() { return simpleObject()->m_rotateAsAnimatedUV; } // 281 / 0x14D + static void setRotateAsAnimatedUV(bool value) { simpleObject()->m_rotateAsAnimatedUV = value; } + static const std::string& getRotateAsAnimatedUVObject() // 284 / 0x150 + { return simpleObject()->m_rotateAsAnimatedUVObject; } + static void setRotateAsAnimatedUVObject(const std::string& value) + { simpleObject()->m_rotateAsAnimatedUVObject = value; } + static bool getRotateAsAnimatedUVReverse() { return simpleObject()->m_rotateAsAnimatedUVReverse; } // 288 / 0x16C + static void setRotateAsAnimatedUVReverse(bool value) { simpleObject()->m_rotateAsAnimatedUVReverse = value; } + // Console setters update individual physics bits. Physics-type changes recompute the selected type; sleeping does not. static bool getIsSleeping() { return (simpleObject()->m_physicsFlags & 0x01) != 0; } static void setIsSleeping(bool value) @@ -560,6 +606,60 @@ BF2_CONSOLE_PROPERTY_FN(floaterMod, float, getActiveTemplate(CID_SimpleObjectTem BF2_CONSOLE_PROPERTY_FN(otherCollisionLod, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, BaseTemplateConsoleAccess::getOtherCollisionLod(), BaseTemplateConsoleAccess::setOtherCollisionLod, kObjTemplBaseConsoleTag) + +// The animated-UV properties, in shipped registration order, all under the physics sub-table's +// defaults ("ObjectTemplate", 2, 23 - the BF2.exe TU initializer constructs them at 0x84E96C.. +// 0x84EA8F right after that SetConsoleClassDefaults call). PE constructors 0x553485, 0x553599, +// 0x5536FA, 0x55386E, 0x5539E2, 0x553AF6, 0x553C0A, 0x553D24, 0x553E38, 0x553FAC, 0x5540C9, +// 0x5541DD, 0x5542F1, 0x55445E; executors 0x553543, 0x553684, 0x5537E5, 0x553959, 0x553AA0, +// 0x553BB4, 0x553CC8, 0x553DE2, 0x553F23, 0x55406A, 0x554187, 0x55429B, 0x55436E, 0x55451C. The +// ELF executors are ModuleWorldObjTemplBase.cpp ConsoleClass147..157, 159, 160 and 161 +// (0x8680310..0x8684030). Content authors these on vehicle parts (tank road wheels and tracks): +// without them SimpleObject never allocates its AnimatedUV, the geometry keeps identity UV +// matrices, and the BundledMesh _hasuvanimation_ shader samples the wrong texture region. +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslation, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslation(), + BaseTemplateConsoleAccess::setAnimatedUVTranslation, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationSpeed, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationSpeed(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationSpeed, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationSize, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationSize(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationSize, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationMax, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationMax(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationMax, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationIndex, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationIndex(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationIndex, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVTranslationReverse, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVTranslationReverse(), + BaseTemplateConsoleAccess::setAnimatedUVTranslationReverse, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotation, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotation(), + BaseTemplateConsoleAccess::setAnimatedUVRotation, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationIndex, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationIndex(), + BaseTemplateConsoleAccess::setAnimatedUVRotationIndex, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationScale, Vec2, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationScale(), + BaseTemplateConsoleAccess::setAnimatedUVRotationScale, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationRadius, float, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationRadius(), + BaseTemplateConsoleAccess::setAnimatedUVRotationRadius, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(animatedUVRotationReverse, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getAnimatedUVRotationReverse(), + BaseTemplateConsoleAccess::setAnimatedUVRotationReverse, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(rotateAsAnimatedUV, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getRotateAsAnimatedUV(), + BaseTemplateConsoleAccess::setRotateAsAnimatedUV, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(rotateAsAnimatedUVObject, std::string, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getRotateAsAnimatedUVObject(), + BaseTemplateConsoleAccess::setRotateAsAnimatedUVObject, kObjTemplBaseConsoleTag) +BF2_CONSOLE_PROPERTY_FN(rotateAsAnimatedUVReverse, bool, getActiveTemplate(CID_SimpleObjectTemplate) != 0, + BaseTemplateConsoleAccess::getRotateAsAnimatedUVReverse(), + BaseTemplateConsoleAccess::setRotateAsAnimatedUVReverse, kObjTemplBaseConsoleTag) + BF2_CONSOLE_PROPERTY_FN(physicsFrequency, int, getActiveTemplate(CID_SimpleObjectTemplate) != 0, BaseTemplateConsoleAccess::getPhysicsFrequency(), BaseTemplateConsoleAccess::setPhysicsFrequency, kObjTemplBaseConsoleTag) @@ -748,8 +848,9 @@ BF2_CONSOLE_FIELD(regulateRoll, Vec2, activeRotBundle(), m_r // Class-gated executors re-read the active template; geometry accesses the raw string field. // Preserve scale's reversed get/set slots and getConeAngle1 returning coneAngle2. // Range/angle setters report fatal errors above their caps (100 / 180); empty arguments are gets. -// RW-261: the earlier objectManager castsDynamicShadow row remains withheld, so this -// LightSource-specific row currently receives those calls. Registration order matters. +// castsDynamicShadow: the objectManager row of the same name (Scene/Object/ObjectManagerConsole.cpp) +// registers earlier and is active for every template, so console lookup never reaches this row; it +// is kept because the shipped images register it. Registration order matters. namespace { LightSourceTemplate* activeLightSource() diff --git a/Code/BF2/Game/Objects/Base/SimpleObject.cpp b/Code/BF2/Game/Objects/Base/SimpleObject.cpp index e7c03e564..8326be70a 100644 --- a/Code/BF2/Game/Objects/Base/SimpleObject.cpp +++ b/Code/BF2/Game/Objects/Base/SimpleObject.cpp @@ -2,6 +2,7 @@ // Contents: recovered SimpleObject construction, teardown, and bounded overrides. #include "SimpleObject.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "SimpleObjectTemplate.h" #include "../../../AI/AIInterface/AIInstance.h" @@ -17,7 +18,7 @@ #include "../../../Geom/DecalSystem/DecalObjectAccess.h" // ~SimpleObject's DecalObject slot 10 (release) #include "../../../Geom/DecalSystem/IDecalManager.h" // the ctor's object decal (createClient +0x14) #include "../../../Geom/IGeometryTemplate.h" -#if !DEDICATED && BF2_PLUGIN_ABI_NATIVE && defined(_M_IX86) +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) #include "../../../Geom/GeometryTemplateManager.h" #endif #include "../../../Physics/CollisionManager.h" @@ -57,11 +58,13 @@ namespace { # define BF2_SIMPLE_VCALL #endif +#if defined(_MSC_VER) template inline Fn simpleVslot(void* object, unsigned int byteOffset) { return reinterpret_cast((*reinterpret_cast(object))[byteOffset / 4]); } +#endif // The two renderer-geometry operations the animated-UV update drives. [INFERRED] names - the server // tree has no IGeometry declaration and neither slot is otherwise reachable, so only the physical @@ -70,22 +73,22 @@ void setGeometryAnimatedUVTranslation(void* geometry, int index, float first, fl { #if defined(_MSC_VER) const unsigned int slot = 0x90; -#else - const unsigned int slot = 0x94; -#endif typedef void (BF2_SIMPLE_VCALL* Fn)(void*, int, float, float); simpleVslot(geometry, slot)(geometry, index, first, second); +#else + geometry_part::setUvTranslation(geometry, index, first, second); // ELF +0x94 +#endif } void setGeometryAnimatedUVRotation(void* geometry, int index, const Mat4& transform) { #if defined(_MSC_VER) const unsigned int slot = 0x98; -#else - const unsigned int slot = 0x9C; -#endif typedef void (BF2_SIMPLE_VCALL* Fn)(void*, int, const Mat4&); simpleVslot(geometry, slot)(geometry, index, transform); +#else + geometry_part::setUvTransformation(geometry, index, &transform); // ELF +0x9C +#endif } // Leaves nearly unit vectors unchanged and collapses nearly zero vectors to zero. @@ -144,7 +147,8 @@ bool setGeometry(IObject* object, const std::string& geometry) if (!::dice::hfe::g_geometryTemplateManager) return false; -#if BF2_PLUGIN_ABI_NATIVE && defined(_M_IX86) +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) + // Native static builds call the audited IGeometryTemplateManager view (+0x18). geom::IGeometryTemplate* const geometryTemplate = static_cast( ::dice::hfe::g_geometryTemplateManager)->getTemplate(geometry); @@ -173,9 +177,13 @@ bool setGeometry(IObject* object, const std::string& geometry) // The geometry instance's +0x9C, handed the object it now belongs to. The geometry instance // interface is not modelled anywhere in this tree, so this stays a documented raw slot - the // same policy as ObjectDrawer's +0x18 and +0xCC. +#if defined(_MSC_VER) typedef void (__thiscall* SetGeometryOwnerFn)(void*, IObject*); reinterpret_cast( - (*reinterpret_cast(instance))[0x9C / sizeof(void*)])(instance, object); + (*reinterpret_cast(instance))[0x9C / 4])(instance, object); +#else + geometry_part::setOwnerObject(instance, object); // PE +0x9C +#endif instance->release(); return true; diff --git a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp index 5d90a4e44..85db06618 100644 --- a/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp +++ b/Code/BF2/Game/Objects/Base/SimpleObjectTemplate.cpp @@ -31,7 +31,7 @@ #include "../../../Sound/BfSound.h" #include "../../../Sound/SoundObjectTemplate.h" #endif -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) #include "../../../Geom/GeometryTemplateManager.h" #endif @@ -724,7 +724,7 @@ Vec3 SimpleObjectTemplate::getAnchorPos() const // [PLATFORM] Client calls getAnchorOffset before getAnchor; dedicated code uses the opposite order. Vec3 SimpleObjectTemplate::getAnchorPos() const { -#if defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) geom::IGeometryTemplateManager* const manager = static_cast(::dice::hfe::g_geometryTemplateManager); geom::IGeometryTemplate* const geometry = manager->getTemplate(m_geometry); diff --git a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp index ff32b8911..a7e228ffd 100644 --- a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp +++ b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.cpp @@ -89,10 +89,9 @@ void EffectBundleTemplate::preCache() const ObjectTemplate::preCache(); } -#if DEDICATED -// Dedicated ELF81FC410 / PE5F9250, read in full. The local stream is genuinely empty; -// its zero-byte write still occurs after a successful base writer and its result is checked. -// The client effect-specific writer remains a declaration-only frontier. +// Dedicated ELF81FC410 / PE5F9250 and client BF2.exe 0x6416E0 (table 0x8FF850 +0xF8), read in +// full and identical. The local stream is genuinely empty; its zero-byte write still occurs after a +// successful base writer and its result is checked. bool EffectBundleTemplate::makeMemberScript(const TemplateInfo* info, io::IStream* stream) { std::ostringstream out; @@ -101,7 +100,6 @@ bool EffectBundleTemplate::makeMemberScript(const TemplateInfo* info, io::IStrea const std::string text = out.str(); return stream->write(text.c_str(), static_cast(text.length())) == text.length(); } -#endif // substitute the effect-aware child info for Bundle's plain TemplateInfo. BundleTemplate::TemplateInfo* EffectBundleTemplate::createTemplateInfo(const std::string& name) diff --git a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h index c99cf01e3..3c603ebda 100644 --- a/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h +++ b/Code/BF2/Game/Objects/Fx/EffectBundleTemplate.h @@ -43,7 +43,7 @@ class EffectBundleTemplate : public BundleTemplate, public EffectProperties virtual IObject* createObject() const; // dedicated null; client PE 0x642680 virtual void preCache() const; // flags-gated grandparent call virtual bool makeScript(io::IStream*); // ELF/PE recovered - virtual bool makeMemberScript(const TemplateInfo*, io::IStream*); // dedicated ELF81FC410 / PE5F9250; client frontier + virtual bool makeMemberScript(const TemplateInfo*, io::IStream*); // ELF81FC410 / PE5F9250; client 6416E0 virtual TemplateInfo* createTemplateInfo(const std::string&); // news an EffectInfo virtual void setEmitFrequencyScaleFactorLowerBound(float); // the +0x30C store diff --git a/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp b/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp index 6b92c8dd8..eb6acc407 100644 --- a/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp +++ b/Code/BF2/Game/Objects/Fx/ExplosionEffectFlashBang.cpp @@ -1,6 +1,10 @@ // [INFERRED] path: see header. ELF 812C030..812CD34 / dedicated PE 620780..62113E. // All lifecycle, immediate/persistent/update instructions and both vtables read in full. #include "ExplosionEffectFlashBang.h" +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] This native provider is an explicit PE-order table. +#include "../../../RendMisc/NativePostProductionSlots.h" +#endif #include "PersistentExplosionEffectManager.h" #include "../IPlayer.h" #include "../ICameraObject.h" @@ -43,6 +47,9 @@ template Function postSlot(void* object, unsigned int peOrdinal) { #if defined(_MSC_VER) const unsigned int ordinal = peOrdinal; +#elif defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] No compiler-generated destructor is inserted here. + const unsigned int ordinal = dx9rend::native_post::slot(peOrdinal); #else const unsigned int ordinal = peOrdinal + 1; #endif diff --git a/Code/BF2/Game/Objects/Fx/Particle.cpp b/Code/BF2/Game/Objects/Fx/Particle.cpp index 1178c2dac..c878b81d9 100644 --- a/Code/BF2/Game/Objects/Fx/Particle.cpp +++ b/Code/BF2/Game/Objects/Fx/Particle.cpp @@ -3,6 +3,13 @@ // Geometry setup is client-only. Preserve NaN lifetime handling and fatal checks for invalid lifetime, // unsupported light-source attachment, rejected mesh attachment and invalid geometry part. +#if defined(__APPLE__) +#include "../../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] One native scale-interface declaration in every image. +#include "../../../Geom/IScaleable.h" +#endif +#endif #include "Particle.h" #include "ParticleTemplate.h" #include "Emitter.h" // fx2_emitter's world::Emitter (playParticleCollisionSound) @@ -41,11 +48,15 @@ namespace { // geom::IScaleable - the IBase quartet plus setScale at +0x10, exactly the view GenericProjectile.cpp // declares for the same IID. ELF 0x82090A4 / PE 0x64A1B1 call +0x10 with the address of a Vec3. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +using IScaleable = geom::IScaleable; +#else class IScaleable : public IBase { public: virtual void setScale(const Vec3& scale) = 0; }; +#endif // the RandomDistribution sampler, client order // BF2.exe 0x5E74B0 (121 B) on the process-global Random (ds:977F88; the ELF's Rand 0x8ABBCB0, this @@ -332,8 +343,13 @@ void Particle::init() // [PLATFORM] BF2.exe multiplies the x87 sample by the count (fimul), floors it as a // double (msvcr71 floor) and truncates; the ELF uses floorf on the float product. const float sample = sampleDistribution(partDistribution); +#if defined(__APPLE__) + const int part = bf2x87::toIntTruncate(std::floor(static_cast(sample) + * static_cast(partCount))); +#else const int part = static_cast(std::floor(static_cast(sample) * static_cast(partCount))); +#endif m_geometryPart = part; m_assignedGeometryPart = part; } @@ -436,7 +452,11 @@ void Particle::handleUpdate(float deltaTime, unsigned int) if (clamped > 1.0f) // PE `test ah, 41h; jne` / ELF fcmovnbe clamped = 1.0f; const float scaled = clamped * 100.0f; // 101 curve positions, 0..100 +#if defined(__APPLE__) + sample = bf2x87::toIntTruncate(scaled); // truncation (PE fistp under a chop control word) +#else sample = static_cast(scaled); // truncation (PE fistp under a chop control word) +#endif blend = scaled - static_cast(sample); } diff --git a/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp b/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp index 2e7d8ac7b..589cf0cd1 100644 --- a/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp +++ b/Code/BF2/Game/Objects/Game/AnimatedBundle.cpp @@ -1,6 +1,7 @@ // Animated-bundle lifecycle and skeleton/geometry synchronization. #include "AnimatedBundle.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../../../Animation/BoneAnimation/AnimationSystem.h" #include "../../../Animation/BoneAnimation/Skeleton.h" @@ -21,16 +22,13 @@ namespace { #if defined(_MSC_VER) # define BF2_AB_VCALL __thiscall const unsigned int kGeometryPoseSlot = 0x54; -#else -# define BF2_AB_VCALL -const unsigned int kGeometryPoseSlot = 0x58; -#endif // Geometry pose upload takes one matrix per bone and a count; the slot differs by platform. typedef void (BF2_AB_VCALL* GeometryPoseFn)(void*, void*, int); inline void* rawSlot(void* object, unsigned int byteOffset) { return (*reinterpret_cast(object))[byteOffset / 4]; } +#endif } // namespace AnimatedBundle::AnimatedBundle(const AnimatedBundleTemplate* objectTemplate) @@ -104,8 +102,13 @@ void AnimatedBundle::handleVisualUpdate(float deltaTime, float) } m_skeleton->transform(0, -1); // Upload one transformation matrix per bone. +#if defined(_MSC_VER) reinterpret_cast(rawSlot(geometry, kGeometryPoseSlot))( geometry, m_skeleton->m_transforms, m_skeleton->m_boneCount); +#else + geometry_part::setBoneTransforms(geometry, reinterpret_cast(m_skeleton->m_transforms), + m_skeleton->m_boneCount); // ELF +0x58 +#endif } // / 0x8167940, 74 B each: both systems, slots +0x30 / +0x38. diff --git a/Code/BF2/Game/Objects/Game/AntennaObject.cpp b/Code/BF2/Game/Objects/Game/AntennaObject.cpp index 22c937ef4..4b383ae3b 100644 --- a/Code/BF2/Game/Objects/Game/AntennaObject.cpp +++ b/Code/BF2/Game/Objects/Game/AntennaObject.cpp @@ -1,6 +1,7 @@ // Antenna-object lifecycle and visual simulation. #include "AntennaObject.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include #include @@ -21,15 +22,16 @@ namespace { #if defined(_MSC_VER) #define BF2_ANTENNA_GEOM_CALL __thiscall const unsigned int setBoneTransformsSlot = 0x54; -#else -#define BF2_ANTENNA_GEOM_CALL -const unsigned int setBoneTransformsSlot = 0x58; #endif void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, int boneCount) { +#if defined(_MSC_VER) typedef void (BF2_ANTENNA_GEOM_CALL* F)(void*, const Mat4*, int); reinterpret_cast( (*static_cast(geometry))[setBoneTransformsSlot / 4])(geometry, transforms, boneCount); +#else + geometry_part::setBoneTransforms(geometry, transforms, boneCount); // ELF +0x58 +#endif } #undef BF2_ANTENNA_GEOM_CALL diff --git a/Code/BF2/Game/Objects/Game/AreaObject.cpp b/Code/BF2/Game/Objects/Game/AreaObject.cpp index f691ecdbd..0d31fc34c 100644 --- a/Code/BF2/Game/Objects/Game/AreaObject.cpp +++ b/Code/BF2/Game/Objects/Game/AreaObject.cpp @@ -21,9 +21,9 @@ AreaObject::AreaObject(const AreaObjectTemplate* objectTemplate) AreaObject::~AreaObject() {} void AreaObject::init() { Bundle::init(); } -#if DEDICATED -// The dedicated images leave the observer at (0,0,0). Client camera/render work remains a -// declaration-only frontier; these definitions deliberately belong to the dedicated image. +// Both images measure from the observer at (0,0,0): the client body BF2.exe 0x5FF790 (table +// 0x8F3838 +0xA8) is the dedicated one, with the bounds test as a call (0x5CD130, inclusive +// min/max) instead of inline compares. void AreaObject::handleFrameUpdate(float) { const Mat4& absolute = getAbsoluteTransformation(); @@ -75,6 +75,8 @@ void AreaObject::handleFrameUpdate(float) } } +#if DEDICATED +// Dedicated-only: no client caller. void AreaObject::addAbsolutePoint() { const Vec3& position = getAbsolutePosition(); diff --git a/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp b/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp index 0f68ca1a4..5a3eb1582 100644 --- a/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp +++ b/Code/BF2/Game/Objects/Game/CommanderToolsManager.cpp @@ -30,6 +30,7 @@ #include #include #include +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -129,8 +130,8 @@ bool CommanderToolState::startScan() // half-open modulo expression are both shipped behavior. Vec3 CommanderToolState::CalculateRandomDropVehicleDeviation(int maximum, int minimum) { - const int distance = minimum + std::rand() % (maximum - minimum); - const double angle = static_cast(std::rand() % 360) / 360.0 * 6.28; + const int distance = minimum + bf2crt::rand() % (maximum - minimum); + const double angle = static_cast(bf2crt::rand() % 360) / 360.0 * 6.28; const double cosine = std::cos(angle); const double sine = std::sin(angle); diff --git a/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp b/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp index 645309719..71097e418 100644 --- a/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp +++ b/Code/BF2/Game/Objects/Game/DestroyableWindowsBundle.cpp @@ -1,6 +1,7 @@ // Path: [INFERRED]. Runtime/template pairing follows the ELF TU's global constructor. // Evidence: ELF 0x8175500..0x817693F / PE 0x58F610..0x58FFFF. #include "DestroyableWindowsBundle.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../TemplateLeaves.h" #include "../../IGame.h" #include "../../../Core/Ids.h" @@ -24,10 +25,6 @@ namespace { #if defined(_MSC_VER) #define BF2_WINDOWS_CALL __thiscall const unsigned int partSlot = 0x4C, getSecondarySlot = 0xCC, setSecondarySlot = 0xC8; -#else -#define BF2_WINDOWS_CALL -const unsigned int partSlot = 0x54, getSecondarySlot = 0xD0, setSecondarySlot = 0xCC; -#endif template F geometrySlot(void* geometry, unsigned int offset) { return reinterpret_cast((*static_cast(geometry))[offset / 4]); @@ -48,6 +45,13 @@ void setPartTransformation(void* geometry, const Mat4& matrix, int part) geometrySlot(geometry, partSlot)(geometry, matrix, part); } #undef BF2_WINDOWS_CALL +#else +// Non-MSVC: the named geometry_part operations (ELF +0x54 / +0xD0 / +0xCC). +void* secondaryGeometry(void* geometry) { return geometry_part::getNextGeometry(geometry); } +void setSecondaryGeometry(void* geometry, void* secondary) { geometry_part::setNextGeometry(geometry, secondary); } +void setPartTransformation(void* geometry, const Mat4& matrix, int part) +{ geometry_part::setTransform(geometry, &matrix, part); } +#endif } DestroyableWindowsBundle::DestroyableWindowsBundle(const DestroyableWindowsBundleTemplate* objectTemplate) diff --git a/Code/BF2/Game/Objects/Game/EngineBase.h b/Code/BF2/Game/Objects/Game/EngineBase.h index cbd8b1b3e..b7934fd7c 100644 --- a/Code/BF2/Game/Objects/Game/EngineBase.h +++ b/Code/BF2/Game/Objects/Game/EngineBase.h @@ -60,6 +60,7 @@ class EngineBase : public RotationalBundle friend class Rotor; friend class EffectBundle; // client PE 0x641EB0 / ELF 0x81FB0B0 reads m_engineRunning friend class ::dice::hfe::EngineSound; // sway reads m_gear directly: ELF +0x1E8 / PE +0x200 + friend class ObjectSpawner; // the hold arm reads m_input (retail +0x1C4) directly protected: /* 0x1B0 */ const EngineTemplate* m_template; diff --git a/Code/BF2/Game/Objects/Game/ForceObject.cpp b/Code/BF2/Game/Objects/Game/ForceObject.cpp index c68190b88..52dd9845e 100644 --- a/Code/BF2/Game/Objects/Game/ForceObject.cpp +++ b/Code/BF2/Game/Objects/Game/ForceObject.cpp @@ -1,5 +1,8 @@ // Force-object lifecycle and input-driven force application. +#if defined(__APPLE__) +#include "../../../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "ForceObject.h" #include // FLT_EPSILON - the engine normalise rule @@ -85,8 +88,13 @@ void ForceObject::handleUpdate(float, unsigned int) { // getTickCount() is called before the multiply in the image (0x82A77F3), and the // cast is the ordinary truncating float->int (fistp under a round-to-zero control word). +#if defined(__APPLE__) + m_dword144 = WorldPref::getTickCount() + + bf2x87::toIntTruncate(30.0f * m_template->startDelay); +#else m_dword144 = WorldPref::getTickCount() + static_cast(30.0f * m_template->startDelay); +#endif return; } if (m_dword144 > WorldPref::getTickCount()) diff --git a/Code/BF2/Game/Objects/Game/Kit.cpp b/Code/BF2/Game/Objects/Game/Kit.cpp index ea7c9552f..f9e1144ee 100644 --- a/Code/BF2/Game/Objects/Game/Kit.cpp +++ b/Code/BF2/Game/Objects/Game/Kit.cpp @@ -18,6 +18,7 @@ #include "../IObjectTemplate.h" #include "../IPlayer.h" #include "../ItemContainerTemplate.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../ObjectLayoutAccess.h" // m_geometry (+0x38) - updateGeometry's gate #include // the shipped aborts #include // updateUnlockStatus' two working sets @@ -67,41 +68,46 @@ const unsigned int kGeometrySetGeomIndexSlot = 0x6C; const unsigned int kGeometryGetGeomIndexSlot = 0x70; const unsigned int kGeometryGetGeomCountSlot = 0x74; const unsigned int kGeometrySetBoneTransformsSlot = 0x54; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetIntFn)(void*, int); -typedef void (*GeometrySetBoneTransformsFn)(void*, const Mat4*, unsigned int); -const unsigned int kGeometrySetGeomIndexSlot = 0x70; -const unsigned int kGeometryGetGeomIndexSlot = 0x74; -const unsigned int kGeometryGetGeomCountSlot = 0x78; -const unsigned int kGeometrySetBoneTransformsSlot = 0x58; #endif +// Non-MSVC: the named geometry_part operations (ELF +0x70/+0x74/+0x78/+0x58). int geometryGetGeomCount(void* geometry) { if (!geometry) return 0; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); return reinterpret_cast( vtable[kGeometryGetGeomCountSlot / 4])(geometry); +#else + return geometry_part::getSubgeomCount(geometry); +#endif } int geometryGetGeomIndex(void* geometry) { if (!geometry) return 0; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); return reinterpret_cast( vtable[kGeometryGetGeomIndexSlot / 4])(geometry); +#else + return geometry_part::getSubgeom(geometry); +#endif } void geometrySetGeomIndex(void* geometry, int index) { if (!geometry) return; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); reinterpret_cast( vtable[kGeometrySetGeomIndexSlot / 4])(geometry, index); +#else + geometry_part::setSubgeom(geometry, index); +#endif } @@ -111,9 +117,13 @@ void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, unsigned { if (!geometry) return; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); reinterpret_cast( vtable[kGeometrySetBoneTransformsSlot / 4])(geometry, transforms, boneCount); +#else + geometry_part::setBoneTransforms(geometry, transforms, static_cast(boneCount)); +#endif } // removeAllKitItems - 0x8183ED0, 93 B. TU-local (the ELF's own anonymous namespace, keyed to diff --git a/Code/BF2/Game/Objects/Game/MaskObject.cpp b/Code/BF2/Game/Objects/Game/MaskObject.cpp index d02787f7e..bce367aac 100644 --- a/Code/BF2/Game/Objects/Game/MaskObject.cpp +++ b/Code/BF2/Game/Objects/Game/MaskObject.cpp @@ -1,5 +1,10 @@ // Path: [INFERRED] - see MaskObject.h. Every own body read in both dedicated images. #include "MaskObject.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../Geom/NativeGeometrySlots.h" +#endif #include "Soldier.h" #include "../IPlayer.h" #include "../../../Animation/BoneAnimation/Skeleton.h" @@ -75,12 +80,11 @@ void MaskObject::updateGeometryPosition(Soldier* soldier) #if defined(_MSC_VER) typedef void (__thiscall* GeometryPoseFn)(void*, void*, int); const unsigned int slot = 0x54 / 4; -#else - typedef void (*GeometryPoseFn)(void*, void*, int); - const unsigned int slot = 0x58 / 4; -#endif reinterpret_cast((*reinterpret_cast(m_geometry))[slot])( m_geometry, skeleton->m_transforms, skeleton->m_boneCount); +#else + geometry_part::setBoneTransforms(m_geometry, skeleton->m_transforms, skeleton->m_boneCount); // ELF +0x58 +#endif } } diff --git a/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp b/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp index d72943410..3b195ceca 100644 --- a/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp +++ b/Code/BF2/Game/Objects/Game/ObjectSpawner.cpp @@ -29,6 +29,7 @@ #include "../IPlayer.h" // getVehicle - moveIntersectingSoldiers' occupant test #include "../GameLogicComp/ArmorGLComp.h" // armorTemplateCanBeDestroyed #include "../GameLogicComp/ArmorGLCompTemplate.h" +#include "EngineBase.h" // m_input - the hold arm's engine test #include // sqrtf / fabsf #include @@ -321,12 +322,6 @@ inline IPlayerControlObject* pcoOf(IObject* object) return 0; } -// Reads the engine's current input from its fixed layout. -inline float engineInput(IObject* engine) -{ - return *reinterpret_cast(reinterpret_cast(engine) + 0x1C4); -} - inline Vec3 V3(float x, float y, float z) { Vec3 v; v.x = x; v.y = y; v.z = z; return v; } // Vec3 is an aggregate here inline float distanceBetween(const Vec3& a, const Vec3& b) @@ -472,7 +467,10 @@ void ObjectSpawner::handleUpdate(float dt, unsigned int) { IObject* engine = 0; getEngineFromChildsAndSiblings(held, engine); - if (!engine || fabsf(engineInput(engine)) >= 0.1f) // flt_888CA90 + // The CID_EngineTemplate object is an EngineBase; the PE reads m_input at retail + // +0x1C4. The named member, because this build's layout is not retail's (m_input + // sits at +0x1D0 on x86 here). flt_888CA90 = 0.1. + if (!engine || fabsf(static_cast(engine)->m_input) >= 0.1f) release = true; } if (release) diff --git a/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp b/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp index 222c4c29b..0e1259a4b 100644 --- a/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp +++ b/Code/BF2/Game/Objects/Game/PlayerControlObjectHelpers.cpp @@ -22,6 +22,8 @@ #include "../../../AI/AIInterface/SingletonServer.h" // BFSingletonServer::m_iaiPlayerCourier #include "../../../AI/AIInterface/IAIPlayerCourier.h" // ds:0x8AC35A0 +0x08 - the bot's order #include // the distance +#include // [TEMP] BF2_ENTRY_TRACE +#include // [TEMP] BF2_ENTRY_TRACE #include #if defined(_MSC_VER) @@ -311,6 +313,20 @@ void findPlayerInputObjects(IObject* root, std::list& out, bool stopAt // Returns the closest usable entry point matching the requested template, or null. // Filters by distance, armor, team and line of sight, preferring empty seats over bot occupants. // AI entry uses its own radius and vehicle rules. +#if !defined(_WIN32) +// [TEMP] BF2_ENTRY_TRACE=1: the per-candidate gate results (vehicle-entry diagnosis, no behaviour). +// [RETIRE-WHEN: vehicle-entry-diagnosed] +static bool epTraceArmed() +{ + static const bool armed = std::getenv("BF2_ENTRY_TRACE") != 0; + return armed; +} +#define BF2_EP_TRACE(...) do { if (player && !player->getIsAIPlayer() && epTraceArmed()) { \ + std::fprintf(stderr, "[ENTRY] " __VA_ARGS__); std::fputc('\n', stderr); std::fflush(stderr); } } while (0) +#else +#define BF2_EP_TRACE(...) do { } while (0) +#endif + IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int team, IPlayer* player, bool useEntryPointRadius, bool acceptAiOccupied, bool requireLineOfSight) @@ -349,6 +365,7 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t for (unsigned int i = 0; i < scratch.size(); ++i) candidates.push_back(scratch[i]); + BF2_EP_TRACE("grid: %u objects within %.1f m", (unsigned int) candidates.size(), (double) radius); for (unsigned int c = 0; c < candidates.size(); ++c) { IObject* const object = candidates[c]; @@ -383,6 +400,9 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t { // the field is read RAW in both ports (0x81A35AE: `fld dword ptr [eax+164h]`); // EntryPointTemplate has no getter symbol of its own. + BF2_EP_TRACE("entry point %p at %.1f/%.1f/%.1f dist %.2f entryRadius %.2f", (void*) object, + (double) to.x, (double) to.y, (double) to.z, (double) distance, + (double) static_cast(L::objectTemplate(object))->m_entryRadius); if (distance > static_cast( L::objectTemplate(object))->m_entryRadius) // +0x164 continue; @@ -403,7 +423,10 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t break; } if (armor && armor->isDestroyed()) // +0x54 + { + BF2_EP_TRACE(" refused: destroyed"); continue; + } // gate 6: whose vehicle is it // the `vehicle ?` test is redundant - it was proved non-null above - but retail compiles @@ -421,7 +444,10 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t } // NO NULL guard ON `owner`, as shipped - see the header block. if (team != owner->getTeam() && owner->getTeam() != 0) // +0x98 twice + { + BF2_EP_TRACE(" refused: team %d != owner team %d", team, owner->getTeam()); continue; + } // gate 7: can the player actually see it if (!isAI && requireLineOfSight) @@ -432,7 +458,10 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t Vec3 rayFrom; rayFrom.x = position.x; rayFrom.y = position.y; rayFrom.z = position.z; if (checkIfRayHitAnyObject(rayFrom, rayTo, root, true)) // ; object-line LOS live + { + BF2_EP_TRACE(" refused: line of sight"); continue; + } } // the seat sweep @@ -446,6 +475,7 @@ IPlayerControlObject* BFfindEntryPoint(const Vec3& position, float radius, int t aiRequestedVehicle != candidate->queryInterface(IID_IObject)) // +0x0C continue; + BF2_EP_TRACE(" seat %d occupied=%d", seat->first, candidate->isOccupied() ? 1 : 0); if (!candidate->isOccupied()) // +0x18 { best = candidate; diff --git a/Code/BF2/Game/Objects/Game/Rotor.cpp b/Code/BF2/Game/Objects/Game/Rotor.cpp index 9b5740cb1..f322e27ad 100644 --- a/Code/BF2/Game/Objects/Game/Rotor.cpp +++ b/Code/BF2/Game/Objects/Game/Rotor.cpp @@ -1,6 +1,7 @@ // Rotor lifecycle and visual rotation. #include "Rotor.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include @@ -21,10 +22,6 @@ namespace { #if defined(_MSC_VER) #define BF2_ROTOR_GEOM_CALL __thiscall const unsigned int setGeomSlot = 0x6C, getGeomCountSlot = 0x74; -#else -#define BF2_ROTOR_GEOM_CALL -const unsigned int setGeomSlot = 0x70, getGeomCountSlot = 0x78; -#endif template F geometrySlot(void* geometry, unsigned int offset) { return reinterpret_cast((*static_cast(geometry))[offset / 4]); @@ -40,6 +37,11 @@ int getGeometryGeomCount(void* geometry) return geometrySlot(geometry, getGeomCountSlot)(geometry); } #undef BF2_ROTOR_GEOM_CALL +#else +// Non-MSVC: the named geometry_part operations (ELF +0x70 / +0x78). +void setGeometryGeom(void* geometry, int geom) { geometry_part::setSubgeom(geometry, geom); } +int getGeometryGeomCount(void* geometry) { return geometry_part::getSubgeomCount(geometry); } +#endif } // Bundle(template); the vptrs; the block (m_geomState -1, m_spinDownTimer 3.0, diff --git a/Code/BF2/Game/Objects/Game/Soldier.cpp b/Code/BF2/Game/Objects/Game/Soldier.cpp index f06d415ab..1f0c557da 100644 --- a/Code/BF2/Game/Objects/Game/Soldier.cpp +++ b/Code/BF2/Game/Objects/Game/Soldier.cpp @@ -5,6 +5,7 @@ #include "Soldier.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include #include @@ -335,20 +336,26 @@ anim::IAnimationSystem* animationSystemCreateInstance(void* animationSystemTempl // Forwards field of view to the renderer-owned geometry. // Uses the PE calling convention and slot because the full geometry interface is not declared here. +#if defined(_MSC_VER) void geometrySlot10(void* geometry, float fov) { - typedef void(__fastcall* SetFovFn)(void*, void*, float); + typedef void(__thiscall* SetFovFn)(void*, float); reinterpret_cast( - (*reinterpret_cast(geometry))[0x10 / sizeof(void*)])(geometry, 0, fov); + (*reinterpret_cast(geometry))[0x10 / 4])(geometry, fov); } void geometrySlotD8(void* geometry, bool flag) { - typedef void(__fastcall* Fn)(void*, void*, unsigned int); + typedef void(__thiscall* Fn)(void*, unsigned int); reinterpret_cast( - (*reinterpret_cast(geometry))[0xD4 / sizeof(void*)])( - geometry, 0, flag ? 1u : 0u); + (*reinterpret_cast(geometry))[0xD4 / 4])( + geometry, flag ? 1u : 0u); } +#else +// Non-MSVC: the named geometry_part operations (PE +0x10 / +0xD4). +void geometrySlot10(void* geometry, float fov) { geometry_part::setFov(geometry, fov); } +void geometrySlotD8(void* geometry, bool flag) { geometry_part::setFirstPerson(geometry, flag ? 1u : 0u); } +#endif // Registers animation templates by name; file loading is deferred to the core event. void* animationSystemManagerGet(const std::string& name) @@ -362,20 +369,26 @@ void animationSystemManagerRelease(void* systemTemplate) } // Supplies a borrowed bone-transform palette to the kit geometry through its renderer interface. +#if defined(_MSC_VER) void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, int boneCount) // PE +0x54 { - typedef void(__fastcall* SetBonesFn)(void*, void*, const Mat4*, unsigned int); + typedef void(__thiscall* SetBonesFn)(void*, const Mat4*, unsigned int); reinterpret_cast( - (*reinterpret_cast(geometry))[0x54 / sizeof(void*)])( - geometry, 0, transforms, static_cast(boneCount)); + (*reinterpret_cast(geometry))[0x54 / 4])( + geometry, transforms, static_cast(boneCount)); } void geometrySlot7C(void* geometry, int a) // PE +0x78 { - typedef void*(__fastcall* SetLodFn)(void*, void*, int); + typedef void*(__thiscall* SetLodFn)(void*, int); reinterpret_cast( - (*reinterpret_cast(geometry))[0x78 / sizeof(void*)])(geometry, 0, a); + (*reinterpret_cast(geometry))[0x78 / 4])(geometry, a); } +#else +void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, int boneCount) +{ geometry_part::setBoneTransforms(geometry, transforms, boneCount); } // PE +0x54 +void geometrySlot7C(void* geometry, int a) { geometry_part::setLod(geometry, a); } // PE +0x78 +#endif // AI events are available only when a published AI instance reports a bots game. inline bool aiConnectionIsUp() @@ -3852,6 +3865,20 @@ void Soldier::handlePlayerInput(IPlayer* player, const io::PlayerInput& input, m_pitchDeltaThisTick = pitchDelta; // +0x298 m_yawDeltaThisTick = yawDelta; // +0x294 m_lookUpDownAngle += pitchDelta; +#if !defined(_WIN32) + { + // [TEMP] BF2_LOOK_TRACE=1: per-call pitch inputs (sustained-fire view climb diagnosis). + // [RETIRE-WHEN: view-climb-diagnosed] + static const bool lookTrace = std::getenv("BF2_LOOK_TRACE") != 0; + if (lookTrace && getOccupingPlayer() && (pitchDelta != 0.0f || yawDelta != 0.0f)) + { + std::fprintf(stderr, "[LOOK] tick=%d flags=%u lookY=%.4f recoilP=%.4f lookX=%.4f recoilY=%.4f -> upDown=%.3f camPitch=%.3f\n", + (int) WorldPref::getTickCount(), flags, (double) lookY, (double) (pitchDelta - lookY), + (double) lookX, (double) (yawDelta - lookX), (double) m_lookUpDownAngle, (double) m_cameraPitch); + std::fflush(stderr); + } + } +#endif // 11. the yaw pipeline // the vehicle's own yaw limits, if he is riding one diff --git a/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp b/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp index 674deef3f..2eeb84320 100644 --- a/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp +++ b/Code/BF2/Game/Objects/Game/SoldierAnimation.cpp @@ -45,6 +45,7 @@ #include "../RotationalBundleTemplate.h" #include "RotationalBundle.h" // getCurrentRotation #include "Kit.h" // reviveAnimations' geometry gate +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -59,38 +60,37 @@ typedef object_detail::LayoutAccess L; // the raw Object offsets, as Soldier // reviveAnimations tells the carried kit's geometry that the soldier has returned to the prone // pose. geom::IGeometry is still unrecovered, but this one seam is bounded in both shipped x86 // images: handleMessage is PE/MSVC +0x60 and ELF/Itanium +0x64 (the destructor-pair shift). +// The slot follows the compiler's destructor ABI, so native MSVC x64 takes the PE arm too. void geometryHandleMessage(void* geometry, TemplateMessage message, void* payload) { -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) typedef void (__thiscall *Method)(void*, TemplateMessage, void*); - const unsigned int slot = 0x60 / sizeof(void*); -#else - typedef void (*Method)(void*, TemplateMessage, void*); - const unsigned int slot = 0x64 / sizeof(void*); -#endif + const unsigned int slot = 0x60 / 4; void** const vtable = *reinterpret_cast(geometry); reinterpret_cast(vtable[slot])(geometry, message, payload); +#else + // RendDX9 SkinnedMesh +0x60 (0x101A67E0) is (int part, byte flag): `cmp byte [ebp+0xC],0`, + // then +0x17C = part or -1. The second dword's low byte is the flag (ELF +0x64). + geometry_part::setExcludedPart(geometry, static_cast(message), + (reinterpret_cast(payload) & 0xFFu) != 0); +#endif } // Renderer dispatch for field of view, geometry selection and bone palettes. -// Explicit PE/ELF slot constants account for their differing destructor layouts. -#if defined(_MSC_VER) && defined(_M_IX86) +// Explicit PE/ELF slot constants account for their differing destructor layouts; MSVC x64 keeps +// the MSVC (PE) table order. +#if defined(_MSC_VER) #define BF2_SOLDIER_GEOM_CALL __thiscall const unsigned int kGeometrySetFovSlot = 0x10; const unsigned int kGeometrySetGeomIndexSlot = 0x6C; const unsigned int kGeometrySetBoneTransformsSlot = 0x54; const unsigned int kGeometryGatherUsedBonesSlot = 0x58; -#else -#define BF2_SOLDIER_GEOM_CALL -const unsigned int kGeometrySetFovSlot = 0x10; -const unsigned int kGeometrySetGeomIndexSlot = 0x70; -const unsigned int kGeometrySetBoneTransformsSlot = 0x58; -const unsigned int kGeometryGatherUsedBonesSlot = 0x5C; #endif +#if defined(_MSC_VER) template F geometrySlot(void* geometry, unsigned int offset) { - return reinterpret_cast((*static_cast(geometry))[offset / sizeof(void*)]); + return reinterpret_cast((*static_cast(geometry))[offset / 4]); } void geometrySetFov(void* geometry, float fov) @@ -119,6 +119,14 @@ void geometryGatherUsedBones(void* geometry, std::vector* out) geometrySlot(geometry, kGeometryGatherUsedBonesSlot)(geometry, out); } #undef BF2_SOLDIER_GEOM_CALL +#else +// Non-MSVC: the named geometry_part operations (ELF +0x10 / +0x70 / +0x58 / +0x5C). +void geometrySetFov(void* geometry, float fov) { geometry_part::setFov(geometry, fov); } +void geometrySetGeomIndex(void* geometry, int geom) { geometry_part::setSubgeom(geometry, geom); } +void geometrySetBoneTransforms(void* geometry, const Mat4* transforms, unsigned int boneCount) +{ geometry_part::setBoneTransforms(geometry, transforms, static_cast(boneCount)); } +void geometryGatherUsedBones(void* geometry, std::vector* out) { geometry_part::gatherUsedBones(geometry, out); } +#endif // Soldier animation and physics console tuning values. float* const rd_expForceMod = Vars::getFloat("rd_expForceMod", 1.0f); // applyExplosionForce @@ -900,12 +908,12 @@ void Soldier::updateThirdPersonAnimations(float dt, bool updateGeometry) } else { - const float roll = static_cast(rand() % 16) * 0.0625f; + const float roll = static_cast(bf2crt::rand() % 16) * 0.0625f; m_soldierLookIdleTime = roll * *soldier_lookIdleTime; if (roll >= 0.5f) { m_headPosition.z = *soldier_lookIdleAngle; - if ((rand() & 1) != 0) + if ((bf2crt::rand() & 1) != 0) m_headPosition.z = -m_headPosition.z; } else diff --git a/Code/BF2/Game/Objects/Game/SupplyDepot.cpp b/Code/BF2/Game/Objects/Game/SupplyDepot.cpp index 886815483..57ec5435c 100644 --- a/Code/BF2/Game/Objects/Game/SupplyDepot.cpp +++ b/Code/BF2/Game/Objects/Game/SupplyDepot.cpp @@ -16,6 +16,7 @@ #include #include #include +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { namespace world { namespace { @@ -123,9 +124,9 @@ SupplyDepot::SupplyDepot(const SupplyDepotTemplate* objectTemplate) { #if defined(_MSC_VER) // [PLATFORM] PE 0x573A96 multiplies by float bits 0x3D088889; ELF divides by 30. - m_lastUpdate = static_cast(std::rand() % 30) * 0.033333335f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) * 0.033333335f; #else - m_lastUpdate = static_cast(std::rand() % 30) / 30.0f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) / 30.0f; #endif Object::updateFlags(0x800, 2); } @@ -367,9 +368,9 @@ void SupplyDepot::reset() m_hasRepair = !m_repair.empty(); #if defined(_MSC_VER) // uses the same multiply as its constructor; ELF uses division. - m_lastUpdate = static_cast(std::rand() % 30) * 0.033333335f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) * 0.033333335f; #else - m_lastUpdate = static_cast(std::rand() % 30) / 30.0f; + m_lastUpdate = static_cast(bf2crt::rand() % 30) / 30.0f; #endif } bool SupplyDepot::getWorkOnVehicles() { return m_depotTemplate->m_workOnVehicles; } diff --git a/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp b/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp index f8aed79bd..1f9714dfd 100644 --- a/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp +++ b/Code/BF2/Game/Objects/GameLogicComp/ArmorGLComp.cpp @@ -85,21 +85,19 @@ typedef void (__thiscall *GeometrySetIntFn)(void*, int); const unsigned int kGeometrySetGeomIndexSlot = 0x6C; const unsigned int kGeometryGetGeomIndexSlot = 0x70; const unsigned int kGeometryGetGeomCountSlot = 0x74; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetIntFn)(void*, int); -const unsigned int kGeometrySetGeomIndexSlot = 0x70; -const unsigned int kGeometryGetGeomIndexSlot = 0x74; -const unsigned int kGeometryGetGeomCountSlot = 0x78; #endif int geometryGetGeomCount(void* geometry) { if (!geometry) return 0; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); return reinterpret_cast( vtable[kGeometryGetGeomCountSlot / 4])(geometry); +#else + return geometry_part::getSubgeomCount(geometry); // ELF +0x78 +#endif } int geometryGetPartCount(void* geometry) @@ -113,9 +111,6 @@ int geometryGetPartCount(void* geometry) #ifdef _MSC_VER const unsigned int kGeometryShowDamageSlot = 0xC0; typedef void (__thiscall *GeometryShowDamageFn)(void*, int, int); -#else -const unsigned int kGeometryShowDamageSlot = 0xC4; -typedef void (*GeometryShowDamageFn)(void*, int, int); #endif void geometryInitDamageState(void* geometry) @@ -133,9 +128,13 @@ void geometryShowDamage(void* geometry, int a, int b) if (!geometry) return; +#ifdef _MSC_VER void** const vtable = *reinterpret_cast(geometry); reinterpret_cast( vtable[kGeometryShowDamageSlot / 4])(geometry, a, b); +#else + geometry_part::updateFlags(geometry, static_cast(a), static_cast(b)); // ELF +0xC4 +#endif } void geometrySetPartTransform(void* geometry, const Mat4* transform, int part) diff --git a/Code/BF2/Game/Objects/GeometryPartAccess.h b/Code/BF2/Game/Objects/GeometryPartAccess.h index b886a3eff..94f0c51fb 100644 --- a/Code/BF2/Game/Objects/GeometryPartAccess.h +++ b/Code/BF2/Game/Objects/GeometryPartAccess.h @@ -8,8 +8,11 @@ #include "../../Math/Mat4.h" #include #include +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Static native geometry providers retain explicit PE tables. +#include "../../Geom/NativeGeometrySlots.h" +#endif #if defined(_MSC_VER) && defined(_M_IX86) -#include "../../../RendDX9Abi/Vc71String.h" #define BF2_GEOMETRY_PART_CALL __thiscall #else #define BF2_GEOMETRY_PART_CALL @@ -21,6 +24,9 @@ template inline Function slot(void* geometry, unsigned int pe, u { #if defined(_MSC_VER) const unsigned int offset = pe; +#elif defined(BF2_STATIC_PLUGINS) + // [CHOSEN, not recovered] This is a function table, not an ELF class vtable. + const unsigned int offset = 4 * geom::native_geometry::slot(pe, elf); #else const unsigned int offset = elf; #endif @@ -67,19 +73,81 @@ inline void* getTemplate(void* geometry) return slot(geometry, 0x38, 0x3C)(geometry); } +// Named geometry-instance operations used by game code. Native static builds select the named +// ordinal of the renderer's explicit PE-order tables (Geom/NativeGeometrySlots.h, checked by +// tools/macos/vtable_audit.py against BundledMesh/StaticMesh/SkinnedMesh/MeshParticleMesh); +// MSVC keeps the PE byte offset and other non-MSVC builds the ELF one. Callers never index a +// geometry table themselves (the gate's raw-slot scan rejects new sites). +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +#define BF2_GEOMETRY_OP(pe, elf, name) slot(geometry, 4 * geom::native_geometry::name, 4 * geom::native_geometry::name) +#else +#define BF2_GEOMETRY_OP(pe, elf, name) slot(geometry, pe, elf) +#endif +inline float getBoundingRadius(void* geometry) +{ typedef float (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x44, 0x48, GetBoundingRadius)(geometry); } +inline void setFov(void* geometry, float fov) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, float); BF2_GEOMETRY_OP(0x10, 0x10, SetFov)(geometry, fov); } +inline float getFov(void* geometry) +{ typedef float (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x14, 0x14, GetFov)(geometry); } +inline void setGeometryTransform(void* geometry, const Mat4* transform) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, const Mat4*); BF2_GEOMETRY_OP(0x50, 0x50, SetGeometryTransform)(geometry, transform); } +inline void setBoneTransforms(void* geometry, const Mat4* transforms, int count) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, const Mat4*, int); BF2_GEOMETRY_OP(0x54, 0x58, SetBoneTransforms)(geometry, transforms, count); } +// SkinnedMesh +0x58: appends the used bone indices to the engine's int vector (opaque here). +inline void gatherUsedBones(void* geometry, void* intVector) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, void*); BF2_GEOMETRY_OP(0x58, 0x5C, GatherUsedBones)(geometry, intVector); } +inline void setExcludedPart(void* geometry, int part, bool enable) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int, bool); BF2_GEOMETRY_OP(0x60, 0x64, SetExcludedPart)(geometry, part, enable); } +inline void setSubgeom(void* geometry, int index) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int); BF2_GEOMETRY_OP(0x6C, 0x70, SetSubgeom)(geometry, index); } +inline int getSubgeom(void* geometry) +{ typedef int (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x70, 0x74, GetSubgeom)(geometry); } +inline int getSubgeomCount(void* geometry) +{ typedef int (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0x74, 0x78, GetSubgeomCount)(geometry); } +inline void setUvTranslation(void* geometry, int index, float x, float y) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int, float, float); BF2_GEOMETRY_OP(0x90, 0x94, SetUvTranslation)(geometry, index, x, y); } +inline void setUvTransformation(void* geometry, int index, const Mat4* transform) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int, const Mat4*); BF2_GEOMETRY_OP(0x98, 0x9C, SetUvTransformation)(geometry, index, transform); } +inline void* setOwnerObject(void* geometry, void* object) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*, void*); return BF2_GEOMETRY_OP(0x9C, 0x9C, SetOwnerObject)(geometry, object); } +inline void updateFlags(void* geometry, unsigned int set, unsigned int clear) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, unsigned int, unsigned int); BF2_GEOMETRY_OP(0xC0, 0xC4, UpdateFlags)(geometry, set, clear); } +inline void* setNextGeometry(void* geometry, void* next) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*, void*); return BF2_GEOMETRY_OP(0xC8, 0xCC, SetNextGeometry)(geometry, next); } +inline void* getNextGeometry(void* geometry) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0xCC, 0xD0, GetNextGeometry)(geometry); } +inline void setFirstPerson(void* geometry, unsigned int value) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, unsigned int); BF2_GEOMETRY_OP(0xD4, 0xD8, SetFirstPerson)(geometry, value); } +inline void setLightSourceMask(void* geometry, int mask) +{ typedef void (BF2_GEOMETRY_PART_CALL* Function)(void*, int); BF2_GEOMETRY_OP(0xE0, 0xE4, SetLightSourceMask)(geometry, mask); } +inline int getLightSourceMask(void* geometry) +{ typedef int (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_GEOMETRY_OP(0xE4, 0xE8, GetLightSourceMask)(geometry); } +#undef BF2_GEOMETRY_OP + +#if defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS) +// Renderer-internal reads (DecalShadowManager::addShadow, PE 0x10127260). No ELF image calls these +// slots, so no ELF offset is attested and they exist only where the PE table order applies. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +#define BF2_RENDERER_GEOMETRY_OP(pe, name) slot(geometry, 4 * geom::native_geometry::name, 4 * geom::native_geometry::name) +#else +#define BF2_RENDERER_GEOMETRY_OP(pe, name) slot(geometry, pe, pe) +#endif +// +0x28: the shadow record the geometry draws into (StaticMesh +0x34C, SkinnedMesh +0x33C, +// BundledMesh +0x2B4). +inline void* getShadowRecord(void* geometry) +{ typedef void* (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_RENDERER_GEOMETRY_OP(0x28, GetShadowRecord)(geometry); } +// +0x48: the stored world transform, or the shared identity when none was set. +inline const Mat4* getGeometryTransform(void* geometry) +{ typedef const Mat4* (BF2_GEOMETRY_PART_CALL* Function)(void*); return BF2_RENDERER_GEOMETRY_OP(0x48, GetGeometryTransform)(geometry); } +#undef BF2_RENDERER_GEOMETRY_OP +#endif + inline bool templateNameEquals(void* objectTemplate, const char* name) { -#if defined(_MSC_VER) && defined(_M_IX86) - // MeshTemplate::getName returns vc71::string even in the native renderer. Read its - // borrowed view without creating/destroying a string or importing the renderer allocator. - typedef const vc71::string& (BF2_GEOMETRY_PART_CALL* Function)(void*); - const vc71::string& actual = slot(objectTemplate, 0x18, 0x18)(objectTemplate); - const std::size_t length = std::strlen(name); - return actual.size() == length && std::memcmp(actual.c_str(), name, length) == 0; -#else - typedef const std::string& (*Function)(void*); + // MeshTemplate::getName (+0x18) returns the renderer's std::string: the client and its + // plugins share one STL (issue #7). + typedef const std::string& (BF2_GEOMETRY_PART_CALL* Function)(void*); return slot(objectTemplate, 0x18, 0x18)(objectTemplate) == name; -#endif } } } } } diff --git a/Code/BF2/Game/Objects/IStrategicObjectComp.h b/Code/BF2/Game/Objects/IStrategicObjectComp.h index 7c582eb9a..037f57709 100644 --- a/Code/BF2/Game/Objects/IStrategicObjectComp.h +++ b/Code/BF2/Game/Objects/IStrategicObjectComp.h @@ -4,7 +4,9 @@ #ifndef GAME_OBJECTS_ISTRATEGICOBJECTCOMP_H // [INFERRED] guard style #define GAME_OBJECTS_ISTRATEGICOBJECTCOMP_H +#include #include +#include #include "IObjectComponent.h" #include "../../Math/Vec3.h" @@ -13,6 +15,11 @@ namespace dice { namespace hfe { namespace world { +#if defined(_M_IX86) +static_assert(std::is_same::value, + "x86 strategic icon handles keep the retail int signatures"); +#endif + class IStrategicObjectComp : public IObjectComponent { public: @@ -21,9 +28,10 @@ class IStrategicObjectComp : public IObjectComponent virtual const std::string& getIntactIconName() = 0; // +0x3C virtual const std::string& getDestroyedIconName() = 0; // +0x40 // 77E500 signed-compares both results with zero and stores the same dword directly into - // MapIconRecord::texture. They are integer texture handles, despite the historical Ptr names. - virtual int getIntactIconPtr() = 0; // +0x44 - virtual int getDestroyedIconPtr() = 0; // +0x48 + // MapIconRecord::texture. They are integer texture handles, despite the historical Ptr names; + // std::intptr_t is int on x86 (unchanged mangling) and pointer-wide on native x64. + virtual std::intptr_t getIntactIconPtr() = 0; // +0x44 + virtual std::intptr_t getDestroyedIconPtr() = 0; // +0x48 virtual int getPart() = 0; // +0x4C // Index of the holder assigned by GameLogic. virtual int getIndex() = 0; // +0x50 diff --git a/Code/BF2/Game/Objects/IVehicleHudComp.h b/Code/BF2/Game/Objects/IVehicleHudComp.h index 14d6d41ec..e6420feaf 100644 --- a/Code/BF2/Game/Objects/IVehicleHudComp.h +++ b/Code/BF2/Game/Objects/IVehicleHudComp.h @@ -3,6 +3,7 @@ #ifndef GAME_OBJECTS_IVEHICLEHUDCOMP_H // [INFERRED] guard style #define GAME_OBJECTS_IVEHICLEHUDCOMP_H +#include #include #include "IObjectComponent.h" #include "VehicleHudCompTemplate.h" // VehicleHudInfo / VehicleHudIcons @@ -21,9 +22,10 @@ class IVehicleHudComp : public IObjectComponent // HUD78B1E0 dispatches its getInfo slot. This was incorrectly chosen bool. virtual IPostProcessComp* getEnablePostProcessing(int) = 0; // +0x3C virtual std::string getVehicleIcon(int) = 0; // +0x40 hidden sret - virtual int getVehicleIconPtr(int) = 0; // +0x44 vector + // Texture handles: std::intptr_t is int on x86 (unchanged mangling), pointer-wide on x64. + virtual std::intptr_t getVehicleIconPtr(int) = 0; // +0x44 vector virtual std::string getAbilityIcon(int) = 0; // +0x48 hidden sret - virtual int getAbilityIconPtr(int) = 0; // +0x4C vector + virtual std::intptr_t getAbilityIconPtr(int) = 0; // +0x4C vector virtual bool getShowOnCamMode(int) = 0; // +0x50 movzx eax,al virtual void playingPantingSound(bool) = 0; // +0x54 virtual bool getIsPlayingPantingSound() = 0; // +0x58 [CHOSEN ret] diff --git a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp index 8cded68d5..f4faa21bc 100644 --- a/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp +++ b/Code/BF2/Game/Objects/Projectiles/GenericProjectile.cpp @@ -5,6 +5,15 @@ // Specialized client/effect branches retain named [FRONTIER] boundaries. #include "GenericProjectile.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] One native scale-interface declaration in every image. +#include "../../../Geom/IScaleable.h" +#endif +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../Geom/NativeGeometrySlots.h" +#endif #include // FLT_EPSILON #include @@ -58,11 +67,15 @@ namespace { // IScaleable consists of the IBase quartet followed by setScale. Both activate and updateTracer // query exactly this IID before making the typed call at +0x10. +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +using IScaleable = geom::IScaleable; +#else class IScaleable : public IBase { public: virtual void setScale(const Vec3&) = 0; }; +#endif float unitRandom(Random& random) { @@ -109,13 +122,13 @@ IObjectTemplate* getGeometryTemplate(IBase* geometry) // ordinal, including its single destructor slot, with eight-byte entries. enum { GetTemplateIndex = 0x38 / 4 }; typedef IObjectTemplate* (__thiscall *GetTemplateFn)(void*); -#else - enum { GetTemplateIndex = 0x3C / 4 }; - typedef IObjectTemplate* (*GetTemplateFn)(void*); -#endif void** const vtable = *reinterpret_cast(geometry); GetTemplateFn const getTemplate = reinterpret_cast(vtable[GetTemplateIndex]); return getTemplate(geometry); +#else + // Non-MSVC: the named geometry_part operation (ELF +0x3C). + return static_cast(geometry_part::getTemplate(geometry)); +#endif } IPlayerControlObject* findPlayerControlObject(IObject* object) diff --git a/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp b/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp index 34d23482b..6be63b523 100644 --- a/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp +++ b/Code/BF2/Game/Objects/Projectiles/GenericProjectileTemplate.cpp @@ -11,7 +11,7 @@ #include "../../../Core/Ids.h" #include "../../IGameLogic.h" // gameLogic->addPreStoredTemplate - the 16-deep pre-store #include "../../../Geom/IGeometryTemplate.h" -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) #include "../../../Geom/GeometryTemplateManager.h" #endif @@ -46,7 +46,7 @@ void precacheTracerGeometry(IObjectTemplate* tracerTemplate) // Returns a borrowed geometry template through the legacy cache type. Requires the client manager. IObjectTemplate* lookupTracerGeometryTemplate(const std::string& name) { -#if defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && (defined(_MSC_VER) || defined(BF2_STATIC_PLUGINS)) geom::IGeometryTemplateManager* const manager = static_cast(::dice::hfe::g_geometryTemplateManager); return reinterpret_cast(manager->getTemplate(name)); diff --git a/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h b/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h index 36a5ae593..f7fe99735 100644 --- a/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h +++ b/Code/BF2/Game/Objects/RemoteControlledObjectTemplate.h @@ -12,6 +12,7 @@ namespace dice { namespace hfe { class GameLogic; +class ServerConnection; namespace world { class UAVVehicleManager; @@ -41,6 +42,7 @@ class RemoteControlledObjectTemplate : public BundleTemplate { public: friend class hfe::GameLogic; // the RCO registry reads rcType + friend class hfe::ServerConnection; // getSpecialCommanderObjects reads rcType friend class UAVVehicleManager; // UAV spawn/config reads the +0x188..+0x198 block friend class UAVVehicle; // the live drone reads uavVehicleSpeed each tick friend class CommanderToolsManager; // commander-toy aggregation reads rcType diff --git a/Code/BF2/Game/Objects/StrategicObjectComp.cpp b/Code/BF2/Game/Objects/StrategicObjectComp.cpp index db5366971..fac13a966 100644 --- a/Code/BF2/Game/Objects/StrategicObjectComp.cpp +++ b/Code/BF2/Game/Objects/StrategicObjectComp.cpp @@ -47,8 +47,8 @@ void StrategicObjectComp::handleUpdate(float) {} const std::string& StrategicObjectComp::getStrategicObjectName() { return m_template->getStrategicObjectName(); } const std::string& StrategicObjectComp::getIntactIconName() { return m_template->getIntactIcon(); } const std::string& StrategicObjectComp::getDestroyedIconName() { return m_template->getDestroyedIcon(); } -int StrategicObjectComp::getIntactIconPtr() { return m_template->getIntactIconPtr(); } -int StrategicObjectComp::getDestroyedIconPtr() { return m_template->getDestroyedIconPtr(); } +std::intptr_t StrategicObjectComp::getIntactIconPtr() { return m_template->getIntactIconPtr(); } +std::intptr_t StrategicObjectComp::getDestroyedIconPtr() { return m_template->getDestroyedIconPtr(); } int StrategicObjectComp::getPart() { return m_template->getPart(); } int StrategicObjectComp::getIndex() { return m_index; } void StrategicObjectComp::setIndex(int index) { m_index = index; } diff --git a/Code/BF2/Game/Objects/StrategicObjectComp.h b/Code/BF2/Game/Objects/StrategicObjectComp.h index 1a62a2a57..4d8a18359 100644 --- a/Code/BF2/Game/Objects/StrategicObjectComp.h +++ b/Code/BF2/Game/Objects/StrategicObjectComp.h @@ -38,8 +38,8 @@ class StrategicObjectComp : public IStrategicObjectComp const std::string& getStrategicObjectName() override; const std::string& getIntactIconName() override; const std::string& getDestroyedIconName() override; - int getIntactIconPtr() override; - int getDestroyedIconPtr() override; + std::intptr_t getIntactIconPtr() override; + std::intptr_t getDestroyedIconPtr() override; int getPart() override; int getIndex() override; void setIndex(int) override; diff --git a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp index 267670798..233bb561b 100644 --- a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp +++ b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.cpp @@ -60,7 +60,8 @@ const std::string& StrategicObjectCompTemplate::getStrategicObjectName() { retur namespace { // [INFERRED] helper name. BF2.exe 65A2F0 takes the string by value, calls // getSystem twice and resolves with loadTexture(name, true). ELF inlines null. -int resolveStrategicIcon(std::string name) +// The handle is std::intptr_t: int on x86, the full texture address on native x64. +std::intptr_t resolveStrategicIcon(std::string name) { #if !DEDICATED if (hudManager && hudManager->getSystem()) @@ -81,8 +82,8 @@ void StrategicObjectCompTemplate::setIntactIcon(std::string value) } const std::string& StrategicObjectCompTemplate::getDestroyedIcon() { return m_destroyedIcon; } const std::string& StrategicObjectCompTemplate::getIntactIcon() { return m_intactIcon; } -int StrategicObjectCompTemplate::getDestroyedIconPtr() { return m_destroyedIconPtr; } -int StrategicObjectCompTemplate::getIntactIconPtr() { return m_intactIconPtr; } +std::intptr_t StrategicObjectCompTemplate::getDestroyedIconPtr() { return m_destroyedIconPtr; } +std::intptr_t StrategicObjectCompTemplate::getIntactIconPtr() { return m_intactIconPtr; } void StrategicObjectCompTemplate::setPart(int value) { m_part = value; } int StrategicObjectCompTemplate::getPart() { return m_part; } void StrategicObjectCompTemplate::set3dMapIcon(int value) { m_mapIcon3D = value; } diff --git a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h index 85a25f7a4..c1e82f4f7 100644 --- a/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h +++ b/Code/BF2/Game/Objects/StrategicObjectCompTemplate.h @@ -5,6 +5,7 @@ #ifndef GAME_OBJECTS_STRATEGICOBJECTCOMPTEMPLATE_H // [INFERRED] guard style #define GAME_OBJECTS_STRATEGICOBJECTCOMPTEMPLATE_H +#include #include #include "CompTemplateInterfaces.h" @@ -36,10 +37,10 @@ class StrategicObjectCompTemplate : public IStrategicObjectCompTemplate, public virtual const std::string& getStrategicObjectName(); virtual void setDestroyedIcon(std::string); // resolves virtual const std::string& getDestroyedIcon(); - virtual int getDestroyedIconPtr(); + virtual std::intptr_t getDestroyedIconPtr(); // int on x86 virtual void setIntactIcon(std::string); // resolves virtual const std::string& getIntactIcon(); - virtual int getIntactIconPtr(); + virtual std::intptr_t getIntactIconPtr(); // int on x86 virtual void setPart(int); virtual int getPart(); virtual void set3dMapIcon(int); virtual int get3dMapIcon() const; virtual bool has3dMapIcon() const; @@ -56,8 +57,9 @@ class StrategicObjectCompTemplate : public IStrategicObjectCompTemplate, public /* 20 */ std::string m_destroyedIcon; // authored path /* 24 */ std::string m_intactIcon; // authored path - /* 28 */ int m_destroyedIconPtr; // resolved texture handle - /* 32 */ int m_intactIconPtr; // resolved texture handle + // Resolved texture handles: std::intptr_t is int on x86 (offsets unchanged), pointer-wide on x64. + /* 28 */ std::intptr_t m_destroyedIconPtr; + /* 32 */ std::intptr_t m_intactIconPtr; /* 36 */ int m_mapIcon3D; // console binding: strategicObject.3dMapIcon /* 40 */ bool m_isOnePiece; diff --git a/Code/BF2/Game/Objects/TemplateLeaves.cpp b/Code/BF2/Game/Objects/TemplateLeaves.cpp index 847705eb7..a46254d82 100644 --- a/Code/BF2/Game/Objects/TemplateLeaves.cpp +++ b/Code/BF2/Game/Objects/TemplateLeaves.cpp @@ -8,7 +8,7 @@ #include #include #if defined(_MSC_VER) && defined(_M_IX86) -#include "../../../RendDX9Abi/Vc71String.h" +#include #endif #include "Game/DynamicBundle.h" #include "Game/AreaObject.h" @@ -334,8 +334,8 @@ IObject* EnvMapTemplate::createObject() const { return 0; } bool EnvMapTemplate::writeBinary(io::IStream*) const { return false; } bool EnvMapTemplate::readBinary(io::IStream*) { return false; } -// ELF8201CC0 / clientPE64E4D0, complete reads. Renderer +1C is getTemplate(name); -// the Windows renderer retains VC7.1 strings even when both images use the native ABI. +// ELF8201CC0 / clientPE64E4D0, complete reads. Renderer +1C is getTemplate(name); the renderer +// takes the key as the shared std::string (issue #7: one STL across the image boundary). void EnvMapTemplate::templateInitialize() { updateFlags(1, 0); @@ -343,38 +343,15 @@ void EnvMapTemplate::templateInitialize() if (manager) { const std::string& name=getName(); -#if defined(_MSC_VER) && defined(_M_IX86) - // [CHOSEN, not recovered] Borrowed, read-only VC7.1 argument carrier. The - // recovered getTemplate copies its key; it neither retains nor mutates this - // carrier, so no renderer heap/string destructor crosses the image boundary. - struct BorrowedName - { - unsigned int allocator; - union { char buffer[16]; const char* pointer; } storage; - unsigned int length,capacity; - } argument={}; - static_assert(sizeof(BorrowedName)==sizeof(vc71::string),"VC7.1 argument carrier"); - argument.length=static_cast(name.size()); - if(name.size()<16) - { - std::memcpy(argument.storage.buffer,name.c_str(),name.size()+1); - argument.capacity=15; - } - else - { - argument.storage.pointer=name.c_str(); - argument.capacity=argument.length; - } - typedef void* (__thiscall* GetTemplate)(void*,const vc71::string&); - m_envMap=reinterpret_cast((*reinterpret_cast(manager))[0x1C/4])( - manager,*reinterpret_cast(&argument)); +#if defined(_MSC_VER) + typedef void* (__thiscall* GetTemplate)(void*,const std::string&); #else typedef void* (*GetTemplate)(void*,const std::string&); +#endif // ELF8201D3D / clientPE64E51C: +0x1C is logical slot 7 in both 32-bit // tables. Preserve the ordinal when native pointer width changes. m_envMap=reinterpret_cast((*reinterpret_cast(manager))[7])( manager,name); -#endif } } diff --git a/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp b/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp index 5af889953..4d02a916c 100644 --- a/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp +++ b/Code/BF2/Game/Objects/VehicleHudCompTemplate.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #if !DEDICATED @@ -35,7 +36,8 @@ namespace world { namespace { -int resolveVehicleHudIcon(std::string name) +// The handle is std::intptr_t: int on x86, the full texture address on native x64. +std::intptr_t resolveVehicleHudIcon(std::string name) { #if !DEDICATED // deliberately calls getSystem twice on the success path. @@ -212,9 +214,10 @@ class VehicleHudComp : public IVehicleHudComp return result; } - virtual int getVehicleIconPtr(int index) + virtual std::intptr_t getVehicleIconPtr(int index) { - std::vector::const_iterator icon = m_template->m_vehicleHudIcons.vehicleIconPtrs.begin(); + std::vector::const_iterator icon = + m_template->m_vehicleHudIcons.vehicleIconPtrs.begin(); if (index < m_template->getVehicleIconNumber()) icon += index; if (icon != m_template->m_vehicleHudIcons.vehicleIconPtrs.end()) @@ -233,9 +236,10 @@ class VehicleHudComp : public IVehicleHudComp return result; } - virtual int getAbilityIconPtr(int index) + virtual std::intptr_t getAbilityIconPtr(int index) { - std::vector::const_iterator icon = m_template->m_vehicleHudIcons.abilityIconPtrs.begin(); + std::vector::const_iterator icon = + m_template->m_vehicleHudIcons.abilityIconPtrs.begin(); if (index < m_template->getAbilityIconNumber()) icon += index; if (icon != m_template->m_vehicleHudIcons.abilityIconPtrs.end()) diff --git a/Code/BF2/Game/Objects/VehicleHudIcons.h b/Code/BF2/Game/Objects/VehicleHudIcons.h index c9bc81f1e..37fb6b797 100644 --- a/Code/BF2/Game/Objects/VehicleHudIcons.h +++ b/Code/BF2/Game/Objects/VehicleHudIcons.h @@ -2,11 +2,18 @@ #ifndef GAME_OBJECTS_VEHICLEHUDICONS_H #define GAME_OBJECTS_VEHICLEHUDICONS_H +#include #include +#include #include namespace dice { namespace hfe { namespace world { +#if defined(_M_IX86) +static_assert(std::is_same::value, + "x86 icon handles keep the retail int layout and mangling"); +#endif + // ELF constructor 0x822CE50; BF2.exe constructor 0x65B020. The containing // template initializes the three scalar handles after this constructor returns. // Retail ELF size 0x48, VC7.1 size 0xA0. Native STL determines this build's size; @@ -21,12 +28,13 @@ struct VehicleHudIcons std::string typeIcon; // ELF +1C; PE +3C std::string spottedIcon; // ELF +20; PE +58 // Element type is attested by vector manglings in the ELF setters. - // On the client these integer handles carry Ref2System texture addresses. - std::vector vehicleIconPtrs; // ELF +24; PE +74 - std::vector abilityIconPtrs; // ELF +30; PE +84 - int miniMapIconPtr; // ELF +3C; PE +94 - int typeIconPtr; // ELF +40; PE +98 - int spottedIconPtr; // ELF +44; PE +9C + // On the client these integer handles carry Ref2System texture addresses, so they are + // std::intptr_t: int on x86 (unchanged layout and mangling), pointer-wide on native x64. + std::vector vehicleIconPtrs; // ELF +24; PE +74 + std::vector abilityIconPtrs; // ELF +30; PE +84 + std::intptr_t miniMapIconPtr; // ELF +3C; PE +94 + std::intptr_t typeIconPtr; // ELF +40; PE +98 + std::intptr_t spottedIconPtr; // ELF +44; PE +9C }; } } } diff --git a/Code/BF2/Game/Objects/Visual/LightSource.cpp b/Code/BF2/Game/Objects/Visual/LightSource.cpp index a6d093439..66e00e7b8 100644 --- a/Code/BF2/Game/Objects/Visual/LightSource.cpp +++ b/Code/BF2/Game/Objects/Visual/LightSource.cpp @@ -13,6 +13,7 @@ #include "../../../Core/Debug.h" #include "../../../Core/ClassManager.h" #include "../../../Geom/XpLightManager.h" +#include "../../../Platform/MsvcRand.h" // [CHOSEN, not recovered] the client CRT's rand (MSVCR71) namespace dice { namespace hfe { @@ -215,8 +216,8 @@ void LightSource::handleFrameUpdate(float) const float flicker = m_template->getFlicker(); // template +0x1F8 if (flicker > 0.0f) { - // [PLATFORM] Scale by this platform's RAND_MAX to preserve the full [0, 1] flicker range. - const float r = static_cast(rand()) * (1.0f / RAND_MAX); + // [PLATFORM] Scale by the CRT generator's RAND_MAX (bf2crt) to preserve the full [0, 1] flicker range. + const float r = static_cast(bf2crt::rand()) * (1.0f / bf2crt::kRandMax); m_attenuationRange1 = m_template->getAttenuationRange1() * ((r - 1.0f) * flicker + 1.0f); // +0x148 m_attenuationRange2 = m_template->getAttenuationRange2() * ((r - 1.0f) * flicker + 1.0f); // +0x14C } diff --git a/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp b/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp index 0b4921eb3..c148dd3d2 100644 --- a/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp +++ b/Code/BF2/Game/Objects/WeaponHudCompTemplate.cpp @@ -74,9 +74,10 @@ class WeaponHudComp : public IWeaponHudComp virtual bool hasUpdate() const { return false; } virtual void handleUpdate(float) {} - virtual int getGuiIndex(bool selected) + virtual int getGuiIndex(bool sprinting) { - if (selected && m_template->getDisplaySelectOnActivation()) + // ELF 0x822E620: the template's vslot +0x12C, WeaponHudCompTemplate::getDisableOnSprint. + if (sprinting && m_template->getDisableOnSprint()) return 0; if (m_template->getAltGuiIndex() == -1) return m_template->getGuiIndex(); diff --git a/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp b/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp index ea0c63549..35859179c 100644 --- a/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/DeviationComponents/SoldierDeviationComp.cpp @@ -6,6 +6,7 @@ #include "SoldierDeviationComp.h" #include +#include #include #include @@ -18,6 +19,8 @@ #include "../../../../Core/Ids.h" #include "../../../../IO/Input/PlayerInput.h" #include "../../../../IO/Stream/IStream.h" +#include "../../../../Physics/IResponsePhysics.h" +#include "../../../../Physics/SoldierResponse.h" // m_byteFA (+0xFA), a friend #include "../../../../Scene/Object/ObjectUtil.h" namespace dice { @@ -174,10 +177,15 @@ void SoldierDeviationComp::updateDeviation(io::PlayerInput input, if (!soldierObject->getParent()) { // Retail has no null guard here. A Soldier is expected to carry response physics; - // preserve the raw +0xFA ground-contact read instead of inventing a fallback. - unsigned char* const response = static_cast( - object_detail::LayoutAccess::responsePhysics(soldierObject)); - if (!response[0xFA]) + // preserve the +0xFA ground-contact read instead of inventing a fallback. +#if defined(_M_IX86) + static_assert(offsetof(SoldierResponsePhysics, m_byteFA) == 0xFA, + "retail soldier ground-contact byte"); +#endif + const SoldierResponsePhysics* const response = + static_cast(static_cast( + object_detail::LayoutAccess::responsePhysics(soldierObject))); + if (!response->m_byteFA) pose = SoldierPose_Stand; } diff --git a/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp b/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp index 58e3ba083..fabad090b 100644 --- a/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/FireComponents/SingleFireComp.cpp @@ -1,6 +1,11 @@ // Single-shot firing and template properties. #include "SingleFireComp.h" +#include "../../GeometryPartAccess.h" // named geometry operations (non-MSVC) +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../../Geom/NativeGeometrySlots.h" +#endif #include #include @@ -37,14 +42,9 @@ typedef void (__thiscall *GeometrySetLodFn)(void*, int); const std::size_t kGeometryGetSubgeomSlot = 0x70 / 4; const std::size_t kGeometrySetLodSlot = 0x78 / 4; const std::size_t kGeometryGetLodCountSlot = 0x80 / 4; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetLodFn)(void*, int); -const std::size_t kGeometryGetSubgeomSlot = 0x74 / 4; -const std::size_t kGeometrySetLodSlot = 0x7C / 4; -const std::size_t kGeometryGetLodCountSlot = 0x84 / 4; #endif +#if defined(_MSC_VER) void** geometryVtable(void* geometry) { return *reinterpret_cast(geometry); @@ -67,6 +67,12 @@ int geometryGetLodCount(void* geometry) return reinterpret_cast( geometryVtable(geometry)[kGeometryGetLodCountSlot])(geometry); } +#else +// Non-MSVC: the named geometry_part operations (static native: Geom/NativeGeometrySlots.h). +int geometryGetSubgeom(void* geometry) { return geometry_part::getSubgeom(geometry); } +void geometrySetLod(void* geometry, int lod) { geometry_part::setLod(geometry, lod); } +int geometryGetLodCount(void* geometry) { return geometry_part::getLodCount(geometry); } +#endif } // namespace diff --git a/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp b/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp index f5ebb0b2d..2a7a02003 100644 --- a/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp +++ b/Code/BF2/Game/Objects/Weapons/GenericFireArm.cpp @@ -4,6 +4,7 @@ // [RETIRE-WHEN: unrecovered-factories-registered] Register remaining factories only once their required bodies exist. #include "GenericFireArm.h" +#include "../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include "../Game/TriggerManager.h" #include "FireComponents/FireComp.h" #include "AmmoComponents/AmmoComp.h" // IWeaponAmmoComp - the typed ammo delegates @@ -416,14 +417,18 @@ void GenericFireArm::updateGeometry() // / client PE 0x5E0610: suppress the original mesh while an // alternate display object supplies it. Both ABIs call geometry +0x50; // this is the whole-object transform, not the adjacent per-part slot. -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) +#if defined(_M_IX86) typedef void (__thiscall* SetTransformation)(void*, const Mat4&); #else typedef void (*SetTransformation)(void*, const Mat4&); #endif reinterpret_cast( - (*static_cast(m_geometry))[0x50 / sizeof(void*)])( + (*static_cast(m_geometry))[0x50 / 4])( m_geometry, Mat4::getZero()); +#else + geometry_part::setGeometryTransform(m_geometry, &Mat4::getZero()); // PE +0x50 +#endif } else { diff --git a/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp b/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp index cbf4abe5c..7665f5cd5 100644 --- a/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/TargetComponents/TargetComp.cpp @@ -3,6 +3,7 @@ // cross-checked against the BF2 1.50 Win32 dedicated-server image. #include "TargetComp.h" +#include "../../GeometryPartAccess.h" // named geometry operations (non-MSVC) #include #include @@ -44,17 +45,18 @@ IPlayerControlObject* findPlayerControlObject(IObject* object) // IGeometry is not reconstructed far enough to name this slot yet. Both shipped x86 tables were // read: the same operation is ELF +0xD8 and PE +0xD4 (the Itanium destructor-pair shift). +// The slot follows the compiler's destructor ABI, so native MSVC x64 takes the PE arm too. void geometrySetConnectionEffect(void* geometry, int enabled) { -#if defined(_MSC_VER) && defined(_M_IX86) +#if defined(_MSC_VER) typedef void (__thiscall *Method)(void*, int); - const unsigned int slot = 0xD4 / sizeof(void*); -#else - typedef void (*Method)(void*, int); - const unsigned int slot = 0xD8 / sizeof(void*); -#endif + const unsigned int slot = 0xD4 / 4; void** const vtable = *reinterpret_cast(geometry); reinterpret_cast(vtable[slot])(geometry, enabled); +#else + // The same one-dword entry the renderer's MeshParticleMesh names setFirstPerson (ELF +0xD8). + geometry_part::setFirstPerson(geometry, static_cast(enabled)); +#endif } } // namespace diff --git a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp index 8b5030e89..d28efc684 100644 --- a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp +++ b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.cpp @@ -1,9 +1,13 @@ // Path: [INFERRED] from the recovered ZoomComponents family placement. // Contents: server-reachable DefaultZoomComp and complete DefaultZoomCompTemplate leaf recovered -// from ELF 0x829BED0..0x829D77A and cross-checked against PE 0x5A58xx..0x5A64xx. -// The client-only WeaponHud notification tail is the named frontier at changeZoom(). +// from ELF 0x829BED0..0x829D77A and cross-checked against PE 0x5A58xx..0x5A64xx +// (changeZoom: PE 0x606C20, ELF 0x829C2B0). #include "DefaultZoomComp.h" +#if defined(BF2_STATIC_PLUGINS) && !defined(_MSC_VER) +// [CHOSEN, not recovered] Native static geometry tables retain PE slot order. +#include "../../../../Geom/NativeGeometrySlots.h" +#endif #include #include @@ -13,6 +17,8 @@ #include "../../Game/Soldier.h" #include "../../IObject.h" #include "../../IPlayer.h" +#include "../../IWeaponHudComp.h" +#include "../../WeaponHudCompTemplate.h" // WeaponHudInfo::altGuiIndex #include "../../ObjectLayoutAccess.h" #include "../../GeometryPartAccess.h" #include "../../../../Core/EventManager.h" @@ -29,7 +35,8 @@ namespace { // geom::IGeometry is still unrecovered. This is the complete bounded surface used by DefaultZoom. // Its virtual destructor differs across the two retail ABIs, shifting every geometry slot after it. -#if defined(_MSC_VER) && defined(_M_IX86) +// The slots follow the compiler's destructor ABI, so native MSVC x64 takes the PE arm too. +#if defined(_MSC_VER) typedef int (__thiscall *GeometryGetIntFn)(void*); typedef void (__thiscall *GeometrySetLodFn)(void*, int); typedef void* (__thiscall *GeometryGetTemplateFn)(void*); @@ -38,17 +45,9 @@ const std::size_t kGeometryGetSubgeomSlot = 0x70 / 4; const std::size_t kGeometrySetLodSlot = 0x78 / 4; const std::size_t kGeometryGetLodSlot = 0x7C / 4; const std::size_t kGeometryGetLodCountSlot = 0x80 / 4; -#else -typedef int (*GeometryGetIntFn)(void*); -typedef void (*GeometrySetLodFn)(void*, int); -typedef void* (*GeometryGetTemplateFn)(void*); -const std::size_t kGeometryGetTemplateSlot = 0x3C / 4; -const std::size_t kGeometryGetSubgeomSlot = 0x74 / 4; -const std::size_t kGeometrySetLodSlot = 0x7C / 4; -const std::size_t kGeometryGetLodSlot = 0x80 / 4; -const std::size_t kGeometryGetLodCountSlot = 0x84 / 4; #endif +#if defined(_MSC_VER) void** geometryVtable(void* geometry) { return *reinterpret_cast(geometry); @@ -83,6 +82,14 @@ void* geometryGetTemplate(void* geometry) return reinterpret_cast( geometryVtable(geometry)[kGeometryGetTemplateSlot])(geometry); } +#else +// Non-MSVC: the named geometry_part operations (static native: Geom/NativeGeometrySlots.h). +int geometryGetSubgeom(void* geometry) { return geometry_part::getSubgeom(geometry); } +void geometrySetLod(void* geometry, int lod) { geometry_part::setLod(geometry, lod); } +int geometryGetLod(void* geometry) { return geometry_part::getLod(geometry); } +int geometryGetLodCount(void* geometry) { return geometry_part::getLodCount(geometry); } +void* geometryGetTemplate(void* geometry) { return geometry_part::getTemplate(geometry); } +#endif } // namespace @@ -377,12 +384,15 @@ void DefaultZoomComp::changeZoom(int camera, bool immediate) } } - // [FRONTIER] [RETIRE-WHEN: unrecovered-factories-registered] - // Retail's remaining arm reads the firearm's Object +0x5C WeaponHud component, calls its - // specialized +0x50 getter, tests the returned object's +0x18 field, and only then posts the - // zoom HUD event for a local first-person player. WeaponHud remains factory-dark under RW-6 - // and a dedicated server's is1P() is false, so the arm is unreachable in this slice. It must - // land with the typed WeaponHud interface rather than being mis-dispatched through an ELF slot. + // Tell the HUD to recompute its GUI index (ECHud 31, HudVehicleInformation::updateGuiIndex) + // when the weapon has an alternate index, so a zoomed rifle switches to its altGuiIndex HUD + // (no crosshair for the AK-101's 52). The WeaponHud component is read before is1P(), as in + // both images (PE 0x606CD1..0x606D06, ELF 0x829C350..0x829C39D); the same tail is inlined in + // the PE reload thunk at 0x606E7C. A dedicated server's is1P() is false. + IWeaponHudComp* const weaponHud = static_cast( + object_detail::LayoutAccess::weaponHudComponent(firearm())); + if (is1P() && weaponHud && weaponHud->getHudInfo()->altGuiIndex != -1) + eventManager->postEvent(ECHud, 31, this, 0.0f); } int DefaultZoomComp::getZoomLod() const diff --git a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h index f2db9f30d..154b91f37 100644 --- a/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h +++ b/Code/BF2/Game/Objects/Weapons/ZoomComponents/DefaultZoomComp.h @@ -1,6 +1,6 @@ // Path: [INFERRED] beside the attested weapon-component families. // Contents: server-reachable DefaultZoom runtime and complete template leaf recovered from both -// shipped x86 ports; the client-only WeaponHud notification tail remains named in .cpp. +// shipped x86 ports, including the client-side WeaponHud notification in changeZoom. #ifndef GAME_OBJECTS_WEAPONS_ZOOMCOMPONENTS_DEFAULTZOOMCOMP_H #define GAME_OBJECTS_WEAPONS_ZOOMCOMPONENTS_DEFAULTZOOMCOMP_H diff --git a/Code/BF2/Game/PasswordCodec.cpp b/Code/BF2/Game/PasswordCodec.cpp index 1e754a94e..8544beae9 100644 --- a/Code/BF2/Game/PasswordCodec.cpp +++ b/Code/BF2/Game/PasswordCodec.cpp @@ -1,15 +1,23 @@ // [INFERRED] path. Full client PE66E7D0/5B0190/5B01C0/5B0400/5B0320/5B0260 read. #include "PasswordCodec.h" #if !DEDICATED +#if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include #include +#else +// [CHOSEN, not recovered] macOS: the DPAPI counterpart (docs/macos-port.md, "Protected profile +// data (DPAPI)"). The flow below is the shipped one; only the three API calls differ. +#include "../Platform/macOS/ProtectedData.h" +#endif #include #include #include #include +#if defined(_MSC_VER) #pragma comment(lib, "crypt32.lib") +#endif namespace dice { namespace hfe { @@ -21,7 +29,11 @@ PasswordCodec::PasswordCodec() // PE66E7D0 PasswordCodec::~PasswordCodec() // PE5B0190 { if (m_blob) { +#if defined(_WIN32) LocalFree(m_blob->pbData); +#else + macos::freeProtectedData(m_blob->pbData); +#endif delete m_blob; m_blob = 0; } @@ -31,18 +43,34 @@ bool PasswordCodec::encode(const std::string& plain) // PE5B01C0 { // The input blob is filled (terminator included) before the empty test, as shipped. DATA_BLOB input; +#if defined(_WIN32) input.pbData = (BYTE*)plain.c_str(); input.cbData = (DWORD)std::strlen(plain.c_str()) + 1; +#else + input.pbData = (unsigned char*)plain.c_str(); + input.cbData = (std::uint32_t)std::strlen(plain.c_str()) + 1; +#endif if (plain.size() == 0) return false; if (m_blob) { +#if defined(_WIN32) LocalFree(m_blob->pbData); +#else + macos::freeProtectedData(m_blob->pbData); +#endif delete m_blob; m_blob = 0; } m_blob = new DATA_BLOB; +#if defined(_WIN32) return CryptProtectData(&input, L"This is the description string.", 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, m_blob) != 0; +#else + // A failed protect leaves the blob empty, as a failed CryptProtectData does. + m_blob->cbData = 0; + m_blob->pbData = 0; + return macos::protectData(input.pbData, input.cbData, m_blob); +#endif } void PasswordCodec::write(std::ostream& stream) // PE5B0400 @@ -69,7 +97,9 @@ void PasswordCodec::readHexPairs(const std::string& text, unsigned char* out) // bool PasswordCodec::decode(std::string& text) // PE5B0320 { const unsigned int count = text.size() >> 1; +#if defined(_WIN32) LPWSTR description = 0; +#endif if (!count) return false; unsigned char* bytes = new unsigned char[count]; @@ -78,6 +108,11 @@ bool PasswordCodec::decode(std::string& text) // PE5B0320 input.pbData = bytes; input.cbData = count; DATA_BLOB output; +#if !defined(_WIN32) + output.cbData = 0; + output.pbData = 0; +#endif +#if defined(_WIN32) if (CryptUnprotectData(&input, &description, 0, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output)) { text = std::string((const char*)output.pbData); LocalFree(description); @@ -85,6 +120,21 @@ bool PasswordCodec::decode(std::string& text) // PE5B0320 LocalFree(output.pbData); return true; } +#else + // The plain text carries its terminator (encode protects it), so it is read as a C string. + if (macos::unprotectData(input.pbData, input.cbData, &output) && output.cbData + && output.pbData[output.cbData - 1] == 0) { + text = std::string((const char*)output.pbData); + delete[] bytes; + macos::freeProtectedData(output.pbData); + return true; + } + if (output.pbData) + macos::freeProtectedData(output.pbData); + // As shipped, `bytes` is not freed on failure; there is no system message to format. + return false; +#endif +#if defined(_WIN32) // The system message is formatted and released without being shown; `bytes` is not freed. const DWORD error = GetLastError(); LPSTR message = 0; @@ -93,6 +143,7 @@ bool PasswordCodec::decode(std::string& text) // PE5B0320 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&message, 0, 0)) LocalFree(message); return false; +#endif } } } diff --git a/Code/BF2/Game/ProfileManager.cpp b/Code/BF2/Game/ProfileManager.cpp index 8d0f52337..40f1aa625 100644 --- a/Code/BF2/Game/ProfileManager.cpp +++ b/Code/BF2/Game/ProfileManager.cpp @@ -270,6 +270,17 @@ void profileManagerGPIgnore(GPConnection* /*connection*/, void* /*arg*/, void* / { } +// 0x4A5B80 - the gpSuggestUniqueNick callback requestNickSuggestions installs. `param` is the +// owner's suggestion vector; one entry is appended per suggested nick (push_back 0x450C10). The +// result field is not read: a failed request answers zero suggestions. +void profileManagerGPSuggestions(GPConnection* /*connection*/, void* arg, void* param) +{ + const GPSuggestUniqueNickResponseArg* response = static_cast(arg); + std::vector* suggestions = static_cast*>(param); + for (int i = 0; i < response->numSuggestedNicks; ++i) + suggestions->push_back(std::string(response->suggestedNicks[i])); +} + } // namespace // the connection's own error text, or "general error" when it is empty. @@ -694,22 +705,127 @@ bool ProfileManager::getProfileInformation(int profileId, ProfileInformation& ou return true; } -// [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: profile-manager-account-operations] -// All parameters and returns below are proved by complete PE bodies/callers. -// Their account/GP callback bodies remain visible stops under the client startup -// publication exception. No fabricated account state or successful login is returned. -#define PROFILE_MANAGER_FRONTIER(method) \ - std::fprintf(stderr, "[FRONTIER] dice::hfe::ProfileManager::" #method " reached\n"); \ - std::fflush(stderr); \ - std::abort() +// Adds a GameSpy profile (unique nick) to the logged-in account. PE 0x4A6EB0. +// Refuses without a current profile, or with a nick the host's validator rejects (posted as a +// type-3 message when the host exists). Otherwise the account's e-mail and password are copied, the +// current unique nick remembered, and the session ended (logout). A fresh connection then creates +// the new profile with gpConnectNewUser; on success it becomes the current profile exactly as +// createOnlineAccount's does. On failure the error is reported and the old unique nick logs in +// again; when that also fails the host gets the profile-transition text. +bool ProfileManager::createProfile(const std::string& uniqueNick, const std::string& country) +{ + if (!m_currentProfile) + return false; + IBase* host = classManager->getSingleton(std::string("SwiffHost")); // kept for the end, unguarded + std::string error; + if (!validateProfileName(uniqueNick, error)) // virtual +0x54 + { + IBase* validatorHost = classManager->getSingleton(std::string("SwiffHost")); + if (validatorHost) + static_cast(validatorHost)->postMessage(SwiffHostMessage(3, error, 3)); // +0x1E4 + return false; + } + std::string previousUniqueNick; + std::string password(m_currentProfile->password); // record +0x1C + std::string email(m_currentProfile->email); // record +0x00 + getUniqueNick(previousUniqueNick); // virtual +0x34 + logout(); // virtual +0x28 + bool created = false; + int profileId; // written by the callback only + if (gpInitialize(&m_connection, kGameSpyProductId, kGameSpyNamespaceId, GP_PARTNERID_GAMESPY) != GP_NO_ERROR) + reportError(std::string("serveroffline"), true); + else + { + gpSetCallback(&m_connection, GP_ERROR, &profileManagerGPError, this); + if (gpConnectNewUser(&m_connection, uniqueNick.c_str(), uniqueNick.c_str(), email.c_str(), + password.c_str(), NULL, GP_NO_FIREWALL, GP_BLOCKING, + &profileManagerGPProfileId, &profileId) != GP_NO_ERROR) + reportError(lastErrorString(), false); + else + created = true; + } + if (!created) + { + // 0x4A7016: the shared failure tail - log out again and restore the previous profile. + logout(); // virtual +0x28 + if (!login(previousUniqueNick, password)) // virtual +0x14 + static_cast(host)->handleProfileTransition( + std::string("Connection to profile server lost.")); // +0x244 + return false; + } + createStatsPlayer(profileId, country, uniqueNick); // result unread + setCurrentProfile(email, password, profileId, uniqueNick); + fetchProfileList(m_currentProfile->profiles); + static_cast(host)->setSelectedPlayerId(profileId); // +0x220, unguarded + return true; +} -bool ProfileManager::createProfile(const std::string&, const std::string&) -{ PROFILE_MANAGER_FRONTIER(createProfile); } +// Deletes the current GameSpy profile. PE 0x4A54B0. +// Refuses without a current profile, and with fewer than two profiles on the account (an +// untranslated type-1 message). The first other profile is remembered, gpDeleteProfile is issued +// with a no-op callback (0x5AB2A0), and on success the session ends and that other profile logs in +// (by its nick, entry +4, as shipped). When the login fails the host gets the transition text. bool ProfileManager::deleteProfile() -{ PROFILE_MANAGER_FRONTIER(deleteProfile); } -bool ProfileManager::requestNickSuggestions(const std::string&) -{ PROFILE_MANAGER_FRONTIER(requestNickSuggestions); } -#undef PROFILE_MANAGER_FRONTIER +{ + if (!m_currentProfile) + return false; + if (m_currentProfile->profiles.size() <= 1) + { + reportError(std::string("Unable to delete profile, you must have at least 1 profile"), false); + return false; + } + IBase* host = classManager->getSingleton(std::string("SwiffHost")); // unguarded below + const std::string email(m_currentProfile->email); // copied and never read + std::string password(m_currentProfile->password); + (void)email; + OnlineProfileEntry other; + other.profileId = 0; + // The size is re-read on each pass; the loop stops at the first entry that is not the + // current profile id (record +0x48). + for (std::size_t index = 0; index < m_currentProfile->profiles.size(); ++index) + { + if (m_currentProfile->profiles[index].profileId != m_currentProfile->profileId) + { + other.profileId = m_currentProfile->profiles[index].profileId; + other.nick = m_currentProfile->profiles[index].nick; + other.uniqueNick = m_currentProfile->profiles[index].uniqueNick; + break; + } + } + if (gpDeleteProfile(&m_connection, &profileManagerGPIgnore, &other) != GP_NO_ERROR) + { + reportError(lastErrorString(), false); + return false; + } + logout(); // virtual +0x28 + if (!login(other.nick, password)) // virtual +0x14 + { + static_cast(host)->handleProfileTransition( + std::string("Connection to profile server lost.")); // +0x244 + return false; + } + return true; +} + +// Fetches unique-nick suggestions for `nick` into the owner's list. PE 0x4A5BD0. +// The list is emptied and its buffer released first. The request runs on a private, +// short-lived connection; a failed initialisation reports the OWNER connection's error text (the +// shipped body reads this+0x0C, not the local connection) and answers false. The suggestion +// request's own result is not read, and the answer is then true. +bool ProfileManager::requestNickSuggestions(const std::string& nick) +{ + std::vector().swap(m_nickSuggestions); // 0x445E70 + GPConnection connection; + if (gpInitialize(&connection, kGameSpyProductId, kGameSpyNamespaceId, GP_PARTNERID_GAMESPY) != GP_NO_ERROR) + { + reportError(lastErrorString(), false); + return false; + } + gpSuggestUniqueNick(&connection, nick.c_str(), GP_BLOCKING, &profileManagerGPSuggestions, + &m_nickSuggestions); + gpDestroy(&connection); + return true; +} } } #endif diff --git a/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h b/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h index 3299a46a7..2af48fed5 100644 --- a/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h +++ b/Code/BF2/Geom/ParticleSystem/ParticleSystemManager.h @@ -15,6 +15,8 @@ #include "../../Math/Vec3.h" #include +#include +#include namespace dice { namespace hfe { @@ -52,9 +54,11 @@ class IParticleSystemInstance virtual void reserved08() = 0; // +0x20 detach virtual void reserved09(bool value) = 0; // +0x24 virtual bool reserved10() const = 0; // +0x28 - virtual void reserved11(int value) = 0; // +0x2C - virtual int reserved12() const = 0; // +0x30 - virtual void reserved13(int value) = 0; // +0x34 + // +0x2C..+0x34 carry the owner object and the parent matrix as integers; intptr_t is `int` on + // x86 (same signature) and pointer-sized on x64. + virtual void reserved11(intptr_t value) = 0; // +0x2C + virtual intptr_t reserved12() const = 0; // +0x30 + virtual void reserved13(intptr_t value) = 0; // +0x34 virtual void* reserved14(const void* value) = 0; // +0x38 virtual const void* reserved15() const = 0; // +0x3C virtual void reserved16(const Vec3& value) = 0; // +0x40 @@ -400,35 +404,10 @@ class IParticleSystemEmitterTemplate : public IParticleSystemTemplate virtual float getSpeedFromParticle() const = 0; // +0x188 }; -// The Win32 manager returns its internal VC7.1 vector by reference at +0x38. This is renderer-owned -// storage even in the rebuilt native-host flavour, so it must keep the four-word VC7.1 layout; -// exposing std::vector here would move first from +4 to +0 on modern MSVC. This carrier is for the -// Win32 RendDX9/plugin boundary. The symbolized Linux port was used to cross-check semantics, but -// its libstdc++ vector begins at +0 and would need its own executable carrier. -struct ParticleSystemInstanceList -{ - /* +0x00 */ void* allocator; - /* +0x04 */ IParticleSystemInstance** first; - /* +0x08 */ IParticleSystemInstance** last; - /* +0x0C */ IParticleSystemInstance** endStorage; - - IParticleSystemInstance* const* begin() const { return first; } - IParticleSystemInstance* const* end() const { return last; } - - unsigned int size() const - { - return first ? static_cast(last - first) : 0u; - } -}; - -#if defined(_M_IX86) || defined(__i386__) -static_assert(sizeof(ParticleSystemInstanceList) == 16, - "ParticleSystemManager's VC7.1 instance vector must remain 16 bytes"); -static_assert(offsetof(ParticleSystemInstanceList, first) == 4, - "ParticleSystemManager's instance-vector begin pointer must remain at +4"); -static_assert(offsetof(ParticleSystemInstanceList, last) == 8, - "ParticleSystemManager's instance-vector end pointer must remain at +8"); -#endif +// The manager's active-instance vector, returned by reference at +0x38. BF2.exe +// (Game/GameLogic/Player.cpp) reads it directly: the client and its renderer share one STL +// (issue #7). +typedef std::vector ParticleSystemInstanceList; // +0x3C consumes exactly 60 bytes. Names for the four pool counts and final two renderer knobs are // unresolved; their widths, offsets, and the float fields are recovered from 0x100D37A0. @@ -472,9 +451,10 @@ class IParticleSystemManager : public IBase public: // +0x00..+0x0C: IBase quartet. - // +0x10, PE 0x100D2E30. Calls +0x30, then reacquires the WindManager singleton. The exact - // source name remains [UNRESOLVED]. postLoadLevel is the separate direct BF2 0x100D2FD0 body, - // named by the Editor caller, which reacquires HeightmapCluster at manager +0x8C14. + // +0x10 (body: psm_reserved10). Calls +0x30, then reacquires the WindManager singleton. The exact + // source name remains [UNRESOLVED]. postLoadLevel is the separate direct body + // (particleSystemManagerPostLoadLevel), named by the Editor caller, which reacquires + // HeightmapCluster at manager +0x8C14. virtual void reserved_reacquireWindManager() = 0; virtual IParticleSystemInstance* createInstance( @@ -520,13 +500,17 @@ inline IParticleSystemManager* asParticleSystemManager(IBase* base) void particleSystemManagerBeginFrame(IParticleSystemManager* manager); void particleSystemManagerEndFrame(IParticleSystemManager* manager); -// Direct ResourceManager lifecycle calls, PE 0x100D38D0 / 0x100D2FD0. The preLoadLevel +// Direct ResourceManager lifecycle calls (preLoadLevel PE 0x100D38D0, postLoadLevel 0x100D2FD0). The preLoadLevel // spelling is [INFERRED] from the Editor ResourceManager caller; no virtual slots are added. void particleSystemManagerPreLoadLevel(IParticleSystemManager* manager); void particleSystemManagerPostLoadLevel(IParticleSystemManager* manager); // Releases level instances/descriptors, queues, registries, renderer buffers, pools, and atlas. void particleSystemManagerUnloadLevel(IParticleSystemManager* manager); +// The HeightmapCluster singleton postLoadLevel stored in the manager (retail +0x8C14); borrowed, +// possibly null. No null guard on `manager`. +IBase* particleSystemManagerHeightmapCluster(IBase* manager); + } // namespace geom } // namespace hfe } // namespace dice diff --git a/Code/BF2/GeomMisc/DebugCircleDrawer.h b/Code/BF2/GeomMisc/DebugCircleDrawer.h new file mode 100644 index 000000000..3d1a9272f --- /dev/null +++ b/Code/BF2/GeomMisc/DebugCircleDrawer.h @@ -0,0 +1,31 @@ +// Circular debug line strips. Header placement [INFERRED]. +#ifndef BF2_GEOMMISC_DEBUGCIRCLEDRAWER_H +#define BF2_GEOMMISC_DEBUGCIRCLEDRAWER_H + +#include "../Core/IBase.h" +#include "../Math/Vec3.h" + +namespace dice { namespace hfe { namespace geom { + +// PE table 0x1020CB98. The Boolean replaces vertex heights with terrain heights; +// the count includes both endpoints. Names of the two drawing overloads are [INFERRED]. +class IDebugCircleDrawer : public IBase +{ +public: + virtual void drawCircle(const Vec3& normal, const Vec3& centre, float radius, + unsigned int colour, bool terrain, + unsigned int vertexCount) = 0; // +0x10 + virtual void drawArc(const Vec3& normal, const Vec3& reference, const Vec3& centre, + float radius, unsigned int colour, bool terrain, + unsigned int vertexCount, float startDegrees, + float sweepDegrees) = 0; // +0x14 + // [CHOSEN, not recovered] Name for the PE deleting-destructor entry; keeping + // it explicit avoids the additional Itanium destructor slot in the native ABI. + virtual void* destroy(unsigned int flags) = 0; // +0x18 +}; + +extern const unsigned int CID_DebugCircleDrawer; +IBase* __fastcall createDebugCircleDrawer(unsigned int iid, IBase* outer); + +} } } +#endif diff --git a/Code/BF2/GeomMisc/DebugLineDrawer.h b/Code/BF2/GeomMisc/DebugLineDrawer.h new file mode 100644 index 000000000..06ff5192c --- /dev/null +++ b/Code/BF2/GeomMisc/DebugLineDrawer.h @@ -0,0 +1,54 @@ +// Debug line and triangle drawing. Header placement and drawing names [INFERRED]. +#ifndef BF2_GEOMMISC_DEBUGLINEDRAWER_H +#define BF2_GEOMMISC_DEBUGLINEDRAWER_H + +#include "../Core/IBase.h" +#include "../Math/Vec3.h" +#include + +struct D3DXVECTOR3; + +namespace dice { namespace hfe { namespace geom { + +// PE table 0x1020C758. D3DX overloads consume contiguous three-float positions; +// the Vec3 overload converts to that vector before dispatching to drawRibbon. +class IDebugLineDrawer : public IBase +{ +public: + virtual void drawD3dxLine(const std::vector& points, + unsigned int colour, float width) = 0; // +0x10 + virtual void drawD3dxLine(unsigned int count, const D3DXVECTOR3* points, + unsigned int colour, float width) = 0; // +0x14 + virtual void drawD3dxLine(float x0, float y0, float z0, float x1, float y1, + float z1, unsigned int colour, float width) = 0; // +0x18 + // The four-byte ZBUFFER value is forwarded unchanged to the shader parameter. + virtual void drawThinLine(float x0, float y0, float z0, float x1, float y1, + float z1, unsigned int colour, + unsigned int depthValue) = 0; // +0x1C + virtual void drawRibbon(const std::vector& points, + unsigned int colour, float width, bool depth) = 0; // +0x20 + virtual void drawLine(const std::vector& points, unsigned int colour, + float width, bool depth) = 0; // +0x24 + virtual void drawTriangle(const Vec3& a, const Vec3& b, const Vec3& c, + unsigned int colour, bool depth) = 0; // +0x28 + // Colours are per triangle, with the last repeated when the vector is shorter. + virtual void drawTriangles(const std::vector& points, + const std::vector& colours, + bool depth) = 0; // +0x2C + virtual void drawMesh(Vec3* points, unsigned int* indices, int triangleCount, + unsigned int* colours, bool depth) = 0; // +0x30 + virtual void drawLineList(const std::vector& points, + const std::vector& colours, + float width, bool depth) = 0; // +0x34 + // [CHOSEN, not recovered] Explicit PE deleting-destructor entry, avoiding + // the extra Itanium destructor slot in the native interface. + virtual void* destroy(unsigned int flags) = 0; // +0x38 + virtual void drawScreenLine(float x0, float y0, float x1, float y1, + unsigned int colour, float width) = 0; // +0x3C +}; + +extern const unsigned int CID_DebugLineDrawer; +IBase* __fastcall createDebugLineDrawer(unsigned int iid, IBase* outer); + +} } } +#endif diff --git a/Code/BF2/IO/BitStream.cpp b/Code/BF2/IO/BitStream.cpp index 45ffc68d1..667b0d351 100644 --- a/Code/BF2/IO/BitStream.cpp +++ b/Code/BF2/IO/BitStream.cpp @@ -1,6 +1,9 @@ // Bit-level serialization and compressed vector and quaternion codecs. #include "BitStream.h" +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] x86 conversion results on both Mac architectures. +#endif #include // sqrtf, atan2f, acosf, sinf, cosf, fabsf — the vector and normal encoders #include // std::memcpy — setData's payload copy #include "../Core/Debug.h" // resetWritePosition's attested guard line @@ -101,7 +104,16 @@ void BitStream::resetWritePosition() return; } m_canResetWritePosition = false; +#if defined(_WIN32) setPosition(*reinterpret_cast(&m_dword24)); // +0x24 block, BSPosition-shaped +#else + // [CHOSEN, not recovered] POSIX: materialize the saved fields without a typed overlay. + // The two unknown BSPosition words are not read by setPosition. + BSPosition saved{}; + saved.m_position = m_writePosition; + saved.m_readWriteSwitch = m_readWriteSwitch2; + setPosition(saved); +#endif } // Copies n bytes into the existing buffer and makes them readable. @@ -203,7 +215,13 @@ bool BitStream::writeBits(const void* src, unsigned int nbits) // source byte's low bits — the classic unaligned bit blit. while (firstPtr <= lastPtr) { +#if defined(_WIN32) const unsigned char cur = *in++; +#else + // [CHOSEN, not recovered] POSIX: no speculative source byte beyond the field. + const unsigned char cur = in < static_cast(src) + (nbits + 7u) / 8u + ? *in++ : 0; +#endif *firstPtr = (unsigned char)((cur << startBit) | (prev >> (8 - startBit))); ++firstPtr; prev = cur; @@ -254,7 +272,12 @@ bool BitStream::readBits(void* dst, unsigned int nbits) // Whole output bytes. while (remaining > 7) { +#if defined(_WIN32) const unsigned char cur = *in++; +#else + // [CHOSEN, not recovered] POSIX buffers need no extra byte after the last field. + const unsigned char cur = in < m_buffer + (end + 7u) / 8u ? *in++ : 0; +#endif *out++ = (unsigned char)((cur << upShift) | (prev >> bitOffset)); remaining -= 8; prev = cur; @@ -265,7 +288,11 @@ bool BitStream::readBits(void* dst, unsigned int nbits) // last byte's outside bits from a pre-loop copy. Both are needed; neither is redundant. if (remaining > 0) { +#if defined(_WIN32) const unsigned char cur = *in; +#else + const unsigned char cur = in < m_buffer + (end + 7u) / 8u ? *in : 0; +#endif const unsigned char v = (unsigned char)((cur << upShift) | (prev >> bitOffset)); *out = (unsigned char)(v & ((1u << remaining) - 1u)); } @@ -327,7 +354,11 @@ void BitStream::writeCompressedVectorWithTable(const Vec3& v, const Vec3& ref, f for (int i = 0; i < 3; ++i) { +#if defined(__APPLE__) + int q = bf2x87::toIntTruncate(d[i] * invScale); +#else int q = (int)(d[i] * invScale); // cvttss2si — truncates toward zero +#endif unsigned int sign = 0; if (q < 0) { sign = 1; q = -q; } // Plain sign-magnitude: the same width either way, and negative zero is representable. @@ -439,7 +470,11 @@ void BitStream::writeCompressedVector2(const Vec3& v, const Vec3& ref, float sca const float d[3] = { dx, dy, dz }; for (int i = 0; i < 3; ++i) { +#if defined(__APPLE__) + int q = bf2x87::toIntTruncate(d[i] * invScale); +#else int q = (int)(d[i] * invScale); +#endif unsigned int sign = 0; if (q < 0) { sign = 1; q = -q; } writeBits(&sign, 1); @@ -533,7 +568,11 @@ void BitStream::writeNormalAngle(float angle, int nbits) // The nonnegative angle mapping uses the full width for magnitude, with truncating conversion. const unsigned int max = (1u << nbits) - 1u; +#if defined(__APPLE__) + unsigned int q = static_cast(bf2x87::toIntTruncate(unit * (float)max)); +#else unsigned int q = (unsigned int)(unit * (float)max); +#endif writeBits(&q, nbits); } @@ -631,7 +670,11 @@ void BitStream::writeQuatComponent(float v, int nbits) if (unit < 0.0f) unit = 0.0f; const unsigned int max = (1u << nbits) - 1u; +#if defined(__APPLE__) + unsigned int qv = static_cast(bf2x87::toIntTruncate(unit * (float)max)); +#else unsigned int qv = (unsigned int)(unit * (float)max); // fnstcw/or 0xC00/fistp == a truncating cast +#endif writeBits(&qv, nbits); } @@ -694,7 +737,11 @@ void writeUnitQuatComponent(BitStream& s, float v, int nbits) else if (unit > 1.0f) unit = 1.0f; const unsigned int max = (1u << nbits) - 1u; +#if defined(__APPLE__) + const unsigned int qv = static_cast(bf2x87::toIntTruncate(unit * (float)max)); +#else const unsigned int qv = (unsigned int)(unit * (float)max); // truncating cast (fnstcw/0xC00/fistp) +#endif s.writeBits(&qv, nbits); } @@ -780,7 +827,11 @@ Vec3 BitStream::shrinkNormalVector(const Vec3& v, int nbits) float unit = (normalised + 1.0f) * 0.5f; if (unit < 0.0f) unit = 0.0f; else if (unit > 1.0f) unit = 1.0f; +#if defined(__APPLE__) + const float q = static_cast(bf2x87::toIntTruncate(unit * (float)max)) / (float)max; +#else const float q = (float)((int)(unit * (float)max)) / (float)max; // truncate, then dequantise +#endif return PI * (q + q - 1.0f); }; diff --git a/Code/BF2/IO/Console/Console.cpp b/Code/BF2/IO/Console/Console.cpp index c1a6eda84..068cc8308 100644 --- a/Code/BF2/IO/Console/Console.cpp +++ b/Code/BF2/IO/Console/Console.cpp @@ -14,6 +14,7 @@ #include #include // sprintf - autoCompletion pastes the argument match #include // tolower - autoCompletion's common-prefix loop +#include // run() executes scripts in a nested scope; include() executes in the caller's scope and access level. @@ -35,6 +36,48 @@ namespace io { extern OldConsole* mainConsole; // _ZN4dice3hfe2io11mainConsoleE extern OldConsole* g_executingConsole; // ds:0x8AC3C88 - see handleCommand +namespace { +#if !DEDICATED +// [TEMP] [CHOSEN, not recovered] Local console testing requested by the owner. +// Only keyboard Enter/Tab can establish this scope; calls outside that scope retain their +// access policy. Scripts invoked by an unlocked command inherit its local scope. +// [RETIRE-WHEN: client-console-testing] Remove after developer-console policy +// is settled and its interactive and remote authorization checks are validated. +thread_local OldConsole* s_unlockedInteractiveConsole = nullptr; + +bool interactiveFullAccessEnabled() +{ + // Opt-in: without BF2_CLIENT_CONSOLE_FULL_ACCESS the retail end-user access policy applies. + const char* value = std::getenv("BF2_CLIENT_CONSOLE_FULL_ACCESS"); + return value && std::strcmp(value, "0") != 0; +} + +class InteractiveAccessScope +{ +public: + explicit InteractiveAccessScope(OldConsole* console) + : m_previous(s_unlockedInteractiveConsole) + { + if (interactiveFullAccessEnabled()) + s_unlockedInteractiveConsole = console; + } + ~InteractiveAccessScope() { s_unlockedInteractiveConsole = m_previous; } +private: + OldConsole* m_previous; +}; +#endif + +bool isUnlockedInteractiveConsole(const OldConsole* console) +{ +#if !DEDICATED + return s_unlockedInteractiveConsole == console; +#else + (void)console; + return false; +#endif +} +} // namespace + // Shared mutable output sink for callers that discard console output. std::string Console::ignoredString_; @@ -617,7 +660,11 @@ int OldConsole::handleCommand(const std::string& cmd, std::string& result, Acces // Bindings carrying access bit 4 use the archive-specific policy; others require an intersecting caller access mask. const int methodAccess = binding->getAccess(); // vtbl +0x18 - if (methodAccess & 4) + if (isUnlockedInteractiveConsole(this)) + { + // The local testing scope bypasses access only, not activity or argument checks. + } + else if (methodAccess & 4) { // The privileged policy: the script must have come from an archive and the // caller must hold bit 2. @@ -872,7 +919,8 @@ std::string OldConsole::listConstants(const std::string& filter) } // Updates the edited line, history recall or scroll position from a key. -// Enter and Tab temporarily use end-user access on mainConsole. Delete clears the whole line. +// Enter and Tab use the local testing access policy, or end-user access on mainConsole +// when that policy is disabled. Delete clears the whole line. // [UNRESOLVED] Return contract beyond the current void declaration. void OldConsole::updateAsciiKey(char key) { @@ -880,12 +928,17 @@ void OldConsole::updateAsciiKey(char key) { case 13: // Enter - execute the line { +#if !DEDICATED + InteractiveAccessScope interactiveAccess(this); + if (isUnlockedInteractiveConsole(this)) + output("[CHOSEN] Local client console full access enabled for this command."); +#endif m_currentLineBuffer[m_currentLineLength] = '\n'; m_currentLineBuffer[m_currentLineLength + 1] = '\0'; std::string result; const int savedAccess = mainConsole->getAccess(); - mainConsole->setAccess(1); // mainConsole, not this - see above + mainConsole->setAccess(isUnlockedInteractiveConsole(this) ? 2 : 1); executeLine(std::string(m_currentLineBuffer), result, true, true, true, false, false); @@ -907,10 +960,13 @@ void OldConsole::updateAsciiKey(char key) m_currentLineLength = 0; break; - case 9: // Tab - autocomplete, also sandboxed at access 1 + case 9: // Tab - autocomplete with the same local access policy { +#if !DEDICATED + InteractiveAccessScope interactiveAccess(this); +#endif const int savedAccess = mainConsole->getAccess(); - mainConsole->setAccess(1); + mainConsole->setAccess(isUnlockedInteractiveConsole(this) ? 2 : 1); autoCompletion(); mainConsole->setAccess(savedAccess); break; @@ -1101,7 +1157,7 @@ void OldConsole::autoCompletion() if (!obj->isActive()) continue; - if ((m_access & 2) == 0 && (obj->getAccess() & 2) != 0) + if (!isUnlockedInteractiveConsole(this) && (m_access & 2) == 0 && (obj->getAccess() & 2) != 0) continue; // A hit assigns the stored candidate into `completion` and then does nothing with it - @@ -1144,7 +1200,7 @@ void OldConsole::autoCompletion() if (!obj->isActive()) continue; - if ((m_access & 2) == 0 && (obj->getAccess() & 2) != 0) + if (!isUnlockedInteractiveConsole(this) && (m_access & 2) == 0 && (obj->getAccess() & 2) != 0) continue; if (compareIgnoreCase(object.c_str(), obj->getObjectName()) != 0) continue; diff --git a/Code/BF2/IO/File/File.cpp b/Code/BF2/IO/File/File.cpp index 986e7cc71..9ec7627c8 100644 --- a/Code/BF2/IO/File/File.cpp +++ b/Code/BF2/IO/File/File.cpp @@ -5,6 +5,9 @@ #include "FileManager.h" // io::fileManager - open() goes through the virtual filesystem #include "../../Math/Vec3.h" #include +#if !defined(_WIN32) +#include "../../Platform/Utf16.h" +#endif namespace dice { namespace hfe { @@ -132,6 +135,7 @@ bool File::read(std::string& out, char delimiter) // ELF 0x48D050; engine 0x8435620 use sizeof(wchar_t) disk units. bool File::read(std::wstring& out, wchar_t delimiter) { +#if defined(_WIN32) || defined(BF2_IMAGE_AIDLL) wchar_t buffer[4096]; unsigned int count = 0; while (m_file->read(buffer + count, sizeof(wchar_t)) == sizeof(wchar_t) @@ -139,6 +143,18 @@ bool File::read(std::wstring& out, wchar_t delimiter) ++count; buffer[count] = 0; out = buffer; +#else + // [CHOSEN, not recovered] The native engine reads retail UTF-16LE game text. + // The AI DLL retains the ELF's native-wchar_t reader. See docs/macos-s2-10-threads.md. + // Preserve delimiter consumption, NUL truncation, EOF success and the original buffer bound. + char16_t buffer[4096]; + unsigned int count = 0; + while (platform::readUtf16LE(*m_file, buffer[count]) + && buffer[count] != delimiter) + ++count; + buffer[count] = 0; + out = platform::utf16ToWide(buffer); +#endif return true; } diff --git a/Code/BF2/IO/File/FileChangeManager.h b/Code/BF2/IO/File/FileChangeManager.h index cd0f9cbe6..6a2542974 100644 --- a/Code/BF2/IO/File/FileChangeManager.h +++ b/Code/BF2/IO/File/FileChangeManager.h @@ -12,6 +12,7 @@ #include #include "../../Core/IBase.h" +#include "../../Core/Ids.h" // the io:: filesystem-change IDs #include "IFileSystem.h" // dice::hfe::NoCaseStringCompare, io::FileInfo, IFileSystem namespace dice { @@ -171,12 +172,11 @@ class FileChangeManager : public IFileChangeManager, public IDirectoryChangeList // do not define it here. extern FileChangeManager* fileChangeManager; -// Filesystem-change IDs belong to dice::hfe::io; keep namespace declarations consistent. -extern const unsigned int IID_IFileChangeManager; // 2985214972u -extern const unsigned int IID_IFileChangeListener; // 1014715647u -extern const unsigned int IID_IDirectoryChangeListener; // 3032597244u -extern const unsigned int IID_IDirectoryChangeNotifier; // 1193638398u -extern const unsigned int CID_FileChangeManager; // 862549759u +// The filesystem-change IDs (IID_IFileChangeManager, IID_IFileChangeListener, +// IID_IDirectoryChangeListener, IID_IDirectoryChangeNotifier, CID_FileChangeManager) are the +// dice::hfe::io constants in Core/Ids.h, included above. They used to be declared extern here, +// which gave Ids.h's definitions external linkage in every TU that included this header first: +// FileChangeManager.cpp and the client's BF2Engine.cpp then defined them twice. } // namespace io } // namespace hfe diff --git a/Code/BF2/IO/File/FileManager.cpp b/Code/BF2/IO/File/FileManager.cpp index 3cf7e06e2..64b1e8d3e 100644 --- a/Code/BF2/IO/File/FileManager.cpp +++ b/Code/BF2/IO/File/FileManager.cpp @@ -16,6 +16,7 @@ #include #else #include +#include #endif #include @@ -38,6 +39,26 @@ static const char* const kRootOverloadReplacement = ""; // Absolute paths bypass substitution. namespace { +#if defined(__APPLE__) && !DEDICATED +// [CHOSEN, not recovered] macOS client port (docs/macos-c-metal-ingame.md, loading screen). +// Game paths may start with '/': SwiffPlayer's "$/Levels//Info/loadMap.png" reaches open() +// as "/Levels/...". On Windows isPathAbsolute only accepts drive paths, so such a name is prefixed +// with each search-path entry ("mods/bf2/" + "/Levels/..."). On a POSIX host every '/' path counts +// as absolute and the lookup went to the host root. Host-absolute paths in the client come from +// the absolute @HOME@ substitution (or a developer's own absolute path); they are told apart by a +// first component that exists at the host root ("/Users", "/private", "/Volumes", ...). Any +// other '/' path keeps the Windows meaning. +bool isHostAbsolutePath(const std::string& path) +{ + if (!isPathAbsolute(path)) + return false; + const std::string::size_type end = path.find('/', 1); + const std::string first = path.substr(0, end); + struct stat st; + return first.size() > 1 && ::stat(first.c_str(), &st) == 0; +} +#endif + // `base` is the search-path entry being tried. `out` receives the expanded result. void expandPath(std::string& path, const std::string& base, std::string* out, @@ -47,7 +68,11 @@ void expandPath(std::string& path, const std::string& base, std::string* out, static const std::string rootPrefix = "@ROOT@"; // guard 0x8AC3D58 static const std::string modPrefix = "@MOD@"; // guard 0x8AC3D60 +#if defined(__APPLE__) && !DEDICATED + if (isHostAbsolutePath(path)) +#else if (isPathAbsolute(path)) +#endif { out->assign(path); return; @@ -87,6 +112,25 @@ void expandPath(std::string& path, const std::string& base, std::string* out, else *out = prefix + base + path; } +// Folds an expanded loose-file path before an existence or enumeration test. +#if defined(__APPLE__) && !DEDICATED +// [CHOSEN, not recovered] c-loopback: the macOS client's @HOME@ substitution is absolute +// (Platform/macOS/ClientPaths), and goUpInPath turns "/Users/..." into the cwd-relative +// "Users/...". fileExistsEx/getFileExists/findFiles then never see @HOME@ files (no local +// profile was ever found), while open(), which skips the fold, reads them. Keep the leading '/'. +// The Windows home is a drive path and the ELF dedicated home is never read, so both keep the +// shipped fold unchanged. +void goUpInExpandedPath(std::string& full) +{ + const bool absolute = !full.empty() && full[0] == '/'; + goUpInPath(full); + if (absolute && (full.empty() || full[0] != '/')) + full.insert(full.begin(), '/'); +} +#else +inline void goUpInExpandedPath(std::string& full) { goUpInPath(full); } +#endif + } // anonymous namespace // Reports and removes the legacy bf2/content/ path segment, matched case-insensitively. @@ -125,8 +169,20 @@ void FileManager::getWritePath(const std::string& name, std::string& out) if (path.find("@ROOT@") == 0) out = m_fileSystem->getRootSubstitution() + path.substr(6); // 3. @home@ prefix +#if defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The macOS client's @HOME@ is absolute; goUpInPath below drops a + // leading '/' (harmless for Windows drive paths). Normalize only the part after the macro. + else if (path.find("@HOME@") == 0) + { + std::string tail = path.substr(6); + goUpInPath(tail); + out = m_fileSystem->getHomeSubstitution() + "/" + tail; + return; + } +#else else if (path.find("@HOME@") == 0) out = m_fileSystem->getHomeSubstitution() + path.substr(6); +#endif // 4. otherwise relative to the write path else out = writePath + path; @@ -271,7 +327,7 @@ std::string FileManager::fileExistsEx2(const std::string& name) std::string full; std::string copy = path; expandPath(copy, *it, &full, m_fileSystem); - goUpInPath(full); + goUpInExpandedPath(full); if (m_fileSystem->fileExists(full)) return full; } @@ -535,7 +591,7 @@ std::string FileManager::fileExistsEx(const std::string& name, bool skipArchives std::string full; std::string p = path; expandPath(p, *it, &full, m_fileSystem); - goUpInPath(full); + goUpInExpandedPath(full); if (m_fileSystem->fileExists(full)) return full; @@ -945,7 +1001,7 @@ int FileManager::findFiles(const std::string& pattern, bool recursive, std::string full; std::string p = path; expandPath(p, *it, &full, m_fileSystem); - goUpInPath(full); + goUpInExpandedPath(full); m_fileSystem->findFiles(full, recursive, scratch); diff --git a/Code/BF2/IO/File/FileManager.h b/Code/BF2/IO/File/FileManager.h index 0a43c07ca..ad7964517 100644 --- a/Code/BF2/IO/File/FileManager.h +++ b/Code/BF2/IO/File/FileManager.h @@ -213,6 +213,12 @@ static_assert(sizeof(std::list) == 16 && sizeof(std::multimap) == 16, "native x64 FileManager list/map widths"); static_assert(sizeof(FileManager) == 0xA0, "native x64 FileManager layout changed - revalidate STL widths"); +#elif defined(__LP64__) && defined(_LIBCPP_VERSION) +// [CHOSEN, not recovered] Native macOS port on libc++: string 24, vector 24, list 24. As on +// Linux, no total size is pinned and nothing reads a shipped host object through this class. +static_assert(sizeof(std::string) == 24 && sizeof(std::vector) == 24 && + sizeof(std::list) == 24, + "libc++ FileManager string/vector/list widths"); #elif defined(__LP64__) // [CHOSEN, not recovered] Native Linux x86-64 port on libstdc++: the same // native declaration as the MSVC x64 branch, but libstdc++'s containers are wider (list 24, map and diff --git a/Code/BF2/IO/File/FileManagerConsole.cpp b/Code/BF2/IO/File/FileManagerConsole.cpp index 33aaaeb8b..09f24919d 100644 --- a/Code/BF2/IO/File/FileManagerConsole.cpp +++ b/Code/BF2/IO/File/FileManagerConsole.cpp @@ -5,6 +5,7 @@ #include "../Console/Console.h" // io::mainConsole - console.allowMultipleFileLoad's receiver #include "../../Core/SettingsRepostitory.h" #include "../../Core/EventManager.h" +#include "../../Core/Types.h" #include "../../Core/StringUtil.h" // compareIgnoreCase - the Console reflection rows #include // sprintf - Console_getEnumName #include @@ -533,6 +534,7 @@ class ConsoleClass503 : public ConsoleObjectBaseImpl static ConsoleClass503 s_settingsStringSet; } +#if DEDICATED // SettingsManager.boolSet / SettingsManager.floatGet - dedicated PE defaults 0x770E66 // ("SettingsManager", access 1, category 0); ctors 0x646FB9 / 0x647DFC (vtable off_7F1930 / // off_7F1D20, both file-static, m_isDynamic = 0). isObjectActive 0x70FC1B is unconditionally true. @@ -637,6 +639,106 @@ class ConsoleClass_floatGet : public ConsoleObjectBaseImpl }; static ConsoleClass_floatGet s_settingsFloatGet; } // namespace +#endif + +#if !DEDICATED +namespace { +// Typed settings commands only expose names registered by SettingsManager. Setters still +// store equal values but publish the setting-change event only when the value changes. +template +bool consoleSettingsSet(std::string& name, const T& value, const T& fallback, + const T& (SettingsRepostitory::*get)(const std::string&, const T&), + void (SettingsRepostitory::*set)(const std::string&, const T&)) +{ + if (settingsManager->m_registeredVars.find(name) == settingsManager->m_registeredVars.end()) + return false; + const bool changed = (settings->*get)(name, fallback) != value; + (settings->*set)(name, value); + if (changed && eventManager) + eventManager->postEvent(EventCategory(5), 1, &name, 0.0f); + return true; +} + +template +T consoleSettingsGet(const std::string& name, const T& fallback, + const T& (SettingsRepostitory::*get)(const std::string&, const T&)) +{ + if (settingsManager->m_registeredVars.find(name) == settingsManager->m_registeredVars.end()) + return fallback; + return (settings->*get)(name, fallback); +} + +// These fixed-arity methods return values, unlike the void-command generator macros. +#define SETTINGS_SET_BINDING(method, T, getter, setter, fallback) \ +class Settings_##method : public ConsoleObjectBaseImpl { \ +public: \ + Settings_##method() { \ + m_objectName = "SettingsManager"; m_functionName = #method; \ + m_access = 1; m_category = 0; m_type = 0; m_minNoArgs = m_maxNoArgs = 2; \ + m_returnType = "bool"; m_hasReturnValue = false; m_isDynamic = false; \ + m_argTypes[0] = "std::string"; m_argTypes[1] = #T; \ + m_argNeedsConversion[0] = 0; m_argNeedsConversion[1] = -1; \ + consoleBindingList(kFileConsoleTag).push_back(this); \ + } \ + bool isObjectActive() const override { return true; } \ + void executeObjectMethod() override { \ + if (m_argCount != 2) return; \ + std::string name = BF2_CC_ARG(std::string, 0); \ + const T value = BF2_CC_ARG(T, 1); \ + m_hasReturnValue = true; \ + m_returnValue = consoleSettingsSet(name, value, fallback, \ + &SettingsRepostitory::getter, &SettingsRepostitory::setter); \ + } \ + void setArgFromString(int index, const std::string& value) override { \ + BF2_CC_CONVERT(std::string, 1) BF2_CC_CONVERT(T, 2) \ + } \ + BF2_CC_RETURN_AS_STRING \ + BF2_CC_COMMON_HOOKS \ +private: bool m_returnValue; \ +}; \ +static Settings_##method s_settings_##method; + +#define SETTINGS_GET_BINDING(method, T, getter, fallback) \ +class Settings_##method : public ConsoleObjectBaseImpl { \ +public: \ + Settings_##method() { \ + m_objectName = "SettingsManager"; m_functionName = #method; \ + m_access = 1; m_category = 0; m_type = 0; m_minNoArgs = m_maxNoArgs = 1; \ + m_returnType = #T; m_hasReturnValue = false; m_isDynamic = false; \ + m_argTypes[0] = "std::string"; m_argNeedsConversion[0] = 0; \ + consoleBindingList(kFileConsoleTag).push_back(this); \ + } \ + bool isObjectActive() const override { return true; } \ + void executeObjectMethod() override { \ + if (m_argCount != 1) return; \ + const std::string name = BF2_CC_ARG(std::string, 0); \ + m_hasReturnValue = true; \ + m_returnValue = consoleSettingsGet(name, fallback, &SettingsRepostitory::getter); \ + } \ + void setArgFromString(int index, const std::string& value) override { \ + BF2_CC_CONVERT(std::string, 1) \ + } \ + BF2_CC_RETURN_AS_STRING \ + BF2_CC_COMMON_HOOKS \ +private: T m_returnValue; \ +}; \ +static Settings_##method s_settings_##method; + +SETTINGS_SET_BINDING(boolSet, bool, boolGet, boolSet, false) +SETTINGS_SET_BINDING(intSet, int, intGet, intSet, -1) +SETTINGS_SET_BINDING(floatSet, float, floatGet, floatSet, -1.0f) +SETTINGS_SET_BINDING(U32Set, U32, U32Get, U32Set, 0u) +SETTINGS_GET_BINDING(stringGet, std::string, stringGet, std::string("UnSet")) +SETTINGS_GET_BINDING(boolGet, bool, boolGet, false) +SETTINGS_GET_BINDING(intGet, int, intGet, -1) +SETTINGS_GET_BINDING(floatGet, float, floatGet, -1.0f) +SETTINGS_GET_BINDING(U32Get, U32, U32Get, 0u) + +#undef SETTINGS_SET_BINDING +#undef SETTINGS_GET_BINDING +} // namespace +#endif + BF2_CONSOLE_OBJECT("FileManager", 2, 0) // mountArchive accepts an optional contentCheck argument. diff --git a/Code/BF2/IO/File/IFileSystem.h b/Code/BF2/IO/File/IFileSystem.h index 5bd18153b..d78214756 100644 --- a/Code/BF2/IO/File/IFileSystem.h +++ b/Code/BF2/IO/File/IFileSystem.h @@ -16,6 +16,8 @@ namespace hfe { // Case-insensitive strict ordering for engine string-keyed containers. struct NoCaseStringCompare { + // RendDX9.dll PE 0x10015140 (COMDAT copy, `retn 8`, this unread: _stricmp(a, b) < 0 via setl), + // folded across the image's six string-keyed tree instantiations. bool operator()(const std::string& a, const std::string& b) const { #ifdef _MSC_VER diff --git a/Code/BF2/IO/File/UnixFileStream.cpp b/Code/BF2/IO/File/UnixFileStream.cpp index b3a270fdc..ca6d47891 100644 --- a/Code/BF2/IO/File/UnixFileStream.cpp +++ b/Code/BF2/IO/File/UnixFileStream.cpp @@ -262,6 +262,14 @@ bool UnixFileStream::open(const std::string& name, FileMode mode, FileAccess acc if (mode == FileMode(0) || mode == FileMode(1)) m_fileSystem.createDirectory(extractFilePath(file, '/')); +#if defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The macOS client stands in for the Win32 client, whose stream also + // creates the parent directories for open-always (Win32FileSystem.cpp openFile: modes 0, 1 + // and 3); the ELF does it for modes 0 and 1 only. The screenshot capture opens its file with + // mode 3 under @HOME@/Screenshots, which nothing else creates. + else if (mode == FileMode(3)) + m_fileSystem.createDirectory(extractFilePath(file, '/')); +#endif m_fd = ::open(file.c_str(), flags, 0600); // 0x180: owner read/write only if (m_fd == -1) diff --git a/Code/BF2/IO/File/UnixFileSystem.cpp b/Code/BF2/IO/File/UnixFileSystem.cpp index 14230fc87..b30034fe2 100644 --- a/Code/BF2/IO/File/UnixFileSystem.cpp +++ b/Code/BF2/IO/File/UnixFileSystem.cpp @@ -17,6 +17,9 @@ #include "../../Core/Debug.h" #include "../../Core/Ids.h" #include "UnixFileStream.h" +#if defined(__APPLE__) && !DEDICATED +#include "../../Platform/macOS/ClientPaths.h" +#endif namespace dice { namespace hfe { @@ -42,6 +45,39 @@ void buildFileInfo(FileInfo* info, const struct stat* st) info->lastWriteTimeHigh = 0; } +#if defined(__APPLE__) && !DEDICATED +// [CHOSEN, not recovered] The client image's directory removal. BF2.exe's Win32FileSystem::deleteFile +// (0x676440) removes a directory recursively through the shell (FO_DELETE); the dedicated ELF's +// unlink cannot. LocalProfileManager::deleteProfile (PE 0x4AAF70) deletes a whole profile directory +// through deleteFile, so the macOS client removes the tree depth-first. Symbolic links are removed, +// never followed. +bool removeDirectoryTree(const std::string& path) +{ + DIR* dir = opendir(path.c_str()); + if (!dir) + return false; + bool ok = true; + while (struct dirent* entry = readdir(dir)) + { + if (std::strcmp(entry->d_name, ".") == 0 || std::strcmp(entry->d_name, "..") == 0) + continue; + const std::string child = path + "/" + entry->d_name; + struct stat st; + if (lstat(child.c_str(), &st) != 0) + { + ok = false; + continue; + } + if (S_ISDIR(st.st_mode)) + ok = removeDirectoryTree(child) && ok; + else if (unlink(child.c_str()) != 0) + ok = false; + } + closedir(dir); + return rmdir(path.c_str()) == 0 && ok; +} +#endif + } // anonymous namespace // Construction and destruction @@ -114,7 +150,18 @@ IBase* UnixFileSystem::create(unsigned int iid, IBase* outer) // Normalizes a path in place by folding case and converting backslashes to forward slashes. void UnixFileSystem::fixUnixPath(std::string& path) { - for (std::string::size_type i = 0; i < path.size(); ++i) + std::string::size_type first = 0; +#if defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The ELF lowercases whole paths, which are relative game paths there. + // The macOS client's @HOME@ substitution is an absolute user path (clientDataDirectory): + // lowercasing it named a different path on case-sensitive volumes and under the runner's + // sandbox, so a fresh home's Profile.con/Global.con writes silently failed. Keep that prefix + // as it is; everything after it is lowered as before (docs/macos-c-asan-heap.md). + const std::string& home = macos::clientDataDirectory(); + if (!home.empty() && path.compare(0, home.size(), home) == 0) + first = home.size(); +#endif + for (std::string::size_type i = first; i < path.size(); ++i) { if (path[i] == '\\') path[i] = '/'; @@ -208,6 +255,18 @@ bool UnixFileSystem::deleteFile(const std::string& name) std::string path(name); fixUnixPath(path); +#if defined(__APPLE__) && !DEDICATED + struct stat st; + if (lstat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) + { + if (!removeDirectoryTree(path)) + { + logError("rmdir", path); + return false; + } + return true; + } +#endif if (unlink(path.c_str()) == -1) { logError("unlink", path); @@ -299,6 +358,13 @@ bool UnixFileSystem::createDirectory(const std::string& path) { if (path[i] != '/') continue; +#if defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] The ELF only sees relative paths. The macOS client writes + // under an absolute @HOME@, whose leading '/' made the first part "" and mkdir("") + // fail with ENOENT, which aborted the walk: a fresh home never got Profiles/Default/. + if (i == 0) + continue; +#endif std::string part(path, 0, i); if (mkdir(part.c_str(), 0755) == -1 && errno != EEXIST) @@ -376,11 +442,16 @@ int UnixFileSystem::findFiles_recursionHelper(const std::string& path, bool recu // then hands back "/tmp" anyway. Line 435 of this file, and the source of its attested path. const std::string& UnixFileSystem::getHomeSubstitution() const { +#if defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] Client data is independent of the read-only game installation. + return macos::clientDataDirectory(); +#else Debug(DEBUGTYPE_6, __FILE__, 435, std::string()) << "dep: dedicated servers aren't allowed to write to @HOME@"; static const std::string home("/tmp"); return home; +#endif } // @root@ is the current directory. diff --git a/Code/BF2/IO/Input/ControlMap.cpp b/Code/BF2/IO/Input/ControlMap.cpp index 8a6dad6a2..109461d45 100644 --- a/Code/BF2/IO/Input/ControlMap.cpp +++ b/Code/BF2/IO/Input/ControlMap.cpp @@ -906,9 +906,42 @@ void ControlMap::reset() m_keyboardSensitivity = 0.1f; } -// [CHOSEN-STUB] - the selective reset. -void ControlMap::reset(int /*id*/, bool /*a*/, bool /*b*/, bool /*c*/) -{ +// ELF 0x8492AC0. Clears one binding of input id (mapNextInput's Escape). A trigger loses its +// primary or alternate mapping whole. An axis loses its positive half, its negative half, or (both +// set) everything; once neither half holds a key or button the mapping also drops its device and +// axis (15 = none). +void ControlMap::reset(int id, bool positive, bool negative, bool alternate) +{ + std::map::iterator t = m_triggerMappings.find(id); + if (t != m_triggerMappings.end()) + { + (alternate ? t->second->alternate : t->second->primary).reset(); + return; + } + std::map::iterator a = m_axisMappings.find(id); + if (a == m_axisMappings.end()) + return; + AxisMapping& m = alternate ? a->second->alternate : a->second->primary; + if (positive) + { + if (negative) + { + m.reset(); + return; + } + m.positiveKey = 0; + m.positiveButton = 0; + } + else if (negative) + { + m.negativeKey = 0; + m.negativeButton = 0; + } + if (m.positiveKey == 0 && m.negativeKey == 0 && m.positiveButton == 0 && m.negativeButton == 0) + { + m.axis = 15; + m.device = 0; + } } @@ -1204,13 +1237,108 @@ void ControlMap::dump(bool /*b*/) { } -// [CHOSEN-STUB] Duplicate-input detection is unimplemented. -// A complete implementation must account for axis, trigger and button equivalences. -bool ControlMap::findDuplicate(InputDeviceFlags& /*device*/, InputDeviceAxes& /*axis*/, - InputDeviceButtons& /*button*/, InputDeviceKeys& /*key*/, - DuplicateKeyVector& /*out*/) +// ELF 0x8494960 (4595 bytes). Collects every binding of this map that already uses the device +// input (device, axis, button, key) into out and answers whether there was any. A keyboard key +// held by an unassigned trigger answers true at once with nothing collected. Keyboard bindings +// are matched on the key alone (the device argument is not consulted for them); other bindings +// need the same device and the axis (15 = none) or button (0 = none). Triggers whose threshold +// is 1000 (the double-tap companions, e.g. c_PIAltSprint) never count as duplicates. +bool ControlMap::findDuplicate(InputDeviceFlags& device, InputDeviceAxes& axis, + InputDeviceButtons& button, InputDeviceKeys& key, + DuplicateKeyVector& out) { - return false; + if (device == 2) // IDFKeyboard + { + for (unsigned int i = 0; i < m_unassignedTriggerMappings.size(); ++i) + if (m_unassignedTriggerMappings[i]->key == key) + return true; + } + + for (std::map::iterator it = m_axisMappings.begin(); it != m_axisMappings.end(); ++it) + { + for (int slot = 0; slot < 2; ++slot) + { + const AxisMapping& m = slot != 0 ? it->second->alternate : it->second->primary; + if (m.device == 0) + continue; + if (m.device == 2) + { + if (key == 0) + continue; + if (key == m.positiveKey) + { + out.ids.push_back(it->first); + out.negative.push_back(false); + out.alternate.push_back(slot > 0); + } + else if (key == m.negativeKey) + { + out.ids.push_back(it->first); + out.negative.push_back(true); + out.alternate.push_back(slot > 0); + } + } + else if (device == m.device) + { + if (axis != 15 && axis == m.axis) + { + out.ids.push_back(it->first); + out.negative.push_back(false); + out.alternate.push_back(slot > 0); + } + else if (button != 0) + { + if (button == m.positiveButton) + { + out.ids.push_back(it->first); + out.negative.push_back(false); + out.alternate.push_back(slot > 0); + } + else if (button == m.negativeButton) + { + out.ids.push_back(it->first); + out.negative.push_back(true); + out.alternate.push_back(slot > 0); + } + } + } + } + } + + for (std::map::iterator it = m_triggerMappings.begin(); it != m_triggerMappings.end(); ++it) + { + for (int slot = 0; slot < 2; ++slot) + { + const TriggerMapping& m = slot != 0 ? it->second->alternate : it->second->primary; + if (m.device == 0) + continue; + if (m.device == 2) + { + if (key != 0 && key == m.key && m.threshold != 1000.0f) + { + out.ids.push_back(it->first); + out.negative.push_back(false); + out.alternate.push_back(slot > 0); + } + } + else if (m.type == 1) + { + if (device == m.device && axis != 15 && axis == m.axis) + { + out.ids.push_back(it->first); + out.negative.push_back(false); + out.alternate.push_back(slot > 0); + } + } + else if (device == m.device && button != 0 && button == m.button) + { + out.ids.push_back(it->first); + out.negative.push_back(false); + out.alternate.push_back(slot > 0); + } + } + } + return out.ids.size() != 0; } // ELF 0x8495B60. [CHOSEN-STUB] diff --git a/Code/BF2/IO/Input/ControlMap.h b/Code/BF2/IO/Input/ControlMap.h index 7309c09b3..1aeec2d98 100644 --- a/Code/BF2/IO/Input/ControlMap.h +++ b/Code/BF2/IO/Input/ControlMap.h @@ -142,7 +142,7 @@ class ControlMap : public IControlMap virtual void removeMapping(unsigned int id); virtual void reset(); - virtual void reset(int id, bool a, bool b, bool c); + virtual void reset(int id, bool positive, bool negative, bool alternate); // 0x8492AC0, 256 recovered virtual void setButtonRiseTime(float t); // 0x8492BE0, 14 recovered virtual void setButtonFallTime(float t); // 0x8492C00, 14 recovered diff --git a/Code/BF2/IO/Input/ControlMapManager.cpp b/Code/BF2/IO/Input/ControlMapManager.cpp index 5702e1a40..b68460583 100644 --- a/Code/BF2/IO/Input/ControlMapManager.cpp +++ b/Code/BF2/IO/Input/ControlMapManager.cpp @@ -4,6 +4,11 @@ #include "../../Core/ClassManager.h" // create() builds a ControlMap through the class manager #include "../../Core/Ids.h" // [INFERRED] header name; the constants are attested +#include "../../Core/System.h" // g_system - mapNextInput's 10 s limit +#if defined(__APPLE__) && !DEDICATED +#include "../../Platform/macOS/CocoaHost.h" // [CHOSEN, not recovered] mapNextInput's event pump +#endif + #include // std::make_pair - create()'s m_byId insert namespace dice { @@ -15,6 +20,7 @@ namespace io { // Keep this declaration's type consistent with the singleton definition; MSVC mangles variable types. extern IBase* controlMapManager; // ds:0x8AC8C8C - type must match Core/Globals.cpp +extern IBase* inputDeviceManager; // ds:0x8AC8C88 - mapNextInput polls its devices // constructor / destructor @@ -175,13 +181,209 @@ IControlMap* ControlMapManager::getActive() const return m_active; } -// [CHOSEN-STUB] Input capture is unimplemented and always reports no captured input. -bool ControlMapManager::mapNextInput(IControlMap* /*map*/, int /*id*/, bool /*a*/, bool /*b*/, - bool /*c*/, bool /*d*/, std::string& /*out*/) +namespace { +// Inputs that may share a binding with another input (ds:0x898CD70 / ds:0x898CDA0), each table +// ending with its own enum's None sentinel. +const int playerInputAllowDuplicate[] = { + PICameraX, PICameraY, PIMouseLookX, PIMouseLookY, PINextItem, PIPrevItem, PINone +}; +const int gameInputAllowDuplicate[] = { + GIRightShift, GILeftShift, GIRightCtrl, GILeftCtrl, GIRightAlt, GIOk, GIAltOk, GIMouseLookX, + GIMouseLookY, GIMouseWheelUp, GIMouseWheelDown, GISelectAll, GIDeselectAll, GIUp, GIDown, + GILeft, GIRight, GIBack, GIPageUp, GIPageDown, GIMenuSelect0, GIMenuSelect1, GIMenuSelect2, + GIMenuSelect3, GIMenuSelect4, GIMenuSelect5, GIMenuSelect6, GIMenuSelect7, GIMenuSelect8, + GIMenuSelect9, GIToggleFreeCamera, GIDelete, GINone +}; +} + +// ELF 0x8498F50: membership in the player or game table. +bool ControlMapManager::allowDuplicate(int id, bool playerMap) { + if (playerMap) + { + for (int i = 0; playerInputAllowDuplicate[i] != PINone; ++i) + if (id == playerInputAllowDuplicate[i]) + return true; + } + else + { + for (int i = 0; gameInputAllowDuplicate[i] != GINone; ++i) + if (id == gameInputAllowDuplicate[i]) + return true; + } return false; } +// ELF 0x8497AC0 (5133 bytes). The "press a key to bind it" capture. It polls every input device +// (no frame runs meanwhile) until one reports an input, at most 10 s (answer 2; a null map is 2 at +// once). Escape clears the binding (and, for the player map's throttle on its primary positive +// half, the c_PIAltSprint companion) and answers 0. An input the map, or with a default map the +// other default maps, already uses for an input not allowed to share it answers 1 and names the +// map in out. Otherwise the input is bound and the answer is 0. +// id: the PlayerInputMap / GameInputMap id; alternate: the secondary column; isAxis: bind as an +// axis (keys and buttons then fill one half); negative: that half is the negative one; +// playerMap: id is a player input (ControlSettings passes !gameInput). +int ControlMapManager::mapNextInput(IControlMap* map, int id, bool alternate, bool isAxis, + bool negative, bool playerMap, std::string& out) +{ + if (map == 0) + return 2; + + IInputDeviceManager* devices = static_cast(static_cast(inputDeviceManager)); + const float start = static_cast(g_system->getWallClockTime()); // +0x1C + for (;;) + { + const float now = static_cast(g_system->getWallClockTime()); + if (start + 10.0f <= now) + return 2; +#if defined(__APPLE__) && !DEDICATED + // [CHOSEN, not recovered] DirectInput fills its device buffers without the message loop; + // the macOS devices are fed by the Cocoa pump, so the capture loop pumps it. A quit + // request stays latched for the main loop. + (void) macos::CocoaHost::instance().pumpEvents(); +#endif + devices->update(0.1f); // +0x24 + devices->update(-1.0f); + std::map& all = + *static_cast*>(devices->getAllDevices()); // +0x2C + for (std::map::iterator it = all.begin(); it != all.end(); ++it) + { + InputDeviceAxes axis; + InputDeviceButtons button; + InputDeviceKeys key; + bool inverted; + if (!it->second->getNextInput(axis, button, key, inverted)) // +0x2C + continue; + + DuplicateKeyVector dups; + if (!isAxis && axis != 15) // an axis motion cannot become a trigger + continue; + + if (key == 1) // IDKey_Escape: clear the binding + { + map->reset(id, !negative, negative, alternate); // +0x58 + if (playerMap && id == PIThrottle && !negative && !alternate) + map->reset(PIAltSprint, true, true, false); + return 0; + } + + IControlMap* playerDefault = this->getControlMap(std::string("_defaultPlayerInputControlMap")); + IControlMap* gameDefault = this->getControlMap(std::string("_defaultGameControlMap")); + InputDeviceFlags device = it->first; + + if (map->findDuplicate(device, axis, button, key, dups)) // +0xB8 + { + for (unsigned int i = 0; i < dups.ids.size(); ++i) + { + if (dups.ids[i] == id && dups.negative[i] == negative && dups.alternate[i] == alternate) + continue; // the binding being replaced + if (!allowDuplicate(dups.ids[i], playerMap)) + { + out = map->getName(); // +0x14 + return 1; + } + } + dups.ids.resize(0); + dups.negative.resize(0); + dups.alternate.resize(0); + } + + if (map == gameDefault || map == playerDefault) + { + // A default map is checked against the other default maps ("_" names). + for (std::map::iterator m = m_byId.begin(); m != m_byId.end(); ++m) + { + IControlMap* other = m->second; + if (other == map || other->getName()[0] != '_') + continue; + if (!other->findDuplicate(device, axis, button, key, dups)) + continue; + for (unsigned int i = 0; i < dups.ids.size(); ++i) + { + if (!allowDuplicate(dups.ids[i], other != gameDefault)) + { + out = other->getName(); + return 1; + } + } + dups.ids.resize(0); + dups.negative.resize(0); + dups.alternate.resize(0); + } + } + else + { + if (gameDefault && gameDefault->findDuplicate(device, axis, button, key, dups)) + { + for (unsigned int i = 0; i < dups.ids.size(); ++i) + { + if (!allowDuplicate(dups.ids[i], !playerMap)) + { + out = gameDefault->getName(); + return 1; + } + } + dups.ids.resize(0); + dups.negative.resize(0); + dups.alternate.resize(0); + } + if (playerDefault && playerDefault->findDuplicate(device, axis, button, key, dups)) + { + for (unsigned int i = 0; i < dups.ids.size(); ++i) + { + if (!allowDuplicate(dups.ids[i], playerMap)) + { + // Retail names the game default map here too (0x84983DE reads the + // _defaultGameControlMap pointer), not the player map that clashed. + out = gameDefault->getName(); + return 1; + } + } + dups.ids.resize(0); + dups.negative.resize(0); + dups.alternate.resize(0); + } + } + + if (key == 0) + { + if (button == 0) + { + if (isAxis && axis != 15) + map->addAxisMapping(id, device, axis, inverted != negative, alternate); // +0x2C + } + else if (isAxis) + { + map->addAxisMapping(id, device, + negative ? static_cast(0) : button, + negative ? button : static_cast(0), + alternate); // +0x30 + } + else + { + map->addTriggerMapping(id, device, button, this->getRepeatRate(id, playerMap), + alternate); // +0x44 + } + } + else if (isAxis) + { + map->addAxisMapping(id, device, + negative ? static_cast(0) : key, + negative ? key : static_cast(0), + alternate); // +0x34 + } + else + { + map->addTriggerMapping(id, device, key, this->getRepeatRate(id, playerMap), alternate); // +0x48 + } + // The throttle's forward key also drives c_PIAltSprint (double tap, 1000). + if (playerMap && id == PIThrottle && !negative && !alternate && key != 0) + map->addTriggerMapping(PIAltSprint, device, key, 1000.0f, false); // +0x48 + return 0; + } + } +} + // Inputs held continuously rather than auto-repeated. Each table ends with its own enum's None sentinel. namespace { const int playerInputPushAndHold[] = { diff --git a/Code/BF2/IO/Input/ControlMapManager.h b/Code/BF2/IO/Input/ControlMapManager.h index d7bc0feef..9a6518c07 100644 --- a/Code/BF2/IO/Input/ControlMapManager.h +++ b/Code/BF2/IO/Input/ControlMapManager.h @@ -45,9 +45,9 @@ class ControlMapManager : public IControlMapManager virtual void setActive(const std::string& name); // 0x84977A0, 46 recovered virtual void setActive(const IControlMap* map); // 0x84977D0, 27 recovered virtual IControlMap* getActive() const; // 0x8497790, 11 recovered - virtual bool mapNextInput(IControlMap* map, int id, bool a, bool b, bool c, bool d, - std::string& out); // 0x8497AC0, 5146 [CHOSEN-STUB] - virtual float getRepeatRate(int id, bool b); // 0x8498EE0, 103 [CHOSEN-STUB] + virtual int mapNextInput(IControlMap* map, int id, bool a, bool b, bool c, bool d, + std::string& out); // 0x8497AC0, 5133 recovered + virtual float getRepeatRate(int id, bool b); // 0x8498EE0, 103 recovered virtual void applyActive(); // 0x84977F0, 164 recovered // +0x44 / +0x48 @@ -58,6 +58,9 @@ class ControlMapManager : public IControlMapManager // _ZN4dice3hfe2io17ControlMapManager6createEjPNS0_5IBaseE. static IBase* create(unsigned int iid, IBase* outer); + // True when input id may share its binding with another input (the shipped tables). + bool allowDuplicate(int id, bool playerMap); // 0x8498F50, 101 recovered + private: /* 0x04 */ int m_refCount; /* 0x08 */ std::map m_byId; diff --git a/Code/BF2/IO/Input/FalconDevice.cpp b/Code/BF2/IO/Input/FalconDevice.cpp index 08d36501a..96957448c 100644 --- a/Code/BF2/IO/Input/FalconDevice.cpp +++ b/Code/BF2/IO/Input/FalconDevice.cpp @@ -1,7 +1,13 @@ // Path [INFERRED]. Client PE recovery; symbolized ELF supplies names/signatures. // [PLATFORM] ELF has no Novint imports and compiled-out init/update/device calls. #include "FalconDevice.h" -#if !DEDICATED +#if !DEDICATED && !defined(_WIN32) +namespace dice { namespace hfe { namespace io { +// [CHOSEN, not recovered] Native POSIX clients have no Falcon (see FalconDevice.h); the menu's +// mouse-mode global keeps its shipped initial value. +int g_falconMouseMode = 1; // PE978FC4 +} } } +#elif !DEDICATED #include "../../Core/Ids.h" #include #include @@ -24,10 +30,27 @@ FalconInputFormat inputBuffer[1]; // PE 0xA03918, static polling buffer const float lowerTravel[3] = { -0.0025f, -0.0025f, -0.001f }; const float upperTravel[3] = { 0.0025f, 0.0025f, 0.001f }; } +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): NovintHFX ships only as a +// 32-bit DLL. The x64 image never calls it: init() reports the device absent through the same +// `false` retail returns with no device connected, so m_device stays null and every device path +// below returns at its existing null test. +#if defined(_M_IX86) +#define BF2_FALCON_SDK 1 +#else +#define BF2_FALCON_SDK 0 +#endif FalconDevice::FalconDevice() - : m_refCount(1), m_active(false), m_pollTime(0), m_haptics(&Haptics), m_device(0) + : m_refCount(1), m_active(false), m_pollTime(0), +#if BF2_FALCON_SDK + m_haptics(&Haptics), +#else + m_haptics(0), +#endif + m_device(0) { +#if defined(_M_IX86) static_assert(offsetof(FalconDevice, m_samples) == 0xE4, "x86 scalar prefix"); +#endif static_assert(sizeof(FalconInputFormat) == 40, "x86 input sample alignment"); m_field100 = 0; g_falconDevice = 0; @@ -46,12 +69,14 @@ FalconDevice::FalconDevice() } FalconDevice::~FalconDevice() { +#if BF2_FALCON_SDK if (m_device) { m_haptics->StopRunningDevice(&m_device); m_haptics = 0; g_falconDevice = 0; m_device = 0; } +#endif } void FalconDevice::addRef() { ++m_refCount; } int FalconDevice::getRef() { return m_refCount; } @@ -125,6 +150,12 @@ float FalconDevice::buttonPressedSampleLatency(InputDeviceButtons button) const bool FalconDevice::init() { if (!inputDeviceManager) return false; +#if !BF2_FALCON_SDK + std::fprintf(stderr, "[x64] dice::hfe::io::FalconDevice::init: no 64-bit NovintHFX SDK; " + "the Falcon is reported as not connected\n"); + std::fflush(stderr); + return false; +#else const HWND window = GetForegroundWindow(); NovintHFX::ApplicationData application; application.window = window; @@ -141,12 +172,14 @@ bool FalconDevice::init() m_numButtons = 4; // AttachApplication failure still returns true; zero devices returns false. return true; +#endif } bool FalconDevice::getNextInput(InputDeviceAxes& axis, InputDeviceButtons& button, InputDeviceKeys& key, bool& negative) { if (!m_active) return false; if (!m_device) return false; +#if BF2_FALCON_SDK m_device->InputUpdate(); int buttons, pressed, released; m_device->GetButtonData(&buttons, &pressed, &released); @@ -179,6 +212,7 @@ bool FalconDevice::getNextInput(InputDeviceAxes& axis, InputDeviceButtons& butto return true; } } +#endif return false; } void FalconDevice::update(float dt) @@ -188,6 +222,7 @@ void FalconDevice::update(float dt) updateCurrentState(dt); // [FRONTIER] retained actual positive-dt dependency return; } +#if BF2_FALCON_SDK if (m_samples.size() > 256) m_samples.clear(); m_haptics->InputUpdate(); double position[3]; @@ -201,6 +236,7 @@ void FalconDevice::update(float dt) m_sampleTime = m_pollTime; m_pollTime = GetTickCount(); for (unsigned int i = 0; i < 1; ++i) m_samples.push_back(inputBuffer[i]); +#endif } } } } #endif diff --git a/Code/BF2/IO/Input/FalconDevice.h b/Code/BF2/IO/Input/FalconDevice.h index eb39cc58f..073401a9a 100644 --- a/Code/BF2/IO/Input/FalconDevice.h +++ b/Code/BF2/IO/Input/FalconDevice.h @@ -3,6 +3,16 @@ #define IO_INPUT_FALCONDEVICE_H #include "../../Core/BuildConfig.h" #if !DEDICATED +#if !defined(_WIN32) +// [CHOSEN, not recovered] Native POSIX clients: the Novint HFX SDK is a Windows-only DLL and no +// Falcon is ever present, so neither the SDK header nor FalconDevice exists there; the device +// manager reports IDFFalcon as not opened (MacInputDeviceManager). Only the menu's mouse-mode +// global, which the menu and HUD code write on every platform, is declared. See +// docs/macos-port.md, "Bink, Novint and VoIP capture (S2.8)". +namespace dice { namespace hfe { namespace io { +extern int g_falconMouseMode; // [INFERRED] name, PE978FC4 initialized1; HUD/updateCurrentState writers +} } } +#else #include "Input.h" #include "../../External/NovintHFX/NovintHFX.h" #include @@ -71,5 +81,6 @@ class FalconDevice : public IAdvancedInputDevice { DWORD m_field100; // [UNRESOLVED] initialized zero }; } } } +#endif // _WIN32 #endif #endif diff --git a/Code/BF2/IO/Input/GameControllerDevice.cpp b/Code/BF2/IO/Input/GameControllerDevice.cpp index 22cf803d9..973d6da36 100644 --- a/Code/BF2/IO/Input/GameControllerDevice.cpp +++ b/Code/BF2/IO/Input/GameControllerDevice.cpp @@ -364,10 +364,16 @@ bool GameControllerDevice::init(int index) return true; } +#if defined(_M_IX86) static_assert(sizeof(GameControllerDevice) == 0xBC, "BF2 client GameControllerDevice layout"); +#endif static_assert(sizeof(DIDEVCAPS) == 44, "Retail DirectInput capabilities size"); static_assert(sizeof(DIJOYSTATE2) == 272, "Retail joystick2 data format"); +// GetDeviceData is passed sizeof(DIDEVICEOBJECTDATA) and a typed array, so the x64 stride +// (24 bytes, UINT_PTR uAppData) needs no adjustment. +#if defined(_M_IX86) static_assert(sizeof(DIDEVICEOBJECTDATA) == 20, "Retail x86 buffered record stride"); +#endif } } } #endif diff --git a/Code/BF2/IO/Input/Input.h b/Code/BF2/IO/Input/Input.h index aef5638fc..badf5d947 100644 --- a/Code/BF2/IO/Input/Input.h +++ b/Code/BF2/IO/Input/Input.h @@ -189,8 +189,16 @@ class IAdvancedInputDevice : public IInputDevice virtual float buttonPressedSampleLatency(InputDeviceButtons button) const = 0; // +0x64 }; -// Duplicate-key result collection. [UNRESOLVED] Original element type. -typedef std::vector DuplicateKeyVector; // [UNRESOLVED] element type +// The bindings ControlMap::findDuplicate found for one device input: the axis or trigger id, whether +// the clash is on the negative half of an axis pair, and whether it is the alternate binding. The +// ELF mangles it as a class (_ZN...18DuplicateKeyVectorE); in ia-32 findDuplicate and mapNextInput +// it is three parallel vectors at +0x00 (int), +0x0C and +0x20 (bool). Member names [INFERRED]. +struct DuplicateKeyVector +{ + std::vector ids; // +0x00 + std::vector negative; // +0x0C + std::vector alternate; // +0x20 +}; // Input identifiers. None is the one-past-end sentinel and has no mapping bit. enum PlayerInputMap @@ -361,7 +369,9 @@ class IControlMapManager : public IBase // 5,146 bytes in the ELF (0x8497AC0) - the "press a key to bind it" capture mode, and the // single largest routine in the whole input subsystem. - virtual bool mapNextInput(IControlMap* map, int id, bool a, bool b, bool c, bool d, + // Returns an int status, not a Boolean: ControlSettings +0x30 (BF2.exe 0x4B2CA0) passes this + // full EAX on, and SwiffPlayer mapInput (sub_1000EDA0) compares it with 1 (duplicate) and 2. + virtual int mapNextInput(IControlMap* map, int id, bool a, bool b, bool c, bool d, std::string& out) = 0; // +0x38 virtual float getRepeatRate(int id, bool b) = 0; // +0x3C virtual void applyActive() = 0; // +0x40 diff --git a/Code/BF2/IO/Input/KeyboardDevice.cpp b/Code/BF2/IO/Input/KeyboardDevice.cpp index a46bed6a6..4f9034ac4 100644 --- a/Code/BF2/IO/Input/KeyboardDevice.cpp +++ b/Code/BF2/IO/Input/KeyboardDevice.cpp @@ -6,6 +6,7 @@ #include "../../Core/Ids.h" #include "../../Game/Main/BF2ClientSeams.h" #include "../../Game/Main/BF2Window.h" +#include "../../Platform/Windows/WinInputScript.h" // [TEMP] BF2_INPUT_SCRIPT feed #include namespace dice { namespace hfe { namespace io { @@ -67,7 +68,15 @@ bool KeyboardDevice::setCooperativeModeForWindow(HWND window, InputDeviceMode mo bool KeyboardDevice::activate() { if (!m_device) return false; - if (!m_active) m_active = m_device->Acquire() == DI_OK; + if (!m_active) { + m_active = m_device->Acquire() == DI_OK; + // [TEMP] [CHOSEN, not recovered] BF2_INPUT_SCRIPT (Platform/Windows/WinInputScript.h): the + // scripted feed counts as acquired without focus. [RETIRE-WHEN: client-test-automation-replaced] + if (inputscript::winInputScriptActive()) { + m_active = true; + inputscript::winInputScriptClearKeyboardData(); + } + } return true; // Retail reports success even if Acquire failed. } bool KeyboardDevice::deActivate() @@ -184,6 +193,12 @@ void KeyboardDevice::update(float dt) } DWORD count; HRESULT hr; + // [TEMP] [CHOSEN, not recovered] BF2_INPUT_SCRIPT: scripted device data replaces the real + // device's. [RETIRE-WHEN: client-test-automation-replaced] + if (inputscript::winInputScriptActive()) { + count = inputscript::winInputScriptTakeKeyboardData(bufferedEvents, 100); + hr = DI_OK; + } else for (;;) { count = 100; hr = m_device->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), bufferedEvents, &count, 0); diff --git a/Code/BF2/IO/Input/MouseDevice.cpp b/Code/BF2/IO/Input/MouseDevice.cpp index 65b46414b..e7fbce06e 100644 --- a/Code/BF2/IO/Input/MouseDevice.cpp +++ b/Code/BF2/IO/Input/MouseDevice.cpp @@ -6,7 +6,9 @@ #include "../../Core/Ids.h" #include "../../Game/Main/BF2ClientSeams.h" #include "../../Game/Main/BF2Window.h" +#include "../../Platform/Windows/WinInputScript.h" // [TEMP] BF2_INPUT_SCRIPT feed #include +#include namespace dice { namespace hfe { namespace io { extern IBase* inputDeviceManager; @@ -89,8 +91,15 @@ bool MouseDevice::activate() { if (!m_device) return false; - if (!m_active) + if (!m_active) { m_active = m_device->Acquire() == DI_OK; + // [TEMP] [CHOSEN, not recovered] BF2_INPUT_SCRIPT (Platform/Windows/WinInputScript.h): the + // scripted feed counts as acquired without focus. [RETIRE-WHEN: client-test-automation-replaced] + if (inputscript::winInputScriptActive()) { + m_active = true; + inputscript::winInputScriptClearMouseData(); + } + } return true; // also when Acquire fails } @@ -220,10 +229,12 @@ void MouseDevice::updateSamples(float deltaTime) break; // equality waits for next sample const float age = static_cast(m_pollTime - event.dwTimeStamp) * 0.001f; const float latency = age <= 0.033333335f ? age : 0.033333335f; + // DIMOFS_X/Y/Z are FIELD_OFFSET(DIMOUSESTATE, lX/lY/lZ); offsetof gives the same + // constants without the x64 C4644 macro-offsetof warning. switch (event.dwOfs) { - case DIMOFS_X: m_axes[0] += static_cast(event.dwData); break; - case DIMOFS_Y: m_axes[1] += static_cast(event.dwData); break; - case DIMOFS_Z: m_axes[2] += static_cast(event.dwData); break; + case offsetof(DIMOUSESTATE, lX): m_axes[0] += static_cast(event.dwData); break; + case offsetof(DIMOUSESTATE, lY): m_axes[1] += static_cast(event.dwData); break; + case offsetof(DIMOUSESTATE, lZ): m_axes[2] += static_cast(event.dwData); break; case DIMOFS_BUTTON0: case DIMOFS_BUTTON1: case DIMOFS_BUTTON2: case DIMOFS_BUTTON3: case DIMOFS_BUTTON4: case DIMOFS_BUTTON5: case DIMOFS_BUTTON6: case DIMOFS_BUTTON7: { const unsigned int index = event.dwOfs - DIMOFS_BUTTON0; @@ -261,6 +272,12 @@ void MouseDevice::update(float deltaTime) } DWORD count; HRESULT result; + // [TEMP] [CHOSEN, not recovered] BF2_INPUT_SCRIPT: scripted device data replaces the real + // device's. [RETIRE-WHEN: client-test-automation-replaced] + if (inputscript::winInputScriptActive()) { + count = inputscript::winInputScriptTakeMouseData(mouseEvents, 128); + result = DI_OK; + } else for (;;) { count = 128; result = m_device->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), mouseEvents, &count, 0); diff --git a/Code/BF2/IO/Localization/ExcelLexicon.cpp b/Code/BF2/IO/Localization/ExcelLexicon.cpp index aec4808ca..7ed1aded2 100644 --- a/Code/BF2/IO/Localization/ExcelLexicon.cpp +++ b/Code/BF2/IO/Localization/ExcelLexicon.cpp @@ -5,6 +5,9 @@ #include "../../Core/StringUtil.h" // getUpperCase, calcStringHashValueNoCase #include "../../Core/Debug.h" #include "../File/File.h" +#if !defined(_WIN32) +#include "../../Platform/Utf16.h" +#endif namespace dice { namespace hfe { @@ -65,7 +68,7 @@ void* ExcelLexicon::queryInterface(unsigned int iid) const } // Loads ESC-delimited localization pairs. Empty values are skipped and the first key insertion wins. -// Failures retain earlier entries. The BOM is two bytes; later units use native wchar_t width. +// Failures retain earlier entries. Text on disk is UTF-16LE, including the two-byte BOM. // A final nonspace character at EOF is consumed by trailing-whitespace handling. bool ExcelLexicon::load(const std::string& filename) { @@ -88,10 +91,18 @@ bool ExcelLexicon::load(const std::string& filename) while (file.getAvailableBytes()) { std::wstring wideKey, value; +#if defined(_WIN32) if (!file.read(wideKey, wchar_t(27)) || wideKey.empty() || !file.seek(static_cast(1), sizeof(wchar_t)) || !file.read(value, wchar_t(27)) || !file.seek(static_cast(1), sizeof(wchar_t))) +#else + // [CHOSEN, not recovered] POSIX seeks count UTF-16 units, not native wide characters. + if (!file.read(wideKey, wchar_t(27)) || wideKey.empty() + || !file.seek(static_cast(1), sizeof(char16_t)) + || !file.read(value, wchar_t(27)) + || !file.seek(static_cast(1), sizeof(char16_t))) +#endif return false; std::string key = makeNarrow(wideKey); const std::string::size_type space = key.find(' '); @@ -106,12 +117,21 @@ bool ExcelLexicon::load(const std::string& filename) if (!m_strings.exists(upper, bucket)) m_strings.insert(upper, value, bucket); } +#if defined(_WIN32) wchar_t character; while (file.read(&character, sizeof(wchar_t)) && (character == L'\n' || character == L'\r' || character == L' ' || character == L'\t')) {} if (file.getAvailableBytes()) file.seek(static_cast(1), -static_cast(sizeof(wchar_t))); +#else + char16_t character; + while (platform::readUtf16LE(file, character) + && (character == u'\n' || character == u'\r' || character == u' ' || character == u'\t')) + {} + if (file.getAvailableBytes()) + file.seek(static_cast(1), -static_cast(sizeof(char16_t))); +#endif } return true; } diff --git a/Code/BF2/IO/Network/NetworkLayer/Socket/UDPSocket.cpp b/Code/BF2/IO/Network/NetworkLayer/Socket/UDPSocket.cpp index 50d049f3d..1c3d256b4 100644 --- a/Code/BF2/IO/Network/NetworkLayer/Socket/UDPSocket.cpp +++ b/Code/BF2/IO/Network/NetworkLayer/Socket/UDPSocket.cpp @@ -99,9 +99,9 @@ bool UDPSocket::setBroadcast(unsigned short port) { struct sockaddr_in address; std::memset(&address, 0, sizeof(address)); - address.sin_addr.s_addr = ::htonl(INADDR_BROADCAST); + address.sin_addr.s_addr = htonl(INADDR_BROADCAST); // unqualified: a macro on macOS address.sin_family = AF_INET; - address.sin_port = ::htons(port); + address.sin_port = htons(port); // unqualified: a macro on macOS std::memcpy(m_address.sockaddr, &address, 16); } return true; @@ -419,6 +419,12 @@ bool UDPSocket::listen(std::string addressAndPort, bool blocking) if (::bind(static_cast(m_socket), reinterpret_cast(&addr), 16) != 0) { +#if defined(__APPLE__) + // [TEMP] [CHOSEN, not recovered] [RETIRE-WHEN: macos-singleplayer-hosting-validated] + // BF2_HOST_TRACE=1: name the listen address and errno of a failed bind (read-only). + if (std::getenv("BF2_HOST_TRACE")) + std::fprintf(stderr, "[host] UDPSocket::listen bind %s failed errno %d\n", addressAndPort.c_str(), errno); +#endif closeSocketHandle(m_socket); return false; } diff --git a/Code/BF2/IO/Network/NetworkStats.cpp b/Code/BF2/IO/Network/NetworkStats.cpp index d20fc15c0..e037c345f 100644 --- a/Code/BF2/IO/Network/NetworkStats.cpp +++ b/Code/BF2/IO/Network/NetworkStats.cpp @@ -1,5 +1,8 @@ // Network telemetry sampling and aggregation. Graphical statistics retain a client rendering frontier. +#if defined(__APPLE__) +#include "../../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "NetworkStats.h" #include "../../Core/Ids.h" #include "../../Game/IGame.h" @@ -145,6 +148,16 @@ void BasicNetworkStats::updateServerStats() readTotal = readTotal + m_streamManagerReadBits[2]; const long double writeTotal = static_cast(m_streamManagerWriteBits[0]) + m_streamManagerWriteBits[1] + m_streamManagerWriteBits[2]; +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + // ELF 847181E..847183C retains both totals in x87 and multiplies by 100 before division. + bf2x87::Real readTotal = 0.0L; + bf2x87::Real writeTotal = 0.0L; + for (unsigned int i = 0; i < 3; ++i) { + readTotal += m_streamManagerReadBits[i]; + writeTotal += m_streamManagerWriteBits[i]; + } #else // ELF 847181E..847183C retains both totals in x87 and multiplies by 100 before division. long double readTotal = 0.0L; @@ -153,24 +166,37 @@ void BasicNetworkStats::updateServerStats() readTotal += m_streamManagerReadBits[i]; writeTotal += m_streamManagerWriteBits[i]; } +#endif #endif for (unsigned int i = 0; i < 3; ++i) { if (readTotal > 0.0f) { #if defined(_WIN32) m_streamManagerReadPercent[i] = static_cast( static_cast(m_streamManagerReadBits[i]) / readTotal * 100.0L); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + m_streamManagerReadPercent[i] = static_cast( + static_cast(m_streamManagerReadBits[i]) * 100.0L / readTotal); #else m_streamManagerReadPercent[i] = static_cast( static_cast(m_streamManagerReadBits[i]) * 100.0L / readTotal); +#endif #endif } if (writeTotal > 0.0f) { #if defined(_WIN32) m_streamManagerWritePercent[i] = static_cast( static_cast(m_streamManagerWriteBits[i]) / writeTotal * 100.0L); +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + m_streamManagerWritePercent[i] = static_cast( + static_cast(m_streamManagerWriteBits[i]) * 100.0L / writeTotal); #else m_streamManagerWritePercent[i] = static_cast( static_cast(m_streamManagerWriteBits[i]) * 100.0L / writeTotal); +#endif #endif } // Nonpositive/NaN totals leave the previous percentage intact, but still reset samples. diff --git a/Code/BF2/IO/Network/ProtocolLayer/NetClient.cpp b/Code/BF2/IO/Network/ProtocolLayer/NetClient.cpp index f79c0041c..51091ed04 100644 --- a/Code/BF2/IO/Network/ProtocolLayer/NetClient.cpp +++ b/Code/BF2/IO/Network/ProtocolLayer/NetClient.cpp @@ -20,6 +20,8 @@ #if defined(_WIN32) #include #include +#else +#include // gettimeofday - the POSIX counter below #endif namespace dice { @@ -40,7 +42,9 @@ namespace { if (threaded) ::WaitForSingleObject(mutex, INFINITE); #else - (void) threaded; (void) mutex; + // [CHOSEN, not recovered] No worker owns state before mutex creation. + if (threaded && mutex) + static_cast(mutex)->lock(); #endif } inline void unlockIf(bool threaded, void* mutex) @@ -49,9 +53,21 @@ namespace { if (threaded) ::ReleaseMutex(mutex); #else - (void) threaded; (void) mutex; + // [CHOSEN, not recovered] Pair with the POSIX connection lock above. + if (threaded && mutex) + static_cast(mutex)->unlock(); #endif } +#if !defined(_WIN32) + // [CHOSEN, not recovered] The POSIX stand-in for QueryPerformanceCounter: microseconds from + // gettimeofday, the clock NetServer uses on Unix. Frequency 1000000 goes with it. + inline long long posixCounterMicros() + { + struct timeval now; + gettimeofday(&now, 0); + return static_cast(now.tv_sec) * 1000000 + now.tv_usec; + } +#endif inline unsigned int bytesOf(const BitStream* stream) { return (stream->m_highWaterBits >> 3) + ((stream->m_highWaterBits & 7) != 0 ? 1u : 0u); @@ -94,8 +110,11 @@ NetClient::NetClient() ::QueryPerformanceFrequency(&counter); // +0x0F0 m_counterFrequency = counter.QuadPart; #else - m_startCounter = 0; - m_counterFrequency = 1; + // [CHOSEN, not recovered] c-loopback: POSIX has no QueryPerformanceCounter. The counter is + // gettimeofday in microseconds (NetServer's Unix clock), so elapsedMs keeps the PE formula. + // The old 0/1 pair with an elapsedMs of 0 froze every handshake timeout and retry. + m_startCounter = posixCounterMicros(); + m_counterFrequency = 1000000; #endif } @@ -189,11 +208,16 @@ int NetClient::closeConnection(unsigned int reason) return 9; #if defined(_WIN32) ::WaitForSingleObject(m_mutex, INFINITE); +#else + // [CHOSEN, not recovered] Serialize disconnect with the receive worker. + lockIf(m_threaded, m_mutex); #endif for (int i = 0; i < 3; ++i) sendDisconnect(reason); #if defined(_WIN32) ::ReleaseMutex(m_mutex); +#else + unlockIf(m_threaded, m_mutex); #endif return 0; } @@ -275,7 +299,8 @@ unsigned int NetClient::elapsedMs() const return static_cast(static_cast(now.QuadPart - m_startCounter) / static_cast(m_counterFrequency) * 1000.0); #else - return 0; + return static_cast(static_cast(posixCounterMicros() - m_startCounter) + / static_cast(m_counterFrequency) * 1000.0); #endif } int NetClient::getTime() const @@ -394,6 +419,9 @@ int NetClient::connect(const std::string& address, int port, bool blocking, cons m_startCounter = counter.QuadPart; ::QueryPerformanceFrequency(&counter); m_counterFrequency = counter.QuadPart; +#else + m_startCounter = posixCounterMicros(); // [CHOSEN, not recovered] see the constructor + m_counterFrequency = 1000000; #endif m_connectAttemptsLeft = kConnectRequestAttempts; // the canary seeded (0x5959C58A) m_mustSendRequest = true; @@ -928,6 +956,34 @@ namespace { return 0; } } +#else +namespace { + // [CHOSEN, not recovered] POSIX counterpart of the Windows receive loop. + // Borrowed client/socket remain alive until the owner signals and joins. + class NetClientThread : public Thread + { + public: + explicit NetClientThread(NetClient* client) : m_client(client) {} + void run() override + { + std::vector sockets(1, m_client->m_socket); + while (!m_client->m_stopRequested.load()) + { + socketManager->sleep(sockets, 3.0f); + m_client->m_mutex->lock(); + int result; + do + { + result = m_client->_update(0); + } + while (result != 8 && result != 14); + m_client->m_mutex->unlock(); + } + } + private: + NetClient* m_client; + }; +} #endif bool NetClient::startReceiveThread() @@ -938,10 +994,23 @@ bool NetClient::startReceiveThread() m_thread = ::CreateThread(0, 0, &netClientThreadProc, this, 0, &threadId); if (m_thread) { - static_cast(profiler)->registerThread(reinterpret_cast(m_thread), threadId, + // The shipped signature takes the handle as a 32-bit value; its (empty) body ignores it, so + // the explicit narrowing on x64 loses nothing. + static_cast(profiler)->registerThread(static_cast(reinterpret_cast(m_thread)), threadId, std::string("NetClientThread")); // 4594F0 on the Profiler singleton return true; } +#else + // [CHOSEN, not recovered] Initialize before pthread creation publishes state. + m_stopRequested.store(false); + m_mutex = new Mutex; + m_thread = new NetClientThread(this); + if (m_thread->start("NetClientThread", Thread::Priority_AboveNormal)) + return true; + delete m_thread; + m_thread = 0; + delete m_mutex; + m_mutex = 0; #endif Debug(DEBUGTYPE_6, NETCLIENT_FILE, 1416, "") << "clientReceiveThread was not created successfully"; return false; @@ -960,6 +1029,22 @@ void NetClient::stopReceiveThread() ::CloseHandle(m_thread); m_thread = 0; } +#else + // [CHOSEN, not recovered] Never free borrowed state before the worker joins. + if (m_thread) + { + m_stopRequested.store(true); + if (!m_thread->stop()) + { + std::fprintf(stderr, "NetClient::stopReceiveThread: POSIX join failed\n"); + std::fflush(stderr); + std::abort(); + } + delete m_thread; + m_thread = 0; + delete m_mutex; + m_mutex = 0; + } #endif } diff --git a/Code/BF2/IO/Network/ProtocolLayer/NetClient.h b/Code/BF2/IO/Network/ProtocolLayer/NetClient.h index 875a9bb96..289579202 100644 --- a/Code/BF2/IO/Network/ProtocolLayer/NetClient.h +++ b/Code/BF2/IO/Network/ProtocolLayer/NetClient.h @@ -6,6 +6,11 @@ #if !DEDICATED #include +#if !defined(_WIN32) +#include +#include "../../../Core/Mutex.h" +#include "../../../Core/Thread.h" +#endif #include "../PacketFilter.h" // by-value member at +0x128 #include "Packet.h" // io::Packet - by-value member at +0xC8 @@ -164,9 +169,17 @@ class NetClient : public INetClient bool m_bInit; // +0x10C bool m_threaded; // +0x10D bool m_byte10E; // +0x10E [UNRESOLVED] +#if defined(_WIN32) void* m_mutex; // +0x110 handle void* m_thread; // +0x114 handle bool m_stopRequested; // +0x118 +#else + // [CHOSEN, not recovered] POSIX ownership; create publishes state, stop joins + // before freeing the mutex/socket. The stop request uses S2.10 seq-cst publication. + Mutex* m_mutex; + Thread* m_thread; + std::atomic m_stopRequested; +#endif unsigned int m_totalTimeSentinel; // +0x11C bool m_bDebugNetwork; // +0x124 PacketFilter m_packetFilter; // +0x128 diff --git a/Code/BF2/IO/Network/ProtocolLayer/NetServer.cpp b/Code/BF2/IO/Network/ProtocolLayer/NetServer.cpp index 5eff6af26..eb7d2e04d 100644 --- a/Code/BF2/IO/Network/ProtocolLayer/NetServer.cpp +++ b/Code/BF2/IO/Network/ProtocolLayer/NetServer.cpp @@ -26,6 +26,22 @@ namespace dice { namespace hfe { namespace io { +#if !defined(_WIN32) +// [CHOSEN, not recovered] c-loopback: Darwin's struct timeval has a 32-bit tv_usec, so writing it +// over a {long, long} TimeStamp left the upper half of tv_usec stale. A TimeStamp on the stack +// then held garbage microseconds and the handshake timeout (state 1, 10 s) fired at random: +// about one loopback join in three was dropped with reason 10. ELF and LP64 Linux timevals are +// {long, long}, where this is the same as the shipped direct write. +template +inline void gettimeofdayInto(Stamp& stamp) +{ + struct timeval now; + gettimeofday(&now, 0); + stamp.tv_sec = now.tv_sec; + stamp.tv_usec = now.tv_usec; +} +#endif + // Starts with one reference, 64 connections and a 10,000 ms timeout; init replaces the stock port. // [UNRESOLVED] Unmodeled reference-layout storage. Use named members rather than retail offsets. NetServer::NetServer() @@ -74,7 +90,7 @@ NetServer::NetServer() m_initTime.tv_sec = (long)(ticks / 10000000ULL); m_initTime.tv_usec = (long)((ticks % 10000000ULL) / 10ULL); #else - gettimeofday(reinterpret_cast(&m_initTime), 0); // +0x498, as read + gettimeofdayInto(m_initTime); // +0x498, as read #endif } @@ -219,7 +235,7 @@ int NetServer::getTime() const now.tv_sec = (long)(ticks / 10000000ULL); now.tv_usec = (long)((ticks % 10000000ULL) / 10ULL); #else - gettimeofday(reinterpret_cast(&now), 0); + gettimeofdayInto(now); #endif return (int)((now.tv_sec - m_initTime.tv_sec) * 1000 @@ -257,7 +273,7 @@ int NetServer::init(const std::string& address, unsigned int port, bool /* [UNRE m_initTime.tv_usec = (long)((ticks % 10000000ULL) / 10ULL); } #else - gettimeofday(reinterpret_cast(&m_initTime), 0); + gettimeofdayInto(m_initTime); #endif // 4. the server name is "
:", and it is also what gets listened on. @@ -332,7 +348,7 @@ unsigned int NetServer::elapsedMsSinceInit() const now.tv_sec = (long)(ticks / 10000000ULL); now.tv_usec = (long)((ticks % 10000000ULL) / 10ULL); #else - gettimeofday(reinterpret_cast(&now), 0); + gettimeofdayInto(now); #endif // the ELF order: usec term first, then 1000 * sec. Transcribed as written - see the note above. @@ -1092,7 +1108,7 @@ void NetServer::sendRawPacket(const char* address, unsigned short port, const ch sockaddr_in nativeAddress = {}; nativeAddress.sin_addr.s_addr = ::inet_addr(address); nativeAddress.sin_family = AF_INET; - nativeAddress.sin_port = ::htons(port); + nativeAddress.sin_port = htons(port); // unqualified: a macro on macOS ISocket::Address peer = {}; std::memcpy(peer.sockaddr, &nativeAddress, 16); peer.length = 16; @@ -1514,7 +1530,7 @@ bool NetServer::startReceiveThread() } // Sets both stop flags, then stops and deletes the receive thread. -// Only stopRequested is protected by the stop mutex; shutting-down remains an unsynchronized write. +// Only stopRequested uses the stop mutex; POSIX publishes shutting-down through its atomic member. void NetServer::endReceiveThread() { if (!m_netServerThread) diff --git a/Code/BF2/IO/Network/ProtocolLayer/NetServer.h b/Code/BF2/IO/Network/ProtocolLayer/NetServer.h index 7b2c91ef1..b1d1aabd9 100644 --- a/Code/BF2/IO/Network/ProtocolLayer/NetServer.h +++ b/Code/BF2/IO/Network/ProtocolLayer/NetServer.h @@ -8,6 +8,9 @@ #include #include #include +#if !defined(_WIN32) +#include +#endif #include "../../../Core/Mutex.h" // three by-value Mutexes, sizeof 4 each #include "../PacketFilter.h" // by-value member at +0x4F0 @@ -243,9 +246,14 @@ class NetServer : public INetServer /* +0x474 */ BitStream* m_bitStreamOut; // = 0 - built by init() /* +0x478 */ BitStream* m_bitStreamIn; // = 0 - built by init() /* +0x47C */ bool m_bInit; // = 0 +#if defined(_WIN32) /* +0x47D */ bool m_shuttingDown; // the receive // thread's exit flag, read under m_mutex. // endReceiveThread sets it first. +#else + // [CHOSEN, not recovered] POSIX: shutdown writes outside m_mutex while the worker reads it. + std::atomic m_shuttingDown; +#endif /* +0x480 */ std::string m_name; // = "" - init() sets "
:" /* +0x484 */ unsigned int m_version; // = 0 - the protocol compatibility gate /* +0x488 */ unsigned int m_connectionTimeOut; // = 10000 diff --git a/Code/BF2/IO/Network/ProtocolLayer/SWConnection.cpp b/Code/BF2/IO/Network/ProtocolLayer/SWConnection.cpp index 8cc073a12..e1bc7c0f2 100644 --- a/Code/BF2/IO/Network/ProtocolLayer/SWConnection.cpp +++ b/Code/BF2/IO/Network/ProtocolLayer/SWConnection.cpp @@ -20,6 +20,22 @@ namespace dice { namespace hfe { namespace io { +#if !defined(_WIN32) +// [CHOSEN, not recovered] c-loopback: Darwin's struct timeval has a 32-bit tv_usec, so writing it +// over a {long, long} TimeStamp left the upper half of tv_usec stale. A TimeStamp on the stack +// then held garbage microseconds and the handshake timeout (state 1, 10 s) fired at random: +// about one loopback join in three was dropped with reason 10. ELF and LP64 Linux timevals are +// {long, long}, where this is the same as the shipped direct write. +template +inline void gettimeofdayInto(Stamp& stamp) +{ + struct timeval now; + gettimeofday(&now, 0); + stamp.tv_sec = now.tv_sec; + stamp.tv_usec = now.tv_usec; +} +#endif + namespace { // Seeds a wall-clock timestamp. Keep the Windows epoch conversion consistent with NetServer. @@ -33,7 +49,7 @@ void seedTimeStamp(SWConnection::TimeStamp& ts) ts.tv_sec = (long)(t / 10000000ULL); ts.tv_usec = (long)((t % 10000000ULL) / 10); #else - gettimeofday(reinterpret_cast(&ts), 0); + gettimeofdayInto(ts); #endif } @@ -326,7 +342,14 @@ int SWConnection::getPacketPtrFromRecvQueue(unsigned char** buff, unsigned int* const unsigned char* const slot = static_cast(front->pvoid14) + front->currBytePositionBitStream; +#if defined(_WIN32) const unsigned int len = *reinterpret_cast(slot); +#else + // [CHOSEN, not recovered] POSIX packet prefixes need not be aligned for a short load. + unsigned short encodedLength; + std::memcpy(&encodedLength, slot, sizeof(encodedLength)); + const unsigned int len = encodedLength; +#endif if (len == 0) { m_recvBuffer->popFront(); @@ -354,7 +377,14 @@ int SWConnection::getPacketFromRecvQueue(unsigned char* dest, unsigned int* leng const unsigned char* const slot = static_cast(front->pvoid14) + front->currBytePositionBitStream; +#if defined(_WIN32) unsigned int len = *reinterpret_cast(slot); +#else + // [CHOSEN, not recovered] Preserve the little-endian prefix without a typed overlay. + unsigned short encodedLength; + std::memcpy(&encodedLength, slot, sizeof(encodedLength)); + unsigned int len = encodedLength; +#endif // the clamp its sibling does not have. Note that it clamps to `size - dword8`, not to // `size - currBytePositionBitStream`, so whatever +0x08 counts is what bounds the tail. diff --git a/Code/BF2/IO/Stream/BoundingBox.cpp b/Code/BF2/IO/Stream/BoundingBox.cpp index 9a0702765..b70947436 100644 --- a/Code/BF2/IO/Stream/BoundingBox.cpp +++ b/Code/BF2/IO/Stream/BoundingBox.cpp @@ -89,7 +89,8 @@ Vec3 BoundingBox::getMin() const return result; } -// ELF 0x492F20; engine ELF 0x83AFA40. +// ELF 0x492F20; engine ELF 0x83AFA40; RendDX9.dll copy PE 0x101C6FB0 (unreachable there: no code or +// data references; the result is written through a pointer argument). Vec3 BoundingBox::getCentre() const { return {(m_corners[7].x + m_corners[0].x) * 0.5f, @@ -97,7 +98,9 @@ Vec3 BoundingBox::getCentre() const (m_corners[7].z + m_corners[0].z) * 0.5f}; } -// ELF 0x492F80; engine ELF 0x83AFA90. +// ELF 0x492F80; engine ELF 0x83AFA90; RendDX9.dll copy PE 0x101C7000 (unreachable there: no code or +// data references; listing read for its skeleton only: six fsqrt, 24 fabs and 15 comparisons, as +// below). bool BoundingBox::intersect(const BoundingBox& other) const { Vec3 a[3], b[3]; diff --git a/Code/BF2/IO/Tokenizer.cpp b/Code/BF2/IO/Tokenizer.cpp index 261f82163..2bc88a1d7 100644 --- a/Code/BF2/IO/Tokenizer.cpp +++ b/Code/BF2/IO/Tokenizer.cpp @@ -6,10 +6,11 @@ #include "../../RendDX9Abi/PluginEntry.h" #include "../../RendDX9Abi/HostFileAbi.h" #include "../../RendDX9Abi/BfMemory.h" -#include "../../RendDX9Abi/Vc71String.h" +#include #include "Tokenizer.h" #include +#include namespace dice { namespace hfe { @@ -17,7 +18,6 @@ namespace hfe { namespace { // Select the file-info representation required by the host ABI. -#if BF2_PLUGIN_ABI_NATIVE // The native host's own record - this image shares the host's STL and CRT. typedef ::dice::hfe::io::FileInfo TokenizerFileInfo; @@ -27,37 +27,14 @@ inline ::dice::hfe::io::FileInfo& hostFileInfo(TokenizerFileInfo& info) return info; } -#else - -// Retail file-info carrier. Its filename uses the VC7.1 string allocator and lifecycle. -struct TokenizerFileInfo -{ - vc71::string name; // +0 the only member the shipped frame constructs - unsigned char isDirectory; // +28 - unsigned char pad29[3]; - unsigned int size; // +32 the buffer size and the read size - unsigned int pad36; // +36 MSVC 8-aligns the FILETIMEs - unsigned int times[6]; // +40..+63 creation, last access, last write -}; - -#if defined(_M_IX86) -static_assert(sizeof(TokenizerFileInfo) == 64, "the PE io::FileInfo the shipped frame reserves"); -static_assert(offsetof(TokenizerFileInfo, size) == 32, "sub_10076C90 reads the size at +0x20"); -#endif - -inline ::renddx9abi::HostFileInfo& hostFileInfo(TokenizerFileInfo& info) -{ - return reinterpret_cast< ::renddx9abi::HostFileInfo&>(info); -} - -#endif // BF2_PLUGIN_ABI_NATIVE // End-of-input token text: ASCII ETX followed by the string terminator. const char kEndTokenText[] = "\x03"; } // anonymous namespace -// owner 0, index -1, the text constructed empty, line and column 0xFFFF, type 0, in +// PE 0x10076450 (the out-of-line copy; unreachable in 1.50: no code or data references) / ELF +// 0x8438A60. owner 0, index -1, the text constructed empty, line and column 0xFFFF, type 0, in // declaration order. RendDX9 inlines it (0x1007688F.. in clean(), 0x10076913.. in the scan). Token::Token() : owner(0), @@ -68,7 +45,7 @@ Token::Token() { } -// Advances to the next token and returns this cursor. Advancing the end token leaves it at the end. +// PE 0x10076490. Advances to the next token and returns this cursor. Advancing the end token leaves it at the end. Token& Token::operator++() { Tokenizer* const tokenizer = owner; @@ -78,6 +55,57 @@ Token& Token::operator++() return *this; } +// PE 0x100764F0 / ELF 0x8438B10. Steps back one token unless at the first, then copies that token. +// Unreachable in 1.50: no code or data references. +Token& Token::operator--() +{ + if (index > 0) + --index; + *this = owner->m_tokens[index]; + return *this; +} + +// PE 0x10076550 / ELF 0x8438B80. A target at or past the token count takes the end token's own +// index (the record at m_count), else the target; then the cursor copies that token. Unreachable in +// 1.50: no code or data references. +Token& Token::operator+=(unsigned int count) +{ + Tokenizer* const tokenizer = owner; + const unsigned int target = index + count; + if (target >= tokenizer->m_count) + index = tokenizer->m_tokens[tokenizer->m_count].index; + else + index = target; + *this = tokenizer->m_tokens[index]; + return *this; +} + +// PE 0x100765D0 / ELF 0x8438C10. Both images compare signed (`jl`), so the clamp is done on int. +// Unreachable in 1.50: no code or data references. +const Token& Token::operator[](unsigned int count) const +{ + const Tokenizer* const tokenizer = owner; + int target = static_cast(index + count); + const int end = static_cast(tokenizer->m_count); + if (target >= end) + target = end; + return tokenizer->m_tokens[target]; +} + +// PE 0x100767C0 (the token in ECX, the result in EDX:EAX) / ELF 0x84398D0. getIntNumber's sign rule, +// converted with _atoi64. Unreachable in 1.50: no code or data references. +long long Tokenizer::getInt64Number(Token& token) +{ + std::string number(token.text.c_str()); + ++token; + if (number == "-" || number == "+") + { + number += token.text.c_str(); + ++token; + } + return _atoi64(number.c_str()); +} + // ELF 0x8438C90 / sub_10076860, 27 B - see the header: the vector empty, the name empty, the count // left unset. Tokenizer::Tokenizer() @@ -98,7 +126,7 @@ void Tokenizer::clean() m_count = 0; } -// Loads and tokenizes fileName through FileManager. Returns the scan result. +// PE 0x10076C90 (FileManager vtable +0x38 getFileInfo, +0x2C readFile). Loads and tokenizes fileName through FileManager. Returns the scan result. // Requires FileManager; records the name after successful file access even when scanning fails. bool Tokenizer::init(const char* fileName) { diff --git a/Code/BF2/IO/Tokenizer.h b/Code/BF2/IO/Tokenizer.h index bcc5ec742..c9c976979 100644 --- a/Code/BF2/IO/Tokenizer.h +++ b/Code/BF2/IO/Tokenizer.h @@ -2,7 +2,7 @@ // Token indices are unsigned; m_tokens[m_count] is the end token. // The selected Windows build places bodies in RendDX9. [CHOSEN, not recovered] build placement // and native STL containers keep these objects local to their image; PE and ELF sizes differ. -// Member names are [INFERRED]; unimplemented cursor/numeric helpers remain declarations. +// Member names are [INFERRED] where the ELF carries no symbol. #ifndef BF2_IO_TOKENIZER_H #define BF2_IO_TOKENIZER_H @@ -23,6 +23,12 @@ class Token // Advances to the next token, stopping at the end token, and returns this cursor. Token& operator++(); + // Steps back one token, stopping at the first, and returns this cursor. + Token& operator--(); + // Advances by count tokens, stopping at the end token, and returns this cursor. + Token& operator+=(unsigned int count); + // The token count positions ahead of this cursor, clamped to the end token. + const Token& operator[](unsigned int count) const; Tokenizer* owner; // RendDX9 +0x00 unsigned int index; // RendDX9 +0x04 @@ -58,6 +64,10 @@ class Tokenizer // 0x8439530 / sub_10076880 - the name to one NUL character, no tokens, count 0. void clean(); + // The integer starting at token, consuming its tokens: a "-" or "+" token is glued to the next + // token, then the text is converted with _atoi64. + static long long getInt64Number(Token& token); + // [INFERRED] accessors: the shipped users inline these reads (the water loader reads // m_tokens[0] and m_tokens[m_count]); the ELF carries no out-of-line accessor. const Token& token(unsigned int i) const { return m_tokens[i]; } diff --git a/Code/BF2/Math/Frustum.cpp b/Code/BF2/Math/Frustum.cpp index 509e30a3b..59bb38c78 100644 --- a/Code/BF2/Math/Frustum.cpp +++ b/Code/BF2/Math/Frustum.cpp @@ -1,5 +1,8 @@ // Frustum setup and intersection queries. +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "Frustum.h" #include "../Core/Debug.h" @@ -33,7 +36,8 @@ inline void normalizePlaneNormal(Vec3& n) } } // namespace -// ELF 0x1A0D00. +// ELF 0x1A0D00; RendDX9.dll copy PE 0x10030F30 (listing read: the same stores, including the +// bounding box's own constructor values; nothing else is written). // Initializes plane normals, corners, bounds, centre, and identity transform; marks derived data dirty. // Leaves plane distances, outcodes, radii, and projection scalars untouched. Frustum::Frustum() @@ -59,7 +63,7 @@ Frustum::Frustum() m_type = 2; // +0x1E4 } -// ELF 0x494130. Copies setup parameters and transformation, then rebuilds derived planes and corners. +// ELF 0x494130 (RendDX9.dll's copy is rendmath::frustumAssign). Copies setup parameters and transformation, then rebuilds derived planes and corners. Frustum& Frustum::operator=(const Frustum& other) { m_fov = other.m_fov; @@ -128,7 +132,7 @@ void Frustum::setPerspective(float fov, float aspect, float nearDist, float farD updateSecondarySizes(); } -// ELF 0x494A20; engine ELF 0x83B1500 / client PE6DD4C0 / renderer PE1007A7F0. Width/height and distance +// ELF 0x494A20; engine ELF 0x83B1500 / client PE6DD4C0 (RendDX9.dll's copy is rendmath::frustumSetOrtho). Width/height and distance // stores, six axial planes, native plane transform/sign masks, matrix and centre, // then the same secondary-size recompute as perspective. FOV/aspect stay untouched. void Frustum::setOrtho(float width, float height, float nearDist, float farDist, const Mat4& m) @@ -215,6 +219,18 @@ void Frustum::setOrtho(float width, float height, float nearDist, float farDist, fstp dword ptr [edx+4] fstp dword ptr [edx+8] } +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + const bf2x87::Real midpoint = (static_cast(nearDist) + farDist) * 0.5L; + m_boundingRadius = static_cast(midpoint); + m_boundingRadiusSq = static_cast(midpoint * midpoint); + m_center.x = m_center.y = 0.0f; + m_center.z = static_cast(midpoint); + const bf2x87::Real x = m_center.x, y = m_center.y, z = m_center.z; + m_center.z = static_cast(m.m[10] * z + m.m[6] * y + m.m[2] * x + m.m[14]); + m_center.y = static_cast(m.m[9] * z + m.m[5] * y + m.m[1] * x + m.m[13]); + m_center.x = static_cast(m.m[0] * x + m.m[4] * y + m.m[8] * z + m.m[12]); #else const long double midpoint = (static_cast(nearDist) + farDist) * 0.5L; m_boundingRadius = static_cast(midpoint); @@ -225,6 +241,7 @@ void Frustum::setOrtho(float width, float height, float nearDist, float farDist, m_center.z = static_cast(m.m[10] * z + m.m[6] * y + m.m[2] * x + m.m[14]); m_center.y = static_cast(m.m[9] * z + m.m[5] * y + m.m[1] * x + m.m[13]); m_center.x = static_cast(m.m[0] * x + m.m[4] * y + m.m[8] * z + m.m[12]); +#endif #endif updateSecondarySizes(); } @@ -288,7 +305,7 @@ void Frustum::transform(const Mat4& transformation) reSetup(); } -// ELF 0x4956B0; engine ELF 0x83B2050 / PE6DD7F0: unconditional store followed by reSetup. +// ELF 0x4956B0; engine ELF 0x83B2050 / PE6DD7F0 (RendDX9.dll's copy is rendmath::frustumSetFarDist): unconditional store followed by reSetup. void Frustum::setFarDist(float distance) { m_farDist = distance; diff --git a/Code/BF2/Math/Frustum.h b/Code/BF2/Math/Frustum.h index 5119cae5b..3f44ac8d8 100644 --- a/Code/BF2/Math/Frustum.h +++ b/Code/BF2/Math/Frustum.h @@ -31,11 +31,11 @@ class Frustum void expandToEncapsulate(const Frustum& other); void reSetup(); void transform(const Mat4& m); - float getFov() { return m_fov; } + float getFov() { return m_fov; } // RendDX9.dll inline copy PE 0x10079790: float +0x1CC void setFov(float fov); float getNearDist() const { return m_nearDist; } void setNearDist(float d); - float getFarDist() const { return m_farDist; } + float getFarDist() const { return m_farDist; } // RendDX9.dll inline copy PE 0x100797B0: float +0x1E0 void setFarDist(float d); // Returns one of four corners for a plane; invalid input emits an error. const Vec3& getCornerForPlane(unsigned int corner, FrustumPlane plane) const; diff --git a/Code/BF2/Math/Intersect.cpp b/Code/BF2/Math/Intersect.cpp index d3147d14d..0afd9bf8f 100644 --- a/Code/BF2/Math/Intersect.cpp +++ b/Code/BF2/Math/Intersect.cpp @@ -12,7 +12,9 @@ namespace dice { namespace hfe { -// ELF 0x495E20; engine ELF 0x83B26D0. +// ELF 0x495E20; engine ELF 0x83B26D0; RendDX9.dll copy PE 0x101C78F0 (unreachable there: no code or +// data references). [PLATFORM] the PE copy forms the denominator as (nz*dz + ny*dy) + nx*dx; the order +// below differs in the last float bit only. An unordered denominator proceeds, as the PE does. bool findIntersection(const Plane3& plane, const Ray3& ray, Vec3& position) { const float denominator = plane.normal.x * ray.direction.x @@ -52,7 +54,7 @@ bool intersect(const Frustum& frustum, const LocalBoundingBox& box) return true; } -// ELF 0x496180. Per axis: below the box -> (c - min)^2, above it -> (c - max)^2, inside -> 0. +// ELF 0x496180; RendDX9.dll copy PE 0x101C7C00 (unreachable there: no code or data references). Per axis: below the box -> (c - min)^2, above it -> (c - max)^2, inside -> 0. bool sphereIntersectsAABB(const Vec3& centre, float radius, const Vec3& boxMin, const Vec3& boxMax) { const float* c = ¢re.x; @@ -111,14 +113,17 @@ inline bool slabTest(const Vec3& origin, const Vec3& dir, const float* lo, const } // namespace -// ELF 0x496010. +// ELF 0x496010; RendDX9.dll copy PE 0x101C7A60 (unreachable there: no code or data references). The +// PE tests each reciprocal with `fcomp 0; test ah, 1; jne`, so a NaN reciprocal takes the negative-slab +// arm there. bool rayIntersectsAABB(const Vec3& origin, const Vec3& dir, const Vec3& boxMin, const Vec3& boxMax, float& tMin, float& tMax) { return slabTest(origin, dir, &boxMin.x, &boxMax.x, tMin, tMax); } -// ELF 0x4961F0. The box grown by `radius` on all six sides first. +// ELF 0x4961F0; RendDX9.dll copy PE 0x101C7CB0 (unreachable there: no code or data references; +// the grown corners are formed first, then the same slab test as PE 0x101C7A60). The box grown by `radius` on all six sides first. bool rayRadiusIntersectsAABB(const Vec3& origin, const Vec3& dir, float radius, const Vec3& boxMin, const Vec3& boxMax, float& tMin, float& tMax) { diff --git a/Code/BF2/Math/LocalBoundingBox.cpp b/Code/BF2/Math/LocalBoundingBox.cpp index dd2744ec0..a2b99fda0 100644 --- a/Code/BF2/Math/LocalBoundingBox.cpp +++ b/Code/BF2/Math/LocalBoundingBox.cpp @@ -74,7 +74,8 @@ bool LocalBoundingBox::inside(const Frustum* frustum, const Mat4* transform, uns return false; } -// ELF 0x4969F0; engine ELF 0x83B31F0. +// ELF 0x4969F0; engine ELF 0x83B31F0; RendDX9.dll copy PE 0x101C5FE0 (unreachable there: no code or +// data references). int LocalBoundingBox::getMajorAxis() const { if (m_derivedDataDirty) @@ -84,13 +85,16 @@ int LocalBoundingBox::getMajorAxis() const return m_size.z > m_size.x ? 2 : 0; } -// ELF 0x497560; engine ELF 0x83B3CE0. +// ELF 0x497560; engine ELF 0x83B3CE0; RendDX9.dll copy PE 0x101C5490 (unreachable there: no code or +// data references; it forwards to the RendDX9 copy of intersect, PE 0x101C7980). bool LocalBoundingBox::inside(const Frustum& frustum) const { return intersect(frustum, *this); } -// ELF 0x4981F0; engine ELF 0x83B49B0. +// ELF 0x4981F0; engine ELF 0x83B49B0; RendDX9.dll copy PE 0x101C5D00 (unreachable there: no code or +// data references). [PLATFORM] the PE copy sums the rotated components in a different association +// ((dz*m10 + dx*m2) + dy*m6 for lz); the ELF-derived order below differs in the last float bit only. bool LocalBoundingBox::isInside(const Vec3& point, const Vec3& ownerPosition, const Mat4& ownerInverse) const { @@ -109,14 +113,18 @@ bool LocalBoundingBox::isInside(const Vec3& point, const Vec3& ownerPosition, return m_max.z >= lz; } -// ELF 0x496A70. The source overload is only an identity-transform +// ELF 0x496A70; RendDX9.dll copy PE 0x101C6050 (unreachable there: no code or data references; the +// identity matrix comes from the function-local static at PE 0x100791E0). The source overload is only an identity-transform // forwarding wrapper in both ports. bool LocalBoundingBox::intersectRay(const Ray3& ray, Vec3& position, Vec3* normal) const { return intersectRay(ray, Mat4::getIdentity(), position, normal); } -// ELF 0x496AC0. Tests the ray against this box under transform and writes intersection data when found. +// ELF 0x496AC0; RendDX9.dll copy PE 0x101C56C0 (unreachable there: no code or data references; +// instruction-identical, once addresses are normalised, to the BF2.exe copy at PE 0x6DADF0, and its +// two plane intersections call the RendDX9 copy of findIntersection, PE 0x101C78F0). +// Tests the ray against this box under transform and writes intersection data when found. bool LocalBoundingBox::intersectRay(const Ray3& ray, const Mat4& transform, Vec3& position, Vec3* normal) const { @@ -243,7 +251,9 @@ bool LocalBoundingBox::intersectRay(const Ray3& ray, const Mat4& transform, return true; } -// ELF 0x497600. Tests two oriented bounding boxes using their separating axes. +// ELF 0x497600; RendDX9.dll copy PE 0x101C6080 (unreachable there: no code or data references; +// instruction-identical, once addresses are normalised, to the BF2.exe copy at PE 0x6DB6E0, and like +// it never reads the grow argument). Tests two oriented bounding boxes using their separating axes. bool LocalBoundingBox::testIntersectWithOBB(const Mat4& thisTransform, const LocalBoundingBox& other, const Mat4& otherTransform, diff --git a/Code/BF2/Math/LocalBoundingBox.h b/Code/BF2/Math/LocalBoundingBox.h index b9ff537f8..886f4c60f 100644 --- a/Code/BF2/Math/LocalBoundingBox.h +++ b/Code/BF2/Math/LocalBoundingBox.h @@ -21,6 +21,8 @@ class BoundingBox; struct LocalBoundingBox { + // RendDX9.dll PE 0x10030EF0 (COMDAT copy, answers this): +0x00..+0x1C zero, dirty byte +0x20 = 1, + // +0x24..+0x38 zero; the lightmap traces construct their light bounds with it. LocalBoundingBox() { m_min.x = m_min.y = m_min.z = 0.0f; @@ -120,7 +122,9 @@ struct LocalBoundingBox return m_size; } - // ELF 0x4982E0; engine ELF 0x83B4AA0. + // ELF 0x4982E0; engine ELF 0x83B4AA0; RendDX9.dll copy PE 0x101C5DD0 (unreachable there: no code or + // data references; instruction-identical, once addresses are normalised, to BF2.exe PE 0x6DB430, and + // its rotated components use the same different association as the PE copy of isInside(point)). // Tests the world-space sphere center against this box expanded by radius in the owner's local frame. bool isInside(const Vec3& centre, float radius, const Vec3& ownerPosition, const Mat4& ownerInverse) const diff --git a/Code/BF2/Math/Mat4Inverse.cpp b/Code/BF2/Math/Mat4Inverse.cpp index e19b4f2ae..b96944dad 100644 --- a/Code/BF2/Math/Mat4Inverse.cpp +++ b/Code/BF2/Math/Mat4Inverse.cpp @@ -1,5 +1,7 @@ // Full 4x4 inverse for client and aidll builds. -// AIDLL.dll 0x10123490 is instruction-identical to RendDX9.dll 0x10078270. +// AIDLL.dll 0x10123490 is instruction-identical to the client's RendDX9.dll 0x10078270 (only the +// 1.0f constant's address differs); its two callers are QuadTree::getPolygonsWithinBoundary and +// getPolygonsWithinBoundaryDoubles. Every AI image, including the native POSIX one, uses this body. // The dedicated engine implementation has different rounding and remains declaration-only. #include "Mat4.h" #if !defined(_MSC_VER) || !defined(_M_IX86) @@ -8,6 +10,7 @@ #if !DEDICATED || defined(BF2_IMAGE_AIDLL) namespace dice { namespace hfe { namespace { +#if defined(_M_IX86) // Explicit x87 arithmetic keeps the caller's precision/rounding control and // the shipped float stores. A product of two input floats fits in a double; // the second group's pair10 deliberately has no intermediate float store. @@ -109,7 +112,77 @@ void divideByDeterminant(const float* input, float* output) bf2x87::divideByDeterminant(input, output); #endif } +#else +// [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates, under the caller's precision +// control). Each helper keeps the x87 body's operation order and its float/double store widths +// (issue #7). +float roundedPairProduct(float left, float right) +{ +#if defined(_WIN32) + // fld; fmul; fstp dword - one rounding of the exact product to float. + return static_cast(static_cast(left) * static_cast(right)); +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float value; + // [CHOSEN, not recovered] Preserve x87 product float store. + value = bf2x87::store(bf2x87::mul(bf2x87::wide(left), bf2x87::wide(right))); + return value; +#endif +} +double pairProduct(float left, float right) +{ +#if defined(_WIN32) + // fld; fmul; fstp qword - the exact product, no float rounding. + return static_cast(left) * static_cast(right); +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + double value; + // [CHOSEN, not recovered] Preserve x87 product double store. + value = bf2x87::storeDouble(bf2x87::mul(bf2x87::wide(left), bf2x87::wide(right))); + return value; +#endif +} +void cofactor(float& output, double a0, double b0, double a1, double b1, + double a2, double b2, double a3, double b3, double a4, double b4, + double a5, double b5) +{ +#if defined(_WIN32) + // (a0*b0 + a1*b1) + a2*b2 is stored as a float first; the second sum is then subtracted from + // that stored float (fsubr dword) and the difference stored as a float again. + output = static_cast(a0 * b0 + a1 * b1 + a2 * b2); + const double second = a3 * b3 + a4 * b4 + a5 * b5; + output = static_cast(static_cast(output) - second); +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + // [CHOSEN, not recovered] Preserve x87 staged cofactor float stores. + bf2x87::cofactor(output, a0, b0, a1, b1, a2, b2, a3, b3, a4, b4, a5, b5); +#endif +} +void divideByDeterminant(const float* input, float* output) +{ +#if defined(_WIN32) + // ((in4*out1 + in0*out0) + in8*out2) + in12*out3, then 1/det kept unrounded across all sixteen + // scaled float stores. No zero/NaN/infinity test exists in either shipped image. + const double determinant = + static_cast(input[4]) * static_cast(output[1]) + + static_cast(input[0]) * static_cast(output[0]) + + static_cast(input[8]) * static_cast(output[2]) + + static_cast(input[12]) * static_cast(output[3]); + const double reciprocal = static_cast(1.0f) / determinant; + for (int i = 0; i < 16; ++i) + output[i] = static_cast(reciprocal * static_cast(output[i])); +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float one = 1.0f; + // Retain the reciprocal on the x87 stack throughout all16 scaled stores. + // No zero/NaN/infinity test exists in either shipped image. + // [CHOSEN, not recovered] Preserve x87 retained determinant reciprocal for all stores. + bf2x87::divideByDeterminant(input, output); +#endif +} +#endif } +// RendDX9.dll copy PE 0x10078270 (instruction-identical to AIDLL.dll 0x10123490, see the file comment). void fullInvert(const Mat4& source, Mat4& destination) { // Every input is captured before the first output store, including aliases. diff --git a/Code/BF2/Math/PortableX87.h b/Code/BF2/Math/PortableX87.h index a77f36be6..70c8e94ff 100644 --- a/Code/BF2/Math/PortableX87.h +++ b/Code/BF2/Math/PortableX87.h @@ -232,10 +232,11 @@ inline void lod(float lodScale, float view, float nearRatio, float farRatio, float& base, float& nearDistance, float& inverseNear, float& farDistance, float& inverseFar) { const Real product = mul(wide(lodScale),wide(view)); base = store(product); - const Real near = mul(product,wide(nearRatio)); nearDistance = store(near); - inverseNear = store(div(1.0L,sub(wide(base),near))); - const Real far = mul(wide(farRatio),wide(base)); farDistance = store(far); - inverseFar = store(div(1.0L,sub(wide(base),far))); + // Not named near/far: defines both as empty macros. + const Real nearValue = mul(product,wide(nearRatio)); nearDistance = store(nearValue); + inverseNear = store(div(1.0L,sub(wide(base),nearValue))); + const Real farValue = mul(wide(farRatio),wide(base)); farDistance = store(farValue); + inverseFar = store(div(1.0L,sub(wide(base),farValue))); } inline float effectiveDistance(float renderer, float global, float factor) { diff --git a/Code/BF2/Math/Vec3.cpp b/Code/BF2/Math/Vec3.cpp index 9f4a97b5e..48ce85703 100644 --- a/Code/BF2/Math/Vec3.cpp +++ b/Code/BF2/Math/Vec3.cpp @@ -115,6 +115,7 @@ std::istream& operator>>(std::istream& in, Vec3& v) return in; } +// PE 0x100277C0: fastcall, receiver ecx and vector edx; float, then each '/' separator and float, stream returned by the last insertion. std::ostream& operator<<(std::ostream& out, const Vec3& v) { out << v.x << '/' << v.y << '/' << v.z; // default precision, '/' separators @@ -134,6 +135,7 @@ std::istream& operator>>(std::istream& in, Vec2& v) return in; } +// PE 0x1005BD40: fastcall, receiver ecx and vector edx; float, then each '/' separator and float, stream returned by the last insertion. std::ostream& operator<<(std::ostream& out, const Vec2& v) { out << v.x << '/' << v.y; @@ -159,6 +161,7 @@ std::istream& operator>>(std::istream& in, Vec4& v) return in; } +// PE 0x100584B0: fastcall, receiver ecx and vector edx; float, then each '/' separator and float, stream returned by the last insertion. std::ostream& operator<<(std::ostream& out, const Vec4& v) { out << v.x << '/' << v.y << '/' << v.z << '/' << v.w; diff --git a/Code/BF2/Math/Vec3.h b/Code/BF2/Math/Vec3.h index c578c3a5f..a40e993af 100644 --- a/Code/BF2/Math/Vec3.h +++ b/Code/BF2/Math/Vec3.h @@ -51,6 +51,38 @@ struct Vec2 float x, y; }; +// Component arithmetic the RendDX9 image emits as separate functions (the callers in this source spell +// the components inline). [INFERRED] names; each is one float operation per component. +// PE 0x100513A0: rhs + self, per component. +inline Vec3 vec3Sum(const Vec3& self, const Vec3& rhs) +{ + Vec3 result = { rhs.x + self.x, rhs.y + self.y, rhs.z + self.z }; + return result; +} + +// PE 0x10030D50: self scaled by `scale`, per component. +inline Vec3 vec3Scaled(const Vec3& self, float scale) +{ + Vec3 result = { scale * self.x, scale * self.y, scale * self.z }; + return result; +} + +// PE 0x1000BDD0: copies the four components of `rhs` into `self`. +inline void vec4Assign(Vec4& self, const Vec4& rhs) +{ + self.x = rhs.x; + self.y = rhs.y; + self.z = rhs.z; + self.w = rhs.w; +} + +// PE 0x100513D0: self scaled by `scale`, per component. +inline Vec4 vec4Scaled(const Vec4& self, float scale) +{ + Vec4 result = { scale * self.x, scale * self.y, scale * self.z, scale * self.w }; + return result; +} + // Colour plus intensity in one token group - four numbers, not three. Console metadata declares // this type for `color`, `speccolor` and the sun colour properties. struct Vec3ColorFloatIntensity diff --git a/Code/BF2/Menu/BF2HudManager.cpp b/Code/BF2/Menu/BF2HudManager.cpp index 59cbe1ba5..083c7733b 100644 --- a/Code/BF2/Menu/BF2HudManager.cpp +++ b/Code/BF2/Menu/BF2HudManager.cpp @@ -1,5 +1,8 @@ // Owns the HUD modules and their shared menu system. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "HudBlinker.h" #include "Ref2System.h" @@ -46,6 +49,10 @@ #include #include #include +// [CHOSEN, not recovered] SSE2 is used only by the Windows x64 arm; arm64 has no emmintrin.h. +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace hfe { extern hud::BF2HudManager* hudManager; } } namespace dice { namespace hfe { class IMenuLogic; extern IMenuLogic* menuLogic; } } @@ -67,9 +74,11 @@ const std::string defaultSquadNames[27] = { // values. Only the rejected arm then materializes the double passed to ceil. bool commanderWaitRemaining(double last, double cooldown, double now, double& remaining) { +#if defined(_WIN32) const double minutesPerSecond = 1.0 / 60.0; double value; bool denied; +#if defined(_M_IX86) __asm { fld now fsub last @@ -86,12 +95,30 @@ bool commanderWaitRemaining(double last, double cooldown, double now, double& re fstp st(0) wait_done: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // setp after test ah,41h: denied for a positive or unordered wait, not for <= 0. + value = cooldown - (now - last) * minutesPerSecond; + denied = !(value <= 0.0); +#endif + if (denied) remaining = value; + return denied; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const double minutesPerSecond = 1.0 / 60.0; + double value; + bool denied; + // [CHOSEN, not recovered] Preserve x87 positive-or-unordered wait and double store. + denied = bf2x87::waitRemaining(last, cooldown, now, value); if (denied) remaining = value; return denied; +#endif } int commanderWaitInteger(double remaining) { +#if defined(_WIN32) const double rounded = std::ceil(remaining); +#if defined(_M_IX86) unsigned short original, truncating; int result; __asm { @@ -105,6 +132,19 @@ int commanderWaitInteger(double remaining) fldcw original } return result; +#else + // cvttsd2si truncates like the chopped fistp, including the 0x80000000 indefinite result. + return _mm_cvttsd_si32(_mm_set_sd(rounded)); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const double rounded = std::ceil(remaining); + unsigned short original, truncating; + int result; + // [CHOSEN, not recovered] Preserve x87 truncating int32 with integer indefinite. + result = bf2x87::integer(bf2x87::wide(rounded)); + return result; +#endif } } @@ -452,7 +492,7 @@ bool BF2HudManager::isPlayerAlive(world::IPlayer* player) return static_cast(object->m_armorComponent)->getStatus() == 1; } -int BF2HudManager::getPlayerKitIcon(world::IPlayer* player, bool mapIcon, bool spotted) +std::intptr_t BF2HudManager::getPlayerKitIcon(world::IPlayer* player, bool mapIcon, bool spotted) { if (!player) return 0; world::IPlayer* local = world::playerManager->getLocalHumanPlayer(); @@ -463,13 +503,13 @@ int BF2HudManager::getPlayerKitIcon(world::IPlayer* player, bool mapIcon, bool s if (player->getTeam() != team) { if (!m_field184 && ref2System) m_field184 = ref2System->loadTexture("Ingame/Scoreboard/Icons/icon_Faded.tga", true); - return static_cast(m_field184); + return static_cast(m_field184); } } } else { if (!m_field188 && ref2System) m_field188 = ref2System->loadTexture("Ingame/Scoreboard/Icons/icon_Death.tga", true); - return static_cast(m_field188); + return static_cast(m_field188); } } world::IObject* object = player->getDefaultVehicle(); @@ -880,7 +920,7 @@ bool BF2HudManager::hasActiveMenu() return state != 0 && state != 2 && state != 9 && state != 10; } -int BF2HudManager::getPlayerVehicleIcon(world::IPlayer* player, bool typeIcon) +std::intptr_t BF2HudManager::getPlayerVehicleIcon(world::IPlayer* player, bool typeIcon) { if (!player) return 0; @@ -907,7 +947,7 @@ world::ICameraObject* BF2HudManager::getCameraObject(int team) return camera; } -int BF2HudManager::getPlayerRankIcon(world::IPlayer* player) +std::intptr_t BF2HudManager::getPlayerRankIcon(world::IPlayer* player) { if (player) { @@ -927,7 +967,7 @@ int BF2HudManager::getPlayerRankIcon(world::IPlayer* player) return m_field18c[0]; } -int BF2HudManager::getVehicleTypeIcon(int type) +std::intptr_t BF2HudManager::getVehicleTypeIcon(int type) { switch (type) { diff --git a/Code/BF2/Menu/BF2HudManager.h b/Code/BF2/Menu/BF2HudManager.h index 711ab7e3e..79060c687 100644 --- a/Code/BF2/Menu/BF2HudManager.h +++ b/Code/BF2/Menu/BF2HudManager.h @@ -90,10 +90,11 @@ class BF2HudManager : public io::IInputFilter, public IEventListener virtual std::wstring toWideString(const std::string& text); // +0x54 virtual std::wstring replaceWideInputKeys(std::wstring text); // +0x58 virtual std::string replaceInputKeys(std::string text); // +0x5C - virtual int getPlayerVehicleIcon(world::IPlayer*, bool typeIcon); - virtual int getPlayerKitIcon(world::IPlayer*, bool mapIcon, bool spotted); - virtual int getPlayerRankIcon(world::IPlayer*); // +68 0x74F8D0; root texture dependency - virtual int getVehicleTypeIcon(int type); // +6C 0x74F980; root texture dependency + // Icon getters answer meme texture handles (meme::TextureHandle, int on x86). + virtual std::intptr_t getPlayerVehicleIcon(world::IPlayer*, bool typeIcon); + virtual std::intptr_t getPlayerKitIcon(world::IPlayer*, bool mapIcon, bool spotted); + virtual std::intptr_t getPlayerRankIcon(world::IPlayer*); // +68 0x74F8D0; root texture dependency + virtual std::intptr_t getVehicleTypeIcon(int type); // +6C 0x74F980; root texture dependency virtual world::ICameraObject* getCameraObject(int team); virtual int getPlayerVehicleType(world::IPlayer*); virtual void showRankUpIcon(std::string path, float seconds); @@ -166,7 +167,7 @@ class BF2HudManager : public io::IInputFilter, public IEventListener virtual void callForAmmo(); virtual void callForRepair(); virtual bool isPointerEnabled(); - virtual void enablePointer(int texture, int mode); // +16C 7510C0; picture/descriptor dependencies remain + virtual void enablePointer(std::intptr_t texture, int mode); // +16C 7510C0; picture/descriptor dependencies remain virtual void disablePointer(); virtual bool setPointerSize(int width, int height); virtual bool setMouseTextureEmpty(std::string); @@ -390,11 +391,12 @@ class BF2HudManager : public io::IInputFilter, public IEventListener float m_field154, m_field158; bool m_field15c; std::uint32_t m_field160; // untouched - std::uint32_t m_field164, m_field168, m_field16c, m_field170, m_field174; - std::uint32_t m_field178; // untouched + // Pointer texture handles; uintptr_t is uint32_t on x86. + std::uintptr_t m_field164, m_field168, m_field16c, m_field170, m_field174; + std::uintptr_t m_field178; // untouched by the constructor int m_field17c, m_field180; - std::uint32_t m_field184, m_field188; - int m_field18c[22]; // rank texture handles, 0x74F8D0 + std::uintptr_t m_field184, m_field188; // faded/death icon handles + std::intptr_t m_field18c[22]; // rank texture handles, 0x74F8D0 unsigned short m_field1e4; // networkable id, setter751B20 Vec3 m_field1e8; // spotted position, setter751F50 float m_field1f4; diff --git a/Code/BF2/Menu/BF2HudManagerAbilities.cpp b/Code/BF2/Menu/BF2HudManagerAbilities.cpp index 1f54faa00..63986c623 100644 --- a/Code/BF2/Menu/BF2HudManagerAbilities.cpp +++ b/Code/BF2/Menu/BF2HudManagerAbilities.cpp @@ -1,11 +1,15 @@ // Ability display. [INFERRED] Source split from Menu/BF2HudManager.cpp. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "Bf2MenuMapNode.h" #include "HudCommander.h" #include "HudArtillerySeams.h" #include "../AI/AIInterface/AIInstance.h" #include "../AI/AIInterface/SingletonServer.h" +#include "../AI/AIInterface/IAIEventCourier.h" #include "../Core/EventManager.h" #include "../Core/System.h" #include "../Game/IGameLogic.h" @@ -23,17 +27,32 @@ #include "../Sound/BfSound.h" #include #include +#if !defined(_M_IX86) +#include +#include +#endif namespace dice { namespace hfe { extern IBase* squadManager; +namespace ai { +// BF2.exe launchArtillery 7B25D8..7B2605: the courier (ds:A386C8, filled from the +// "IAIEventCourier" simple singleton at 809121) is called at +5C, event_incomingArtillery, with the +// team and the target by value. No courier null check, as shipped. +void dispatchArtilleryRequest(IAIEventCourier* courier, int team, Vec2 target) +{ + courier->event_incomingArtillery(team, target); +} +} namespace hud { namespace { // [INFERRED] spelling of Vec2 inequality5EA630. The sum is retained in x87 // precision, and unordered values take the same arm as a sum above epsilon. bool hasAbilityPosition(const Vec2& position) { +#if defined(_WIN32) const float sentinel = -4000.0f; const float epsilon = FLT_EPSILON; +#if defined(_M_IX86) bool valid; __asm { mov ecx, position @@ -50,6 +69,22 @@ bool hasAbilityPosition(const Vec2& position) setp valid } return valid; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Vec2 +4 is y and +0 x. setp after test ah,41h: valid above epsilon or unordered. + const double sum = std::fabs(static_cast(position.y) - sentinel) + + std::fabs(static_cast(position.x) - sentinel); + return !(sum <= epsilon); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float sentinel = -4000.0f; + const float epsilon = FLT_EPSILON; + bool valid; + // [CHOSEN, not recovered] Preserve x87 positive-or-unordered sentinel comparison. + valid = bf2x87::abilityPosition(position.x, position.y); + return valid; +#endif } // Preserve both the unrounded x87 sum and the two producers' distinct store @@ -57,6 +92,8 @@ bool hasAbilityPosition(const Vec2& position) void beginSupplyCooldown(double now, const float& duration, float& remaining, bool& reloading, float& deadline) { +#if defined(_WIN32) +#if defined(_M_IX86) __asm { fld now mov eax, duration @@ -69,11 +106,27 @@ void beginSupplyCooldown(double now, const float& duration, float& remaining, mov ecx, deadline fstp dword ptr [ecx] } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Duration is read once, before the raw copy; the shipped store order is kept. + const float length = duration; + const double sum = now + length; + std::memcpy(&remaining, &length, sizeof remaining); + reloading = true; + deadline = static_cast(sum); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + // [CHOSEN, not recovered] Preserve x87 sum and supply store ordering. + bf2x87::beginCooldown(now, duration, remaining, reloading, deadline, true); +#endif } void beginVehicleCooldown(double now, const float& duration, float& remaining, float& deadline, bool& reloading) { +#if defined(_WIN32) +#if defined(_M_IX86) __asm { fld now mov eax, duration @@ -86,6 +139,20 @@ void beginVehicleCooldown(double now, const float& duration, float& remaining, mov ecx, reloading mov byte ptr [ecx], 1 } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Duration is read once, before the raw copy; the shipped store order is kept. + const float length = duration; + const double sum = now + length; + std::memcpy(&remaining, &length, sizeof remaining); + deadline = static_cast(sum); + reloading = true; +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + // [CHOSEN, not recovered] Preserve x87 sum and vehicle store ordering. + bf2x87::beginCooldown(now, duration, remaining, reloading, deadline, false); +#endif } } diff --git a/Code/BF2/Menu/BF2HudManagerChatInput.cpp b/Code/BF2/Menu/BF2HudManagerChatInput.cpp index 7534a55d7..2966ba4fd 100644 --- a/Code/BF2/Menu/BF2HudManagerChatInput.cpp +++ b/Code/BF2/Menu/BF2HudManagerChatInput.cpp @@ -1,5 +1,8 @@ // HUD chat-input routing. [INFERRED] Source split. Named send and descriptor frontiers remain at their call sites. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "BfEditData.h" #include "HudInformationAdapter.h" @@ -15,12 +18,18 @@ #include "../IO/Input/GameInput.h" #include "../Scene/Object/PlayerManager.h" #include +// [CHOSEN, not recovered] SSE2 is used only by the Windows x64 arm; arm64 has no emmintrin.h. +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace hfe { extern IBase* squadManager; namespace hud { namespace { // Expression helper for PE7B371D..373A /7B3980..399D, not a separate retail // method. Keep the x87 subtraction, truncation and saved rounding control. int chatSecondsRemaining(double deadline, double now) { +#if defined(_WIN32) +#if defined(_M_IX86) unsigned short original, truncating; int result; __asm { @@ -35,6 +44,19 @@ int chatSecondsRemaining(double deadline, double now) fldcw original } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). cvttsd2si truncates + // like the chopped fistp, including the 0x80000000 indefinite result. + return _mm_cvttsd_si32(_mm_set_sd(deadline - now)); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + unsigned short original, truncating; + int result; + // [CHOSEN, not recovered] Preserve x87 extended subtraction and truncation. + result = bf2x87::integer(bf2x87::sub(bf2x87::wide(deadline), bf2x87::wide(now))); + return result; +#endif } // Identical spam-display arms in sendSayAll7B36C4 and sendSayTeam7B3926. diff --git a/Code/BF2/Menu/BF2HudManagerHudEvents.cpp b/Code/BF2/Menu/BF2HudManagerHudEvents.cpp index 334bb1780..96ff30bd2 100644 --- a/Code/BF2/Menu/BF2HudManagerHudEvents.cpp +++ b/Code/BF2/Menu/BF2HudManagerHudEvents.cpp @@ -1,4 +1,7 @@ // HUD event payload handling. [INFERRED] Source split. Unimplemented leaves stop when invoked. +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] +#endif #include "BF2HudManager.h" #if !DEDICATED #include "Bf2MenuMapNode.h" @@ -65,8 +68,13 @@ float stingerDelay(const char* name) fadd dword ptr [eax] fstp delay } +#else +#if defined(__APPLE__) + // [CHOSEN, not recovered] Retain x87-width values on both Mac architectures. + delay = static_cast(static_cast(sample[2]) + sample[1] + sample[0]); #else delay = static_cast(static_cast(sample[2]) + sample[1] + sample[0]); +#endif #endif } sound->play(); // PE+14 is the no-argument overload in MSVC order. diff --git a/Code/BF2/Menu/BF2HudManagerInit.cpp b/Code/BF2/Menu/BF2HudManagerInit.cpp index b9e9de20e..af871c43c 100644 --- a/Code/BF2/Menu/BF2HudManagerInit.cpp +++ b/Code/BF2/Menu/BF2HudManagerInit.cpp @@ -188,7 +188,7 @@ bool BF2HudManager::init() ref2System->loadMenu("Menu/InGame",nullptr); runHudScript("Menu/HUD/HudSetup/HudSetupMain.con"); runHudScript("Menu/Nametag/nametags.con"); - const int texture=ref2System->loadTexture("Ingame/GeneralIcons/full.tga",true); + const meme::TextureHandle texture=ref2System->loadTexture("Ingame/GeneralIcons/full.tga",true); ref2System->setDefaultTexture(texture); hudMap=m_field0fc->m_field008; // Retail _Tidy releases all storage, not just the logical elements. diff --git a/Code/BF2/Menu/BF2HudManagerInput.cpp b/Code/BF2/Menu/BF2HudManagerInput.cpp index 21389e1cf..64148d516 100644 --- a/Code/BF2/Menu/BF2HudManagerInput.cpp +++ b/Code/BF2/Menu/BF2HudManagerInput.cpp @@ -1,6 +1,9 @@ // [INFERRED] split in the attested BF2HudManager.cpp family. Complete653-byte // PE752B00 and its helpers read. Filters stay separate. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "Ref2System.h" #include "../External/BFMeme/Pointer.h" @@ -11,7 +14,9 @@ namespace dice { namespace hfe { namespace hud { namespace { float centeredInputOrigin(float origin, float dimension) { +#if defined(_WIN32) const float half = 0.5f; +#if defined(_M_IX86) float result; __asm { fld dimension @@ -20,13 +25,27 @@ float centeredInputOrigin(float origin, float dimension) fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(origin - static_cast(dimension) * half); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float half = 0.5f; + float result; + // [CHOSEN, not recovered] Preserve x87 extended centering before float store. + result = bf2x87::center(origin, dimension); + return result; +#endif } void moveInputPointer(float* position, float x, float y, int sensitivity, bool absolute, float width, float height) { +#if defined(_WIN32) const float half = 0.5f; if (absolute) { +#if defined(_M_IX86) __asm { mov eax, position fld x @@ -38,8 +57,14 @@ void moveInputPointer(float* position, float x, float y, int sensitivity, fmul half fstp dword ptr [eax+4] } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + position[0] = static_cast(static_cast(x) * width * half); + position[1] = static_cast(static_cast(y) * height * half); +#endif } else { // fild preserves all bits of the signed sensitivity until multiplication. +#if defined(_M_IX86) __asm { mov eax, position fild sensitivity @@ -51,12 +76,33 @@ void moveInputPointer(float* position, float x, float y, int sensitivity, fadd dword ptr [eax+4] fstp dword ptr [eax+4] } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates); the int is + // exact in double, its product with a float is rounded to 53 bits. + const double scale = sensitivity; + position[0] = static_cast(x * scale + position[0]); + position[1] = static_cast(scale * y + position[1]); +#endif } +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float half = 0.5f; + if (absolute) { + // [CHOSEN, not recovered] Preserve x87 absolute scaled float stores. + bf2x87::movePointer(position, x, y, sensitivity, true, width, height); + } else { + // fild preserves all bits of the signed sensitivity until multiplication. + // [CHOSEN, not recovered] Preserve x87 signed integer sensitivity before multiply/add. + bf2x87::movePointer(position, x, y, sensitivity, false, width, height); + } +#endif } void clampInputCoordinate(float& value, float origin, float extent) { +#if defined(_WIN32) // Keep the unrounded upper-bound sum and the shipped unordered comparisons. +#if defined(_M_IX86) __asm { mov edx, value fld dword ptr [edx] @@ -80,6 +126,23 @@ void clampInputCoordinate(float& value, float origin, float extent) fstp st(0) clamp_done: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered value below the origin is raised (raw copy); otherwise only an ordered + // unrounded upper bound below the value lowers it. Unordered compares change nothing. + if (value < origin) { + value = origin; + } else { + const double upper = static_cast(extent) + origin; + if (upper < value) value = static_cast(upper); + } +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + // Keep the unrounded upper-bound sum and the shipped unordered comparisons. + // [CHOSEN, not recovered] Preserve x87 ordered clamps with retained upper sum. + bf2x87::clampCoordinate(value, origin, extent); +#endif } } diff --git a/Code/BF2/Menu/BF2HudManagerPointer.cpp b/Code/BF2/Menu/BF2HudManagerPointer.cpp index 2e6e94210..e0d878320 100644 --- a/Code/BF2/Menu/BF2HudManagerPointer.cpp +++ b/Code/BF2/Menu/BF2HudManagerPointer.cpp @@ -1,5 +1,8 @@ // HUD pointer positioning and routing. [INFERRED] Source split. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "Ref2System.h" #include "HudAmmo.h" @@ -11,7 +14,9 @@ namespace dice { namespace hfe { namespace hud { namespace { float centerPointer(float center, float dimension) { +#if defined(_WIN32) const float half=0.5f; +#if defined(_M_IX86) float result; __asm { fld dimension @@ -20,18 +25,43 @@ float centerPointer(float center, float dimension) fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(center - static_cast(dimension) * half); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float half=0.5f; + float result; + // [CHOSEN, not recovered] Preserve x87 extended centering before float store. + result = bf2x87::center(center, dimension); + return result; +#endif } float pointerDimension(int dimension) // 751200 fild and two equal float stores { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fild dimension fstp result } return result; +#else + // The int is exact in double; the single float rounding is the fstp's. + return static_cast(static_cast(dimension)); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 signed FILD and float store. + result = bf2x87::store(bf2x87::wide(dimension)); + return result; +#endif } } -void BF2HudManager::enablePointer(int texture, int mode) +void BF2HudManager::enablePointer(std::intptr_t texture, int mode) { menu::Ref2System* initialSystem=ref2System; m_field15c=true; diff --git a/Code/BF2/Menu/BF2HudManagerProjection.cpp b/Code/BF2/Menu/BF2HudManagerProjection.cpp index 9cd615b9a..3553ef4ca 100644 --- a/Code/BF2/Menu/BF2HudManagerProjection.cpp +++ b/Code/BF2/Menu/BF2HudManagerProjection.cpp @@ -1,5 +1,8 @@ // World-to-HUD projection. [INFERRED] Source split from Menu/BF2HudManager.cpp. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "Ref2System.h" #include "../RendMisc/IRenderView.h" @@ -13,6 +16,8 @@ namespace { float affineComponent(float a, float ma, float b, float mb, float c, float mc, float translation) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld a @@ -27,6 +32,18 @@ float affineComponent(float a, float ma, float b, float mb, fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(static_cast(a) * ma + static_cast(b) * mb + + static_cast(c) * mc + translation); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 retained products and additions. + result = bf2x87::affine(a, ma, b, mb, c, mc, translation); + return result; +#endif } Vec3 affineInOrder(const Mat4& matrix, const Vec3& point, int first, int second, int third) @@ -44,6 +61,8 @@ Vec3 affineInOrder(const Mat4& matrix, const Vec3& point, int first, int second, float screenCoordinate(float numerator, float denominator) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld numerator @@ -51,10 +70,22 @@ float screenCoordinate(float numerator, float denominator) fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(static_cast(numerator) / denominator); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 division before float store. + result = bf2x87::store(bf2x87::div(bf2x87::wide(numerator), bf2x87::wide(denominator))); + return result; +#endif } void projectToScreen(const Vec3& clip, float halfWidth, float height, Vec3& result) { +#if defined(_WIN32) const float half = 0.5f; // The PE divides by transformed Z, not by a homogeneous W. Unordered, // zero and negative Z take the same hidden-point arm; X/Y stay zero. @@ -64,6 +95,7 @@ void projectToScreen(const Vec3& clip, float halfWidth, float height, Vec3& resu } const float x = clip.x, y = clip.y, z = clip.z; float outputX, outputY, outputZ; +#if defined(_M_IX86) __asm { fld height fmul half @@ -80,9 +112,34 @@ void projectToScreen(const Vec3& clip, float halfWidth, float height, Vec3& resu fstp outputY fstp outputZ } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + const double halfHeight = static_cast(height) * half; + const double inverse = 1.0 / z; + outputX = static_cast(x * inverse * halfWidth); + outputY = static_cast(-halfHeight * y * inverse); + outputZ = static_cast(inverse); +#endif result.x = outputX; result.y = outputY; result.z = outputZ; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float half = 0.5f; + // The PE divides by transformed Z, not by a homogeneous W. Unordered, + // zero and negative Z take the same hidden-point arm; X/Y stay zero. + if (!(clip.z > 0.0f)) { + result.z = -1.0f; + return; + } + const float x = clip.x, y = clip.y, z = clip.z; + float outputX, outputY, outputZ; + // [CHOSEN, not recovered] Preserve x87 retained reciprocal and projection products. + bf2x87::project(x, y, z, height, halfWidth, outputX, outputY, outputZ); + result.x = outputX; + result.y = outputY; + result.z = outputZ; +#endif } } diff --git a/Code/BF2/Menu/BF2HudManagerSpotted.cpp b/Code/BF2/Menu/BF2HudManagerSpotted.cpp index d93f7fb11..593877d8e 100644 --- a/Code/BF2/Menu/BF2HudManagerSpotted.cpp +++ b/Code/BF2/Menu/BF2HudManagerSpotted.cpp @@ -11,7 +11,11 @@ #include "../Scene/Object/ObjectTypes/Game/IPlayerControlObject.h" #include #include +#if defined(_WIN32) #include +#else +#include "../Core/PosixRegistry.h" +#endif namespace dice { namespace hfe { namespace hud { namespace { bool invalidSpottedPosition(const Vec3& position) // complete Vec3 comparison53C200 @@ -60,10 +64,23 @@ void BF2HudManager::sendSpottedMessage(bool announce, world::VehicleType type) if (occupant && occupant->getIsManDown()) { // Shipped BF2142-install check. The opened handle is leaked and // this arm bypasses spam filtering and radio announcement. +#if defined(_WIN32) HKEY installedKey; - if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, +#if defined(_M_IX86) + const REGSAM installedAccess = KEY_QUERY_VALUE; +#else + // [CHOSEN, not recovered] x64 (issue #7): the 32-bit installer's registry view. + const REGSAM installedAccess = KEY_QUERY_VALUE | KEY_WOW64_32KEY; +#endif + const bool bf2142Installed = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Electronic Arts\\EA Games\\Battlefield 2142\\InstallDir", - 0, KEY_QUERY_VALUE, &installedKey) == ERROR_SUCCESS) { + 0, installedAccess, &installedKey) == ERROR_SUCCESS; +#else + // [CHOSEN, not recovered] The install-key probe uses the same local file. + const bool bf2142Installed = posixRegistry::keyExists(RegKeyLocalMachine, + "SOFTWARE\\Electronic Arts\\EA Games\\Battlefield 2142\\InstallDir"); +#endif + if (bf2142Installed) { if (m_field1e4 || !invalidSpottedPosition(m_field1e8)) game->sendSpottedMessage(local, m_field1e4, Vec2{m_field1e8.x, m_field1e8.z}, type); diff --git a/Code/BF2/Menu/BF2HudManagerSpottedTarget.cpp b/Code/BF2/Menu/BF2HudManagerSpottedTarget.cpp index d42218aeb..6f9da3263 100644 --- a/Code/BF2/Menu/BF2HudManagerSpottedTarget.cpp +++ b/Code/BF2/Menu/BF2HudManagerSpottedTarget.cpp @@ -1,6 +1,9 @@ // [INFERRED] split in the attested BF2HudManager.cpp family. Complete PE755870 // and every local helper read. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "Ref2System.h" #include "../Core/ClassManager.h" @@ -54,11 +57,15 @@ class SpottedPcoPredicator : public SpottedRayPredicator { && world::getRootParent(object) == object; } }; +#if defined(_M_IX86) static_assert(sizeof(SpottedRayPredicator)==16 && sizeof(SpottedPcoPredicator)==16, "native client spotted-query predicate storage"); +#endif float multiplyAdd(float value, float factor, float translation) { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld value @@ -67,15 +74,28 @@ float multiplyAdd(float value, float factor, float translation) fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + return static_cast(static_cast(value) * factor + translation); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 retained multiply/add. + result = bf2x87::multiplyAdd(value, factor, translation); + return result; +#endif } // PE755A60/755B1E retain all differences through sqrt; helper464660 instead // stores the X difference first. Both sums are Z^2 + X^2 + Y^2. float targetDistance(const Vec3& from, const Vec3& to, float scale, bool storeX) { +#if defined(_WIN32) const float fromX=from.x, fromY=from.y, fromZ=from.z; const float toX=to.x, toY=to.y, toZ=to.z; float x, result; +#if defined(_M_IX86) if (storeX) { __asm { fld toX @@ -115,7 +135,35 @@ float targetDistance(const Vec3& from, const Vec3& to, float scale, bool storeX) fstp result } } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Sum order Z^2 + X^2 + Y^2; only the storeX arm rounds the X difference to float first. + const double dz = static_cast(toZ) - fromZ; + double dx = static_cast(toX) - fromX; + if (storeX) { + x = static_cast(dx); + dx = x; + } + const double dy = static_cast(toY) - fromY; + result = static_cast(std::sqrt(dz * dz + dx * dx + dy * dy) * scale); +#endif return result; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float fromX=from.x, fromY=from.y, fromZ=from.z; + const float toX=to.x, toY=to.y, toZ=to.z; + float x, result; + if (storeX) { + // [CHOSEN, not recovered] Preserve x87 explicit X difference float store. + x = bf2x87::store(bf2x87::sub(bf2x87::wide(toX), bf2x87::wide(fromX))); + // [CHOSEN, not recovered] Preserve x87 Z/X/Y squared sum with rounded X. + result = bf2x87::distanceWithX(bf2x87::wide(x), fromY, fromZ, toY, toZ, scale); + } else { + // [CHOSEN, not recovered] Preserve x87 Z/X/Y squared sum without rounded X. + result = bf2x87::distance(fromX, fromY, fromZ, toX, toY, toZ, scale); + } + return result; +#endif } // PE755D11..755DCA biases from the captured shared zero, not the camera. @@ -123,10 +171,12 @@ float targetDistance(const Vec3& from, const Vec3& to, float scale, bool storeX) // differences are stored floats, X's difference is retained until its product. void pullHitTowardOrigin(const Vec3& hit, const Vec3& origin, Vec3& output) { +#if defined(_WIN32) const float hx=hit.x, hy=hit.y, hz=hit.z; const float ox=origin.x, oy=origin.y, oz=origin.z; const float bias=0.2f; float dy, dz, magnitude, scale, offsetX; +#if defined(_M_IX86) float* result=&output.x; __asm { fld hz @@ -169,6 +219,35 @@ void pullHitTowardOrigin(const Vec3& hit, const Vec3& origin, Vec3& output) fstp dword ptr [edx+8] pullDone: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Z and Y differences are stored as floats; X stays unrounded until its product. Only an + // ordered root above the bias writes the output (x, y, z = +0/+4/+8). + const double diffZ = static_cast(hz) - oz; + dz = static_cast(diffZ); + const double diffY = static_cast(hy) - oy; + dy = static_cast(diffY); + const double diffX = static_cast(hx) - ox; + const double root = std::sqrt(diffZ * diffZ + diffY * diffY + diffX * diffX); + magnitude = static_cast(root); + if (root > bias) { + scale = static_cast(bias / static_cast(magnitude)); + offsetX = static_cast(diffX * scale); + output.x = static_cast(static_cast(hx) - offsetX); + output.y = static_cast(hy - static_cast(dy) * scale); + output.z = static_cast(hz - static_cast(dz) * scale); + } +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float hx=hit.x, hy=hit.y, hz=hit.z; + const float ox=origin.x, oy=origin.y, oz=origin.z; + const float bias=0.2f; + float dy, dz, magnitude, scale, offsetX; + float* result=&output.x; + // [CHOSEN, not recovered] Preserve x87 ordered bias test and staged float stores. + bf2x87::pullPoint(hx, hy, hz, ox, oy, oz, result); +#endif } } diff --git a/Code/BF2/Menu/BF2HudManagerUpdate.cpp b/Code/BF2/Menu/BF2HudManagerUpdate.cpp index ad3c83e64..c258936df 100644 --- a/Code/BF2/Menu/BF2HudManagerUpdate.cpp +++ b/Code/BF2/Menu/BF2HudManagerUpdate.cpp @@ -1,5 +1,8 @@ // Per-frame HUD and pending-request updates. [INFERRED] Source split. #include "BF2HudManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "HudVoip.h" #include "Ref2System.h" @@ -30,6 +33,9 @@ #include "../Scene/Object/ObjectPredicator.h" #include "../Core/System.h" #include "../Core/SettingsRepostitory.h" +#if !defined(_M_IX86) +#include +#endif namespace dice { namespace hfe { class IMenuLogic; @@ -42,6 +48,8 @@ namespace { // rounding. Inclusive expiry uses ordered <=0; icon expiry uses ordered <0. bool subtractTimer(float& timer, float delta, bool inclusive) { +#if defined(_WIN32) +#if defined(_M_IX86) bool expired; __asm { mov ecx, timer @@ -62,10 +70,26 @@ bool subtractTimer(float& timer, float delta, bool inclusive) expiry_done: } return expired; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // setnp: inclusive expiry is an ordered <= 0, strict expiry an ordered < 0. + const double remaining = static_cast(timer) - delta; + timer = static_cast(remaining); + return inclusive ? remaining <= 0.0 : remaining < 0.0; +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + bool expired; + // [CHOSEN, not recovered] Preserve x87 ordered retained timer expiry after store. + expired = bf2x87::subtractTimer(timer, delta, inclusive); + return expired; +#endif } bool addDemoTimer(float& timer, float delta) { +#if defined(_WIN32) const float threshold = 10.0f; +#if defined(_M_IX86) bool due; __asm { mov ecx, timer @@ -78,6 +102,21 @@ bool addDemoTimer(float& timer, float delta) setz due } return due; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // C0 clear means an ordered sum at or above the threshold. + const double elapsed = static_cast(delta) + timer; + timer = static_cast(elapsed); + return elapsed >= threshold; +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float threshold = 10.0f; + bool due; + // [CHOSEN, not recovered] Preserve x87 ordered retained timer threshold after store. + due = bf2x87::addDemoTimer(timer, delta); + return due; +#endif } std::string requestInUseMessage(int type) { @@ -250,6 +289,7 @@ void BF2HudManager::updateDemoHelp(float delta) void BF2HudManager::updateMapPosition(world::IPlayer* player, Vec3 direction) { +#if defined(_WIN32) if (!player || !player->getCamera() || !hudMap) return; world::ICameraObject* camera = player->getCamera(); if (player->getIsCommander() && (hudMap->m_overheadZoomActive @@ -271,6 +311,7 @@ void BF2HudManager::updateMapPosition(world::IPlayer* player, Vec3 direction) float heading; if (player->getIsAlive()) { const float x = direction.x, z = direction.z; +#if defined(_M_IX86) __asm { fld x fld z @@ -287,8 +328,16 @@ void BF2HudManager::updateMapPosition(world::IPlayer* player, Vec3 direction) fmul scaleZ fstp position.y } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates); the CRT atan2 + // replaces fpatan (st1 = x over st0 = z) and agrees after the float store. + heading = static_cast(std::atan2(static_cast(x), static_cast(z))); + position.x = static_cast((static_cast(worldX) * half + cameraX) * scaleX); + position.y = static_cast((static_cast(worldZ) * half + cameraZ) * scaleZ); +#endif } else { heading = 0.0f; +#if defined(_M_IX86) __asm { fld worldX fmul half @@ -299,8 +348,48 @@ void BF2HudManager::updateMapPosition(world::IPlayer* player, Vec3 direction) fmul scaleZ fstp position.y } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + position.x = static_cast(static_cast(worldX) * half * scaleX); + position.y = static_cast(static_cast(worldZ) * half * scaleZ); +#endif } hudMap->setPlayerPosition(position, heading); +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + if (!player || !player->getCamera() || !hudMap) return; + world::ICameraObject* camera = player->getCamera(); + if (player->getIsCommander() && (hudMap->m_overheadZoomActive + || (isCommanderShown() && m_field104->getMapZoom() == 1))) + camera = getCameraObject(player->getTeam()); + if (!camera) return; + const Mat4& transform = camera->getTransformation(0.0f); + const float cameraX = transform.m[12], cameraZ = transform.m[14]; + float worldZ, worldX; + { + const std::string keyZ("GLSWorldSizeZ"), keyX("GLSWorldSizeX"); + const int zeroZ = 0, zeroX = 0; + worldZ = static_cast(settings->intGet(keyZ, zeroZ)); + worldX = static_cast(settings->intGet(keyX, zeroX)); + } + const float scaleZ = -1.0f / worldZ, scaleX = 1.0f / worldX; + const float half = 0.5f; + Vec2 position; + float heading; + if (player->getIsAlive()) { + const float x = direction.x, z = direction.z; + // [CHOSEN, not recovered] Preserve x87 atan2 operand order and retained map products. + heading = bf2x87::heading(x, z); + position.x = bf2x87::mapCoordinate(worldX, cameraX, scaleX, true); + position.y = bf2x87::mapCoordinate(worldZ, cameraZ, scaleZ, true); + } else { + heading = 0.0f; + // [CHOSEN, not recovered] Preserve x87 retained map products without camera offset. + position.x = bf2x87::mapCoordinate(worldX, 0.0f, scaleX, false); + position.y = bf2x87::mapCoordinate(worldZ, 0.0f, scaleZ, false); + } + hudMap->setPlayerPosition(position, heading); +#endif } bool BF2HudManager::isVehicleDropPositionBlocked(const Vec3& position) diff --git a/Code/BF2/Menu/BetweenRoundsLogic.cpp b/Code/BF2/Menu/BetweenRoundsLogic.cpp index 1e8192a63..39cf87708 100644 --- a/Code/BF2/Menu/BetweenRoundsLogic.cpp +++ b/Code/BF2/Menu/BetweenRoundsLogic.cpp @@ -1,7 +1,12 @@ // Handles input and presentation for the between-rounds menu. #include "../Core/BuildConfig.h" #if !DEDICATED +#if defined(_WIN32) #include +#elif defined(__APPLE__) +#include "../Platform/macOS/CocoaHost.h" // [CHOSEN, not recovered] cursor and key characters +#include "../Platform/macOS/MacKeyMap.h" +#endif #include "BetweenRoundsLogic.h" #include "IMenuTeamManager.h" #include "ISwiffHost.h" @@ -28,6 +33,25 @@ namespace io { extern IBase* inputDeviceManager; } // Core/Globals.cpp; PE 0x // Translates a DirectInput scan code using the keyboard layout cached on first use. // Returns the number of characters written, or zero when keyboard-state retrieval fails. +#if defined(__APPLE__) +// [CHOSEN, not recovered] macOS: the key code for the scan code, translated with the current +// layout and the Shift/Caps Lock state, as ToAsciiEx translates with GetKeyboardState. Writes one +// character and returns 1, or returns 0 when the key produces none or one outside the 8-bit range +// the ANSI call answers in. +int menuScanCodeToChar(unsigned int scanCode, unsigned short* character) +{ + macos::CocoaHost& host = macos::CocoaHost::instance(); + const unsigned short keyCode = + macos::macKeyCodeFromDik(static_cast(scanCode), host.isISOKeyboard()); + if (keyCode == 0xFFFF) + return 0; + const std::u16string text = host.keyCharacter(keyCode, host.modifierFlags()); + if (text.size() != 1 || text[0] > 0xFF) + return 0; + character[0] = static_cast(text[0]); + return 1; +} +#else int menuScanCodeToChar(unsigned int scanCode, unsigned short* character) { static const HKL layout = GetKeyboardLayout(0); @@ -37,6 +61,7 @@ int menuScanCodeToChar(unsigned int scanCode, unsigned short* character) return ToAsciiEx(MapVirtualKeyExA(scanCode, MAPVK_VSC_TO_VK, layout), scanCode, keyState, character, 0, layout); } +#endif // The string is constructed between the console pointer and the mouse state, which is // where the member sits; the four tail stores follow it. @@ -123,8 +148,13 @@ bool BetweenRoundsLogic::init() setConsole(bf2Engine->bf2Console); // BF2Engine +0x14 io::IInputDevice* mouse = static_cast(io::inputDeviceManager)->getInputDevice(io::IDFMouse); mouse->deActivate(); // +0x20, unguarded in the binary +#if defined(__APPLE__) + macos::CocoaHost::instance().showCursor(true); // [CHOSEN] ShowCursor(TRUE) + macos::CocoaHost::instance().setCursor(m_host->getCursor(0)); // +0x6C, SetCursor +#else ShowCursor(TRUE); SetCursor(static_cast(m_host->getCursor(0))); // +0x6C +#endif io::g_falconMouseMode = 1; // ds:0x978FC4 return true; } @@ -146,8 +176,13 @@ void BetweenRoundsLogic::deactivate() } m_swiffActive = false; m_frameActive = false; +#if defined(__APPLE__) + macos::CocoaHost::instance().setCursor(0); // [CHOSEN] SetCursor(0) + macos::CocoaHost::instance().showCursor(false); // ShowCursor(FALSE) +#else SetCursor(0); ShowCursor(FALSE); +#endif } ui::ISwiffPlayer* BetweenRoundsLogic::getSwiffPlayer() const { return m_player; } @@ -170,9 +205,15 @@ bool BetweenRoundsLogic::beginFrame() { const bool pending = m_player->getSwiffHost()->getFlag7B8(); // +0x5C then +0xCC if (m_player->getSwiffHost()->getFlagEA8() || pending) // +0x5C then +0x2A8 +#if defined(__APPLE__) + macos::CocoaHost::instance().setCursor(m_host->getCursor(1)); // +0x6C, the busy cursor + else + macos::CocoaHost::instance().setCursor(m_host->getCursor(m_host->getBusy()));// +0x2B8 then +0x6C +#else SetCursor(static_cast(m_host->getCursor(1))); // +0x6C, the busy cursor else SetCursor(static_cast(m_host->getCursor(m_host->getBusy())));// +0x2B8 then +0x6C +#endif if (!m_render->beginFrame()) // +0xCC return false; m_frameActive = true; diff --git a/Code/BF2/Menu/Bf2ActionListAction.cpp b/Code/BF2/Menu/Bf2ActionListAction.cpp index 1727f8ab9..e79b417bd 100644 --- a/Code/BF2/Menu/Bf2ActionListAction.cpp +++ b/Code/BF2/Menu/Bf2ActionListAction.cpp @@ -37,6 +37,8 @@ bool Bf2ActionListAction::addAction(System* system, Action* action) if (actions->size() > 0) position = actions->last(); return actions->insert(system, position, action); } +#if defined(_M_IX86) static_assert(sizeof(Bf2ActionListAction) == 24, "client Bf2ActionListAction"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2BarNode.cpp b/Code/BF2/Menu/Bf2BarNode.cpp index 193ed5f6e..faaceed59 100644 --- a/Code/BF2/Menu/Bf2BarNode.cpp +++ b/Code/BF2/Menu/Bf2BarNode.cpp @@ -203,7 +203,7 @@ void Bf2BarNode::paintSelf(System* system, const NodeState* state, break; } - const int barTexture = m_texture; + const TextureHandle barTexture = m_texture; m_texture = m_fillTexture; // swapped for the background paint, restored below if (m_fillTexture != 0) { Bf2PictureNode::paintSelf(system, state, &background, &background, context); @@ -223,8 +223,10 @@ void Bf2BarNode::paintSelf(System* system, const NodeState* state, drawContextTexture(context, system, m_texture, &quad); } +#if defined(_M_IX86) static_assert(sizeof(Bf2BarNode) == 144, "native Bf2BarNode storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2BarNode metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2BarNode.h b/Code/BF2/Menu/Bf2BarNode.h index 1f5f568c0..c4fa78493 100644 --- a/Code/BF2/Menu/Bf2BarNode.h +++ b/Code/BF2/Menu/Bf2BarNode.h @@ -26,7 +26,7 @@ class Bf2BarNode : public Bf2PictureNode { bool setSnapDirectionForHud(bool towardsEnd); protected: // Member names [INFERRED] from the update/paint bodies. - int m_fillTexture; // +60, loaded from the second name pair + TextureHandle m_fillTexture; // +60, loaded from the second name pair int m_fillTop, m_fillBottom; // +64/+68, inset applied to the fill rect int m_fillLeft, m_fillRight; // +6C/+70 int m_snap; // +74, quantiser for the fill length @@ -39,7 +39,9 @@ class Bf2BarNode : public Bf2PictureNode { float* m_value; // +88, defaults to a shared zero float int m_direction; // +8C, 0 up, 1 down, 2 left, 3 right }; +#if defined(_M_IX86) static_assert(sizeof(Bf2BarNode) == 144, "native Bf2BarNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2BlendFuncEffect.cpp b/Code/BF2/Menu/Bf2BlendFuncEffect.cpp index 69d0da773..7c9b7b2f4 100644 --- a/Code/BF2/Menu/Bf2BlendFuncEffect.cpp +++ b/Code/BF2/Menu/Bf2BlendFuncEffect.cpp @@ -27,8 +27,10 @@ void Bf2BlendFuncEffect::setSource(int source) { m_source = source; } void Bf2BlendFuncEffect::setDestination(int destination) { m_destination = destination; } +#if defined(_M_IX86) static_assert(sizeof(Bf2BlendFuncEffect) == 12, "native Bf2BlendFuncEffect storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2BlendFuncEffect metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2BlendFuncEffect.h b/Code/BF2/Menu/Bf2BlendFuncEffect.h index 7757c320c..2ae49049e 100644 --- a/Code/BF2/Menu/Bf2BlendFuncEffect.h +++ b/Code/BF2/Menu/Bf2BlendFuncEffect.h @@ -16,7 +16,9 @@ class Bf2BlendFuncEffect : public BlendFuncEffect { virtual void setDestination(int destination); static TypeDescriptor* getClassType(); // 7CB740, metadata937B8C }; +#if defined(_M_IX86) static_assert(sizeof(Bf2BlendFuncEffect) == 12, "native Bf2BlendFuncEffect storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2ButtonNode.cpp b/Code/BF2/Menu/Bf2ButtonNode.cpp index 0ab608f57..6a4b7f1b9 100644 --- a/Code/BF2/Menu/Bf2ButtonNode.cpp +++ b/Code/BF2/Menu/Bf2ButtonNode.cpp @@ -77,7 +77,7 @@ bool Bf2ButtonNode::releasePointerForHud() // 7D0650, +EC. A zero texture is refused before the index is even looked at, // index 0 and anything above 3 are refused, and the index-1 arm answers with the // index's low byte instead of a literal 1 (the same value, reproduced as read). -bool Bf2ButtonNode::setTextureForHud(int index, int texture) +bool Bf2ButtonNode::setTextureForHud(int index, TextureHandle texture) { if (!texture) return false; if (index == 1) { diff --git a/Code/BF2/Menu/Bf2ButtonNode.h b/Code/BF2/Menu/Bf2ButtonNode.h index 57e9f2013..80c2f25d4 100644 --- a/Code/BF2/Menu/Bf2ButtonNode.h +++ b/Code/BF2/Menu/Bf2ButtonNode.h @@ -33,7 +33,7 @@ class Bf2ButtonNode : public Bf2PictureNode { // Index 0 and any index above 3 are refused, and so is a zero texture; the // shipped body also returns the index's low byte rather than a literal 1 on // the index-1 arm, which happens to be the same value. - bool setTextureForHud(int index, int texture); // 7D0650, +EC + bool setTextureForHud(int index, TextureHandle texture); // 7D0650, +EC bool setActionForHud(Action* action, int index); // 7D0B50, +F0 bool setAltActionForHud(Action* action, int index); // 7D0B70, +F4 Action* getActionForHud(int index); // 7D0B90, +F8 @@ -49,10 +49,10 @@ class Bf2ButtonNode : public Bf2PictureNode { friend struct Bf2ButtonNodeFixture; // The three texture handles the console row selects by index, and the one // the paint path actually uses. Index 1 also writes PictureNode::m_texture. - int m_normalTexture; // +60, index 1 - int m_pressedTexture; // +64, index 2 [INFERRED] role - int m_highlightTexture; // +68, index 3 [INFERRED] role - int m_currentTexture; // +6C + TextureHandle m_normalTexture; // +60, index 1 + TextureHandle m_pressedTexture; // +64, index 2 [INFERRED] role + TextureHandle m_highlightTexture; // +68, index 3 [INFERRED] role + TextureHandle m_currentTexture; // +6C // Four action slots and four alternate action slots. The console rows accept // an index below 4, which is exactly these four entries. Action* m_actions[4]; // +70..7C @@ -67,7 +67,9 @@ class Bf2ButtonNode : public Bf2PictureNode { std::uint32_t m_fieldb4, m_fieldb8; // [UNRESOLVED], never written bool m_fieldbc; // +BC [UNRESOLVED] role, ctor false }; +#if defined(_M_IX86) static_assert(sizeof(Bf2ButtonNode) == 192, "native Bf2ButtonNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2CallFunctionAction.cpp b/Code/BF2/Menu/Bf2CallFunctionAction.cpp index 627aeb69c..4be157f1d 100644 --- a/Code/BF2/Menu/Bf2CallFunctionAction.cpp +++ b/Code/BF2/Menu/Bf2CallFunctionAction.cpp @@ -16,6 +16,8 @@ bool Bf2CallFunctionAction::setFunction(Function* function) m_function = function; return true; } +#if defined(_M_IX86) static_assert(sizeof(Bf2CallFunctionAction) == 8, "client Bf2CallFunctionAction"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2ColorEffect.cpp b/Code/BF2/Menu/Bf2ColorEffect.cpp index 0fb630eff..07601e004 100644 --- a/Code/BF2/Menu/Bf2ColorEffect.cpp +++ b/Code/BF2/Menu/Bf2ColorEffect.cpp @@ -61,7 +61,7 @@ Color sampleBoundColor(const Color& base, const float* alpha, const float* red, } } -bool Bf2ColorEffect::drawCharacter(System* system, int character, int font, +bool Bf2ColorEffect::drawCharacter(System* system, int character, FontHandle font, int elementIndex, Quad* quad, RenderContext* context) { const Color color = sampleBoundColor(*getColor(), m_alphaBinding, m_redBinding, @@ -69,7 +69,7 @@ bool Bf2ColorEffect::drawCharacter(System* system, int character, int font, colorQuad(quad, &color); return Effect::drawCharacter(system, character, font, elementIndex, quad, context); } -bool Bf2ColorEffect::drawTexture(System* system, int texture, Quad* quad, +bool Bf2ColorEffect::drawTexture(System* system, TextureHandle texture, Quad* quad, RenderContext* context) { const Color color = sampleBoundColor(*getColor(), m_alphaBinding, m_redBinding, @@ -78,8 +78,10 @@ bool Bf2ColorEffect::drawTexture(System* system, int texture, Quad* quad, return Effect::drawTexture(system, texture, quad, context); } +#if defined(_M_IX86) static_assert(sizeof(Bf2ColorEffect) == 48, "native Bf2ColorEffect storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2ColorEffect metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2ColorEffect.h b/Code/BF2/Menu/Bf2ColorEffect.h index 28c8de8ab..5c85bde89 100644 --- a/Code/BF2/Menu/Bf2ColorEffect.h +++ b/Code/BF2/Menu/Bf2ColorEffect.h @@ -13,9 +13,9 @@ class Bf2ColorEffect : public ColorEffect { TypeDescriptor* getType() override; unsigned int getObjectSize() override; bool setColor(float r, float g, float b, float a) override; - bool drawCharacter(System*, int character, int font, int elementIndex, + bool drawCharacter(System*, int character, FontHandle font, int elementIndex, Quad*, RenderContext*) override; - bool drawTexture(System*, int texture, Quad*, RenderContext*) override; + bool drawTexture(System*, TextureHandle texture, Quad*, RenderContext*) override; // Names [INFERRED]; the three slots this class adds above Effect's21. virtual bool setOwnerNode(void* owner); virtual bool setAlphaBinding(const float* alpha); @@ -32,7 +32,9 @@ class Bf2ColorEffect : public ColorEffect { int m_field28; // +28, cleared by the constructor, else unread float m_disabledBinding; // +2C, -1 so every default binding is inactive }; +#if defined(_M_IX86) static_assert(sizeof(Bf2ColorEffect) == 48, "native Bf2ColorEffect storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2CompassNode.cpp b/Code/BF2/Menu/Bf2CompassNode.cpp index 8c8e77870..4526a254a 100644 --- a/Code/BF2/Menu/Bf2CompassNode.cpp +++ b/Code/BF2/Menu/Bf2CompassNode.cpp @@ -65,7 +65,7 @@ bool Bf2CompassNode::setSnapOffsetForHud(int a, int b, int c, int d) m_snapOffset[3] = d; return true; } -bool Bf2CompassNode::setSnapTextureForHud(bool primary, int texture) +bool Bf2CompassNode::setSnapTextureForHud(bool primary, TextureHandle texture) { if (primary) m_snapTexturePrimary = texture; else m_snapTextureSecondary = texture; @@ -88,7 +88,7 @@ void Bf2CompassNode::paintSelf(System* system, const NodeState* state, strip.height = m_textureRect.height; strip.z = 0.0f; int shift = 0; - int texture = m_texture; + TextureHandle texture = m_texture; if (m_direction == 0) { const float travel = (m_textureRect.height - static_cast(m_fillBottom)) @@ -155,8 +155,10 @@ void Bf2CompassNode::paintSelf(System* system, const NodeState* state, } } +#if defined(_M_IX86) static_assert(sizeof(Bf2CompassNode) == 196, "native Bf2CompassNode storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2CompassNode metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2CompassNode.h b/Code/BF2/Menu/Bf2CompassNode.h index 6f129cff7..5c6331426 100644 --- a/Code/BF2/Menu/Bf2CompassNode.h +++ b/Code/BF2/Menu/Bf2CompassNode.h @@ -21,20 +21,22 @@ class Bf2CompassNode : public Bf2BarNode { bool setTextureSizeForHud(float width, float height); bool setOffsetForHud(int offset); // 7D00D0, +10C bool setSnapOffsetForHud(int a, int b, int c, int d); - bool setSnapTextureForHud(bool primary, int texture); + bool setSnapTextureForHud(bool primary, TextureHandle texture); protected: // Member names [INFERRED] from paintSelf. The first five words are a Rect // whose origin setTextureSize always clears. Rect m_textureRect; // +90..+A0 - int m_snapTexturePrimary; // +A4, drawn when the leading limit is hit - int m_snapTextureSecondary; // +A8, drawn when the trailing limit is hit + TextureHandle m_snapTexturePrimary; // +A4, drawn when the leading limit is hit + TextureHandle m_snapTextureSecondary; // +A8, drawn when the trailing limit is hit int m_offset; // +AC, added to the scrolled position int m_snapOffset[4]; // +B0..+BC; [1]/[0] vertical, [2]/[3] horizontal bool m_snapEnabled; // +C0 bool m_wrapEnabled; // +C1 unsigned char m_paddingc2[2]; // untouched }; +#if defined(_M_IX86) static_assert(sizeof(Bf2CompassNode) == 196, "native Bf2CompassNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2CullNode.cpp b/Code/BF2/Menu/Bf2CullNode.cpp index eb290b5eb..7949b7632 100644 --- a/Code/BF2/Menu/Bf2CullNode.cpp +++ b/Code/BF2/Menu/Bf2CullNode.cpp @@ -1,6 +1,9 @@ // Menu culling node. [INFERRED] Source placement. // Inherited unimplemented Node operations retain their diagnostic stops. #include "Bf2CullNode.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "../External/BFMeme/Data.h" #include "../External/BFMeme/TypeDescriptor.h" @@ -44,6 +47,8 @@ char* cloneCullNodeName(const char* name) // Names are [INFERRED]. Typed float storage avoids any cross-build field offset. void decreaseCullFade(float& current, float delta, float duration) { +#if defined(_WIN32) +#if defined(_M_IX86) const float zero = 0.0f; __asm { mov ecx, current @@ -58,9 +63,24 @@ void decreaseCullFade(float& current, float delta, float duration) mov dword ptr [ecx], 0 decreased: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // The rounded value is stored first; only an ordered negative result then becomes +0. + const double unrounded = static_cast(current) - static_cast(delta) / duration; + current = static_cast(unrounded); + if (unrounded < 0.0) current = 0.0f; +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float zero = 0.0f; + // [CHOSEN, not recovered] Preserve x87 retained decrease comparison after store. + bf2x87::fadeInPlace(current, delta, duration, false); +#endif } void increaseCullFade(float& current, float delta, float duration) { +#if defined(_WIN32) +#if defined(_M_IX86) const float one = 1.0f; __asm { mov ecx, current @@ -75,6 +95,19 @@ void increaseCullFade(float& current, float delta, float duration) mov dword ptr [ecx], 3F800000h increased: } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // The rounded value is stored first; only an ordered result above one is then clamped. + const double unrounded = static_cast(delta) / duration + current; + current = static_cast(unrounded); + if (unrounded > 1.0) current = 1.0f; +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float one = 1.0f; + // [CHOSEN, not recovered] Preserve x87 retained increase comparison after store. + bf2x87::fadeInPlace(current, delta, duration, true); +#endif } } @@ -173,7 +206,9 @@ bool Bf2CullNode::update(System* system, const NodeState* state, m_previousVisibility = visible; return true; } +#if defined(_M_IX86) static_assert(sizeof(Bf2CullNodeTypeDescriptor) == 16, "client Bf2CullNode metadata"); static_assert(sizeof(Bf2CullNode) == 32, "client Bf2CullNode storage"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2EditNode.cpp b/Code/BF2/Menu/Bf2EditNode.cpp index 932f03042..c984930a8 100644 --- a/Code/BF2/Menu/Bf2EditNode.cpp +++ b/Code/BF2/Menu/Bf2EditNode.cpp @@ -62,7 +62,7 @@ bool Bf2EditNode::setEditDataForHud(BfEditData* data) // 7CDFC0, +C8 bool Bf2EditNode::setStringForHud(Data* string) // 7CE250, +CC { m_string = string; return true; } // Two members from one call, and the flag is the outline bit at +3D. -bool Bf2EditNode::setFontForHud(int font, bool outline) +bool Bf2EditNode::setFontForHud(FontHandle font, bool outline) { m_font = font; m_outline = outline; return true; } bool Bf2EditNode::setMaxLengthForHud(int characters) // 7C21D0, +D4 { m_maxCharacters = characters; return true; } diff --git a/Code/BF2/Menu/Bf2EditNode.h b/Code/BF2/Menu/Bf2EditNode.h index 12a8b1ba3..e05a091d6 100644 --- a/Code/BF2/Menu/Bf2EditNode.h +++ b/Code/BF2/Menu/Bf2EditNode.h @@ -25,7 +25,7 @@ class Bf2EditNode : public BfEditNode { bool setStringForHud(Data* string); // 7CE250, +CC -> +0C // The second argument is the outline flag (+3D), not anything about the // font - the console row that drives it is called `setEditNodeFont`. - bool setFontForHud(int font, bool outline); // 7D0F20, +D0 -> +14/+3D + bool setFontForHud(FontHandle font, bool outline); // 7D0F20, +D0 -> +14/+3D bool setMaxLengthForHud(int characters); // 7C21D0, +D4 -> +18 bool setColorForHud(float r, float g, float b, float a); // 7D0F40, +D8 -> +40..4C @@ -33,7 +33,9 @@ class Bf2EditNode : public BfEditNode { friend struct Bf2EditNodeFixture; char* m_name; // +50, owned clone }; +#if defined(_M_IX86) static_assert(sizeof(Bf2EditNode) == 84, "native Bf2EditNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2EffectNode.cpp b/Code/BF2/Menu/Bf2EffectNode.cpp index 166e5624d..41952ce25 100644 --- a/Code/BF2/Menu/Bf2EffectNode.cpp +++ b/Code/BF2/Menu/Bf2EffectNode.cpp @@ -55,8 +55,10 @@ bool Bf2EffectNode::setName(const char* name) return true; } +#if defined(_M_IX86) static_assert(sizeof(Bf2EffectNode) == 16, "native Bf2EffectNode storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2EffectNode metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2EffectNode.h b/Code/BF2/Menu/Bf2EffectNode.h index 4c483b251..ceb04b96a 100644 --- a/Code/BF2/Menu/Bf2EffectNode.h +++ b/Code/BF2/Menu/Bf2EffectNode.h @@ -21,7 +21,9 @@ class Bf2EffectNode : public EffectNode { protected: char* m_name; // +0C, owned clone }; +#if defined(_M_IX86) static_assert(sizeof(Bf2EffectNode) == 16, "native Bf2EffectNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2FixedSliderNode.h b/Code/BF2/Menu/Bf2FixedSliderNode.h index df24eb7eb..d6ab9eecc 100644 --- a/Code/BF2/Menu/Bf2FixedSliderNode.h +++ b/Code/BF2/Menu/Bf2FixedSliderNode.h @@ -31,7 +31,9 @@ class Bf2FixedSliderNode : public BfFixedSliderNode friend struct Bf2FixedSliderNodeFixture; char* m_name; // +58, owned clone, never freed }; +#if defined(_M_IX86) static_assert(sizeof(Bf2FixedSliderNode) == 92, "retail and native Bf2FixedSliderNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2HoverNode.cpp b/Code/BF2/Menu/Bf2HoverNode.cpp index 789a85e45..2f21006e5 100644 --- a/Code/BF2/Menu/Bf2HoverNode.cpp +++ b/Code/BF2/Menu/Bf2HoverNode.cpp @@ -1,4 +1,7 @@ // HUD hover-node layout and updates. [INFERRED] Source placement. +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "Bf2HoverNode.h" #if !DEDICATED #include "../Core/StringUtil.h" @@ -149,19 +152,44 @@ bool Bf2HoverNode::updateSelf(System*, const NodeState*, const Rect*, float delt const double deltaZ = m_anchorZ < 0.0f // see the note above ? static_cast(positionZ) - m_anchorZ : static_cast(positionZ) + m_anchorZ; +#if defined(__APPLE__) + m_yPos = bf2x87::toIntTruncate(static_cast(yScale) * deltaZ) + m_middleY; // +2C +#else m_yPos = static_cast(static_cast(yScale) * deltaZ) + m_middleY; // +2C +#endif const float xScale = static_cast(m_boundsWidthInt) / m_width; const float positionX = vehicle->getAbsolutePosition().x; +#if defined(__APPLE__) + m_xPos = m_middleX + - bf2x87::toIntTruncate((static_cast(positionX) - m_anchorX) * xScale); // +28 +#else m_xPos = m_middleX - static_cast((static_cast(positionX) - m_anchorX) * xScale); // +28 +#endif } // Runs whether or not the indicator is shown. +#if defined(__APPLE__) + const int left = bf2x87::toIntTruncate(m_boundsX); // __ftol2 +#else const int left = static_cast(m_boundsX); // __ftol2 +#endif +#if defined(__APPLE__) + bool outside = m_xPos < left || m_xPos > bf2x87::toIntTruncate(m_boundsWidth) + left; +#else bool outside = m_xPos < left || m_xPos > static_cast(m_boundsWidth) + left; +#endif if (!outside) { +#if defined(__APPLE__) + const int top = bf2x87::toIntTruncate(m_boundsY); // __ftol2 +#else const int top = static_cast(m_boundsY); // __ftol2 +#endif +#if defined(__APPLE__) + outside = m_yPos < top || m_yPos > bf2x87::toIntTruncate(m_boundsHeight) + top; +#else outside = m_yPos < top || m_yPos > static_cast(m_boundsHeight) + top; +#endif } if (outside) { m_show = false; @@ -180,7 +208,9 @@ namespace { TypeDescriptor* const registeredBf2HoverNodeType = Bf2HoverNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(Bf2HoverNodeTypeDescriptor) == 16, "client BF2 hover metadata"); static_assert(sizeof(Bf2HoverNode) == 84, "native Bf2HoverNode storage"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2HoverNode.h b/Code/BF2/Menu/Bf2HoverNode.h index 0d25e4b5b..833e79e81 100644 --- a/Code/BF2/Menu/Bf2HoverNode.h +++ b/Code/BF2/Menu/Bf2HoverNode.h @@ -59,7 +59,9 @@ class Bf2HoverNode : public Node { float m_boundsWidth, m_boundsHeight; // +44/+48, arguments 3 and 4 of +D4 float m_boundsX, m_boundsY; // +4C/+50, arguments 1 and 2 of +D4 }; +#if defined(_M_IX86) static_assert(sizeof(Bf2HoverNode) == 84, "native Bf2HoverNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2HudBuilder.cpp b/Code/BF2/Menu/Bf2HudBuilder.cpp index de8efacc4..a5c495dc3 100644 --- a/Code/BF2/Menu/Bf2HudBuilder.cpp +++ b/Code/BF2/Menu/Bf2HudBuilder.cpp @@ -436,7 +436,7 @@ bool Bf2HudBuilder::setCompassNodeSnapOffset(int a, int b, int c, int d) bool Bf2HudBuilder::setCompassNodeSnapTexture(bool primary, std::string texture) { if (m_system) { - const int handle = m_system->loadTexture(texture.c_str(), true); + const meme::TextureHandle handle = m_system->loadTexture(texture.c_str(), true); if (handle) { meme::Bf2CompassNode* compass = builderCast(m_field014); if (compass) return compass->setSnapTextureForHud(primary, handle); @@ -494,7 +494,7 @@ bool Bf2HudBuilder::setNodeShowVariable(std::string name) meme::Bf2CullNode* cull = createVisibilityNode(m_field050, value); cull->setChild(0, node->getChild(1)); node->setChild(1, cull); - return m_system->registerObject(cull, nullptr) != false; + return m_system->registerObject(cull, nullptr) != nullptr; } } Debug(DebugTypeError, builderSource, 1875, "") @@ -629,7 +629,7 @@ bool Bf2HudBuilder::setNodeLogicShowVariable(std::string operation, std::string if (operation != "AND") { cull->setChild(0, node->getChild(1)); node->setChild(1, cull); - return m_system->registerObject(cull, nullptr) != false; + return m_system->registerObject(cull, nullptr) != nullptr; } } failed: @@ -818,7 +818,7 @@ bool Bf2HudBuilder::setNodeColor(float r, float g, float b, float a) } carrier->setChild(0, node->getChild(1)); node->setChild(1, carrier); - return m_system->registerObject(carrier, nullptr) != false; + return m_system->registerObject(carrier, nullptr) != nullptr; } } } @@ -843,7 +843,7 @@ bool Bf2HudBuilder::setNodeInTime(float seconds) cull->setChild(0, node->getChild(1)); node->setChild(1, cull); cull->setInTimeForHud(seconds); - return m_system->registerObject(cull, nullptr) != false; + return m_system->registerObject(cull, nullptr) != nullptr; } } } @@ -867,7 +867,7 @@ bool Bf2HudBuilder::setNodeOutTime(float seconds) cull->setChild(0, node->getChild(1)); node->setChild(1, cull); cull->setOutTimeForHud(seconds); - return m_system->registerObject(cull, nullptr) != false; + return m_system->registerObject(cull, nullptr) != nullptr; } } } @@ -1656,9 +1656,9 @@ bool Bf2HudBuilder::createButtonNode(std::string parent, std::string name, bool Bf2HudBuilder::setButtonNodeTexture(int index, std::string texture) { if (m_system) { - m_buttonTexture = static_cast(m_system->loadTexture(texture.c_str(), true)); + m_buttonTexture = static_cast(m_system->loadTexture(texture.c_str(), true)); meme::Bf2ButtonNode* node = builderCast(m_field014); - if (node) return node->setTextureForHud(index, static_cast(m_buttonTexture)); + if (node) return node->setTextureForHud(index, static_cast(m_buttonTexture)); } Debug(DebugTypeError, builderSource, 1434, "") << "Failed setting Picture on node: " << m_field018; @@ -2069,7 +2069,7 @@ bool Bf2HudBuilder::setEditNodeColor(float r, float g, float b, float a) bool Bf2HudBuilder::setEditNodeFont(std::string font, bool outline) { if (m_system && font != "") { - const int handle = m_system->loadFont(font.c_str()); + const meme::FontHandle handle = m_system->loadFont(font.c_str()); meme::Bf2EditNode* node = builderCast(m_field014); if (node) return node->setFontForHud(handle, outline); } @@ -2239,6 +2239,8 @@ bool Bf2HudBuilder::setSliderNodeChild(std::string name) return false; } +#if defined(_M_IX86) static_assert(sizeof(Bf2HudBuilder) == 0x8c, "native x86 HUD builder; retail0x9C uses larger strings"); +#endif } } } #endif diff --git a/Code/BF2/Menu/Bf2HudBuilder.h b/Code/BF2/Menu/Bf2HudBuilder.h index e647bcfaf..081a689ff 100644 --- a/Code/BF2/Menu/Bf2HudBuilder.h +++ b/Code/BF2/Menu/Bf2HudBuilder.h @@ -166,8 +166,10 @@ class Bf2HudBuilder // unresolved payload word: `setButtonNodeTexture` (798D20) parks the handle // it just loaded there on its way to the node, and nothing ever reads it // back. The remaining three are still [UNRESOLVED]. - std::uint32_t m_buttonTexture; // retail+8C - std::uint32_t m_field090, m_field094, m_field098; + // The two handle words are pointer-sized; uintptr_t is uint32_t on x86. + std::uintptr_t m_buttonTexture; // retail+8C + std::uintptr_t m_field090; // retail+90, last loaded text-node font + std::uint32_t m_field094, m_field098; }; } } } #endif diff --git a/Code/BF2/Menu/Bf2MenuMapNode.cpp b/Code/BF2/Menu/Bf2MenuMapNode.cpp index 5d8ce4d0a..219bbdb93 100644 --- a/Code/BF2/Menu/Bf2MenuMapNode.cpp +++ b/Code/BF2/Menu/Bf2MenuMapNode.cpp @@ -215,7 +215,7 @@ void dispatchMapSetSelectionWord(Bf2MenuMapNode* node, int index, unsigned int w // +110, 7730B0 (61 B). (D1). [INFERRED] name. A five-way switch on // eventId - 46: the constructor's four support textures at +9A8..+9B4 (see the constructor's // mini_Ammo / mini_Repair / mini_Revive / mini_Medic loads). 46 and every other id fall to medic. -int Bf2MenuMapNode::getSupportRequestTexture(int eventId) +TextureHandle Bf2MenuMapNode::getSupportRequestTexture(int eventId) { switch (eventId) { case 47: return m_field9a8[0]; // +9A8 mini_Ammo @@ -599,22 +599,8 @@ void rasterizeCombatArea(hfe::geom::IMemeTexture* texture, } } if (!measureOnly) { - // hand over A buffer the callee may free. plotAndFill releases `first` itself, so it - // must not be `canvas`'s own storage - that would be freed twice. The span layout is the - // shipped sixteen-byte one; see IMemeTexture.h for why a std::vector cannot be used here. - hfe::geom::IMemeTexture::CanvasPointSpan span = { 0, 0, 0, 0 }; - if (!canvas.empty()) { - const std::size_t bytes = - canvas.size() * sizeof(hfe::geom::IMemeTexture::CanvasPoint); - span.first = static_cast(std::malloc(bytes)); // engineFree's heap (native) - if (span.first) { - std::memcpy(span.first, &canvas[0], bytes); - span.last = reinterpret_cast( - reinterpret_cast(span.first) + bytes); - span.end = span.last; - } - } - texture->plotAndFill(span, value); + // By value: plotAndFill receives its own copy of the points and frees it. + texture->plotAndFill(canvas, value); } } } @@ -750,6 +736,12 @@ Bf2MenuMapNode::Bf2MenuMapNode(System* system, const char* name, int, int, int, m_field8a0 = m_system->loadTexture("Ingame/GeneralIcons/empty.tga", true); // +8A0 m_field694 = 0.5f; // +694 m_expandedMap = false; m_field690 = false; // +68E/+690 (78181C/781822) + // [CHOSEN, not recovered]: memory-safety deviation. The shipped constructor (0x7801AB..0x780206) + // never writes +0x68D, but update (0x77C330) reads it at 0x77C48F / 0x77C7E9 before its first + // write at 0x77D383. Retail runs on whatever the heap holds there (Memory.dll does not zero user + // blocks; fresh Windows pages are zero); on macOS it came back non-zero and the first spawn + // screen kept the map at its mini size with no DONE/SUICIDE row. Zero it. + m_field68d = false; // +68D m_commanderMode = false; m_squadMode = false; m_field776 = true; // +776 m_selectedRequestSquad = -1; // +B88 @@ -787,7 +779,13 @@ Bf2MenuMapNode::Bf2MenuMapNode(System* system, const char* name, int, int, int, m_suppliesTexture = m_system->loadTexture("Ingame/Minimap/Icons/icon_supplies.tga", true); // +B24 m_field07f = m_field07c = m_field07d = m_field07e = false; // +7F,+7C,+7D,+7E m_field678 = 8; // +678 +#if defined(_MSC_VER) m_field71c[2] = 0; // +724 +#else + // [CHOSEN, not recovered] The shipped dword 0 at +724 is m_wobbleTime; index 2 of the + // two-word array is out of bounds (UBSan), so non-MSVC builds name the field. + m_wobbleTime = 0.0f; // +724 +#endif m_field76c = 0.0f; m_field770 = 0; // +76C/+770 m_field75c = 0; m_delayedMapAngle = 0.0f; m_field764[0] = m_field764[1] = 0; // +75C..768 m_field758 = 1.0f; // +758 @@ -1767,14 +1765,13 @@ void Bf2MenuMapNode::updatePaintCenter() hfe::geom::IMemeTexture* Bf2MenuMapNode::combatAreaTexture() const { - // System::loadTexture's historical interface spells every renderer handle - // `int`; this particular handle is proven to be an IMemeTexture object. - return reinterpret_cast( - static_cast(static_cast(m_field93c[2]))); + // Texture handles are pointer-sized; this particular handle is proven to be an + // IMemeTexture object. + return reinterpret_cast(m_field93c[2]); } // 774A60. [INFERRED] void return; the caller discards the incidental draw result. -void Bf2MenuMapNode::drawMapTexture(int texture, const Rect* adjusted, +void Bf2MenuMapNode::drawMapTexture(TextureHandle texture, const Rect* adjusted, const Rect* bounds, System* system, RenderContext* context) { @@ -1791,7 +1788,7 @@ void Bf2MenuMapNode::drawMapTexture(int texture, const Rect* adjusted, // The adjusted Rect argument is genuinely unused: retail constructs // the tint Quad with `bounds` as both its geometry and clipping rectangle. -void Bf2MenuMapNode::drawMapTint(int texture, const Color* color, const Rect*, +void Bf2MenuMapNode::drawMapTint(TextureHandle texture, const Color* color, const Rect*, const Rect* bounds, System* system, RenderContext* context) { @@ -1907,7 +1904,7 @@ bool Bf2MenuMapNode::updateCombatAreaTexture(bool measureOnly) } // 774EB0. [INFERRED] void return. -void Bf2MenuMapNode::drawCombatAreaTexture(int texture, const Rect* adjusted, +void Bf2MenuMapNode::drawCombatAreaTexture(TextureHandle texture, const Rect* adjusted, const Rect* bounds, System* system, RenderContext* context) { @@ -1978,7 +1975,7 @@ void Bf2MenuMapNode::clearMapIcons() // 7746E0, virtual +124. [INFERRED] void return/name. void Bf2MenuMapNode::paintMapIcon(hfe::Vec2 position, float rotation, - hfe::Vec2 size, unsigned int texture, System* system, + hfe::Vec2 size, std::uintptr_t texture, System* system, const Rect* adjusted, const Rect* bounds, const Color* color, RenderContext* context) { @@ -2162,7 +2159,7 @@ void Bf2MenuMapNode::loadSupplyLineTextures(System* system) const std::string name = hfe::formatString( "Levels/%s/HUD/Minimap/supplyline_%02d.tga", // ds:92FF5C hfe::game->getCurrentMapName().c_str(), stage); // client +0xEC - const int texture = system->loadTexture(name.c_str(), false); // +0x8C + const TextureHandle texture = system->loadTexture(name.c_str(), false); // +0x8C if (!texture) return; m_supplyLineTextures[stage] = texture; // +BA8 onwards @@ -2294,7 +2291,7 @@ void Bf2MenuMapNode::drawSupplyLine(const Rect* adjusted, const Rect* bounds, Sy // 775110. [INFERRED] void return. The shadow is a full-bounds black quad whose opacity follows the // map layer alpha. Retail does not rotate it or attach the secondary texture. -void Bf2MenuMapNode::drawMapShadow(int texture, const Rect* bounds, +void Bf2MenuMapNode::drawMapShadow(TextureHandle texture, const Rect* bounds, System* system, RenderContext* context) { const Color color = {0.0f, 0.0f, 0.0f, m_field708[2] * 0.6f}; @@ -2304,7 +2301,7 @@ void Bf2MenuMapNode::drawMapShadow(int texture, const Rect* bounds, // 775170. [INFERRED] void return. Like the shadow pass this uses the same Rect for geometry and clip, // but the frame color is a constant opaque black. -void Bf2MenuMapNode::drawMapFrame(int texture, const Rect* bounds, +void Bf2MenuMapNode::drawMapFrame(TextureHandle texture, const Rect* bounds, System* system, RenderContext* context) { const Color color = {0.0f, 0.0f, 0.0f, 1.0f}; @@ -2484,7 +2481,7 @@ int __stdcall classifyObjectForMap(hfe::world::IObject* object, } // 7779B0 / 7779E0, virtual +E4/+E8. -int Bf2MenuMapNode::timedMarkerTexture(unsigned int id) +TextureHandle Bf2MenuMapNode::timedMarkerTexture(unsigned int id) { for (std::vector::const_iterator it = m_timedMarkers.begin(); it != m_timedMarkers.end(); ++it) @@ -2618,9 +2615,9 @@ bool Bf2MenuMapNode::populateNetworkIcon(int id, MapIconRecord* icon, } // 772ED0, virtual +FC. -int Bf2MenuMapNode::getSmallSquadIcon(int squadId) +TextureHandle Bf2MenuMapNode::getSmallSquadIcon(int squadId) { - int& texture = m_field7fc[squadId]; + TextureHandle& texture = m_field7fc[squadId]; if (!texture) { const std::string path = hfe::formatString( "Ingame/Player/Icons/Minimap/mini_Squad_%d_small.tga", squadId); @@ -2631,9 +2628,9 @@ int Bf2MenuMapNode::getSmallSquadIcon(int squadId) // 772FB0, virtual +140. Retail deliberately indexes size + 2*squad, so the // cache rows overlap; preserve that quirk. -int Bf2MenuMapNode::getLeaderMapIcon(int squadId, int sizeIndex) +TextureHandle Bf2MenuMapNode::getLeaderMapIcon(int squadId, int sizeIndex) { - int& texture = m_field84c[sizeIndex + 2 * squadId]; + TextureHandle& texture = m_field84c[sizeIndex + 2 * squadId]; if (!texture) { std::string size("Medium"); if (sizeIndex == 0) size = "Small"; @@ -2664,7 +2661,7 @@ void Bf2MenuMapNode::projectObject(hfe::world::IObject* object, } -unsigned int Bf2MenuMapNode::remapMapIconType(unsigned int type, int texture, +unsigned int Bf2MenuMapNode::remapMapIconType(unsigned int type, TextureHandle texture, bool timed, float* rotation) { if (type == 37 || type == 36 || type == 25 || type == 24) return type; @@ -2931,7 +2928,7 @@ void Bf2MenuMapNode::colorMapIcon(hfe::world::IPlayer* player, void Bf2MenuMapNode::updateSatelliteTarget(hfe::world::IObject* object, - int networkId, int texture) + int networkId, TextureHandle texture) { if (!object) return; const float objectX = object->getAbsoluteTransformation().m[12]; @@ -2960,7 +2957,7 @@ void Bf2MenuMapNode::updateSatelliteTarget(hfe::world::IObject* object, // Source position and radius deliberately live across iterations: // malformed/null UAV entries reuse the last values observed by retail. void Bf2MenuMapNode::updateUavTarget(hfe::world::IObject* object, - int networkId, int texture) + int networkId, TextureHandle texture) { if (!object) return; @@ -3586,7 +3583,7 @@ void Bf2MenuMapNode::completeLineRecord(float scale, MapLineRecord* line) } // +100, 772F40. Loaded on first use through the System, then cached. No bound on `squad`. -int Bf2MenuMapNode::getSquadNumberIcon(int squad) +TextureHandle Bf2MenuMapNode::getSquadNumberIcon(int squad) { if (m_squadNumberIcons[squad] == 0) m_squadNumberIcons[squad] = m_system->loadTexture( @@ -4342,7 +4339,7 @@ void Bf2MenuMapNode::collectIconFamily77E500() continue; } - const int texture = holder->getNrDestroyedObjects() > 0 + const TextureHandle texture = holder->getNrDestroyedObjects() > 0 ? strategicComponent->getDestroyedIconPtr() : strategicComponent->getIntactIconPtr(); if (texture <= 0) @@ -4494,7 +4491,7 @@ void Bf2MenuMapNode::collectIconFamily77FC30() hfe::Vec3 position; int radius = 0; float rotation = 0.0f; - int texture = 0; + TextureHandle texture = 0; bool emit = false; bool emitCentre = false; @@ -4735,7 +4732,7 @@ void Bf2MenuMapNode::drawControlPointLabels(System* system, const NodeState* sta Bf2TextNode textNode(nullptr); Bf2TransformNode transform(nullptr, 0, 0, 0, 0); - Bf2CenterAlignedStyle style(nullptr, static_cast(m_fieldc64)); + Bf2CenterAlignedStyle style(nullptr, static_cast(m_fieldc64)); void* stringAllocation = ::operator new(sizeof(WstringData)); WstringData* stringData = nullptr; @@ -5317,7 +5314,9 @@ bool Bf2MenuMapNode::onEvent1(System* system, const Rect*, const NodeState*, } return false; } +#if defined(_M_IX86) static_assert(sizeof(Bf2MenuMapNodeTypeDescriptor) == 16, "client BF2 map metadata"); +#endif // Stores the minimap position, requests recentering and returns true. bool Bf2MenuMapNode::setMiniPosForHud(float x, float y) @@ -5353,7 +5352,7 @@ bool Bf2MenuMapNode::setZoomIconsForHud(bool enabled) // row 39, +7F9 // row reports nothing either way, and its console return type is void. void Bf2MenuMapNode::setControlPointFontForHud(std::string font) { - if (m_system) m_fieldc64 = static_cast(m_system->loadFont(font.c_str())); + if (m_system) m_fieldc64 = static_cast(m_system->loadFont(font.c_str())); } // Inlined at 75FC39, row 41: four floats copied straight into +C68. @@ -5542,7 +5541,11 @@ void Bf2MenuMapNode::setPlayerHeading(float heading) { m_field775 = false; m_field777 = false; +#if defined(_MSC_VER) m_field71c[2] = 0; // +724 +#else + m_wobbleTime = 0.0f; // +724, see the constructor +#endif // the plain answer: turn whichever way the number moved m_field758 = (heading - m_field75c) > 0.0f ? 1.0f : -1.0f; diff --git a/Code/BF2/Menu/Bf2MenuMapNode.h b/Code/BF2/Menu/Bf2MenuMapNode.h index b5585df0e..e776b9b5b 100644 --- a/Code/BF2/Menu/Bf2MenuMapNode.h +++ b/Code/BF2/Menu/Bf2MenuMapNode.h @@ -31,7 +31,7 @@ struct MapIconRecord Color color; // +08 hfe::Vec2 size; // +18 float rotation; // +20; retail default construction leaves this untouched - int texture; // +24 + TextureHandle texture; // +24 bool clampToVisibleMap; // +28; 776AF0 applies the 775800 viewport inset clamp when true std::uint8_t padding[3]; // +29; retail copies no padding bytes @@ -46,7 +46,9 @@ struct MapIconRecord rotation(other.rotation), texture(other.texture), clampToVisibleMap(other.clampToVisibleMap) {} }; +#if defined(_M_IX86) static_assert(sizeof(MapIconRecord) == 0x2C, "retail map icon record"); +#endif // Order-line record ending in its drawable icon. [INFERRED] Field names. struct MapLineRecord { @@ -62,10 +64,12 @@ struct MapLineRecord hfe::Vec2 b; // +1C end, map space MapIconRecord line; // +24 the connecting line's icon (map_Line) }; +#if defined(_M_IX86) static_assert(sizeof(MapLineRecord) == 0x50, "retail order-line record"); +#endif struct MapTimedMarker { - int texture; // +00 + TextureHandle texture; // +00 int networkId; // +04 hfe::Vec2 size; // +08 int kind; // +10 @@ -80,11 +84,14 @@ struct MapTimedMarker MapTimedMarker() : size{0.0f, 0.0f}, position{0.0f, 0.0f} {} }; +#if defined(_M_IX86) static_assert(sizeof(MapTimedMarker) == 0x34, "retail timed map marker"); +#endif struct MapField09ec { std::uint32_t words[2]; }; // 8-byte list value;7771D0 allocates the16-byte node struct MapVehicleDrop { bool active; - int texture, id; + TextureHandle texture; + int id; hfe::Vec3 position; // 77ACE0 writes bool,texture,id,x,y,z;24 bytes }; @@ -249,9 +256,9 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { virtual int getSquadRequestType(int squad); // +F4 77A8D0 // +110, 7730B0 (61 B): the icon a support request (ECHud 46..50) draws with - 47 ammo, 48 // repair, 49/50 revive, 46 and anything else medic (the four constructor textures at +9A8). - virtual int getSupportRequestTexture(int eventId); + virtual TextureHandle getSupportRequestTexture(int eventId); // Returns the cached squad-number icon, loading it on demand. Requires a valid squad index. [INFERRED] Name. - virtual int getSquadNumberIcon(int squad); + virtual TextureHandle getSquadNumberIcon(int squad); // +114, 782220 (602 B): one order's line and marker. Always answers true. virtual bool addOrderIcons(hfe::SquadOrder* order, int squad, int leaderNetworkId, int kind, const Rect* bounds); @@ -261,16 +268,16 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { bool active); // Updates map presentation and expires timed markers over delta seconds. virtual void update(float delta); // +E0 77C330, 4,379 B - virtual int timedMarkerTexture(unsigned int id); // +E4 7779B0 + virtual TextureHandle timedMarkerTexture(unsigned int id); // +E4 7779B0 virtual hfe::Vec2 timedMarkerSize(unsigned int id); // +E8 7779E0 virtual bool populateNetworkIcon(int id, MapIconRecord* icon, bool asPlayer); // +EC 775720 virtual void colorMapIcon(hfe::world::IPlayer* player, MapIconRecord* icon, int type, bool compareTeam); // +F0 7788B0 - virtual int getSmallSquadIcon(int squadId); // +FC 772ED0 + virtual TextureHandle getSmallSquadIcon(int squadId); // +FC 772ED0 virtual void paintMapIcon(hfe::Vec2 position, float rotation, - hfe::Vec2 size, unsigned int texture, System* system, + hfe::Vec2 size, std::uintptr_t texture, System* system, const Rect* adjusted, const Rect* bounds, const Color* color, RenderContext* context); virtual void paintMapIcons(System* system, const Rect* adjusted, @@ -294,7 +301,7 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { bool notCapturable, bool cachePresent, bool localCaptureActive); // +13C 7755A0 - virtual int getLeaderMapIcon(int squadId, int sizeIndex); + virtual TextureHandle getLeaderMapIcon(int squadId, int sizeIndex); // 772810, the arm +D8 takes when the map is not expanded. [INFERRED] name. void setCommanderZoom(int level, bool remember); // Retail indexes `[this + 0x69C + type*4]` for a vehicle type in [0, 40) - @@ -324,9 +331,9 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { // addresses, call order and complete argument shapes are recovered. void updateFilterActiveFlags(); void updatePaintCenter(); - void drawMapTexture(int texture, const Rect* adjusted, const Rect* bounds, + void drawMapTexture(TextureHandle texture, const Rect* adjusted, const Rect* bounds, System* system, RenderContext* context); - void drawMapTint(int texture, const Color* color, const Rect* adjusted, + void drawMapTint(TextureHandle texture, const Color* color, const Rect* adjusted, const Rect* bounds, System* system, RenderContext* context); // Updates and draws supply lines. [INFERRED] Helper names. void updateSupplyLine(System* system); @@ -335,7 +342,7 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { void loadSupplyLineTextures(System* system); void advanceSupplyLineGroup(); bool updateCombatAreaTexture(bool measureOnly); - void drawCombatAreaTexture(int texture, const Rect* adjusted, + void drawCombatAreaTexture(TextureHandle texture, const Rect* adjusted, const Rect* bounds, System* system, RenderContext* context); void drawMapBorder(const Rect* adjusted, const Rect* bounds, @@ -359,7 +366,7 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { MapIconRecord* icon); void projectObject(hfe::world::IObject* object, MapIconRecord* icon, bool heading); - unsigned int remapMapIconType(unsigned int type, int texture, + unsigned int remapMapIconType(unsigned int type, TextureHandle texture, bool timed, float* rotation); void addTimedMarker(int networkId, hfe::Vec2 position, MapIconRecord icon, float duration, @@ -369,9 +376,9 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { MapIconRecord* icon, bool* rotate, bool* secondary, int* type); void updateSatelliteTarget(hfe::world::IObject* object, - int networkId, int texture); + int networkId, TextureHandle texture); void updateUavTarget(hfe::world::IObject* object, - int networkId, int texture); + int networkId, TextureHandle texture); // [INFERRED] name; complete PE body is map::erase(key). void removeUavObject(unsigned int networkId); void collectIconFamily783F90(); @@ -399,8 +406,8 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { void collectSuppliesIcon(); // 77FA00 [FRONTIER] void collectVehicleDropIcon(const MapVehicleDrop*); // 77FB20 [FRONTIER] void drawSatellite(System*, const Rect*, RenderContext*); - void drawMapShadow(int texture, const Rect*, System*, RenderContext*); - void drawMapFrame(int texture, const Rect*, System*, RenderContext*); + void drawMapShadow(TextureHandle texture, const Rect*, System*, RenderContext*); + void drawMapFrame(TextureHandle texture, const Rect*, System*, RenderContext*); void drawControlPointLabels(System*, const NodeState*, const Rect*, const Rect*, RenderContext*); hfe::geom::IMemeTexture* combatAreaTexture() const; @@ -444,7 +451,7 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { float m_field67c, m_field680; // +67C/+680, constructor0.55/0.1 bool m_field684; // +684, constructor false std::uint8_t m_field685[7]; // +685..68B untouched - bool m_field68c, m_field68d, m_expandedMap; // +68C..68E,7728F0 exposes68E; 68D untouched + bool m_field68c, m_field68d, m_expandedMap; // +68C..68E,7728F0 exposes68E; 68D: retail's ctor leaves it, ours zeroes it (memory safety) std::uint8_t m_field68f; // untouched bool m_field690; // +690, constructor false bool m_commanderMode, m_squadMode; // +691/+692, constructor false @@ -505,22 +512,22 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { bool m_overheadZoomActive; // +7F8, constructor false bool m_field7f9; // +7F9, true; `setZoomIcons` std::uint8_t m_field7fa[2]; // untouched - int m_field7fc[10]; // +7FC..823, small-squad texture cache + TextureHandle m_field7fc[10]; // +7FC..823, small-squad texture cache // Cached squad-number texture handles. - int m_squadNumberIcons[10]; // +824..84B, constructor 0 - int m_field84c[20]; // +84C..89B, sized leader texture cache - int m_field89c; // texture mini_Squad_request - int m_field8a0; // texture GeneralIcons/empty - int m_defaultMinimapTexture; // +8A4, texture GeneralIcons/full - int m_field8a8[23]; // +8A8..903, textures (constructor order) - int m_controlPointTextures[3]; // +904..90C - int m_controlPointBaseTextures[3]; // +910..918 - int m_teamFlagTextures[3]; // +91C..924 - int m_field928[4]; // +928..937, textures - int m_minimapTexture; // +938 - int m_field93c[26]; // +93C..9A3, textures and zeros + TextureHandle m_squadNumberIcons[10]; // +824..84B, constructor 0 + TextureHandle m_field84c[20]; // +84C..89B, sized leader texture cache + TextureHandle m_field89c; // texture mini_Squad_request + TextureHandle m_field8a0; // texture GeneralIcons/empty + TextureHandle m_defaultMinimapTexture; // +8A4, texture GeneralIcons/full + TextureHandle m_field8a8[23]; // +8A8..903, textures (constructor order) + TextureHandle m_controlPointTextures[3]; // +904..90C + TextureHandle m_controlPointBaseTextures[3]; // +910..918 + TextureHandle m_teamFlagTextures[3]; // +91C..924 + TextureHandle m_field928[4]; // +928..937, textures + TextureHandle m_minimapTexture; // +938 + TextureHandle m_field93c[26]; // +93C..9A3, textures and zeros; [25] spawn group int m_spawnGroup; // +9A4, signed, direct kit writes - int m_field9a8[13]; // +9A8..9DB, textures and zeros + TextureHandle m_field9a8[13]; // +9A8..9DB, textures and zeros bool m_field9dc; // +9DC, constructor false std::uint8_t m_field9dd[3]; std::uint32_t m_field9e0[3]; // +9E0..9EB; +9E8 constructor0 @@ -549,8 +556,8 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { std::uint8_t m_fielda7e[2]; float m_fielda80, m_fielda84, m_fielda88; // +A80/+A84/+A88 satellite scan window float m_fielda8c; // +A8C timed satellite fade - int m_fielda90; // texture map_SatelliteScanLine - int m_fielda94; // texture mini_SatelliteObject + TextureHandle m_fielda90; // texture map_SatelliteScanLine + TextureHandle m_fielda94; // texture mini_SatelliteObject float m_satelliteScanX, m_satelliteScanY; // +A98/+A9C int m_satelliteLineSize; // +AA0 =150 float m_satelliteReloadRemaining; // +AA4 @@ -559,7 +566,8 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { float m_fieldabc, m_fieldac0, m_fieldac4; // 0, 4.0, 0 float m_uavReloadRemaining; // +AC8 bool m_uavActive; // +ACC - int m_uavRadius, m_uavTexture, m_uavIcon; // +AD0..AD8: 100, map_UAV, icon_UAV + int m_uavRadius; // +AD0, 100 + TextureHandle m_uavTexture, m_uavIcon; // +AD4/+AD8: map_UAV, icon_UAV float m_uavReloadFraction; // +ADC =1.0 ("%sUAVTimeUntilReloaded") bool m_uavReloading; // +AE0 float m_uavActiveTime; // +AE4 @@ -567,11 +575,11 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { float m_fieldaec, m_fieldaf0; // 0.5, 0 hfe::Vec3 m_airstrikePosition; // +AF4..AFC bool m_airstrikeActive; // +B00 - int m_airstrikeTexture, m_artilleryIcon; // +B04/+B08 + TextureHandle m_airstrikeTexture, m_artilleryIcon; // +B04/+B08 float m_fieldb0c, m_fieldb10; // +B0C/+B10 hfe::Vec3 m_suppliesPosition; // +B14..B1C bool m_suppliesActive; // +B20 - int m_suppliesTexture; // +B24 icon_supplies + TextureHandle m_suppliesTexture; // +B24 icon_supplies float m_fieldb28; // +B28 =0, supplies duration std::list m_vehicleDrops; // +B2C,77ACE0 std::map m_uavObjects; // +B38, 77A030 @@ -591,13 +599,14 @@ class Bf2MenuMapNode : public Bf2TransformNode, public hfe::IEventListener { std::uint32_t m_fieldb98; // untouched by the constructor; see above std::uint32_t m_fieldb9c, m_fieldba0; // constructor0 // Supply-line texture handles, loaded by stage and initially zero. - int m_supplyLineTextures[20]; // +BA4..BF3, constructor0 + TextureHandle m_supplyLineTextures[20]; // +BA4..BF3, constructor0 std::list m_controlPointIds; // +BF4,77C0A0 std::list m_fieldc00; // +C00,77E720 compares control-point template ID std::uint32_t m_fieldc0c[18]; // +C0C..C53, constructor0 std::map m_controlPoints; // +C54,77E720/779B70 // m_fieldc64 stores the font handle loaded through this map's System. - std::uint32_t m_fieldc60, m_fieldc64; // +C60 untouched; +C64 0 + std::uint32_t m_fieldc60; // +C60 untouched + std::uintptr_t m_fieldc64; // +C64 0; uint32_t on x86 Color m_fieldc68; // (1,1,1,1); `setCPFontColor` float m_fieldc78, m_fieldc7c; // constructor0 }; diff --git a/Code/BF2/Menu/Bf2MiniMenuMapNode.cpp b/Code/BF2/Menu/Bf2MiniMenuMapNode.cpp index 889d9b114..12f4b597d 100644 --- a/Code/BF2/Menu/Bf2MiniMenuMapNode.cpp +++ b/Code/BF2/Menu/Bf2MiniMenuMapNode.cpp @@ -78,7 +78,7 @@ Bf2MiniMenuMapNode::Bf2MiniMenuMapNode(System* system, const char* name, // The four members below are the ones that travel through the obfuscation // pair; the pair is an identity, so each simply receives the handle. The // shipped order is 3, 4, 6, 5 - not sequential. - const int actionTexture = m_system->loadTexture(microMapActionTexture, true); + const TextureHandle actionTexture = m_system->loadTexture(microMapActionTexture, true); m_field8a8[3] = actionTexture; m_field8a8[4] = actionTexture; m_field8a8[6] = actionTexture; @@ -90,7 +90,7 @@ Bf2MiniMenuMapNode::Bf2MiniMenuMapNode(System* system, const char* name, m_field8a8[10] = m_defaultMinimapTexture; m_field8a8[11] = m_defaultMinimapTexture; - const int secondAction = m_system->loadTexture(microMapActionTexture, true); + const TextureHandle secondAction = m_system->loadTexture(microMapActionTexture, true); m_field8a8[13] = secondAction; m_field8a8[14] = secondAction; m_field8a8[16] = secondAction; @@ -194,7 +194,7 @@ void Bf2MiniMenuMapNode::setViewCenter(hfe::Vec2) { resetViewBiasForHud(); } // // The mini-map replaces the base timed-marker lookup quartet. The shared // 4553E0 body returns zero for +E4/+FC; +E8 and +EC were read at 7CF690/7CF660. -int Bf2MiniMenuMapNode::timedMarkerTexture(unsigned int) { return 0; } +TextureHandle Bf2MiniMenuMapNode::timedMarkerTexture(unsigned int) { return 0; } hfe::Vec2 Bf2MiniMenuMapNode::timedMarkerSize(unsigned int) { return hfe::Vec2{4.0f, 4.0f}; @@ -206,9 +206,9 @@ bool Bf2MiniMenuMapNode::populateNetworkIcon(int, MapIconRecord* icon, bool) icon->size = hfe::Vec2{4.0f, 4.0f}; return true; } -int Bf2MiniMenuMapNode::getSmallSquadIcon(int) { return 0; } +TextureHandle Bf2MiniMenuMapNode::getSmallSquadIcon(int) { return 0; } // +110, the same shared 4553E0 (`xor eax, eax; retn 4`) - vtable 938858 slot +110. -int Bf2MiniMenuMapNode::getSupportRequestTexture(int) { return 0; } +TextureHandle Bf2MiniMenuMapNode::getSupportRequestTexture(int) { return 0; } // Adds order markers to the compact map. bool Bf2MiniMenuMapNode::addOrderIcons(hfe::SquadOrder* order, int, int leaderNetworkId, @@ -312,7 +312,7 @@ void Bf2MiniMenuMapNode::populateControlPointMapIcon( // are floored first, positions are not half-pixel snapped, and no mask texture // is installed. void Bf2MiniMenuMapNode::paintMapIcon(hfe::Vec2 position, float rotation, - hfe::Vec2 size, unsigned int texture, System* system, + hfe::Vec2 size, std::uintptr_t texture, System* system, const Rect* adjusted, const Rect* bounds, const Color* color, RenderContext* context) { diff --git a/Code/BF2/Menu/Bf2MiniMenuMapNode.h b/Code/BF2/Menu/Bf2MiniMenuMapNode.h index 41f5a72ab..c90da7fcd 100644 --- a/Code/BF2/Menu/Bf2MiniMenuMapNode.h +++ b/Code/BF2/Menu/Bf2MiniMenuMapNode.h @@ -39,14 +39,14 @@ class Bf2MiniMenuMapNode : public Bf2MenuMapNode { friend struct Bf2MiniMenuMapNodeFixture; // Updates blink state and timed markers, then records world time. void update(float delta) override; // +E0 7CE340 - int timedMarkerTexture(unsigned int id) override; // +E4 4553E0 + TextureHandle timedMarkerTexture(unsigned int id) override; // +E4 4553E0 hfe::Vec2 timedMarkerSize(unsigned int id) override; // +E8 7CF690 bool populateNetworkIcon(int id, MapIconRecord* icon, bool asPlayer) override; // +EC 7CF660 - int getSmallSquadIcon(int squadId) override; // +FC 4553E0 + TextureHandle getSmallSquadIcon(int squadId) override; // +FC 4553E0 // +110, the third slot this class points at the shared "return 0" 4553E0: the // map's support-request icon getter answers no texture on a mini-map. - int getSupportRequestTexture(int eventId) override; + TextureHandle getSupportRequestTexture(int eventId) override; // Adds commander minimap order icons without squad numbers. Order lines require flag2C; requests always draw their marker. bool addOrderIcons(hfe::SquadOrder* order, int squad, int leaderNetworkId, int kind, const Rect* bounds) override; @@ -60,7 +60,7 @@ class Bf2MiniMenuMapNode : public Bf2MenuMapNode { bool cachePresent, bool localCaptureActive) override; // +13C 7CF5A0 void paintMapIcon(hfe::Vec2 position, float rotation, hfe::Vec2 size, - unsigned int texture, System* system, const Rect* adjusted, + std::uintptr_t texture, System* system, const Rect* adjusted, const Rect* bounds, const Color* color, RenderContext* context) override; void collectLocalPlayerIcon() override; // +12C 7CEDD0, 583 B @@ -79,7 +79,9 @@ class Bf2MiniMenuMapNode : public Bf2MenuMapNode { // World time of the last update. The constructor leaves it unset, so update must precede meaningful paint timing. double m_lastUpdateTime; // retail +C80 }; +#if defined(_M_IX86) static_assert(sizeof(Bf2MiniMenuMapNode) == 3008, "native Bf2MiniMenuMapNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2MoveEffect.cpp b/Code/BF2/Menu/Bf2MoveEffect.cpp index 0bffc1622..a5e4e6797 100644 --- a/Code/BF2/Menu/Bf2MoveEffect.cpp +++ b/Code/BF2/Menu/Bf2MoveEffect.cpp @@ -27,8 +27,10 @@ bool Bf2MoveEffect::setDirection(Data* direction) bool Bf2MoveEffect::setLength(Data* length) { m_length = length; return true; } +#if defined(_M_IX86) static_assert(sizeof(Bf2MoveEffect) == 12, "native Bf2MoveEffect storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2MoveEffect metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2MoveEffect.h b/Code/BF2/Menu/Bf2MoveEffect.h index 4c5f3b26b..43cc8786b 100644 --- a/Code/BF2/Menu/Bf2MoveEffect.h +++ b/Code/BF2/Menu/Bf2MoveEffect.h @@ -18,7 +18,9 @@ class Bf2MoveEffect : public MoveEffect { virtual bool setLength(Data* length); static TypeDescriptor* getClassType(); // 7CB620, metadata937A04 }; +#if defined(_M_IX86) static_assert(sizeof(Bf2MoveEffect) == 12, "native Bf2MoveEffect storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2NewListBoxNode.cpp b/Code/BF2/Menu/Bf2NewListBoxNode.cpp index b3a3a9365..518f361d3 100644 --- a/Code/BF2/Menu/Bf2NewListBoxNode.cpp +++ b/Code/BF2/Menu/Bf2NewListBoxNode.cpp @@ -69,7 +69,7 @@ void Bf2NewListBoxNode::bindDataToSelfForHud() { m_data->m_node = this; } // 7CDD80, +D8. Two shipped quirks: a negative index is accepted and writes // before the array, and the return value is the index's low byte - so index 0 // reports false even though the write happened. -bool Bf2NewListBoxNode::setFontForHud(int font, int index) +bool Bf2NewListBoxNode::setFontForHud(FontHandle font, int index) { if (index < 5) m_fonts[index] = font; return index != 0; diff --git a/Code/BF2/Menu/Bf2NewListBoxNode.h b/Code/BF2/Menu/Bf2NewListBoxNode.h index 67f80c501..25f0db0d9 100644 --- a/Code/BF2/Menu/Bf2NewListBoxNode.h +++ b/Code/BF2/Menu/Bf2NewListBoxNode.h @@ -24,7 +24,7 @@ class Bf2NewListBoxNode : public BfNewListBoxNode { void bindDataToSelfForHud(); // 7CDD70, +D4 // Refuses an index of 5 or more but not a negative one, and answers with // the index's low byte rather than a flag - so index 0 reports false. - bool setFontForHud(int font, int index); // 7CDD80, +D8 + bool setFontForHud(FontHandle font, int index); // 7CDD80, +D8 bool setSelectActionForHud(Action* action); // 7CDDA0, +DC -> +48 bool setFieldE0ForHud(Action* action); // 7CDDB0, +E0 -> +4C bool setFocusActionForHud(Action* action); // 7CDDC0, +E4 -> +50 @@ -70,7 +70,9 @@ class Bf2NewListBoxNode : public BfNewListBoxNode { friend struct Bf2NewListBoxNodeFixture; char* m_name; // retail+12C, owned clone }; +#if defined(_M_IX86) static_assert(sizeof(Bf2NewListBoxNode) == 300, "native Bf2NewListBoxNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2ObjectMarkerNode.cpp b/Code/BF2/Menu/Bf2ObjectMarkerNode.cpp index 30545a7ea..128658051 100644 --- a/Code/BF2/Menu/Bf2ObjectMarkerNode.cpp +++ b/Code/BF2/Menu/Bf2ObjectMarkerNode.cpp @@ -189,7 +189,7 @@ bool Bf2ObjectMarkerNode::addLockTextNodeForHud(Bf2TransformNode* node) // 7CD00 m_lockTextNodes.push_back(node); // retail inlines list::insert(end(), node) return true; } -bool Bf2ObjectMarkerNode::setTextureForHud(int index, int texture) // 7CD1C0, +D8 +bool Bf2ObjectMarkerNode::setTextureForHud(int index, TextureHandle texture) // 7CD1C0, +D8 { // Out-of-range is silently ignored and still answers true; a negative // index is not tested at all, so it writes before the array. @@ -415,7 +415,7 @@ void Bf2ObjectMarkerNode::addMarker(unsigned int objectId, hfe::world::IObject* return; quad.width = m_textureSizes[textureIndex].x; quad.height = m_textureSizes[textureIndex].y; - const int texture = m_textures[textureIndex]; + const TextureHandle texture = m_textures[textureIndex]; quad.texture = texture; if (!texture) return; @@ -598,7 +598,7 @@ void Bf2ObjectMarkerNode::drawMarkers(System* system, const Rect* bounds, Render // `this` is never read. The clip is the caller's `bounds` - paintSelf's own clip is unused. // A texture of 0 draws nothing. void Bf2ObjectMarkerNode::drawMarker(float x, float y, float rotation, float width, float height, - int texture, System* system, const Rect* clip, + TextureHandle texture, System* system, const Rect* clip, RenderContext* context) { if (!texture) @@ -629,7 +629,9 @@ namespace { TypeDescriptor* const registeredBf2ObjectMarkerNodeType = Bf2ObjectMarkerNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(Bf2ObjectMarkerNodeTypeDescriptor) == 16, "client BF2 marker metadata"); static_assert(sizeof(Bf2ObjectMarkerNode) == 444, "native Bf2ObjectMarkerNode storage"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2ObjectMarkerNode.h b/Code/BF2/Menu/Bf2ObjectMarkerNode.h index 258cd2a4c..c7a68c28e 100644 --- a/Code/BF2/Menu/Bf2ObjectMarkerNode.h +++ b/Code/BF2/Menu/Bf2ObjectMarkerNode.h @@ -33,11 +33,13 @@ struct MarkerQuad // {1,1,1,1} as constructed, {0,1,0,1} per marker float width, height; // +18/+1C float rotation; // +20 radians; 0 for every marker - int texture; // +24 handle; 0 means nothing is drawn + TextureHandle texture; // +24 handle; 0 means nothing is drawn std::uint32_t field28; // +28 never written and never read }; +#if defined(_M_IX86) static_assert(sizeof(MarkerTarget) == 8, "retail MarkerTarget list payload"); static_assert(sizeof(MarkerQuad) == 44, "retail MarkerQuad list payload"); +#endif class Bf2ObjectMarkerNode : public Node { public: @@ -61,7 +63,7 @@ class Bf2ObjectMarkerNode : public Node { bool setLockTextOffsetForHud(int x, int y); // 7CD1F0, +CC bool setLockTextForHud(bool enabled, std::string prefix); bool addLockTextNodeForHud(Bf2TransformNode* node); // 7CD000, +D4 - bool setTextureForHud(int index, int texture); // 7CD1C0, +D8 + bool setTextureForHud(int index, TextureHandle texture); // 7CD1C0, +D8 bool setTextureSizeForHud(int index, float width, float height); // 7CD210, +DC bool setLockOnTypeForHud(int type); // 7CDDD0, +E0 bool setWeaponForHud(int weapon); // 7CD1E0, +E4 @@ -75,7 +77,7 @@ class Bf2ObjectMarkerNode : public Node { int m_objects; // PE+08, ctor argument, default5: the marker cap // [INFERRED] Marker range, refreshed from weapon targeting range or player view distance. float m_range; // PE+0C, zeroed - int m_textures[4]; // PE+10, index<4 only; [3] is the range line's + TextureHandle m_textures[4]; // PE+10, index<4 only; [3] is the range line's hfe::Vec2 m_textureSizes[4]; // PE+20, every entry starts (32,32) hfe::Vec2 m_lockTextOffset; // PE+40, starts (-3, 0) std::uint32_t m_field048; // PE+48 [UNRESOLVED], zeroed @@ -121,11 +123,13 @@ class Bf2ObjectMarkerNode : public Node { void updateRangeLine(hfe::Vec3 screen, const Rect* bounds); void updateMarkerLabels(const Rect* bounds); void drawMarkers(System* system, const Rect* bounds, RenderContext* context); - void drawMarker(float x, float y, float rotation, float width, float height, int texture, + void drawMarker(float x, float y, float rotation, float width, float height, TextureHandle texture, System* system, const Rect* clip, RenderContext* context); }; // Retail is 0x1CC; the four containers lose four bytes each on this toolchain. +#if defined(_M_IX86) static_assert(sizeof(Bf2ObjectMarkerNode) == 444, "native Bf2ObjectMarkerNode storage"); +#endif // an eight-byte zeroed .data block whose address is the default value // of every m_names entry. The destructor compares against it before releasing a diff --git a/Code/BF2/Menu/Bf2ObjectSelectionNode.cpp b/Code/BF2/Menu/Bf2ObjectSelectionNode.cpp index 64d42511d..194e366ef 100644 --- a/Code/BF2/Menu/Bf2ObjectSelectionNode.cpp +++ b/Code/BF2/Menu/Bf2ObjectSelectionNode.cpp @@ -145,7 +145,9 @@ TypeDescriptor* const registeredBf2ObjectSelectionNodeType = Bf2ObjectSelectionNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(Bf2ObjectSelectionNodeTypeDescriptor) == 16, "client BF2 selection metadata"); static_assert(sizeof(Bf2ObjectSelectionNode) == 72, "native Bf2ObjectSelectionNode storage"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2ObjectSelectionNode.h b/Code/BF2/Menu/Bf2ObjectSelectionNode.h index 251fcb94d..ec14fa3dc 100644 --- a/Code/BF2/Menu/Bf2ObjectSelectionNode.h +++ b/Code/BF2/Menu/Bf2ObjectSelectionNode.h @@ -33,7 +33,9 @@ class Bf2ObjectSelectionNode : public Bf2TransformNode { float m_pointerHeight; // +40, starts 32 std::uint32_t m_field044; // +44 [UNRESOLVED], zeroed }; +#if defined(_M_IX86) static_assert(sizeof(Bf2ObjectSelectionNode) == 72, "native Bf2ObjectSelectionNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2PictureNode.cpp b/Code/BF2/Menu/Bf2PictureNode.cpp index dd1184cc7..c0d45da71 100644 --- a/Code/BF2/Menu/Bf2PictureNode.cpp +++ b/Code/BF2/Menu/Bf2PictureNode.cpp @@ -96,9 +96,9 @@ bool Bf2PictureNode::setTextureNameForHud(const char* name) m_requestedTextureName = clonePictureName(name); return true; } -bool Bf2PictureNode::setTextureForHud(int texture) +bool Bf2PictureNode::setTextureForHud(TextureHandle texture) { m_texture = texture; return true; } -bool Bf2PictureNode::setSecondaryTextureForHud(int texture) +bool Bf2PictureNode::setSecondaryTextureForHud(TextureHandle texture) { m_secondaryTexture = texture; return true; } bool Bf2PictureNode::setTextureNameBindingForHud(const char** binding) { @@ -134,7 +134,7 @@ bool Bf2PictureNode::setBorderColorForHud(float r, float g, float b, float a) m_borderAlpha = a; return true; } -bool dispatchPictureTexture(Bf2PictureNode* node, int texture) // 7511C0's callee +bool dispatchPictureTexture(Bf2PictureNode* node, TextureHandle texture) // 7511C0's callee { return node->setTextureForHud(texture); } // The texture is (re)loaded only when the requested and previously @@ -245,8 +245,10 @@ void Bf2PictureNode::paintSelf(System* system, const NodeState* state, context->effect->setColor(saved.r, saved.g, saved.b, saved.a); } +#if defined(_M_IX86) static_assert(sizeof(Bf2PictureNode) == 96, "native Bf2PictureNode storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2PictureNode metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2PictureNode.h b/Code/BF2/Menu/Bf2PictureNode.h index 8d3ea9fe5..2a75d71a0 100644 --- a/Code/BF2/Menu/Bf2PictureNode.h +++ b/Code/BF2/Menu/Bf2PictureNode.h @@ -21,8 +21,8 @@ class Bf2PictureNode : public PictureNode { // [CHOSEN, not recovered] Native event-routing accessors. // [RETIRE-WHEN: bf2-picture-native-accessors] Replace them when the corresponding Node virtual methods are typed and validated. bool setTextureNameForHud(const char* name); // 7AC810, +C8 - bool setTextureForHud(int texture); // 7CDFC0, +CC - bool setSecondaryTextureForHud(int texture); + bool setTextureForHud(TextureHandle texture); // 7CDFC0, +CC + bool setSecondaryTextureForHud(TextureHandle texture); bool setTextureNameBindingForHud(const char** binding); // 7AC850, +D4 bool setRotationBindingForHud(const float* binding); // 7ACA30, +D8 bool setAdditionalRotationForHud(float degrees); // 7ACA40, +DC @@ -39,12 +39,14 @@ class Bf2PictureNode : public PictureNode { const char** m_textureNameBinding; // +2C, default &m_textureName char* m_requestedTextureName; // +30, owned or identity sentinel char* m_previousTextureName; // +34, owned or identity sentinel - int m_secondaryTexture; // +38 + TextureHandle m_secondaryTexture; // +38 bool m_borderEnabled; // +3C int m_borderLeft, m_borderRight, m_borderTop, m_borderBottom; // +40..4C; fild in7ACAB0 float m_borderRed, m_borderGreen, m_borderBlue, m_borderAlpha; // +50..5C }; +#if defined(_M_IX86) static_assert(sizeof(Bf2PictureNode)==96, "native Bf2PictureNode storage"); +#endif // 87FB54, the shared empty literal the constructor stores at +28. Bf2BarNode's // indexed setter compares its argument against this address, so both classes @@ -52,7 +54,7 @@ static_assert(sizeof(Bf2PictureNode)==96, "native Bf2PictureNode storage"); extern const char* const emptyHudTextureName; // Sets the picture texture through the shared native accessor. -bool dispatchPictureTexture(Bf2PictureNode*, int texture); +bool dispatchPictureTexture(Bf2PictureNode*, TextureHandle texture); } } #endif #endif diff --git a/Code/BF2/Menu/Bf2SplitNode.cpp b/Code/BF2/Menu/Bf2SplitNode.cpp index d9729558b..fab3b3cd9 100644 --- a/Code/BF2/Menu/Bf2SplitNode.cpp +++ b/Code/BF2/Menu/Bf2SplitNode.cpp @@ -68,7 +68,9 @@ namespace { // original eager initializer sets its guard before the base constructor. TypeDescriptor* const registeredBf2SplitNodeType = Bf2SplitNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(Bf2SplitNodeTypeDescriptor) == 16, "client BF2 split metadata"); static_assert(sizeof(Bf2SplitNode) == 16, "client BF2 named SplitNode"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2Style.cpp b/Code/BF2/Menu/Bf2Style.cpp index 8438bc5c8..072f9fb30 100644 --- a/Code/BF2/Menu/Bf2Style.cpp +++ b/Code/BF2/Menu/Bf2Style.cpp @@ -20,10 +20,12 @@ const int sectionSign = 0xA7; // Every body reads the effect's colour field at +4 directly instead of // calling getColor(); an effect that is not colour-shaped yields whatever sits // at that offset. Keep the raw read rather than substituting the virtual. +// +4 is the first word after the vtable pointer (ColorEffect's colour); the +// same word sits at +8 on x64, so the offset is the vtable pointer's size. Color readEffectColorField(Effect* effect) { return *reinterpret_cast( - reinterpret_cast(effect) + 4); + reinterpret_cast(effect) + sizeof(void*)); } // style unsigned conversion: the four escape digits are widened as // unsigned, so a character below '0' becomes a very large float. The values are @@ -32,7 +34,7 @@ float escapeDigit(int value) { return static_cast(static_cast(value)); } } -Bf2Style::Bf2Style(const char* name, int font) +Bf2Style::Bf2Style(const char* name, FontHandle font) : Style(name, font), m_wordWrap(true), m_shadowFont(0), m_texture(0), m_shadowOffsetX(0.0f), m_shadowOffsetY(0.0f) { @@ -52,7 +54,7 @@ namespace { TypeDescriptor* const registeredBf2StyleType = Bf2Style::getClassType(); } -bool Bf2Style::setShadowFont(int font) +bool Bf2Style::setShadowFont(FontHandle font) { if (!font) return false; m_shadowFont = font; @@ -60,7 +62,7 @@ bool Bf2Style::setShadowFont(int font) } bool Bf2Style::setShadowOffset(float x, float y) { m_shadowOffsetX = x; m_shadowOffsetY = y; return true; } -bool Bf2Style::setTexture(int texture) +bool Bf2Style::setTexture(TextureHandle texture) { m_texture = texture; return true; } // The shadow pass then the glyph pass, exactly as all three bodies inline them. @@ -80,7 +82,7 @@ bool Bf2Style::paintGlyph(System* system, int character, int position, const Color black = {0.0f, 0.0f, 0.0f, 1.0f}; colorQuad(&shadowQuad, &black); translateQuad(&shadowQuad, m_shadowOffsetX, m_shadowOffsetY, 0.0f); - const int font = m_shadowFont ? m_shadowFont : m_font; + const FontHandle font = m_shadowFont ? m_shadowFont : m_font; if (!drawContextCharacter(&shadowContext, system, character, font, position, &shadowQuad)) return false; @@ -204,7 +206,7 @@ void Bf2Style::drawText(System* system, Data* data, int elementIndex, } // right aligned -Bf2RightAlignedStyle::Bf2RightAlignedStyle(const char* name, int font) +Bf2RightAlignedStyle::Bf2RightAlignedStyle(const char* name, FontHandle font) : Bf2Style(name, font) {} Bf2RightAlignedStyle::~Bf2RightAlignedStyle() {} // 7C26A0, shared body TypeDescriptor* Bf2RightAlignedStyle::getClassType() @@ -286,7 +288,7 @@ void Bf2RightAlignedStyle::drawText(System* system, Data* data, int elementIndex } // centre aligned -Bf2CenterAlignedStyle::Bf2CenterAlignedStyle(const char* name, int font) +Bf2CenterAlignedStyle::Bf2CenterAlignedStyle(const char* name, FontHandle font) : Bf2Style(name, font) {} Bf2CenterAlignedStyle::~Bf2CenterAlignedStyle() {} // 7C26A0, shared body TypeDescriptor* Bf2CenterAlignedStyle::getClassType() @@ -368,9 +370,13 @@ void Bf2CenterAlignedStyle::drawText(System* system, Data* data, int elementInde } } +#if defined(_M_IX86) static_assert(sizeof(Bf2Style) == 44, "native Bf2Style storage"); -static_assert(sizeof(Bf2RightAlignedStyle) == 44, "right-aligned adds no storage"); -static_assert(sizeof(Bf2CenterAlignedStyle) == 44, "centre-aligned adds no storage"); +#endif +static_assert(sizeof(Bf2RightAlignedStyle) == sizeof(Bf2Style), "right-aligned adds no storage"); +static_assert(sizeof(Bf2CenterAlignedStyle) == sizeof(Bf2Style), "centre-aligned adds no storage"); +#if defined(_M_IX86) static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2Style metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2Style.h b/Code/BF2/Menu/Bf2Style.h index d1b87109f..1d90448e1 100644 --- a/Code/BF2/Menu/Bf2Style.h +++ b/Code/BF2/Menu/Bf2Style.h @@ -8,16 +8,16 @@ namespace dice { namespace meme { class Bf2Style : public Style { public: // Defaults [INFERRED] from factory7C1530, which supplies a null name and 0. - Bf2Style(const char* name = nullptr, int font = 0); + Bf2Style(const char* name = nullptr, FontHandle font = 0); ~Bf2Style() override; TypeDescriptor* getType() override; unsigned int getObjectSize() override; void drawText(System*, Data*, int elementIndex, const Rect* bounds, const Rect* clip, RenderContext*) override; // Names [INFERRED]; the three slots this class adds above Style's 23. - virtual bool setShadowFont(int font); // +5C 7C1490 + virtual bool setShadowFont(FontHandle font); // +5C 7C1490 virtual bool setShadowOffset(float x, float y); - virtual bool setTexture(int texture); + virtual bool setTexture(TextureHandle texture); static TypeDescriptor* getClassType(); // 7C1B20, metadata935E90 protected: // [INFERRED] spelling for the shadow and highlight passes every drawText @@ -27,18 +27,20 @@ class Bf2Style : public Style { RenderContext*, bool highlight); bool m_wordWrap; // +18, true from the constructor unsigned char m_padding19[3]; // untouched - int m_shadowFont; // +1C, zero means reuse the ordinary font - int m_texture; // +20, copied into every glyph quad when set + FontHandle m_shadowFont; // +1C, zero means reuse the ordinary font + TextureHandle m_texture; // +20, copied into every glyph quad when set float m_shadowOffsetX; // +24 float m_shadowOffsetY; // +28 }; +#if defined(_M_IX86) static_assert(sizeof(Bf2Style) == 44, "native Bf2Style storage"); +#endif // 7D1CE0 / table939250. Walks the string backwards from its last character, // decreasing the pen, so the text ends at the right edge of the bounds. class Bf2RightAlignedStyle : public Bf2Style { public: - Bf2RightAlignedStyle(const char* name = nullptr, int font = 0); + Bf2RightAlignedStyle(const char* name = nullptr, FontHandle font = 0); ~Bf2RightAlignedStyle() override; // 7C26A0, shared body TypeDescriptor* getType() override; void drawText(System*, Data*, int elementIndex, const Rect* bounds, @@ -49,7 +51,7 @@ class Bf2RightAlignedStyle : public Bf2Style { // centre of the bounds. class Bf2CenterAlignedStyle : public Bf2Style { public: - Bf2CenterAlignedStyle(const char* name = nullptr, int font = 0); + Bf2CenterAlignedStyle(const char* name = nullptr, FontHandle font = 0); ~Bf2CenterAlignedStyle() override; // 7C26A0, shared body TypeDescriptor* getType() override; void drawText(System*, Data*, int elementIndex, const Rect* bounds, diff --git a/Code/BF2/Menu/Bf2TextNode.cpp b/Code/BF2/Menu/Bf2TextNode.cpp index 8f5929c5f..008f09844 100644 --- a/Code/BF2/Menu/Bf2TextNode.cpp +++ b/Code/BF2/Menu/Bf2TextNode.cpp @@ -64,8 +64,10 @@ bool Bf2TextNode::setTypeDataForHud(Data* type) Data* Bf2TextNode::getStringDataForHud() { return m_string; } Style* Bf2TextNode::getStyleForHud() { return m_style; } +#if defined(_M_IX86) static_assert(sizeof(Bf2TextNode) == 28, "native Bf2TextNode storage"); static_assert(sizeof(ClassTypeDescriptor) == 16, "Bf2TextNode metadata"); +#endif } } #endif diff --git a/Code/BF2/Menu/Bf2TextNode.h b/Code/BF2/Menu/Bf2TextNode.h index 2cc7b2c5a..25c7034e2 100644 --- a/Code/BF2/Menu/Bf2TextNode.h +++ b/Code/BF2/Menu/Bf2TextNode.h @@ -26,7 +26,9 @@ class Bf2TextNode : public BfTextNode { protected: char* m_name; // +18, owned clone }; +#if defined(_M_IX86) static_assert(sizeof(Bf2TextNode) == 28, "native Bf2TextNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2TransformListNode.cpp b/Code/BF2/Menu/Bf2TransformListNode.cpp index 88db28999..eb447e2bf 100644 --- a/Code/BF2/Menu/Bf2TransformListNode.cpp +++ b/Code/BF2/Menu/Bf2TransformListNode.cpp @@ -2,6 +2,8 @@ #include "Bf2TransformListNode.h" #if !DEDICATED #include "Bf2TransformNode.h" +#include "../External/BFMeme/Style.h" +#include "../External/BFMeme/System.h" #include "../External/BFMeme/TypeDescriptor.h" #include namespace dice { namespace meme { @@ -61,6 +63,55 @@ bool Bf2TransformListNode::setName(const char* name) } bool Bf2TransformListNode::slot_0x24() { return true; } +// Arrange the borrowed transforms before the ordinary Node update traversal. +bool Bf2TransformListNode::update(System* system, const NodeState* state, + const Rect* bounds, float delta) +{ + if (m_positionBinding0) m_positionX = static_cast(*m_positionBinding0); + if (m_positionBinding1) m_positionY = static_cast(*m_positionBinding1); + m_positionX += static_cast(m_offsetX); + m_positionY += static_cast(m_offsetY); + + float width = 0.0f; + float height = 0.0f; + const float gapY = static_cast(m_count) * m_field034; + const float gapX = static_cast(m_count) * m_field030; + for (Bf2TransformNode* child : m_children) { + if (m_field030 > 0.0f) { + width += child->getSize().x; + if (height < child->getSize().y) height = child->getSize().y; + } else { + height += child->getSize().y; + if (width < child->getSize().x) width = child->getSize().x; + } + width += gapX; + height += gapY; + } + + // The far edges are captured before either near-edge clamp. Even an + // oversized list therefore follows the original two independent tests. + const float right = width + m_positionX; + const float bottom = height + m_positionY; + if (system->getWidth() * 0.5f + bounds->x > m_positionX) + m_positionX = system->getWidth() * 0.5f + bounds->x; + if (system->getWidth() * 0.5f + bounds->x + bounds->width < right) + m_positionX = system->getWidth() * 0.5f + bounds->x + bounds->width - width; + if (system->getHeight() * 0.5f + bounds->y > m_positionY) + m_positionY = system->getHeight() * 0.5f + bounds->y; + if (system->getHeight() * 0.5f + bounds->height + bounds->y < bottom) + m_positionY = system->getHeight() * 0.5f + bounds->height + bounds->y - height; + + float x = m_positionX; + float y = m_positionY; + for (Bf2TransformNode* child : m_children) { + child->setPositionForHud(x, y); + const float childStepY = child->getSize().y * m_field034; + x = m_field030 * child->getSize().x + x + gapX; + y = childStepY + y + gapY; + } + return Node::update(system, state, bounds, delta); +} + namespace { TypeDescriptor* const registeredBf2TransformListNodeType = Bf2TransformListNode::getClassType(); } diff --git a/Code/BF2/Menu/Bf2TransformListNode.h b/Code/BF2/Menu/Bf2TransformListNode.h index d7ab79d24..22699f46f 100644 --- a/Code/BF2/Menu/Bf2TransformListNode.h +++ b/Code/BF2/Menu/Bf2TransformListNode.h @@ -21,6 +21,7 @@ class Bf2TransformListNode : public Node { const char* getName() override; bool setName(const char*) override; bool slot_0x24() override; // 5A5E20, true + bool update(System*, const NodeState*, const Rect*, float) override; static TypeDescriptor* getClassType(); // 7D18B0, metadata9390B0 // [CHOSEN, not recovered] Native transform-list property access. @@ -43,11 +44,13 @@ class Bf2TransformListNode : public Node { int* m_positionBinding1; // +20, every other index int m_count; // +24, the fourth argument int m_offsetX, m_offsetY; // +28/+2C - std::uint32_t m_field030; // +30, constructor0 + float m_field030; // +30, horizontal direction, constructor0 float m_field034; // +34, constructor 1.0 float m_positionX, m_positionY; // +38/+3C }; +#if defined(_M_IX86) static_assert(sizeof(Bf2TransformListNode) == 60, "native Bf2TransformListNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/Bf2TransformNode.cpp b/Code/BF2/Menu/Bf2TransformNode.cpp index 52836a786..cf9d6b5f4 100644 --- a/Code/BF2/Menu/Bf2TransformNode.cpp +++ b/Code/BF2/Menu/Bf2TransformNode.cpp @@ -1,6 +1,9 @@ // HUD transform-node position and bounds. [INFERRED] Source placement. // Higher accessors use the documented native interface where original Node slots remain incomplete. #include "Bf2TransformNode.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "Bf2ButtonNode.h" #include "../External/BFMeme/NodeState.h" @@ -16,6 +19,8 @@ void (*editorHudNodeUpdated)(Bf2TransformNode*, float, float, float, float) = nu namespace { bool sumNotLess(float first, float second, float limit) // 7C1ED1..7C1EEE, unordered passes { +#if defined(_WIN32) +#if defined(_M_IX86) bool result; __asm { fld first @@ -26,9 +31,24 @@ bool sumNotLess(float first, float second, float limit) // 7C1ED1..7C1EEE, unord setp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // setp after test ah,5: false only for an ordered sum below the limit. + const double sum = static_cast(first) + second; + return !(sum < limit); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + bool result; + // [CHOSEN, not recovered] Preserve x87 unordered-or-not-less sum. + result = bf2x87::sumNotLess(first, second, limit); + return result; +#endif } bool stateEnabled(float value) // 7C1EF3..7C1F24; decoded value stays in x87 { +#if defined(_WIN32) +#if defined(_M_IX86) const float one = 1.0f; bool result; __asm { @@ -47,6 +67,20 @@ bool stateEnabled(float value) // 7C1EF3..7C1F24; decoded value stays in x87 setp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered negative value is decoded; unordered compares pass. + const double decoded = value < 0.0f ? -(static_cast(value) + 1.0) : value; + return !(decoded < 1.0); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float one = 1.0f; + bool result; + // [CHOSEN, not recovered] Preserve x87 unspilled decoded state comparison. + result = bf2x87::notLess(bf2x87::decoded(value), bf2x87::wide(one)); + return result; +#endif } // [INFERRED] descriptor class name. Counter A22194 has only the add/sub/get @@ -200,7 +234,9 @@ namespace { // pointer); native C++ supplies the guard/teardown spelling. TypeDescriptor* const registeredBf2TransformNodeType = Bf2TransformNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(Bf2TransformNodeTypeDescriptor) == 16, "client BF2 transform metadata"); static_assert(sizeof(Bf2TransformNode) == 0x3C, "client BF2 named TransformNode"); +#endif } } #endif diff --git a/Code/BF2/Menu/BfEditNode.cpp b/Code/BF2/Menu/BfEditNode.cpp index 821e367f9..965a915a2 100644 --- a/Code/BF2/Menu/BfEditNode.cpp +++ b/Code/BF2/Menu/BfEditNode.cpp @@ -1,15 +1,20 @@ -// [INFERRED] path/names. Bounded real BfEditNode storage/properties/update; -// no complete Node descriptor or edit-node factory is published. +// [INFERRED] path/names. BfEditNode storage, properties, update, painting and +// input; no complete Node descriptor or edit-node factory is published. #include "BfEditNode.h" #if !DEDICATED #include "BfEditData.h" +#include "DifFontMetadata.h" +#include "Font.h" +#include "../External/BFMeme/Action.h" +#include "../External/BFMeme/Effect.h" +#include "../External/BFMeme/Pointer.h" #include "../External/BFMeme/Stream.h" #include "../External/BFMeme/System.h" #include "../External/BFMeme/TypeDescriptor.h" -#include -#include +#include #include #include +#include namespace dice { namespace meme { BfEditNode::BfEditNode() : m_editData(nullptr), m_string(nullptr), m_selectAction(nullptr), m_font(0), @@ -66,7 +71,7 @@ void BfEditNode::updateVisibleStart(System* system, const Rect* rect) float remaining = rect->width; for (int index = m_cursor - 1; index >= m_firstVisible; --index) { GlyphMetrics metrics; - const int font = m_font; + const FontHandle font = m_font; const int character = m_string->getCharacter(system, index); system->getGlyphMetrics(character, font, &metrics); // result deliberately discarded // Right + width + left, preserving the actual evaluation order. @@ -123,20 +128,236 @@ TypeDescriptor* BfEditNode::getClassType() // 7AC340, singletonA } TypeDescriptor* BfEditNode::getType() { return getClassType(); } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Edit-node painting and pointer-event handling stop on invocation. -// [RETIRE-WHEN: hud-edit-node-frame] Replace with complete, validated frame and pointer-event implementations. -void BfEditNode::paintSelf(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) +// Draws the visible characters from m_firstVisible onward, each glyph clipped +// to the node's own bounds, with an optional eight-neighbour outline, and the +// blinking two-unit cursor while focused. A carriage return ends the line. +void BfEditNode::paintSelf(System* system, const NodeState*, const Rect* bounds, + const Rect*, RenderContext* context) // 7AAEF0; clip unused { - std::fprintf(stderr, "[FRONTIER] dice::meme::BfEditNode::paintSelf reached\n"); - std::fflush(stderr); - std::abort(); + if (!m_string) return; + float penX = bounds->x; + const float penY = bounds->y; + const float right = static_cast(static_cast(penX) + bounds->width); + const float lineHeight = system->getFontHeight(m_font); + Rect glyph = *bounds; + int index = m_firstVisible; + int elementIndex = 0; + bool cursorDrawn = false; + float scale = 1.0f; + hfe::menu::Font* const font = reinterpret_cast(m_font); + const std::string fontName(font->getName()); // retail has no null-font guard + if (fontName.find(".dif", 0, 4) != std::string::npos) + scale = static_cast(font)->getMetadata()->getScale(); + const float reciprocalScale = static_cast(1.0 / scale); + int character = m_string->getCharacter(system, index); + while (character) { + if (character == 13) { + // 7AB56C: a line break leaves the loop; an undrawn cursor is then + // placed at the pen as though the cursor index had been reached. + if (!cursorDrawn) index = m_cursor; + break; + } + GlyphMetrics metrics; // failure leaves the shipped output uninitialized + system->getGlyphMetrics(character, m_font, &metrics); + glyph.width = metrics.width; + glyph.height = metrics.height; + if (scale == 1.0f) { + glyph.x = penX; + glyph.y = static_cast(static_cast(metrics.verticalOffset) + penY); + } else { + // Unlike Style::positionGlyph the pen itself keeps the snapped x, and + // the offset is added before the reciprocal scale. + penX = static_cast(static_cast(scale) * penX); + const float scaledY = static_cast(static_cast(scale) * penY); + // x87 tests C0 alone: unordered follows the same arm as remainder<0.5. + const double roundedX = std::floor(!(std::fmod(penX, 1.0) >= 0.5) ? + penX : static_cast(penX) + 1.0); + penX = static_cast(roundedX * reciprocalScale); + glyph.x = penX; + const double roundedY = std::floor(!(std::fmod(scaledY, 1.0) >= 0.5) ? + scaledY : static_cast(scaledY) + 1.0); + glyph.y = static_cast((roundedY + metrics.verticalOffset) * reciprocalScale); + } + if (!(penX < right)) break; // 7AB0E8; NaN keeps drawing + if (!m_editData || !m_editData->m_hideText) { + if (m_outline) { + // Retail inlines setQuadBounds (7AA7F0) for the last seven + // passes and keeps each x + width and y + height on the x87 + // stack; the out-of-line helper rounds those sums to float. + const Color outlineColor = {0.15000001f, 0.15000001f, 0.15000001f, 1.0f}; + Quad outline(&glyph, bounds, &outlineColor); + translateQuad(&outline, 1.0f, 1.0f, -0.001f); // 7AA750 + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + setQuadBounds(&outline, penX + 1.0f, glyph.y, glyph.width, glyph.height); + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + setQuadBounds(&outline, penX + 1.0f, glyph.y - 1.0f, glyph.width, glyph.height); + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + setQuadBounds(&outline, penX, glyph.y - 1.0f, glyph.width, glyph.height); + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + setQuadBounds(&outline, penX - 1.0f, glyph.y - 1.0f, glyph.width, glyph.height); + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + setQuadBounds(&outline, penX - 1.0f, glyph.y, glyph.width, glyph.height); + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + setQuadBounds(&outline, penX - 1.0f, glyph.y + 1.0f, glyph.width, glyph.height); + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + setQuadBounds(&outline, penX, glyph.y + 1.0f, glyph.width, glyph.height); + drawContextCharacter(context, system, character, m_font, elementIndex, &outline); + } + Quad text(&glyph, bounds, &m_color); + // Only the main glyph's result is tested; a refusal also skips the cursor. + if (!drawContextCharacter(context, system, character, m_font, elementIndex, &text)) + return; + } + if (index == m_cursor && m_blinkTime >= 0.0f && m_focused) { + // Reuses the glyph rectangle: x stays at this glyph; the rest becomes + // the unsnapped line top, the font height and a two-unit width. + glyph.height = lineHeight; + glyph.y = penY; + glyph.width = 2.0f; + Quad cursor(&glyph, nullptr); + drawContextTexture(context, system, 0, &cursor); + cursorDrawn = true; + } + // Right + width + left, then the pen, preserving the evaluation order. + penX = static_cast(((static_cast(metrics.rightBearing) + metrics.width) + + metrics.leftBearing) + penX); + ++elementIndex; + character = m_string->getCharacter(system, ++index); + } + // 7AB578: the cursor after the last drawn character, or after a line break. + if (index == m_cursor && m_blinkTime >= 0.0f && m_focused) { + glyph.x = penX; + glyph.height = lineHeight; + glyph.y = penY; + glyph.width = 2.0f; + Quad cursor(&glyph, nullptr); + drawContextTexture(context, system, 0, &cursor); + } } -bool BfEditNode::onEvent1(System*, const Rect*, const NodeState*, int, int, int) +// Key and pointer input for index 1. Key 18 runs the select action and drops +// focus; key 1 is a click that takes focus inside the bounds, or drops it and +// forwards the click to the System pointer outside them, then places the +// cursor. Editing keys apply only while focused. Returns false when the event +// was refused or focus was lost. +bool BfEditNode::onEvent1(System* system, const Rect* rect, const NodeState* state, + int key, int index, int second) // 7AB5F0 { - std::fprintf(stderr, "[FRONTIER] dice::meme::BfEditNode::onEvent1 reached\n"); - std::fflush(stderr); - std::abort(); + if (index != 1) return false; + if (key == 18) { + if (m_selectAction) { + const NodeInputEvent event = {1, 0, 0.0f, 0.0f, 0}; + m_selectAction->execute(system, rect, state, &event); // result ignored + if (!m_focused) return false; + m_focused = false; + system->unlockPointer(); // 82A3C0 + } + } else if (key == 1 && !m_ignoreClick) { + const float* const pointer = system->getPointerPosition(); // 682BA0 + const float x = pointer[0]; + const float y = pointer[1]; + const float rightEdge = static_cast(static_cast(rect->width) + rect->x); + const float bottomEdge = static_cast(static_cast(rect->height) + rect->y); + // Retail tests m_focused first and repeats these comparisons in both + // arms. Edges and NaN count as outside. + if (x > rect->x && x < rightEdge && y > rect->y && y < bottomEdge) { + if (!m_focused) { + m_focused = true; + system->lockPointer(); // 82A3B0 + } + } else { + m_focused = false; + system->unlockPointer(); + // System 82A2D0 reloads its +20 pointer and tail-calls the guarded + // 828DF0 wrapper; the result is ignored. + pointerEvent1(system, static_cast(system->getPointerObject()), + 1, 1, second); + return false; + } + } + if (!m_focused || !m_string) return false; + const int length = m_string->getStringLength(system); + switch (key) { + case 1: + if (m_ignoreClick) { + m_ignoreClick = false; + break; + } + { + const float* const pointer = system->getPointerPosition(); + float offset = static_cast(static_cast(rect->x) - pointer[0]); + if (offset < 0.0f) offset = offset * -1.0f; // ds:8AA8C0 + float remaining = rect->width; + int position = 0; + for (; position < length; ++position) { + GlyphMetrics metrics; + const FontHandle font = m_font; + const int character = m_string->getCharacter(system, position); + system->getGlyphMetrics(character, font, &metrics); // result discarded + const double width = (static_cast(metrics.rightBearing) + metrics.width) + + metrics.leftBearing; + const double next = static_cast(remaining) - width; + remaining = static_cast(next); + // The unrounded difference meets the unrounded width - offset. + if (next <= static_cast(rect->width) - offset) { + m_cursor = position; + updateVisibleStart(system, rect); + break; + } + } + if (position == length) { + m_cursor = position; + updateVisibleStart(system, rect); + } + } + break; + case 5: + if (m_cursor > 0) --m_cursor; + break; + case 7: + if (m_cursor < length) ++m_cursor; + break; + case 9: + m_cursor = 0; + updateVisibleStart(system, rect); + break; + case 10: + m_cursor = length - 1; // shipped: one before the end, -1 for empty text + updateVisibleStart(system, rect); + break; + case 14: + if (m_cursor < length) { + char* buffer = static_cast(::operator new(length + 1)); // 447EF0 + m_string->getString(system, buffer, length + 1); + std::memmove(buffer + m_cursor, buffer + m_cursor + 1, length - m_cursor); // 73C5D0 + m_string->setString(system, buffer); // result ignored + ::operator delete(buffer); // 737EE0 frees and nulls + buffer = nullptr; + } + break; + case 15: + if (m_cursor > 0) { + char* buffer = static_cast(::operator new(length + 1)); + m_string->getString(system, buffer, length + 1); + std::memmove(buffer + m_cursor - 1, buffer + m_cursor, length - m_cursor + 1); + m_string->setString(system, buffer); + ::operator delete(buffer); + buffer = nullptr; + --m_cursor; // member reloaded after the callback + } + break; + case 16: + return true; // the only arm without the trailing visible-start update + case 17: + if (m_ignoreClick) m_ignoreClick = false; + break; + default: + break; + } + updateVisibleStart(system, rect); + return true; } +#if defined(_M_IX86) static_assert(sizeof(BfEditNode) == 80, "native BfEditNode storage"); +#endif } } #endif diff --git a/Code/BF2/Menu/BfEditNode.h b/Code/BF2/Menu/BfEditNode.h index f8f097b84..0f6b2e479 100644 --- a/Code/BF2/Menu/BfEditNode.h +++ b/Code/BF2/Menu/BfEditNode.h @@ -11,14 +11,15 @@ class Action; class BfEditNode : public Node { friend class BfEditData; + friend bool dispatchNodeEvent16(Node*, System*, const Rect*, const NodeState*); public: BfEditNode(); // 7AAE90; no owned resources TypeDescriptor* getType() override; // 7AC340 [FRONTIER] Node suffix unsigned int getObjectSize() override; bool streamProperties(System*, Stream*) override; bool updateSelf(System*, const NodeState*, const Rect*, float) override; - void paintSelf(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) override; // 7AAEF0 [FRONTIER] - bool onEvent1(System*, const Rect*, const NodeState*, int first, int index, int second) override; // 7AB5F0 [FRONTIER] + void paintSelf(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) override; // 7AAEF0 + bool onEvent1(System*, const Rect*, const NodeState*, int first, int index, int second) override; // 7AB5F0 bool onEvent4(System*, const Rect*, const NodeState*, int first, int index, int second) override; void updateVisibleStart(System*, const Rect*); static TypeDescriptor* getClassType(); // 7AC340, metadata934DA0 @@ -27,7 +28,7 @@ class BfEditNode : public Node BfEditData* m_editData; // +08, borrowed Data* m_string; // +0C, borrowed Action* m_selectAction; // +10, borrowed - int m_font; // +14, opaque font handle + FontHandle m_font; // +14, opaque font handle int m_maxCharacters; // +18 int m_firstVisible, m_cursor; // +1C,+20 float m_blinkTime; // +24 diff --git a/Code/BF2/Menu/BfFixedSliderNode.h b/Code/BF2/Menu/BfFixedSliderNode.h index 5324ad442..a18086f37 100644 --- a/Code/BF2/Menu/BfFixedSliderNode.h +++ b/Code/BF2/Menu/BfFixedSliderNode.h @@ -42,7 +42,9 @@ class BfFixedSliderNode : public SliderNode NodeState m_state; // +4C/+50, ctor {1.0, 1.0} std::uint32_t m_field054; // +54, ctor 0 [UNRESOLVED] }; +#if defined(_M_IX86) static_assert(sizeof(BfFixedSliderNode) == 88, "retail and native BfFixedSliderNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/BfListBoxData.cpp b/Code/BF2/Menu/BfListBoxData.cpp index da88c52a3..03ff85941 100644 --- a/Code/BF2/Menu/BfListBoxData.cpp +++ b/Code/BF2/Menu/BfListBoxData.cpp @@ -1,5 +1,8 @@ // Client list-box cell data. [INFERRED] Source placement. #include "BfListBoxData.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #include "BfNewListBoxNode.h" #if !DEDICATED #include "../External/BFMeme/TypeDescriptor.h" @@ -9,16 +12,33 @@ #include "../External/BFMeme/Style.h" #include "../External/BFMeme/System.h" #include +#include +#include #include +// [CHOSEN, not recovered] SSE2 is used only by the Windows x64 arm; arm64 has no emmintrin.h. +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace meme { -// [FRONTIER] Releases a cell resource through an unidentified interface. [INFERRED] Name and void return. -// Keep declaration-only until the full typed interface prefix is established. -void releaseListBoxCellResource(dice::hfe::IBase*, int resourceIndex); +// [FRONTIER] [TEMP] [CHOSEN, not recovered] Releases a cell resource through an unidentified +// interface. [INFERRED] Name and void return. BF2.exe clearCell (7C4CE7) and copyCell (7C4A5B) call +// the list's +48 object at vtable +20 with the cell's resource index and discard the result; the +// object's interface is not identified, so this stops before any call. +// [RETIRE-WHEN: LISTBOX-CELL-RESOURCE] Identify the +48 owner and its typed +20 method, call it +// here, and validate a list box that clears cells with a resource attached. +void releaseListBoxCellResource(dice::hfe::IBase*, int) +{ + std::fprintf(stderr, "[FRONTIER] dice::meme::releaseListBoxCellResource reached\n"); + std::fflush(stderr); + std::abort(); +} namespace { // PE's x87 fistp integer conversion, including its saved rounding mode. This // expression helper is not a separately attested retail function. int truncateListWidth(double value) { +#if defined(_WIN32) +#if defined(_M_IX86) unsigned short original, truncating; int result; __asm { @@ -32,6 +52,18 @@ int truncateListWidth(double value) fldcw original } return result; +#else + // cvttsd2si truncates like the chopped fistp, including the 0x80000000 indefinite result. + return _mm_cvttsd_si32(_mm_set_sd(value)); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + unsigned short original, truncating; + int result; + // [CHOSEN, not recovered] Preserve x87 truncating int32 with integer indefinite. + result = bf2x87::integer(bf2x87::wide(value)); + return result; +#endif } } ListBoxData::ListBoxData(const char* name) : Data(name), m_row(0) {} @@ -123,7 +155,7 @@ ListBoxCell::ListBoxCell(std::wstring text, float x, float y, float r, float g, ListBoxColumn::ListBoxColumn(int number, int size, bool flag, bool flag2) : index(number), cells(), width(size), enabled(true), field019(flag), field01a(flag2), field01c(0), field020(-1) {} -ListBoxCell::ListBoxCell(int image, float width, float height, float x, float y, +ListBoxCell::ListBoxCell(TextureHandle image, float width, float height, float x, float y, float r, float g, float b, float a) : narrow(), wide() { texture = image; @@ -258,7 +290,7 @@ bool BfListBoxData::appendCell(int index, std::string text, float r, float g, fl bool BfListBoxData::appendCell0x7c81c0(int index, std::string text, float r, float g, float b, float a, int value) { return appendCell(index, text, r, g, b, a, value); } -bool BfListBoxData::appendImageCell0x7c8300(int index, int texture, float width, float height, +bool BfListBoxData::appendImageCell0x7c8300(int index, TextureHandle texture, float width, float height, float x, float y, float r, float g, float b, float a) { return appendImageCell(index, texture, width, height, x, y, r, g, b, a); } // 7C8120 / 7C83D0 and their forwarders. See BfListBoxData.h for the shape and the two inherited @@ -338,7 +370,7 @@ std::wstring BfListBoxData::getWideCell(int index, int row) } return L""; } -bool BfListBoxData::appendImageCell(int index, int texture, float width, float height, +bool BfListBoxData::appendImageCell(int index, TextureHandle texture, float width, float height, float x, float y, float r, float g, float b, float a) { if (static_cast(index) < m_columns.size()) { @@ -351,7 +383,7 @@ bool BfListBoxData::appendImageCell(int index, int texture, float width, float h } return true; } -bool BfListBoxData::setImageCell(int index, int row, int texture, float width, float height, +bool BfListBoxData::setImageCell(int index, int row, TextureHandle texture, float width, float height, float x, float y, float r, float g, float b, float a, int extra) { if (static_cast(index) < m_columns.size()) { @@ -664,6 +696,7 @@ bool BfListBoxData::insertWideCell(int index, int row, std::wstring text, } int BfListBoxData::measureText(System* system, std::wstring text, int column, int row, int* fontMode) { +#if defined(_WIN32) int characters[256]; std::string narrow; std::wstring wide; @@ -684,6 +717,7 @@ int BfListBoxData::measureText(System* system, std::wstring text, int column, in system->getGlyphMetrics(character, m_node->m_fonts[mode], &metrics); ++index; // Keep all three additions on x87 until the single float store. +#if defined(_M_IX86) __asm { lea eax, metrics fld dword ptr [eax+8] @@ -692,6 +726,12 @@ int BfListBoxData::measureText(System* system, std::wstring text, int column, in fadd width fstp width } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // +8 rightBearing, +4 width, +0 leftBearing. + width = static_cast(static_cast(metrics.rightBearing) + metrics.width + + metrics.leftBearing + width); +#endif } if (index >= 250) break; float imageX = 0; @@ -715,6 +755,54 @@ int BfListBoxData::measureText(System* system, std::wstring text, int column, in } *fontMode = mode; return index; +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + int characters[256]; + std::string narrow; + std::wstring wide; + float width = 0; + int index = 0, mode = *fontMode; + GlyphMetrics metrics; // retail ignores getGlyphMetrics failure; do not initialize + while (true) { + const int character = static_cast(text.c_str()[index]); + characters[index] = character; + if (!character) break; + const int next = static_cast(text.c_str()[index + 1]); + characters[index + 1] = next; + if (character == 0xA7 && next >= '0' && next <= '3') { + mode = next - '0'; index += 2; + } else if (character == 0xA7 && (next == 'C' || next == 'c')) { + index += 6; + } else { + system->getGlyphMetrics(character, m_node->m_fonts[mode], &metrics); + ++index; + // Keep all three additions on x87 until the single float store. + // [CHOSEN, not recovered] Preserve x87 right/width/left additions before float store. + width = bf2x87::glyphWidth(metrics.rightBearing, metrics.width, metrics.leftBearing, width); + } + if (index >= 250) break; + float imageX = 0; + if (static_cast(column) < m_columns.size()) { + ListBoxColumn* entry = m_columns[column]; + if (entry && static_cast(row) < entry->cells.size()) { + ListBoxCell* cell = entry->cells[row]; + if (cell) imageX = cell->imageX; + } + } + int alignment = 0; + if (static_cast(column) < m_columns.size()) { + ListBoxColumn* entry = m_columns[column]; + if (entry && static_cast(row) < entry->cells.size()) { + ListBoxCell* cell = entry->cells[row]; + if (cell) alignment = cell->field064; + } + } + const float used = imageX + width; + if (getAvailableWidth(column, alignment) < used) break; + } + *fontMode = mode; + return index; +#endif } // 659EE0, a shared one-byte setter the HUD builder's outline row calls directly. void BfListBoxData::setOutlineForHud(bool outline) { m_outline = outline; } diff --git a/Code/BF2/Menu/BfListBoxData.h b/Code/BF2/Menu/BfListBoxData.h index f64dbabb9..e9d1f701b 100644 --- a/Code/BF2/Menu/BfListBoxData.h +++ b/Code/BF2/Menu/BfListBoxData.h @@ -64,13 +64,13 @@ struct ListBoxCell // stays false and texture stays 0). imageWidth/imageHeight are still zeroed. ListBoxCell(std::string, float x, float y, float r, float g, float b, float a, int); ListBoxCell(std::wstring, float x, float y, float r, float g, float b, float a, int); - ListBoxCell(int texture, float width, float height, float x, float y, + ListBoxCell(TextureHandle texture, float width, float height, float x, float y, float r, float g, float b, float a); std::string narrow; // retail+00 std::wstring wide; // +1C bool isWide; // +38 Color color; // +3C - int texture; // +4C + TextureHandle texture; // +4C float imageWidth, imageHeight, imageX, imageY; // +50..5C bool isImage; // +60 int field064, field068; // +64/+68 @@ -145,11 +145,11 @@ class BfListBoxData : public ListBoxData float r, float g, float b, float a, int); bool appendPositionedWideCell0x7c8470(int column, std::wstring, float x, float y, float r, float g, float b, float a, int); - bool appendImageCell(int column, int texture, float, float, float, float, + bool appendImageCell(int column, TextureHandle texture, float, float, float, float, float, float, float, float); - bool appendImageCell0x7c8300(int column, int texture, float, float, float, float, + bool appendImageCell0x7c8300(int column, TextureHandle texture, float, float, float, float, float, float, float, float); - bool setImageCell(int column, int row, int texture, float, float, float, float, + bool setImageCell(int column, int row, TextureHandle texture, float, float, float, float, float, float, float, float, int extra); bool setWideCell(int column, int row, std::wstring, float, float, float, float, int, int); bool setWideCell0x7c87f0(int, int, std::wstring, float, float, float, float, int, int); diff --git a/Code/BF2/Menu/BfNewListBoxNode.cpp b/Code/BF2/Menu/BfNewListBoxNode.cpp index 8ca80ceca..31d76a65a 100644 --- a/Code/BF2/Menu/BfNewListBoxNode.cpp +++ b/Code/BF2/Menu/BfNewListBoxNode.cpp @@ -1,4 +1,7 @@ #include "BfNewListBoxNode.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "BfListBoxData.h" #include "DifFontMetadata.h" @@ -13,6 +16,10 @@ #include #include #include +// [CHOSEN, not recovered] SSE2 is used only by the Windows x64 arm; arm64 has no emmintrin.h. +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace hfe { namespace io { extern IBase* inputDeviceManager; } } } @@ -21,7 +28,9 @@ namespace { // Floors then converts to int with truncating x87 control, preserving NaN and out-of-range results. int floorToInt(double value) { +#if defined(_WIN32) const double floored = std::floor(value); +#if defined(_M_IX86) unsigned short original, truncating; int result; __asm { @@ -35,6 +44,19 @@ int floorToInt(double value) fldcw original } return result; +#else + // cvttsd2si truncates like the chopped fistp, including the 0x80000000 indefinite result. + return _mm_cvttsd_si32(_mm_set_sd(floored)); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const double floored = std::floor(value); + unsigned short original, truncating; + int result; + // [CHOSEN, not recovered] Preserve x87 truncating int32 with integer indefinite. + result = bf2x87::integer(bf2x87::wide(floored)); + return result; +#endif } int floorFloatToInt(float value) { return floorToInt(static_cast(value)); } } @@ -54,7 +76,7 @@ BfNewListBoxNode::BfNewListBoxNode() m_field108(false), m_field109(false), m_field128(false) { for (auto& word : m_field10c) word = 0; - for (int& font : m_fonts) font = 0; + for (FontHandle& font : m_fonts) font = 0; } BfNewListBoxNode::~BfNewListBoxNode() {} // list destruction, then Node/Object unsigned int BfNewListBoxNode::getObjectSize() { return sizeof(BfNewListBoxNode); } @@ -122,13 +144,39 @@ bool BfNewListBoxNode::scrollDownOneRow(System*) return true; } -// [FRONTIER] [TEMP] [CHOSEN, not recovered] Remaining stream and event methods stop on invocation. -// [RETIRE-WHEN: hud-list-box-frame] Replace after all remaining list-box stream and event operations are implemented and validated. -bool BfNewListBoxNode::streamProperties(System*, Stream*) +// Streams the list box's properties after Node's. The deletion visitor runs it when the HUD tree is +// destroyed. "Font" and "Select action" both stream the +48 word, as shipped; nothing streams +4C. +// A data object, once streamed, gets this node as its back-pointer. +bool BfNewListBoxNode::streamProperties(System* system, Stream* stream) { - std::fprintf(stderr, "[FRONTIER] dice::meme::BfNewListBoxNode::streamProperties reached\n"); - std::fflush(stderr); - std::abort(); + if (!Node::streamProperties(system, stream)) return false; + if (!stream->streamData(system, reinterpret_cast(m_data), "Listbox data", + ListBoxData::getClassType())) return false; + if (m_data) m_data->m_node = this; + if (!stream->streamFont(system, &m_font048, "Font")) return false; + if (!stream->streamAction(system, m_selectAction, "Select action", nullptr)) return false; + if (!stream->streamAction(system, m_focusAction, "Focus action", nullptr)) return false; + if (!stream->streamSound(system, &m_sound068, "Step sound")) return false; + if (!stream->streamSound(system, &m_sound06c, "Select sound")) return false; + if (!stream->streamSound(system, &m_sound070, "Failed select sound")) return false; + if (!stream->streamFloat(&m_rowHeight, "Row height")) return false; + if (!stream->streamBool(&m_selectable, "IsSelectable")) return false; + if (!stream->streamBool(&m_border, "Border or not")) return false; + if (!stream->streamFloat(&m_background.r, "Background color red")) return false; + if (!stream->streamFloat(&m_background.g, "Background color green")) return false; + if (!stream->streamFloat(&m_background.b, "Background color blue")) return false; + if (!stream->streamFloat(&m_background.a, "Background color alpha")) return false; + if (!stream->streamFloat(&m_scrollWidth, "Scrollbar width")) return false; + if (!stream->streamFloat(&m_frame.r, "Frame color red")) return false; + if (!stream->streamFloat(&m_frame.g, "Frame color green")) return false; + if (!stream->streamFloat(&m_frame.b, "Frame color blue")) return false; + if (!stream->streamFloat(&m_frame.a, "Frame color alpha")) return false; + if (!stream->streamFloat(&m_selection.r, "Select color red")) return false; + if (!stream->streamFloat(&m_selection.g, "Select color green")) return false; + if (!stream->streamFloat(&m_selection.b, "Select color blue")) return false; + if (!stream->streamFloat(&m_selection.a, "Select color alpha")) return false; + if (!stream->streamBool(&m_field109, "Show tooltip")) return false; + return stream->streamFloat(&m_scrollOffset, "Scrollbar offset from border") != false; } bool BfNewListBoxNode::updateSelf(System* system, const NodeState* state, const Rect* bounds, float delta) @@ -1009,12 +1057,16 @@ bool BfNewListBoxNode::onEvent2(System* system, const Rect* bounds, const NodeSt m_field064 = -1; return false; } +// [FRONTIER] [TEMP] [CHOSEN, not recovered] The remaining event method stops on invocation. +// [RETIRE-WHEN: hud-list-box-frame] Replace after the remaining list-box event operations are implemented and validated. bool BfNewListBoxNode::onEvent3(System*, const Rect*, const NodeState*, int, int) { std::fprintf(stderr, "[FRONTIER] dice::meme::BfNewListBoxNode::onEvent3 reached\n"); std::fflush(stderr); std::abort(); } +#if defined(_M_IX86) static_assert(sizeof(BfNewListBoxNode) == 296, "native BfNewListBoxNode storage"); +#endif } } #endif diff --git a/Code/BF2/Menu/BfNewListBoxNode.h b/Code/BF2/Menu/BfNewListBoxNode.h index fc32fec51..8738ea6bc 100644 --- a/Code/BF2/Menu/BfNewListBoxNode.h +++ b/Code/BF2/Menu/BfNewListBoxNode.h @@ -16,7 +16,7 @@ class BfNewListBoxNode : public Node ~BfNewListBoxNode() override; TypeDescriptor* getType() override; unsigned int getObjectSize() override; - bool streamProperties(System*, Stream*) override; // 7C33E0 [FRONTIER] + bool streamProperties(System*, Stream*) override; // 7C33E0 bool updateSelf(System*, const NodeState*, const Rect*, float) override; void paintSelf(System*, const NodeState*, const Rect*, const Rect*, RenderContext*) override; bool onEvent1(System*, const Rect*, const NodeState*, int, int, int) override; // 7C40A0 [FRONTIER] @@ -42,8 +42,8 @@ class BfNewListBoxNode : public Node BfListBoxData* m_data; // +14, borrowed float m_rowHeight, m_spacing, m_borderWidth, m_scrollWidth; // +18..24 float m_field028, m_field02c, m_field030; - int m_fonts[5]; // +34..44 - union { Action* m_selectAction; int m_font048; }; // +48: both streamed here in retail + FontHandle m_fonts[5]; // +34..44 + union { Action* m_selectAction; FontHandle m_font048; }; // +48: both streamed here in retail // Actions invoked on release inside the list and on a press elsewhere. [UNRESOLVED] Role names. Action* m_field04c; // +4C, run by onEvent1 on release Action* m_focusAction; // +50 diff --git a/Code/BF2/Menu/BfOccupiedVehicleData.cpp b/Code/BF2/Menu/BfOccupiedVehicleData.cpp index cff125387..917b23416 100644 --- a/Code/BF2/Menu/BfOccupiedVehicleData.cpp +++ b/Code/BF2/Menu/BfOccupiedVehicleData.cpp @@ -41,7 +41,7 @@ bool BfOccupiedVehicleData::setOccupantIcon(int position, int icon) else found->second = icon; return true; } -int BfOccupiedVehicleData::getOccupantTexture(System*, int position) +TextureHandle BfOccupiedVehicleData::getOccupantTexture(System*, int position) { auto found = m_occupantIcons.find(position); if (found == m_occupantIcons.end()) return 0; diff --git a/Code/BF2/Menu/BfOccupiedVehicleData.h b/Code/BF2/Menu/BfOccupiedVehicleData.h index e518fe832..f9f2d926c 100644 --- a/Code/BF2/Menu/BfOccupiedVehicleData.h +++ b/Code/BF2/Menu/BfOccupiedVehicleData.h @@ -15,16 +15,26 @@ class BfOccupiedVehicleData : public Data { bool streamProperties(System*, Stream*) override; static TypeDescriptor* getClassType(); bool setOccupantIcon(int position, int icon); // 7C8DB0; [INFERRED] name - int getOccupantTexture(System*, int position); // 7C8CC0; System argument unused + TextureHandle getOccupantTexture(System*, int position); // 7C8CC0; System argument unused private: friend struct BfOccupiedVehicleDataFixture; std::map m_occupantIcons; // PE+8, signed key and icon index // Retail allocation/getSize48 leaves exactly seven handles after its12-byte // map. Constructor and getter nevertheless access index7: shipped overflow. // Do not enlarge this array or silently repair the allocation. - int m_textures[7]; // PE+14..2F; native+10..2B +#if defined(_M_IX86) + TextureHandle m_textures[7]; // PE+14..2F; native+10..2B +#else + // [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the shipped index-7 + // write lands in the x86 heap block's padding (44 bytes in an 8-byte-granular block), but on + // x64 the 8 bytes after the object can be the next block's header, so the write corrupted the + // heap at random during HUD loading. x64 owns the eighth slot the shipped code writes and reads. + TextureHandle m_textures[8]; +#endif }; +#if defined(_M_IX86) static_assert(sizeof(BfOccupiedVehicleData) == 44, "native x86 Data/map/seven handles"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/BfOccupiedVehicleNode.cpp b/Code/BF2/Menu/BfOccupiedVehicleNode.cpp index 865079ddc..23ce672ed 100644 --- a/Code/BF2/Menu/BfOccupiedVehicleNode.cpp +++ b/Code/BF2/Menu/BfOccupiedVehicleNode.cpp @@ -105,7 +105,7 @@ void BfOccupiedVehicleNode::paintSelf(System* system, const NodeState*, RenderContext* context) { if (!m_data) return; - const int texture = m_data->getOccupantTexture(system, m_seat); + const TextureHandle texture = m_data->getOccupantTexture(system, m_seat); Rect placed; placed.x = static_cast(*m_positionX) + bounds->x; // fild then fadd placed.y = static_cast(*m_positionY) + bounds->y; @@ -138,7 +138,9 @@ TypeDescriptor* const registeredBfOccupiedVehicleNodeType = BfOccupiedVehicleNode::getClassType(); } +#if defined(_M_IX86) static_assert(sizeof(BfOccupiedVehicleNodeTypeDescriptor) == 16, "client BF2 occupied metadata"); static_assert(sizeof(BfOccupiedVehicleNode) == 44, "native BfOccupiedVehicleNode storage"); +#endif } } #endif diff --git a/Code/BF2/Menu/BfOccupiedVehicleNode.h b/Code/BF2/Menu/BfOccupiedVehicleNode.h index f5a1e19c4..aa0ce6013 100644 --- a/Code/BF2/Menu/BfOccupiedVehicleNode.h +++ b/Code/BF2/Menu/BfOccupiedVehicleNode.h @@ -42,7 +42,9 @@ class BfOccupiedVehicleNode : public Node { int* m_positionY; // +20, starts &m_zero float m_width, m_height; // +24/+28, both fild'd from the ctor }; +#if defined(_M_IX86) static_assert(sizeof(BfOccupiedVehicleNode) == 44, "native BfOccupiedVehicleNode storage"); +#endif } } #endif #endif diff --git a/Code/BF2/Menu/BfTransformNode.cpp b/Code/BF2/Menu/BfTransformNode.cpp index 31ad592d5..6d010b6e1 100644 --- a/Code/BF2/Menu/BfTransformNode.cpp +++ b/Code/BF2/Menu/BfTransformNode.cpp @@ -1,6 +1,9 @@ // Menu transform node. [INFERRED] Source placement. // Inherited unimplemented Node operations retain their diagnostic stops. #include "BfTransformNode.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "../External/BFMeme/Data.h" #include "../External/BFMeme/NodeState.h" @@ -34,6 +37,8 @@ class BfTransformNodeTypeDescriptor final : public TypeDescriptor float decodedState(float value) // 7D2FBD..7D2FFC /838F40, binary32 store { +#if defined(_WIN32) +#if defined(_M_IX86) float result; __asm { fld value @@ -48,6 +53,20 @@ float decodedState(float value) // 7D2FBD..7D2FFC /838F40, binary32 store fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // Only an ordered negative value is decoded; zero, positive and NaN pass through the + // double round trip, which quiets a signalling NaN as fld/fstp does. + const double loaded = value; + return static_cast(value < 0.0f ? -(loaded + 1.0) : loaded); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float result; + // [CHOSEN, not recovered] Preserve x87 negative-state decoding and float store. + result = bf2x87::store(bf2x87::decoded(value)); + return result; +#endif } float stateRate(const NodeState& state) // 838F40 ->82BD30; unused receivers { @@ -59,6 +78,8 @@ float stateRate(const NodeState& state) // 838F40 ->82BD30; unused receivers } bool sumNotLess(float first, float second, float limit) { +#if defined(_WIN32) +#if defined(_M_IX86) bool result; __asm { fld first @@ -69,9 +90,24 @@ bool sumNotLess(float first, float second, float limit) setp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // setp after test ah,5: false only for an ordered sum below the limit. + const double sum = static_cast(first) + second; + return !(sum < limit); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + bool result; + // [CHOSEN, not recovered] Preserve x87 unordered-or-not-less sum. + result = bf2x87::sumNotLess(first, second, limit); + return result; +#endif } bool stateEnabled(float value) // 7D3230..7D325E; no float spill before comparison { +#if defined(_WIN32) +#if defined(_M_IX86) const float one = 1.0f; bool result; __asm { @@ -90,6 +126,20 @@ bool stateEnabled(float value) // 7D3230..7D325E; no float spill before comparis setp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // The decoded value is compared unrounded; unordered compares pass. + const double decoded = value < 0.0f ? -(static_cast(value) + 1.0) : value; + return !(decoded < 1.0); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float one = 1.0f; + bool result; + // [CHOSEN, not recovered] Preserve x87 unspilled decoded state comparison. + result = bf2x87::notLess(bf2x87::decoded(value), bf2x87::wide(one)); + return result; +#endif } } @@ -194,6 +244,8 @@ bool BfTransformNode::updateSelf(System* system, const NodeState*, const Rect*, sampleData(system); return true; } +#if defined(_M_IX86) static_assert(sizeof(BfTransformNode) == 80, "client BfTransformNode layout"); +#endif } } #endif diff --git a/Code/BF2/Menu/DifFontMetadata.cpp b/Code/BF2/Menu/DifFontMetadata.cpp index 013b61976..53b5ab2da 100644 --- a/Code/BF2/Menu/DifFontMetadata.cpp +++ b/Code/BF2/Menu/DifFontMetadata.cpp @@ -164,6 +164,8 @@ int DifFontMetadata::resolutionForWidth(int& width) } } static_assert(sizeof(DifGlyph) == 32, "eight-word scalar glyph record"); +#if defined(_M_IX86) static_assert(sizeof(DifFontMetadata) == 100, "native x86 STL metadata"); +#endif } } } #endif diff --git a/Code/BF2/Menu/Font.cpp b/Code/BF2/Menu/Font.cpp index 5a7624f06..946984678 100644 --- a/Code/BF2/Menu/Font.cpp +++ b/Code/BF2/Menu/Font.cpp @@ -102,9 +102,11 @@ bool BitmapFont::drawCharacter(int character, meme::Quad* quad) m_texture->drawUV(quad, glyph.u, glyph.v, u1, v1); return true; } +#if defined(_M_IX86) static_assert(sizeof(Font) == 32, "native x86 string-bearing Font"); static_assert(sizeof(DifFont) == 40, "native x86 DifFont"); static_assert(sizeof(BitmapFont) == 52, "native x86 BitmapFont"); +#endif static_assert(sizeof(BitmapGlyph) == 16, "four scalar glyph values"); } } } #endif diff --git a/Code/BF2/Menu/HudAmmo.cpp b/Code/BF2/Menu/HudAmmo.cpp index 0d186d407..8ba612a21 100644 --- a/Code/BF2/Menu/HudAmmo.cpp +++ b/Code/BF2/Menu/HudAmmo.cpp @@ -1,5 +1,8 @@ // Weapon status and ammunition display. #include "HudAmmo.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "BF2HudManager.h" #include "HudBlinker.h" @@ -39,7 +42,11 @@ #include "../External/BFMeme/Data.h" #include "../External/BFMeme/System.h" #include "../External/BFMeme/Pointer.h" +#if defined(_WIN32) #include +#elif defined(__APPLE__) +#include "../Platform/macOS/MacSystem.h" // [CHOSEN, not recovered] MessageBoxA's counterpart +#endif #include #include #include // wcscmp / wcslen - the wide updateString @@ -254,7 +261,7 @@ void HudAmmo::updatePointer(bool enabled) { if (hudManager->isPointerEnabled() == enabled) return; if (enabled) { - const int texture = m_system->loadTexture(m_field1a0, true); + const meme::TextureHandle texture = m_system->loadTexture(m_field1a0, true); const int mode = hudManager->getMode(); hudManager->enablePointer(texture, mode); auto* pointer = static_cast(m_system->getPointerObject()); @@ -1010,7 +1017,9 @@ bool abilityFlag(world::IAbilityGLComp* ability, unsigned index) } float armorAbilityRatio(float hitPoints, float maximum, float previous, bool blend) { +#if defined(_WIN32) const float half = 0.5f; +#if defined(_M_IX86) float result; __asm { fld hitPoints @@ -1023,11 +1032,27 @@ float armorAbilityRatio(float hitPoints, float maximum, float previous, bool ble fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + double ratio = static_cast(hitPoints) / maximum; + if (blend) ratio = (ratio + previous) * half; + return static_cast(ratio); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float half = 0.5f; + float result; + // [CHOSEN, not recovered] Preserve x87 retained division and optional blend. + result = bf2x87::armorRatio(hitPoints, maximum, previous, blend); + return result; +#endif } float ammoAbilityRatio(int status, float previous, bool blend) { +#if defined(_WIN32) const float scale = 0.06666667014360428f; // PE934BB0, bits3D888889 const float half = 0.5f; +#if defined(_M_IX86) float result; __asm { fild status @@ -1040,6 +1065,21 @@ float ammoAbilityRatio(int status, float previous, bool blend) fstp result } return result; +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + double ratio = static_cast(status) * scale; + if (blend) ratio = (ratio + previous) * half; + return static_cast(ratio); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + const float scale = 0.06666667014360428f; // PE934BB0, bits3D888889 + const float half = 0.5f; + float result; + // [CHOSEN, not recovered] Preserve x87 signed integer multiply and optional blend. + result = bf2x87::ammoRatio(status, previous, blend); + return result; +#endif } const char repairAbilityIcon[] = "Ingame/Player/Bars/abilitybar_smallRepairIcon.tga"; const char medicAbilityIcon[] = "Ingame/Player/Bars/abilitybar_smallMedicIcon.tga"; @@ -1228,7 +1268,11 @@ bool registerReference(meme::System* system, Value* value, return true; // The registration result is discarded. } const std::string caption = formatString("Failed to register: %s in %s", name.c_str(), container.c_str()); +#if defined(__APPLE__) + macos::showMessageBox("Error RegisterData", caption.c_str()); +#else MessageBoxA(0, "Error RegisterData", caption.c_str(), 0); // Retail text/caption order. +#endif return false; } } diff --git a/Code/BF2/Menu/HudArtillerySeams.h b/Code/BF2/Menu/HudArtillerySeams.h index 40b63c8a6..297bf464b 100644 --- a/Code/BF2/Menu/HudArtillerySeams.h +++ b/Code/BF2/Menu/HudArtillerySeams.h @@ -6,8 +6,8 @@ #include "../Math/Vec3.h" namespace dice { namespace hfe { namespace ai { class IAIEventCourier; -// [FRONTIER] [CHOSEN, not recovered] Artillery request dispatch with team and target position. -// [RETIRE-WHEN: HUD-ARTILLERY-COURIER] Define after the courier's complete typed interface and request path are validated. +// Artillery request dispatch with team and target position: IAIEventCourier::event_incomingArtillery. +// [INFERRED] helper name; defined in BF2HudManagerAbilities.cpp. void dispatchArtilleryRequest(IAIEventCourier*, int team, Vec2 target); } } } #endif diff --git a/Code/BF2/Menu/HudBlinker.h b/Code/BF2/Menu/HudBlinker.h index dc3df731f..de006a19c 100644 --- a/Code/BF2/Menu/HudBlinker.h +++ b/Code/BF2/Menu/HudBlinker.h @@ -27,8 +27,10 @@ class HudBlinker bool m_adaptive; // +0x1C float m_elapsed; // +0x20 }; +#if defined(_M_IX86) static_assert(sizeof(void*) == 4, "HUD recovery requires x86"); static_assert(sizeof(HudBlinker) == 0x24, "Non-STL retail blink-controller layout"); +#endif // [INFERRED] names/inheritance: the same 0x24-byte prefix, sole update slot and // base-pointer ownership at 0x7A6004 / 0x46B500 establish these controller variants. @@ -39,7 +41,9 @@ class HudHighBlinker : public HudBlinker float period, float otherPeriod, bool adaptive); void update(float dt) override; }; +#if defined(_M_IX86) static_assert(sizeof(HudHighBlinker) == 0x24, "Retail high-threshold blink layout"); +#endif class HudFloatBlinker : public HudBlinker { @@ -54,7 +58,9 @@ class HudFloatBlinker : public HudBlinker bool* m_gate; // +0x30 bool m_gateValue; // +0x34 }; +#if defined(_M_IX86) static_assert(sizeof(HudFloatBlinker) == 0x38, "Retail float-output blink layout"); +#endif class HudBlinkManager { diff --git a/Code/BF2/Menu/HudChat.cpp b/Code/BF2/Menu/HudChat.cpp index fe920a838..a3feefb3e 100644 --- a/Code/BF2/Menu/HudChat.cpp +++ b/Code/BF2/Menu/HudChat.cpp @@ -223,7 +223,7 @@ void HudChat::appendMessage(std::wstring text, int kind, int team, int first, wrapMessage(6, text, team, first, count, capacity, row); break; case 4: { - const int icon = hudManager->getPlayerRankIcon(player); + const meme::TextureHandle icon = hudManager->getPlayerRankIcon(player); m_data->setImageCell(0, row, icon, 16,16,1,-1, 1,1,1,1, 0); std::wstring decorated = std::wstring(L"\xA7" L"1") + text; wrapMessage(4, decorated + L"\xA7" L"0", team, first, count, capacity, row); @@ -231,7 +231,7 @@ void HudChat::appendMessage(std::wstring text, int kind, int team, int first, } case 5: { path = "Ingame/GeneralIcons/empty.dds"; - const int icon = m_system->loadTexture(std::string(path).c_str(), true); + const meme::TextureHandle icon = m_system->loadTexture(std::string(path).c_str(), true); m_data->setImageCell(0, row, icon, 18,11,1,7, 1,1,1,1, 0); std::wstring decorated = std::wstring(L"\xA7" L"1") + text; wrapMessage(5, decorated + L"\xA7" L"0", team, first, count, capacity, row); @@ -269,11 +269,13 @@ void HudChat::wrapMessage(int kind, std::wstring text, int team, int first, } meme::System* system = castChatSystem(hudManager->getSystem()); unsigned int consumed = m_data->measureText(system, text.substr(offset, text.size() - offset), 1, row, &nextMode); - const unsigned int remaining = text.size() - offset; + // 32-bit counts as on x86; a missing space (npos) still narrows to 0xFFFFFFFF on x64. + const unsigned int remaining = static_cast(text.size() - offset); bool skipSpace = false; if (consumed >= remaining) consumed = remaining; else { - const unsigned int space = text.substr(offset, consumed + 1).rfind(L' ', consumed); + const unsigned int space = static_cast( + text.substr(offset, consumed + 1).rfind(L' ', consumed)); if (static_cast(space) > 0 && consumed - space < 20) { consumed = space; skipSpace = true; } diff --git a/Code/BF2/Menu/HudCommander.cpp b/Code/BF2/Menu/HudCommander.cpp index 9b6b4e8de..fb202d9e8 100644 --- a/Code/BF2/Menu/HudCommander.cpp +++ b/Code/BF2/Menu/HudCommander.cpp @@ -1,5 +1,8 @@ // Commander HUD controls. [INFERRED] Owner, name and source placement. #include "HudCommander.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "BF2HudManager.h" #include "Bf2MenuMapNode.h" @@ -71,6 +74,8 @@ namespace { // subtraction before its separate float store, not the rounded remaining field. void updateCooldown(float deadline, double now, float duration, float& remaining, float& fraction) { +#if defined(_WIN32) +#if defined(_M_IX86) float* remainingValue = &remaining; float* fractionValue = &fraction; __asm { @@ -82,6 +87,20 @@ void updateCooldown(float deadline, double now, float duration, float& remaining mov eax, fractionValue fstp dword ptr [eax] } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // The fraction divides the unrounded difference, not the stored remaining value. + const double left = static_cast(deadline) - now; + remaining = static_cast(left); + fraction = static_cast(left / duration); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + float* remainingValue = &remaining; + float* fractionValue = &fraction; + // [CHOSEN, not recovered] Preserve x87 retained remaining value for fraction. + bf2x87::cooldown(deadline, now, duration, remaining, fraction); +#endif } } HudCommander::HudCommander(meme::System* system) @@ -264,9 +283,9 @@ void HudCommander::appendMemberCells(world::IPlayer* player, int slot, int squad { const int sel = isSquadSelected(squad); // +0x30 meme::Color text = commanderIconColors[sel]; // A1C6B8, copied now - int frame = m_textures[3]; // +FC iconframe + meme::TextureHandle frame = m_textures[3]; // +FC iconframe if (player && world::playerManager->getNrOfPlayersInSquad(m_team, squad) > 0) { // PE +0x9C - int icon = hudManager->getPlayerVehicleIcon(player, true); // +0x60 + meme::TextureHandle icon = hudManager->getPlayerVehicleIcon(player, true); // +0x60 if (!icon) { icon = hudManager->getPlayerKitIcon(player, false, false); // +0x64 if (!icon) @@ -358,9 +377,9 @@ void HudCommander::appendLeaderVoipCells(int squad) mutedLocally = true; break; } - int icon; + meme::TextureHandle icon; if (mutedLocally) - icon = m_textures[4]; // +100 voipMuteGreyCommander + icon = m_textures[4]; // +100 voipMuteGreyCommander else if (leader->getIsMuted()) // PE +0x274 icon = m_textures[5]; // +104 voipMuteCommander else if (leader->getIsTalking()) { // PE +0x278 @@ -395,7 +414,7 @@ void HudCommander::appendLeaderVoipCells(int squad) // Appends the pending request indicators. void HudCommander::appendRequestCells(int squad) { - int icon = m_textures[8]; // +110 empty.tga + meme::TextureHandle icon = m_textures[8]; // +110 empty.tga const int sel = isSquadSelected(squad); static_cast(squadManager)->getSquadInfo(m_team, squad); // +0x28, dropped if (world::playerManager->getNrOfPlayersInSquad(m_team, squad) == 0) { diff --git a/Code/BF2/Menu/HudCommander.h b/Code/BF2/Menu/HudCommander.h index c4b753596..971f94324 100644 --- a/Code/BF2/Menu/HudCommander.h +++ b/Code/BF2/Menu/HudCommander.h @@ -7,6 +7,7 @@ #include "../Game/IEventListener.h" #include "../Game/IGame.h" #include +#include #include #include namespace dice { namespace meme { class System; class BfListBoxData; class Bf2MenuMapNode; } } @@ -102,7 +103,7 @@ class HudCommander : public IEventListener { // them. float m_field0b4, m_field0b8, m_field0bc, m_field0c0; // +B4..C0 int m_columnPositions[11]; // +C4..EC, initialized after event registration - int m_textures[14]; // +F0..124, initialized after event registration + std::intptr_t m_textures[14]; // +F0..124, meme texture handles; initialized after event registration float m_colors[8]; // +128..144 meme::BfListBoxData* m_data; // +148 untouched by constructor std::list m_mutedPlayers; // +14C; event59 stores signed player ids diff --git a/Code/BF2/Menu/HudConsoleBindings.cpp b/Code/BF2/Menu/HudConsoleBindings.cpp index fa5152ddf..9cc3a9397 100644 --- a/Code/BF2/Menu/HudConsoleBindings.cpp +++ b/Code/BF2/Menu/HudConsoleBindings.cpp @@ -2,6 +2,9 @@ // Complete BF2.exe A1781C list: 228 constructors75C964..77007E and their // static initialization order862D41..864291. #include "HudConsoleBindings.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "BF2HudManager.h" #include "Bf2HudBuilder.h" @@ -1400,6 +1403,7 @@ class HudBuilderFloatBinding final : public HudConsoleBinding { float argument; // Preserve FLD before the flag and fstp before getBuilder, including // the x87 behavior for a signaling NaN or nondefault exception mask. +#if defined(_MSC_VER) && defined(_M_IX86) __asm { mov eax, input fld dword ptr [eax] @@ -1407,6 +1411,18 @@ class HudBuilderFloatBinding final : public HudConsoleBinding { mov byte ptr [eax], 1 fstp argument } +#else +#if defined(_WIN32) + // [PLATFORM] x64: SSE2 conversions. The double round trip quiets a signalling NaN as + // fld/fstp does; its invalid-operation flag is raised in MXCSR instead of the x87 word. + const double loaded = *input; + *returnFlag = true; + argument = static_cast(loaded); +#else + // [CHOSEN, not recovered] Preserve x87 load before flag and float store before call. + argument = bf2x87::consoleFloat(input, returnFlag); +#endif +#endif m_result = (hudManager->getBuilder()->*Method)(argument); } void setArgFromString(int index, const std::string& value) override diff --git a/Code/BF2/Menu/HudInformationAdapter.cpp b/Code/BF2/Menu/HudInformationAdapter.cpp index fc31c9487..55c655ea2 100644 --- a/Code/BF2/Menu/HudInformationAdapter.cpp +++ b/Code/BF2/Menu/HudInformationAdapter.cpp @@ -15,7 +15,11 @@ #include "../Scene/Object/PlayerManager.h" #include "../External/BFMeme/Data.h" #include "../External/BFMeme/System.h" +#if defined(_WIN32) #include +#elif defined(__APPLE__) +#include "../Platform/macOS/MacSystem.h" // [CHOSEN, not recovered] MessageBoxA's counterpart +#endif #include namespace dice { namespace hfe { namespace world { extern IBase* scoreManager; } } } namespace dice { namespace hfe { namespace hud { @@ -36,7 +40,11 @@ bool registerBoolData(meme::System* system, bool* value, return true; } const std::string caption = formatString("Failed to register: %s in %s", name.c_str(), container.c_str()); +#if defined(__APPLE__) + macos::showMessageBox("Error RegisterData", caption.c_str()); +#else MessageBoxA(0, "Error RegisterData", caption.c_str(), 0); // caption/text ordering is retail +#endif return false; } bool __fastcall executeConsoleCommand(const std::string& command) diff --git a/Code/BF2/Menu/HudQuestionManager.cpp b/Code/BF2/Menu/HudQuestionManager.cpp index 2d13d1630..bccd34e24 100644 --- a/Code/BF2/Menu/HudQuestionManager.cpp +++ b/Code/BF2/Menu/HudQuestionManager.cpp @@ -1,5 +1,8 @@ // Client HUD questions and responses. [INFERRED] Names and source placement. #include "HudQuestionManager.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "../Core/System.h" #include "../Core/ClassManager.h" @@ -16,6 +19,10 @@ #include "HudSquad.h" #include "../Game/GeneralSettings.h" // getOutOfVoting, the +0x80 bridge (was HudQuestionSettings.h's seam) #include +// [CHOSEN, not recovered] SSE2 is used only by the Windows x64 arm; arm64 has no emmintrin.h. +#if defined(_WIN32) && !defined(_M_IX86) +#include +#endif namespace dice { namespace hfe { extern IBase* squadManager; @@ -41,16 +48,23 @@ void replyWithoutQuestion(bool affirmative) // PE787FF0, complete100 bytes } int voteMinutes(float seconds) { +#if defined(_WIN32) // PE7876C7 materializes the float product before ceil(float)->double463930; // the final x87 conversion truncates and preserves the caller's control word. const float fraction = 0.01666666753590107f; float minutes; +#if defined(_M_IX86) __asm { fld seconds fmul fraction fstp minutes } +#else + // The product of two floats is exact in double; the float store is the only rounding. + minutes = static_cast(static_cast(seconds) * fraction); +#endif const double rounded = std::ceil(static_cast(minutes)); +#if defined(_M_IX86) unsigned short saved, truncated; int result; __asm { fnstcw saved } @@ -62,6 +76,25 @@ int voteMinutes(float seconds) fldcw saved } return result; +#else + // cvttsd2si truncates like the chopped fistp, including the 0x80000000 indefinite result. + return _mm_cvttsd_si32(_mm_set_sd(rounded)); +#endif +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + // PE7876C7 materializes the float product before ceil(float)->double463930; + // the final x87 conversion truncates and preserves the caller's control word. + const float fraction = 0.01666666753590107f; + float minutes; + // [CHOSEN, not recovered] Preserve x87 product float store before ceil. + minutes = bf2x87::store(bf2x87::mul(bf2x87::wide(seconds), bf2x87::wide(fraction))); + const double rounded = std::ceil(static_cast(minutes)); + unsigned short saved, truncated; + int result; + // [CHOSEN, not recovered] Preserve x87 truncation without changing caller rounding mode. + result = bf2x87::integer(bf2x87::wide(rounded)); + return result; +#endif } } diff --git a/Code/BF2/Menu/HudScoreboard.cpp b/Code/BF2/Menu/HudScoreboard.cpp index 73d1f1a79..4c6b7f84a 100644 --- a/Code/BF2/Menu/HudScoreboard.cpp +++ b/Code/BF2/Menu/HudScoreboard.cpp @@ -440,8 +440,8 @@ void HudScoreboard::paintRow(meme::BfListBoxData* list, world::IPlayer* player, { if (!player) return; - const int kitIcon = hudManager->getPlayerKitIcon(player, false, false); // PE +0x64 - const int rankIcon = hudManager->getPlayerRankIcon(player); // PE +0x68 + const meme::TextureHandle kitIcon = hudManager->getPlayerKitIcon(player, false, false); // PE +0x64 + const meme::TextureHandle rankIcon = hudManager->getPlayerRankIcon(player); // PE +0x68 const bool ownSide = m_team == team; const int side = ownSide ? 2 : 1; @@ -455,7 +455,7 @@ void HudScoreboard::paintRow(meme::BfListBoxData* list, world::IPlayer* player, text = scoreboardNameColors[side]; // the VoIP column's icon ------------------------------------------------------------ - int voipIcon = m_textures[1]; // checkbox_empty + meme::TextureHandle voipIcon = m_textures[1]; // checkbox_empty if (player->getVoipEnabled()) // PE +0x268 { bool decided = false; @@ -478,7 +478,7 @@ void HudScoreboard::paintRow(meme::BfListBoxData* list, world::IPlayer* player, } // the kick-vote column's icon ------------------------------------------------------- - int voteIcon = 0; + meme::TextureHandle voteIcon = 0; bool voteTarget = false; if (ClientVoteManager::getInstance()->votingEnabled() && !player->getIsAIPlayer()) { diff --git a/Code/BF2/Menu/HudScoreboard.h b/Code/BF2/Menu/HudScoreboard.h index e01a40eb6..c53fe80b7 100644 --- a/Code/BF2/Menu/HudScoreboard.h +++ b/Code/BF2/Menu/HudScoreboard.h @@ -78,7 +78,7 @@ class HudScoreboard : public IHudScoreboard, public IEventListener { std::uint32_t m_field048[9]; // +48..68 untouched scalar storage; meanings unresolved int m_counters[5][3][11]; // +6C..2FF, five integer totals per team/squad int m_columns[9]; // +300..320, initialized after event registration - int m_textures[13]; // +324..354, initialized after event registration + std::intptr_t m_textures[13]; // +324..354, meme texture handles; initialized after event registration std::list m_mutedPlayers; // retail+358, signed player ids, duplicate entries allowed bool m_toggleSquads, m_toggleScore, m_toggleManage, m_teamVoteOnly; // +364..367 meme::BfListBoxData* m_friendlyList; // +368, all five untouched by ctor and not deleted diff --git a/Code/BF2/Menu/HudSquad.cpp b/Code/BF2/Menu/HudSquad.cpp index 005077cf4..4fa587994 100644 --- a/Code/BF2/Menu/HudSquad.cpp +++ b/Code/BF2/Menu/HudSquad.cpp @@ -168,7 +168,7 @@ HudSquad::HudSquad(meme::System* system) m_selectedPlayers.clear(); m_excludedPlayers.clear(); m_invitePlayers.clear(); - for (int& icon : m_squadIcons) icon = 0; + for (std::intptr_t& icon : m_squadIcons) icon = 0; if (m_system) { m_textures[12] = m_system->loadTexture("Ingame/Kits/Icons/kit_Commander.tga", true); m_textures[13] = m_system->loadTexture("Ingame/Kits/Icons/kit_Squad.tga", true); @@ -451,7 +451,7 @@ void HudSquad::paintCommanderHeading(int team) meme::Color color = kColor97DE20; std::wstring text = hudManager->getLocalizedString( std::string("HUD_TEXT_MENU_SPAWN_SQUAD_APPLY")); - int arrow = m_textures[0]; // +14 button_upp + meme::TextureHandle arrow = m_textures[0]; // +14 button_upp if (!m_field09f) // +9F, expanded arrow = m_textures[1]; // +18 button_down if (m_isCommander) { // +9D @@ -567,7 +567,7 @@ void HudSquad::paintSquadRow(int team, int squad, int memberCount) else if (m_squadId == squad) buttonText = hudManager->getLocalizedString( std::string("HUD_TEXT_MENU_SPAWN_SQUAD_LEAVE")); // 78FDDF, copy-assigned - int arrow = m_textures[0]; // +14 button_upp + meme::TextureHandle arrow = m_textures[0]; // +14 button_upp const int bit = squad < 0 ? 0 : (squad > 9 ? 9 : squad); if (!m_expanded.test(static_cast(bit))) // _Xran 78FE1F unreachable arrow = m_textures[1]; // +18 button_down @@ -612,12 +612,12 @@ void HudSquad::paintPlayerRow(world::IPlayer* player, int) { if (!player) return; - const int kitIcon = hudManager->getPlayerKitIcon(player, false, false); // +64 + const meme::TextureHandle kitIcon = hudManager->getPlayerKitIcon(player, false, false); // +64 hudManager->getPlayerRankIcon(player); // +68, discarded - int vehicleIcon = hudManager->getPlayerVehicleIcon(player, true); // +60 + meme::TextureHandle vehicleIcon = hudManager->getPlayerVehicleIcon(player, true); // +60 if (!vehicleIcon) vehicleIcon = m_textures[2]; // empty.tga - int leaderIcon; + meme::TextureHandle leaderIcon; if (player->getIsSquadLeader()) { // PE +0x138 const int squad = player->getSquadId(); // read once if (!m_squadIcons[squad]) // unbounded @@ -627,7 +627,7 @@ void HudSquad::paintPlayerRow(world::IPlayer* player, int) } else { leaderIcon = m_textures[2]; } - int voipIcon = m_textures[10]; // icon_speaker + meme::TextureHandle voipIcon = m_textures[10]; // icon_speaker meme::Color voipColor = kColor97DE40; bool voipShown = false; if (player->getVoipEnabled()) { // PE +0x268 @@ -717,7 +717,7 @@ void HudSquad::paintPlayerRow(world::IPlayer* player, int) void HudSquad::paintInviteRow(world::IPlayer* player, int, int excludedSquad) { if (player) { - int checkIcon = m_textures[3]; // checkbox_empty + meme::TextureHandle checkIcon = m_textures[3]; // checkbox_empty if (excludedSquad < 0 && player->getSquadId() != m_squadId) { checkIcon = m_textures[2]; // no box } else { diff --git a/Code/BF2/Menu/HudSquad.h b/Code/BF2/Menu/HudSquad.h index e8badb27b..fc3e95a2f 100644 --- a/Code/BF2/Menu/HudSquad.h +++ b/Code/BF2/Menu/HudSquad.h @@ -88,9 +88,9 @@ class HudSquad : public IEventListener { const char* m_title; // +08 owned unless sentinel const wchar_t* m_unassignedText; // +0C owned unless sentinel const wchar_t* m_squadCountText; // +10 owned unless sentinel - int m_textures[14]; // +14..48 + std::intptr_t m_textures[14]; // +14..48, meme texture handles // Lazy per-squad icon cache. Squad indices are unchecked; failed loads retry on the next paint. - int m_squadIcons[10]; // +4C..70 + std::intptr_t m_squadIcons[10]; // +4C..70 std::uint32_t m_field074; // untouched by constructor // Current row count and last painted local-player row. The latter can remain stale when its squad is collapsed. int m_rowCount, m_localPlayerRow; // +78/+7C zero diff --git a/Code/BF2/Menu/HudVehicleFrontiers.cpp b/Code/BF2/Menu/HudVehicleFrontiers.cpp index 19384e9ba..22c93ea28 100644 --- a/Code/BF2/Menu/HudVehicleFrontiers.cpp +++ b/Code/BF2/Menu/HudVehicleFrontiers.cpp @@ -1,5 +1,8 @@ // Vehicle HUD layout, occupant display and warning handling. // [RETIRE-WHEN: hud-vehicle-leaf-frontiers] Complete and validate the corresponding HudVehicleFrontiers operation. +#if defined(__APPLE__) +#include "../Platform/X87Compat.h" // [CHOSEN, not recovered] x87 conversion results, including invalid inputs. +#endif #include "HudVehicleInformation.h" #if !DEDICATED #include "HudVehiclePostProcessing.h" @@ -554,7 +557,11 @@ void HudVehicleInformation::updateVehicleAngles(world::IObject* vehicle) const double vx = velocity.x; const double vy = velocity.y; const double vz = velocity.z; +#if defined(__APPLE__) + const int speed = bf2x87::toIntTruncate(std::sqrt((vx * vx + vy * vy) + vz * vz)); // fsqrt, fistp +#else const int speed = static_cast(std::sqrt((vx * vx + vy * vy) + vz * vz)); // fsqrt, fistp +#endif assignString(m_speedString, // +0x280 formatString("%i", speed * 10).c_str()); // *10 after the truncation diff --git a/Code/BF2/Menu/HudVehicleInformation.cpp b/Code/BF2/Menu/HudVehicleInformation.cpp index 921475010..c10e89ace 100644 --- a/Code/BF2/Menu/HudVehicleInformation.cpp +++ b/Code/BF2/Menu/HudVehicleInformation.cpp @@ -1,5 +1,8 @@ // HUD vehicle information. [INFERRED] Class and source placement. #include "HudVehicleInformation.h" +#if !defined(_MSC_VER) || !defined(_M_IX86) +#include "../Math/PortableX87.h" +#endif #if !DEDICATED #include "HudBlinker.h" #include "BF2HudManager.h" @@ -36,7 +39,14 @@ #include #include #include +#if defined(_WIN32) #include +#elif defined(__APPLE__) +#include "../Platform/macOS/MacSystem.h" // [CHOSEN, not recovered] MessageBoxA's counterpart +#endif +#if !defined(_M_IX86) +#include +#endif namespace dice { namespace hfe { extern ClassManager* classManager; extern IBase* squadManager; } } namespace dice { namespace hfe { namespace hud { @@ -541,7 +551,11 @@ bool registerVehicleFloat(meme::System* system, float* value, return true; } const std::string caption = formatString("Failed to register: %s in %s", name.c_str(), container.c_str()); +#if defined(__APPLE__) + macos::showMessageBox("Error RegisterData", caption.c_str()); +#else MessageBoxA(nullptr, "Error RegisterData", caption.c_str(), 0); // 785860, retail text/caption +#endif return false; } HudBlinker* makeVehicleBlinker(float* source, bool* output) @@ -676,6 +690,7 @@ int HudVehicleInformation::getGuiIndex() { return m_guiIndex; } void HudVehicleInformation::setMouseLook(bool active) { +#if defined(_WIN32) world::IPlayer* player = world::playerManager->getLocalHumanPlayer(); if (!player || !player->getCamera() || !player->getCamera()->getToggleMouseLook()) return; @@ -689,6 +704,7 @@ void HudVehicleInformation::setMouseLook(bool active) const float tolerance = 0.01f; const float first = m_playerAngle, second = m_vehicleAngle; bool aligned; +#if defined(_M_IX86) __asm { fld first fsub second @@ -698,8 +714,33 @@ void HudVehicleInformation::setMouseLook(bool active) test ah, 41h setnp aligned } +#else + // [PLATFORM] x64: SSE2 arithmetic (x87 keeps 80-bit intermediates). + // setnp after test ah,41h: an ordered difference at or below the tolerance. + aligned = std::fabs(static_cast(first) - second) <= tolerance; +#endif if (aligned) m_guiIndex = m_field0a4; } +#else +// [CHOSEN, not recovered] Preserve the S2.1 POSIX numeric arm (docs/macos-s2-1-asm.md). + world::IPlayer* player = world::playerManager->getLocalHumanPlayer(); + if (!player || !player->getCamera() || !player->getCamera()->getToggleMouseLook()) + return; + if (active) { + if (m_guiIndex) { + m_field0a4 = m_guiIndex; + m_guiIndex = 0; + } + } else if (!m_guiIndex) { + // Preserve the unrounded x87 subtraction and unordered rejection. + const float tolerance = 0.01f; + const float first = m_playerAngle, second = m_vehicleAngle; + bool aligned; + // [CHOSEN, not recovered] Preserve x87 retained absolute difference and ordered <=. + aligned = bf2x87::lessEqual(bf2x87::abs(bf2x87::sub(bf2x87::wide(first), bf2x87::wide(second))), bf2x87::wide(tolerance)); + if (aligned) m_guiIndex = m_field0a4; + } +#endif } // Updates proximity indicators for nearby medics, mechanics and ammunition sources. diff --git a/Code/BF2/Menu/HudVoip.cpp b/Code/BF2/Menu/HudVoip.cpp index 3caca4296..9bc333344 100644 --- a/Code/BF2/Menu/HudVoip.cpp +++ b/Code/BF2/Menu/HudVoip.cpp @@ -128,7 +128,7 @@ void HudVoip::paintRow(meme::BfListBoxData* list, world::IPlayer* player) } } - int icon = m_emptyTexture; + std::intptr_t icon = m_emptyTexture; if (!talking) { list->appendCell(0, std::string(), 1.0f, 1.0f, 1.0f, 1.0f, 0); list->appendCell(1, std::string(), 1.0f, 1.0f, 1.0f, 1.0f, 0); diff --git a/Code/BF2/Menu/HudVoip.h b/Code/BF2/Menu/HudVoip.h index 603ec54c2..87695d1a2 100644 --- a/Code/BF2/Menu/HudVoip.h +++ b/Code/BF2/Menu/HudVoip.h @@ -50,14 +50,17 @@ class HudVoip : public IHudVoip { int m_speakerColumnWidth; // +1C, ctor 15 int m_nameColumnWidth; // +20, ctor 30 float m_field024; // +24, ctor -1.0f; the cells' sixth float - int m_emptyTexture; // +28, Ingame/GeneralIcons/empty.tga - int m_speakerTexture; // +2C, Ingame/Respawn/icon_speaker.tga - int m_commanderTexture; // +30, Ingame/Kits/Icons/kit_Commander.tga + // Meme texture handles (pointer-sized; int on x86). + std::intptr_t m_emptyTexture; // +28, Ingame/GeneralIcons/empty.tga + std::intptr_t m_speakerTexture; // +2C, Ingame/Respawn/icon_speaker.tga + std::intptr_t m_commanderTexture; // +30, Ingame/Kits/Icons/kit_Commander.tga // +34..+58. Per-squad minimap icons, loaded lazily by the row painter. - int m_squadTextures[10]; // ctor 0 + std::intptr_t m_squadTextures[10]; // ctor 0 meme::BfListBoxData* m_data; // +5C, created by registerData, never deleted }; +#if defined(_M_IX86) static_assert(sizeof(HudVoip) == 0x60, "retail and native HudVoip storage"); +#endif } } } #endif #endif diff --git a/Code/BF2/Menu/ISwiffHost.h b/Code/BF2/Menu/ISwiffHost.h index bbce012ab..2aa68cc0c 100644 --- a/Code/BF2/Menu/ISwiffHost.h +++ b/Code/BF2/Menu/ISwiffHost.h @@ -2,6 +2,7 @@ #ifndef MENU_ISWIFFHOST_H #define MENU_ISWIFFHOST_H #include "../Core/IBase.h" +#include #include "../Game/IModInfo.h" #include "../Game/Persistence/PlayerAwards.h" // getCachedAwards (+0x228): IPlayerAwards::AwardList #include "../Game/Persistence/PlayerRankInfo.h" @@ -373,9 +374,12 @@ struct ISwiffHost : public IBase virtual std::string getCurrentMapGameMode() = 0; // +0x05C virtual int getCurrentMapMaxPlayers() = 0; // +0x060 virtual int getCurrentMapSize() = 0; // +0x064 - virtual bool setPlayerRenderCapability0(int value) = 0; // 26 +0x068 0x486E10 SwiffPlayer +0x60, then window +0x3B = 0 +// [CHOSEN, not recovered] x64 (https://github.com/B2BF/OpenBF2/issues/7): the render-capability +// chain (host +0x68/+0x70 -> player +0x60/+0x64 -> render slots 49/50) carries the address of a +// SwiffPlayer string, so it is intptr_t - int on x86, where signatures and mangling are unchanged. + virtual bool setPlayerRenderCapability0(intptr_t value) = 0; // 26 +0x068 0x486E10 SwiffPlayer +0x60, then window +0x3B = 0 virtual void* getCursor(int which) = 0; // 27 +0x06C 0x488960 hcursor: 0 arrow, 1 busy, 2 keybinding - virtual bool setPlayerRenderCapability1(int value) = 0; // 28 +0x070 0x486E80 SwiffPlayer +0x64 + virtual bool setPlayerRenderCapability1(intptr_t value) = 0; // 28 +0x070 0x486E80 SwiffPlayer +0x64 virtual void setFlag28(bool value) = 0; // 29 +0x074 0x5DF3C0 (ICF) [UNRESOLVED] role virtual bool getFlag28() = 0; // 30 +0x078 0x659F70 (ICF) virtual IServerBrowser* getServerList(const std::string& name) = 0; // 31 +0x07C 0x486D10 ServerBrowserManager +0x14 @@ -450,7 +454,7 @@ struct ISwiffHost : public IBase virtual bool playSound(const std::string& name) = 0; // 98 +0x188 0x493C70 event 6 (dice.bf2.Sound.playSound) virtual void slot18C(int a) = 0; // 99 +0x18C 0x488920 ds:0xA23DC0 +0xB4 [UNRESOLVED] virtual bool getModCount(int* out) = 0; // 100 +0x190 0x48A260 ModInfo list size - virtual bool slot194(int index, int b) = 0; // 101 +0x194 0x4A2B00 0x481490 on the indexed Mod [UNRESOLVED] + virtual bool getModAt(int index, IModInfo::Mod* out) = 0; // 101 +0x194 0x4A2B00 *out = mods[index] (0x481490); [INFERRED] name, pointer spelling virtual bool requestActivateMod(const std::string* mod) = 0; // 102 +0x198 0x493CE0 event 11; null -> "no mod specified" virtual bool requestBrowseModHomepage(const IModInfo::Mod* mod) = 0; // 103 +0x19C 0x493E00 event 10 with the mod's url virtual bool getVersionString(std::string& out) = 0; // 104 +0x1A0 0x486D60 "1.5.3153-802." @@ -571,7 +575,9 @@ struct ISwiffHost : public IBase virtual void setIntF4C(int value) = 0; // 215 +0x35C 0x489080 GameLogic sentinel / EndOfRoundEvent virtual bool isPlayingDemo() = 0; // +0x360 virtual std::string getModName() = 0; // 217 +0x364 0x4890B0 GSModDirectory's leaf, lowercased - virtual bool slot368(int a, int b, int c) = 0; // 218 +0x368 0x626200 constant true + // Argument types from SwiffPlayer 0x1004F91E (Mod.activateModAndJoinServer pushes the addresses of + // "mods/"+mod and the address string, then the port); BF2.exe 0x626200 is `mov al,1; ret 0Ch`. + virtual bool slot368(const std::string& modPath, const std::string& address, int port) = 0; // 218 +0x368 0x626200 constant true virtual int getExpansionPack(const std::string& modName) = 0; // 219 +0x36C 0x4890D0 1 xpack, 2 xpack2 virtual std::string getLanguageSetting() = 0; // 220 +0x370 0x489190 GSLanguage, "English" virtual void parseResolution(const std::string& text, int* width, int* height, int* hz) = 0; // 221 +0x374 0x489210 "x@Hz" tokens diff --git a/Code/BF2/Menu/ISwiffPlayer.h b/Code/BF2/Menu/ISwiffPlayer.h index c1c86db62..45ca198d8 100644 --- a/Code/BF2/Menu/ISwiffPlayer.h +++ b/Code/BF2/Menu/ISwiffPlayer.h @@ -2,6 +2,7 @@ #ifndef MENU_ISWIFFPLAYER_H #define MENU_ISWIFFPLAYER_H #include "../Core/IBase.h" +#include #include #if !DEDICATED namespace dice { namespace hfe { namespace ui { @@ -32,11 +33,16 @@ class ISwiffPlayer : public IBase virtual void getTextInput1(std::string& out) = 0; // 21 +0x54 the clipboard cut virtual void setSwiffHost(ISwiffHost* host) = 0; // 22 +0x58 init virtual ISwiffHost* getSwiffHost() = 0; // 23 +0x5C onResize - virtual char renderCapability0(int a) = 0; // 24 +0x60 SwiffHost 0x486E10 - virtual char renderCapability1(int a) = 0; // 25 +0x64 SwiffHost 0x486E80 + virtual char renderCapability0(intptr_t a) = 0; // 24 +0x60 SwiffHost 0x486E10 + virtual char renderCapability1(intptr_t a) = 0; // 25 +0x64 SwiffHost 0x486E80 virtual int getMovieWidth() = 0; // 26 +0x68 init / onResize virtual int getMovieHeight() = 0; // 27 +0x6C init / onResize - virtual void renderSetPairState(int a, int b) = 0; // 28 +0x70 +#if defined(_MSC_VER) + virtual void renderSetPairState(intptr_t a, int b) = 0; // 28 +0x70 a: texture name address +#else + // [CHOSEN, not recovered] Native: SwiffPlayer 0x10005F50 forwards to SwiffRender::setTextureTechnique. + virtual void renderSetPairState(const std::string& textureName, int techniqueIndex) = 0; +#endif virtual void legacyModeOff() = 0; // 29 +0x74 virtual void legacyModeOn() = 0; // 30 +0x78 virtual char getModeFlag() = 0; // 31 +0x7C diff --git a/Code/BF2/Menu/ISwiffRender.h b/Code/BF2/Menu/ISwiffRender.h index 46b834fa0..ab09c1bbf 100644 --- a/Code/BF2/Menu/ISwiffRender.h +++ b/Code/BF2/Menu/ISwiffRender.h @@ -2,6 +2,7 @@ #ifndef MENU_ISWIFFRENDER_H #define MENU_ISWIFFRENDER_H #include "../Core/IBase.h" +#include #include #if !DEDICATED namespace dice { namespace hfe { namespace ui { @@ -12,7 +13,13 @@ struct ISwiffRender : public IBase virtual int shutdown() = 0; // +0x14 virtual int slot6() = 0; // +0x18 virtual int uploadAlpha(unsigned int w, unsigned int h, const void* data) = 0; // 7 +0x1C +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] SwiffPlayer 0x10005B56 passes its image::rgb*; RendDX9 + // 0x101529D0 ignores it and answers -1 (docs/macos-c-swiff-re.md). + virtual int slot8(void* rgbImage) = 0; +#else virtual int slot8(int a) = 0; // +0x20 +#endif virtual int uploadRgba(unsigned int* desc) = 0; // 9 +0x24 virtual int loadTexture(const char* name, unsigned int* outW, unsigned int* outH) = 0; // 10 +0x28 virtual int releaseTexture(int id) = 0; // +0x2C @@ -35,13 +42,26 @@ struct ISwiffRender : public IBase unsigned int e) = 0; // 25 +0x64 0x10152DE0 retn 14h virtual void* createFont(const char* name, int size) = 0; // +0x68 virtual void releaseFontHandle(void* font) = 0; // +0x6C +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] The native renderer thunk consumes text, not a 32-bit carrier. + virtual int fontForward16(void* font, const wchar_t* text) = 0; +#else virtual int fontForward16(void* font, int arg) = 0; // +0x70 +#endif virtual int destroyFont(void* font) = 0; // +0x74 virtual void drawGlyphBitmap(void* font, const float* m2x3, unsigned int rgba, int unused) = 0; // 30 +0x78 virtual char fontGetExtent(void* font, int arg, float* outW, float* outH) = 0; // +0x7C +#if !defined(_MSC_VER) + // [CHOSEN, not recovered] Shipped text hit / selection outs are pointers: SwiffPlayer + // 0x10005E20/0x10005E50 push stack-slot addresses; RendDX9 0x100A48C0 and 0x10152080 store + // through them (docs/macos-c-swiff-re.md). + virtual char fontForward32(void* font, int* outPos, float x, float y) = 0; + virtual char fontForward40(void* font, int* outA, int* outB) = 0; +#else virtual char fontForward32(void* font, int arg, float x, float y) = 0; // +0x80 virtual char fontForward40(void* font, int a, int b) = 0; // +0x84 +#endif virtual char fontForward44(void* font, float x1, float y1, float x2, float y2) = 0; // +0x88 virtual int fontForward48(void* font) = 0; // +0x8C virtual int fontSetSize(void* font, float size, int flag) = 0; // +0x90 @@ -57,8 +77,8 @@ struct ISwiffRender : public IBase virtual void setMouseState(int x, int y, int buttons) = 0; // +0xB8 virtual int slot47(int a) = 0; // +0xBC virtual void nullsub48(int a) = 0; // 48 +0xC0 0x10153380 retn 4 - virtual char slot49(int a) = 0; // +0xC4 - virtual char slot50(int a) = 0; // +0xC8 + virtual char slot49(intptr_t a) = 0; // +0xC4 + virtual char slot50(intptr_t a) = 0; // +0xC8 virtual int beginFrame() = 0; // 51 +0xCC BF2.exe 0x4A2C26's call virtual int endFrame() = 0; // 52 +0xD0 MainMenuLogic::endFrame virtual void* setTextureTechnique(const std::string& name, int index) = 0; // 53 +0xD4 diff --git a/Code/BF2/Menu/MainMenuLogic.cpp b/Code/BF2/Menu/MainMenuLogic.cpp index 558805f3c..0107856e2 100644 --- a/Code/BF2/Menu/MainMenuLogic.cpp +++ b/Code/BF2/Menu/MainMenuLogic.cpp @@ -1,7 +1,11 @@ // Client main-menu lifecycle and input handling. [INFERRED] Source placement. #include "../Core/BuildConfig.h" #if !DEDICATED +#if defined(_WIN32) #include +#elif defined(__APPLE__) +#include "../Platform/macOS/CocoaHost.h" // [CHOSEN, not recovered] cursor, modifiers, clipboard +#endif #include "MainMenuLogic.h" #include "IMenuTeamManager.h" #include "ISwiffHost.h" @@ -167,8 +171,13 @@ bool MainMenuLogic::init() m_scaleY = movieHeight / static_cast(height); io::IInputDevice* mouse = static_cast(io::inputDeviceManager)->getInputDevice(io::IDFMouse); mouse->deActivate(); // +0x20, unguarded in the binary +#if defined(__APPLE__) + macos::CocoaHost::instance().showCursor(true); // [CHOSEN] ShowCursor(TRUE) + macos::CocoaHost::instance().setCursor(m_host->getCursor(0)); // +0x6C, SetCursor +#else ShowCursor(TRUE); SetCursor(static_cast(m_host->getCursor(0))); // +0x6C +#endif io::g_falconMouseMode = 1; // ds:0x978FC4 if (!s_firstInitDone) { @@ -199,8 +208,13 @@ void MainMenuLogic::deactivate() } m_swiffActive = false; m_frameActive = false; +#if defined(__APPLE__) + macos::CocoaHost::instance().setCursor(0); // [CHOSEN] SetCursor(0) + macos::CocoaHost::instance().showCursor(false); // ShowCursor(FALSE) +#else SetCursor(0); ShowCursor(FALSE); +#endif } ui::ISwiffPlayer* MainMenuLogic::getSwiffPlayer() const { return m_player; } @@ -219,7 +233,11 @@ bool MainMenuLogic::beginFrame() { ui::ISwiffHost* host = m_host; const int busy = host->getBusy(); // +0x2B8 +#if defined(__APPLE__) + macos::CocoaHost::instance().setCursor(host->getCursor(busy)); // +0x6C, [CHOSEN] SetCursor +#else SetCursor(static_cast(host->getCursor(busy))); // +0x6C +#endif if (!m_render->beginFrame() || !m_player->isMovieLoaded()) // +0xCC / +0x20 return false; m_frameActive = true; @@ -282,6 +300,38 @@ bool MainMenuLogic::handleInput(io::GameInput&) // 0x4A2E10 (263 B): with Ctrl held (and not Alt), 'v' pastes CF_TEXT into the player's text // input, 'c' and 'x' copy the player's text out; any other Ctrl character is swallowed. +#if defined(__APPLE__) +// [CHOSEN, not recovered] macOS: the same arms on the Cocoa host. Control or Command counts as +// Ctrl and Option as Alt (BF2.cpp's controlKeyDown/altKeyDown); the clipboard text is +// Windows-1252, the CF_TEXT counterpart. A clipboard the host cannot open or read is skipped, as +// a failed OpenClipboard or an absent CF_TEXT is. +bool MainMenuLogic::handleClipboardShortcut(char character) +{ + macos::CocoaHost& host = macos::CocoaHost::instance(); + const unsigned int modifiers = host.modifierFlags(); + const bool control = (modifiers & (macos::HostModControl | macos::HostModCommand)) != 0; + const bool alt = (modifiers & macos::HostModOption) != 0; + if (!control || (control && alt)) + return false; + if (character != 'v') + { + if (character == 'c' || character == 'x') + { + std::string text; + if (character == 'c') + m_player->getTextInput0(text); // +0x50 + else + m_player->getTextInput1(text); // +0x54 + host.setClipboardText(std::string(text.c_str())); // up to the terminator + } + return true; + } + std::string text; + if (host.getClipboardText(text)) + m_player->setTextInput(text.c_str()); // +0x4C + return true; +} +#else bool MainMenuLogic::handleClipboardShortcut(char character) { if (!GetAsyncKeyState(VK_CONTROL) || (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(VK_MENU))) @@ -332,6 +382,7 @@ bool MainMenuLogic::handleClipboardShortcut(char character) CloseClipboard(); return true; } +#endif // the console pointer, and the console taken inactive when one is given. void MainMenuLogic::setConsole(BF2Console* console) diff --git a/Code/BF2/Menu/Ref2System.cpp b/Code/BF2/Menu/Ref2System.cpp index 57aba4534..285a32c97 100644 --- a/Code/BF2/Menu/Ref2System.cpp +++ b/Code/BF2/Menu/Ref2System.cpp @@ -18,6 +18,7 @@ #include #include #include +#include "../Core/MsvcCrtCompat.h" // [CHOSEN, not recovered] _splitpath outside MSVC namespace dice { namespace hfe { extern ClassManager* classManager; @@ -44,8 +45,10 @@ class Ref2SystemTypeDescriptor final : public meme::TypeDescriptor static int instanceCount; }; int Ref2SystemTypeDescriptor::instanceCount = 0; +#if defined(_M_IX86) static_assert(sizeof(Ref2SystemTypeDescriptor) == 16, "Ref2System metadata stores its counter separately"); +#endif // A20F78 is a plain dword whose bit zero is set before construction. Retail has no lock and no // exception rollback here; avoid the compiler's C++11 thread-safe function-static guard. @@ -248,7 +251,7 @@ meme::OStream* Ref2System::createOutputStream(const char* name) return storage ? new(storage) meme::FileOStream(path.c_str()) : nullptr; } -bool Ref2System::drawCharacter(int character, int handle, meme::Quad* quad) +bool Ref2System::drawCharacter(int character, meme::FontHandle handle, meme::Quad* quad) { Font* font = reinterpret_cast(handle); if (!font) { @@ -257,31 +260,31 @@ bool Ref2System::drawCharacter(int character, int handle, meme::Quad* quad) } return font->drawCharacter(character, quad); } -bool Ref2System::getGlyphMetrics(int character, int handle, meme::GlyphMetrics* out) +bool Ref2System::getGlyphMetrics(int character, meme::FontHandle handle, meme::GlyphMetrics* out) { Font* font = reinterpret_cast(handle); if (!font) font = m_fonts.begin()->second; // Shipped missing empty-map guard. return font->getGlyphMetrics(character, out); } -float Ref2System::getKerning(int previous, int current, int handle) +float Ref2System::getKerning(int previous, int current, meme::FontHandle handle) { Font* font = reinterpret_cast(handle); if (!font) font = m_fonts.begin()->second; return font->getKerning(previous, current); } -float Ref2System::getFontHeight(int handle) +float Ref2System::getFontHeight(meme::FontHandle handle) { Font* font = reinterpret_cast(handle); if (!font) font = m_fonts.begin()->second; return font->getHeight(); } -const char* Ref2System::getFontName(int handle) +const char* Ref2System::getFontName(meme::FontHandle handle) { return handle ? reinterpret_cast(handle)->getName() : nullptr; } -int Ref2System::loadFont(const char* name) +meme::FontHandle Ref2System::loadFont(const char* name) { const auto own = m_fonts.find(std::string(name)); - if (own != m_fonts.end()) return reinterpret_cast(own->second); + if (own != m_fonts.end()) return reinterpret_cast(own->second); const auto shared = sharedFonts.find(std::string(name)); Font* font; if (shared != sharedFonts.end()) { @@ -303,10 +306,10 @@ int Ref2System::loadFont(const char* name) sharedFonts.insert(std::make_pair(std::string(name), font)); } ++font->referenceCount(); - return reinterpret_cast(font); + return reinterpret_cast(font); } -bool Ref2System::drawTexture(int texture, meme::Quad* request) +bool Ref2System::drawTexture(meme::TextureHandle texture, meme::Quad* request) { if (texture) { geom::IMemeTexture* object = reinterpret_cast(texture); @@ -318,7 +321,7 @@ bool Ref2System::drawTexture(int texture, meme::Quad* request) } return m_blankTexture->drawOther(nullptr, request); } -int Ref2System::loadTexture(const char* name, bool menuPath) +meme::TextureHandle Ref2System::loadTexture(const char* name, bool menuPath) { geom::IMemeTexture* texture = m_textureList; while (texture) { @@ -332,9 +335,9 @@ int Ref2System::loadTexture(const char* name, bool menuPath) texture->setUserObject(m_textureList); m_textureList = texture; } - return reinterpret_cast(texture); + return reinterpret_cast(texture); } -void Ref2System::releaseTexture(int handle) +void Ref2System::releaseTexture(meme::TextureHandle handle) { if (!handle) return; geom::IMemeTexture* texture = reinterpret_cast(handle); @@ -351,15 +354,15 @@ void Ref2System::releaseTexture(int handle) texture->setUserObject(nullptr); texture->release(); } -const char* Ref2System::getTextureName(int handle) +const char* Ref2System::getTextureName(meme::TextureHandle handle) { return handle ? reinterpret_cast(handle)->getName() : nullptr; } -float Ref2System::getTextureWidth(int handle) // 7AD330, signed integer conversion +float Ref2System::getTextureWidth(meme::TextureHandle handle) // 7AD330, signed integer conversion { return handle ? static_cast(reinterpret_cast(handle)->getPixelWidth()) : 0.0f; } -float Ref2System::getTextureHeight(int handle) +float Ref2System::getTextureHeight(meme::TextureHandle handle) { return handle ? static_cast(reinterpret_cast(handle)->getPixelHeight()) : 0.0f; } diff --git a/Code/BF2/Menu/Ref2System.h b/Code/BF2/Menu/Ref2System.h index 71a7eb02c..73556d29b 100644 --- a/Code/BF2/Menu/Ref2System.h +++ b/Code/BF2/Menu/Ref2System.h @@ -37,18 +37,19 @@ class Ref2System : public meme::System meme::OStream* getOutputStream() override; meme::IStream* createInputStream(const char*) override; // +5C 7AD510 meme::OStream* createOutputStream(const char*) override; - bool drawCharacter(int, int, meme::Quad*) override; - bool getGlyphMetrics(int, int, meme::GlyphMetrics*) override; - float getKerning(int, int, int) override; - float getFontHeight(int) override; // +7C 7AE8E0 - int loadFont(const char*) override; - const char* getFontName(int) override; - bool drawTexture(int, meme::Quad*) override; - int loadTexture(const char*, bool) override; // +8C 7AD240 - void releaseTexture(int) override; - const char* getTextureName(int) override; - float getTextureWidth(int) override; - float getTextureHeight(int) override; // +9C 7AD300 + // Font handles are Font*, texture handles IMemeTexture* (pointer-sized meme handles). + bool drawCharacter(int, meme::FontHandle, meme::Quad*) override; + bool getGlyphMetrics(int, meme::FontHandle, meme::GlyphMetrics*) override; + float getKerning(int, int, meme::FontHandle) override; + float getFontHeight(meme::FontHandle) override; // +7C 7AE8E0 + meme::FontHandle loadFont(const char*) override; + const char* getFontName(meme::FontHandle) override; + bool drawTexture(meme::TextureHandle, meme::Quad*) override; + meme::TextureHandle loadTexture(const char*, bool) override; // +8C 7AD240 + void releaseTexture(meme::TextureHandle) override; + const char* getTextureName(meme::TextureHandle) override; + float getTextureWidth(meme::TextureHandle) override; + float getTextureHeight(meme::TextureHandle) override; // +9C 7AD300 void beginPaint() override; // +B0 7AE6B0 void endPaint() override; // +B4 7AD3B0 bool preUpdate(float delta) override; // +B8 7AD8B0 diff --git a/Code/BF2/Menu/SwiffHost.cpp b/Code/BF2/Menu/SwiffHost.cpp index 99d052a57..96fb3eb6e 100644 --- a/Code/BF2/Menu/SwiffHost.cpp +++ b/Code/BF2/Menu/SwiffHost.cpp @@ -2,8 +2,21 @@ // [RETIRE-WHEN: swiff-host-bodies] Complete and validate the corresponding SwiffHost operation. #include "../Core/BuildConfig.h" #if !DEDICATED +#if defined(_WIN32) #include // before windows.h: gethostbyname / inet_addr / inet_ntoa / ntohl #include +#else +// [CHOSEN, not recovered] Native POSIX: BSD sockets for the Winsock 1.1 calls (no WSAStartup); +// on macOS the Cocoa host for the cursor handles. docs/macos-port.md, "Win32 and CRT items". +#include +#include +#include +#include +#include +#if defined(__APPLE__) +#include "../Platform/macOS/CocoaHost.h" +#endif +#endif #include "SwiffHost.h" #include "IMenuTeamManager.h" #include "ISwiffPlayer.h" @@ -14,6 +27,7 @@ #include "../Core/Ids.h" #include "../Core/SettingsRepostitory.h" #include "../Core/StringUtil.h" // formatString, compareIgnoreCase, setLowerCase +#include "../Core/StringTokenizer.h" // parseResolution's "x@Hz" tokenizer (0x59E1B0/0x59E1F0) #include "../Core/SystemInfo.h" #include "../Game/IGame.h" #include "../Game/IGameLogic.h" @@ -67,7 +81,14 @@ std::string s_selectedServerAddress; // unk_9A6A04 setSelectedServer / int s_selectedServerQueryPort = 0; // dword_9A6708 int s_selectedServerHostPort = 0; // dword_9A670C char s_resolvedAddress[256]; // unk_9A6A28 resolveHostName's answer -unsigned long s_lastInetAddr = 0; // dword_9A6B28 isPrivateAddress's inet_addr result +// An IPv4 address word as inet_addr answers it: Winsock's 32-bit u_long, a 32-bit in_addr_t on the +// LP64 POSIX ports (where unsigned long would read past the 4-byte h_addr_list entry). +#if defined(_WIN32) +typedef unsigned long InetAddrWord; +#else +typedef std::uint32_t InetAddrWord; +#endif +InetAddrWord s_lastInetAddr = 0; // dword_9A6B28 isPrivateAddress's inet_addr result #define SWIFF_HOST_FRONTIER(method, evidence) \ do { \ std::fprintf(stderr, "[FRONTIER] dice::hfe::SwiffHost::" method " reached (" evidence ")\n"); \ @@ -139,7 +160,7 @@ void runMenuScript(const char* file) } // RFC 1918 test on a network-order address; a null pointer counts as private. -int isPrivateNetworkAddress(const unsigned long* address) +int isPrivateNetworkAddress(const InetAddrWord* address) { if (!address) return 1; @@ -422,7 +443,7 @@ int SwiffHost::getCurrentMapMaxPlayers() { return game ? game->getCurrentMapMaxP int SwiffHost::getCurrentMapSize() { return game ? game->getCurrentMapSize() : 0; } // SwiffPlayer +0x60, then the window stops hiding the cursor (+0x3B). -bool SwiffHost::setPlayerRenderCapability0(int value) +bool SwiffHost::setPlayerRenderCapability0(intptr_t value) { IBase* player = classManager->getSingleton(std::string("SwiffPlayer")); if (!player || !static_cast(player)->renderCapability0(value)) @@ -437,16 +458,30 @@ void* SwiffHost::getCursor(int which) if (s_cursorsLoaded) return m_cursors[which]; std::string arrow = io::fileManager->fileExistsEx(std::string("menu/external/flashmenu/cursor/cursor_arrow.ani"), true); +#if defined(__APPLE__) + // [CHOSEN, not recovered] AppKit cannot load .ani cursors; each handle is the host's token for + // the nearest system shape (the keybinding cursor shows the arrow), and null, as + // LoadCursorFromFileA answers, when the file cannot be read. docs/macos-s2-4.md, "Open items". + m_cursors[0] = (!arrow.empty() && ::access(arrow.c_str(), R_OK) == 0) + ? macos::CocoaHost::cursorHandle(macos::HostCursorArrow) : 0; + std::string busy = io::fileManager->fileExistsEx(std::string("menu/external/flashmenu/cursor/cursor_busy.ani"), true); + m_cursors[1] = (!busy.empty() && ::access(busy.c_str(), R_OK) == 0) + ? macos::CocoaHost::cursorHandle(macos::HostCursorBusy) : 0; + std::string keybinding = io::fileManager->fileExistsEx(std::string("menu/external/flashmenu/cursor/cursor_keybinding.ani"), true); + m_cursors[2] = (!keybinding.empty() && ::access(keybinding.c_str(), R_OK) == 0) + ? macos::CocoaHost::cursorHandle(macos::HostCursorArrow) : 0; +#else m_cursors[0] = LoadCursorFromFileA(arrow.c_str()); std::string busy = io::fileManager->fileExistsEx(std::string("menu/external/flashmenu/cursor/cursor_busy.ani"), true); m_cursors[1] = LoadCursorFromFileA(busy.c_str()); std::string keybinding = io::fileManager->fileExistsEx(std::string("menu/external/flashmenu/cursor/cursor_keybinding.ani"), true); m_cursors[2] = LoadImageA(GetModuleHandleA(0), keybinding.c_str(), IMAGE_CURSOR, 0, 0, LR_LOADFROMFILE | LR_SHARED); +#endif s_cursorsLoaded = true; return m_cursors[which]; } -bool SwiffHost::setPlayerRenderCapability1(int value) +bool SwiffHost::setPlayerRenderCapability1(intptr_t value) { IBase* player = classManager->getSingleton(std::string("SwiffPlayer")); return player && static_cast(player)->renderCapability1(value) != 0; @@ -971,9 +1006,51 @@ void SwiffHost::setIntE98(int value) { m_intE98 = value int SwiffHost::getIntE98() { return m_intE98; } std::string SwiffHost::getGameMode() { return m_gameMode; } void SwiffHost::setGameMode(const std::string& mode) { m_gameMode = mode; } +// 0x497E90 (718 B). Refused while a join is pending (+0xEC4). Otherwise the page is reset, the +// GameServerSettings applied, and the "playNow" list refreshed synchronously and sorted by ping. +// The first row that is ranked, pure, open (no password), on the current mod and on this build's +// version is queried again (fillRecord, basic keys, no cache); a row that answers with players, +// a free slot and a ping becomes the selected server and is joined. The first join that is queued +// answers true. With no such row the front end gets the type-3 "noplaynowservers" message. bool SwiffHost::playNow() { - SWIFF_HOST_FRONTIER("playNow", "PE 0x497E90, 718 B: the playNow ServerBrowser list and its 580-byte rows are unrecovered"); + if (m_flagEC4 == 1) // byte +0xEC4 + return false; + setPage(0); // +0x2C0 + IBase* gameServerSettings = classManager->getSingleton(std::string("GameServerSettings")); + static_cast(gameServerSettings)->apply(); // +0x18, unguarded + ui::IServerBrowser* list = getServerList(std::string("playNow")); // +0x7C, unguarded + list->reset(); // +0x24 + list->startUpdate(false); // +0x28 + list->sort(std::string("ping"), true, 0); // +0x38 + // The bound and every row are read through getRecords() (+0x20) again on each pass. + for (unsigned int index = 0; index < list->getRecords()->records.size(); ++index) + { + ui::ServerBrowserRecord* row = &list->getRecords()->records[index]; + // One condition, evaluated left to right; both temporaries are flag-guarded in the PE + // (0x497FAD/0x497FD3) and destroyed before the join below. + const bool candidate = row + && row->entry.ranked // record +0xE9 + && row->entry.pure == true // record +0x10B + && !row->entry.password // record +0x8C + && row->entry.gameVariant == currentModName() // record +0xB0, 0x59F3F0 + && compareIgnoreCase(row->entry.gameVersion, getVersionStringValue()) == 0; // +0xCC, +0x270 + if (!candidate) + continue; + ui::ServerBrowserRecord fresh; // 0x482190 / 0x4835C0 + list->fillRecord(row->server, &fresh, false, false); // +0x40, result unread + if (fresh.entry.numPlayers > 0 // record +0x64 + && fresh.entry.maxPlayers != fresh.entry.numPlayers // record +0x68 + && fresh.entry.ping > 0) // record +0x60 + { + setSelectedServer(fresh.entry.address, fresh.entry.queryPort, fresh.entry.hostPort); // +0x10C + if (joinServer(fresh.entry.address, fresh.entry.hostPort, fresh.entry.queryPort)) // +0x100 + return true; + } + } + SwiffHostMessage message(3, std::string("noplaynowservers"), 3); + postMessage(message); // +0x1E4 + return false; } // Clears previous round results. [CHOSEN, not recovered] Returns zero; existing callers ignore the result. int SwiffHost::resetEndOfRoundInfo() @@ -1011,9 +1088,14 @@ bool SwiffHost::getModCount(int* out) *out = static_cast(mods->size()); return true; } -bool SwiffHost::slot194(int, int) +// 0x4A2B00: the indexed row of the mod list assigned to the caller's record (0x481490 is +// IModInfo::Mod's implicit operator=: nine strings, the map vector 0x4811D0, the mode vector +// 0x47F260, two strings). The index is not range-checked and the answer is always true. +bool SwiffHost::getModAt(int index, IModInfo::Mod* out) { - SWIFF_HOST_FRONTIER("slot194", "PE 0x4A2B00: 0x481490 on the indexed Mod is unrecovered"); + std::vector* mods = static_cast(getModInfo())->getModList(); // +0x120, +0x14 + *out = (*mods)[index]; + return true; } // event 11 (activateMod), or the "no mod specified" type-1 message for a null name. bool SwiffHost::requestActivateMod(const std::string* mod) @@ -1839,13 +1921,17 @@ void SwiffHost::handleProfileTransition(const std::string& name) // 0x488440 (188 B): Winsock 1.1, gethostbyname, the first address as a dotted quad in a static buffer. std::string SwiffHost::resolveHostName(const std::string& name) { +#if defined(_WIN32) WSADATA data; if (WSAStartup(0x101, &data)) return std::string(""); +#endif hostent* host = gethostbyname(name.c_str()); if (!host) { +#if defined(_WIN32) WSACleanup(); +#endif return std::string(""); } in_addr address; @@ -1860,7 +1946,9 @@ std::string SwiffHost::resolveHostName(const std::string& name) *out++ = *text++; } while (c); +#if defined(_WIN32) WSACleanup(); +#endif return std::string(s_resolvedAddress); } // inet_addr, or a host lookup when the text is not numeric; the RFC 1918 test on it. @@ -1872,7 +1960,7 @@ bool SwiffHost::isPrivateAddress(const std::string& address) return isPrivateNetworkAddress(&s_lastInetAddr) != 0; hostent* host = gethostbyname(text); if (host) - return isPrivateNetworkAddress(reinterpret_cast(host->h_addr_list[0])) != 0; + return isPrivateNetworkAddress(reinterpret_cast(host->h_addr_list[0])) != 0; return isPrivateNetworkAddress(0) != 0; } // 0x488380 (190 B): digits and exactly three dots, each octet under 256. @@ -2059,7 +2147,12 @@ void SwiffHost::setFlagEA8(bool value) { m_flagEA8 = valu bool SwiffHost::setBusy(int busy) { m_busy = busy; +#if defined(__APPLE__) + // [CHOSEN, not recovered] Nothing to repaint synchronously; UpdateWindow fails only without a window. + return bf2Engine->window->getHwnd() != 0; +#else return UpdateWindow(bf2Engine->window->getHwnd()) != 0; +#endif } void SwiffHost::clearBusy() { m_busy = 0; } int SwiffHost::getBusy() { return m_busy; } @@ -2214,7 +2307,7 @@ int SwiffHost::getIntF4C() { return m_intF4C; void SwiffHost::setIntF4C(int value) { m_intF4C = value; } bool SwiffHost::isPlayingDemo() { return game && game->isPlayingDemo(); } std::string SwiffHost::getModName() { return currentModName(); } -bool SwiffHost::slot368(int, int, int) { return true; } +bool SwiffHost::slot368(const std::string&, const std::string&, int) { return true; } // 0x4890D0 (190 B): 1 for xpack, 2 for xpack2, else 0; an empty name means the current mod. int SwiffHost::getExpansionPack(const std::string& modName) { @@ -2232,9 +2325,20 @@ std::string SwiffHost::getLanguageSetting() std::string language = settings->stringGet(std::string("GSLanguage"), std::string("English")); return language; } -void SwiffHost::parseResolution(const std::string&, int*, int*, int*) -{ - SWIFF_HOST_FRONTIER("parseResolution", "PE 0x489210: the \"x@Hz\" tokenizer 0x59E1B0/0x59E1F0 is unrecovered"); +// 0x489210: "WxH@RHz" split on the four delimiter characters 'x', '@', 'H' and 'z'. Each of the +// three tokens is atoi'd; a missing (empty) token stores 0. The nextToken results are unread. +void SwiffHost::parseResolution(const std::string& text, int* width, int* height, int* hz) +{ + StringTokenizer tokens(text, std::string("x@Hz")); + std::string widthText; + std::string heightText; + std::string hzText; + tokens.nextToken(widthText); + tokens.nextToken(heightText); + tokens.nextToken(hzText); + *width = widthText.size() ? std::atoi(widthText.c_str()) : 0; + *height = heightText.size() ? std::atoi(heightText.c_str()) : 0; + *hz = hzText.size() ? std::atoi(hzText.c_str()) : 0; } bool SwiffHost::getFlagF2C() { return m_flagF2C; } void SwiffHost::setFlagF2C(bool value) { m_flagF2C = value; } diff --git a/Code/BF2/Menu/SwiffHost.h b/Code/BF2/Menu/SwiffHost.h index f1d5c2bd0..e4abc824d 100644 --- a/Code/BF2/Menu/SwiffHost.h +++ b/Code/BF2/Menu/SwiffHost.h @@ -48,9 +48,9 @@ class SwiffHost : public ui::ISwiffHost std::string getCurrentMapGameMode() override; int getCurrentMapMaxPlayers() override; int getCurrentMapSize() override; - bool setPlayerRenderCapability0(int value) override; + bool setPlayerRenderCapability0(intptr_t value) override; void* getCursor(int which) override; - bool setPlayerRenderCapability1(int value) override; + bool setPlayerRenderCapability1(intptr_t value) override; void setFlag28(bool value) override; bool getFlag28() override; ui::IServerBrowser* getServerList(const std::string& name) override; @@ -123,7 +123,7 @@ class SwiffHost : public ui::ISwiffHost bool playSound(const std::string& name) override; void slot18C(int a) override; bool getModCount(int* out) override; - bool slot194(int index, int b) override; + bool getModAt(int index, IModInfo::Mod* out) override; bool requestActivateMod(const std::string* mod) override; bool requestBrowseModHomepage(const IModInfo::Mod* mod) override; bool getVersionString(std::string& out) override; @@ -241,7 +241,7 @@ class SwiffHost : public ui::ISwiffHost void setIntF4C(int value) override; bool isPlayingDemo() override; std::string getModName() override; - bool slot368(int a, int b, int c) override; + bool slot368(const std::string& modPath, const std::string& address, int port) override; int getExpansionPack(const std::string& modName) override; std::string getLanguageSetting() override; void parseResolution(const std::string& text, int* width, int* height, int* hz) override; diff --git a/Code/BF2/Physics/CollisionManager.cpp b/Code/BF2/Physics/CollisionManager.cpp index 3cbbcbdec..b6914027d 100644 --- a/Code/BF2/Physics/CollisionManager.cpp +++ b/Code/BF2/Physics/CollisionManager.cpp @@ -15,6 +15,7 @@ #include "../Core/Debug.h" // Debug, DEBUGTYPE_6 - the two constructor failure paths #include "../Core/EventManager.h" // dice::hfe::eventManager, EventManager #include "../Core/Ids.h" // IID_IBase, world::IID_ICollisionManager +#include "../GeomMisc/DebugLineDrawer.h" // typed retail debug submissions #include "../Core/StringUtil.h" // getFixPath / getLowerCase / goUpInPath - postLevelLoad's grouping #include "../Game/Objects/ICameraObject.h" // debug camera transformation #include "../Game/Objects/IObject.h" // recursive child walk @@ -59,28 +60,6 @@ int* s_debugWaterPtr = &s_debugWaterValue; float s_debugLineWidthValue = 0.01f; float* s_debugLineWidthPtr = &s_debugLineWidthValue; -// [FRONTIER] [TEMP] [CHOSEN, not recovered] -// [RETIRE-WHEN: collision-debug-line-drawer-interface] -// Stop debug dispatch until the preceding IDebugLineDrawer overload has a confirmed -// source-vector type and the required interface can be declared safely. -void debugLineDrawerTriangleFrontier() -{ - std::fprintf(stderr, - "[FRONTIER] dice::hfe::world::CollisionManager::drawDebugPrimitives " - "(IDebugLineDrawer +0x2C dependency) reached\n"); - std::fflush(stderr); - std::abort(); -} - -void debugLineDrawerLineListFrontier() -{ - std::fprintf(stderr, - "[FRONTIER] dice::hfe::world::CollisionManager::drawDebugPrimitives " - "(IDebugLineDrawer +0x34 dependency) reached\n"); - std::fflush(stderr); - std::abort(); -} - } // namespace // the factory - written first because it is the entry point the boot reaches @@ -380,6 +359,7 @@ void debugWater(std::vector& out, int extent) out.push_back(maxMax); } +// PE 0x006FD4E0 / ELF 0x0839B7F0. // Draws enabled debug streams, then clears all four member streams. Requires the renderer // singleton. Collision-face vectors are cleared by ResponsePhysicsManager instead. void CollisionManager::drawDebugPrimitives() @@ -388,26 +368,27 @@ void CollisionManager::drawDebugPrimitives() std::vector heightmapVertices; std::vector colors; - IBase* const drawer = classManager->getSingleton(std::string("DebugLineDrawer")); - (void)drawer; + geom::IDebugLineDrawer* const drawer = static_cast( + classManager->getSingleton(std::string("DebugLineDrawer"))); if (m_drawTestedFaces == true) { colors.resize(0); colors.push_back(0xFF00FF00u); - debugLineDrawerTriangleFrontier(); + drawer->drawTriangles(collisionTestedFaces, colors, true); } if (m_drawIntersectFaces == true) { colors.resize(0); colors.push_back(0xFFFF00FFu); - debugLineDrawerTriangleFrontier(); + drawer->drawTriangles(collisionIntersectFaces, colors, true); } if (m_drawPrimitives == true) { - debugLineDrawerLineListFrontier(); + drawer->drawLineList(m_lineVertices, m_lineColors, *s_debugLineWidthPtr, false); + drawer->drawTriangles(m_triangleVertices, m_triangleColors, false); } if (*s_debugHeightmapPtr > 0) @@ -416,7 +397,7 @@ void CollisionManager::drawDebugPrimitives() heightmapVertices.resize(0); colors.push_back(0xFFFF00FFu); debugHeightmap(heightmapVertices, *s_debugHeightmapPtr); - debugLineDrawerLineListFrontier(); + drawer->drawLineList(heightmapVertices, colors, 0.01f, false); } if (*s_debugWaterPtr > 0) @@ -425,7 +406,7 @@ void CollisionManager::drawDebugPrimitives() waterVertices.resize(0); colors.push_back(0xFF0000FFu); debugWater(waterVertices, *s_debugWaterPtr); - debugLineDrawerTriangleFrontier(); + drawer->drawTriangles(waterVertices, colors, true); } m_lineVertices.resize(0); diff --git a/Code/BF2/Physics/CollisionMeshTemplate.cpp b/Code/BF2/Physics/CollisionMeshTemplate.cpp index 72f8267fa..ed727952a 100644 --- a/Code/BF2/Physics/CollisionMeshTemplate.cpp +++ b/Code/BF2/Physics/CollisionMeshTemplate.cpp @@ -14,7 +14,7 @@ #include "../Game/Objects/ObjectTemplate.h" // getMaterialVector (+0xBC) - createMaterialMapping #include "../Game/Utility/Vars.h" // the load tail's two debug-mesh cells #include "../Geom/IGeometryTemplate.h" -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && defined(_M_IX86) #include "../Geom/GeometryTemplateManager.h" #endif #include "../IO/Stream/IStream.h" // INonlinearStream - the parser's input @@ -535,7 +535,7 @@ void createCollisionDebugMesh(IBase** output, const std::string& name, int verte std::sprintf(suffix, "%d", collisionDebugMeshNumber); const std::string templateName = name + suffix; IBase* manager = collisionDebugManager(); -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && defined(_M_IX86) geom::IGeometryTemplate* meshTemplate = static_cast(manager)->createTemplate( geom::CID_DebugXMeshTemplate, templateName); @@ -552,20 +552,9 @@ void createCollisionDebugMesh(IBase** output, const std::string& name, int verte #else const unsigned int setNameOrdinal = 27; #endif -#if defined(_MSC_VER) && defined(_M_IX86) - // [CHOSEN, not recovered] A borrowed VC7.1 short-string carrier. DebugXMesh +68 - // (RendDX9 10082D30) still consumes vc71::string in the rebuilt x86 renderer; - // the manager above instead consumes native HostString. The fixed 13-byte name - // fits inline, so this measured +4/+20/+24 carrier needs no foreign allocator. - const struct { unsigned int allocator; char buffer[16]; unsigned int size, capacity; } - instanceName = { 0, "collisionMesh", 13, 15 }; - static_assert(sizeof(instanceName) == 28, "VC7.1 borrowed short-string carrier"); - typedef void (__thiscall* SetName)(IBase*, const void*); - collisionDebugSlot(*output, setNameOrdinal)(*output, &instanceName); -#else + // DebugXMesh +68 (RendDX9 10082D30) takes the shared std::string (issue #7). typedef void (__thiscall* SetName)(IBase*, const std::string&); collisionDebugSlot(*output, setNameOrdinal)(*output, std::string("collisionMesh")); -#endif // RendDX9 template table 1020C5C0: +D8=10092AE0, +DC=10093590. The sixth // argument is a byte-tested optimization bool; the seventh is a VertexDeclaration*. typedef bool (__thiscall* Build)(IBase*, int, int, int, unsigned char*, unsigned short*, @@ -582,15 +571,15 @@ void createCollisionDebugMesh(IBase** output, const std::string& name, int verte } // PE 6BAB00 / ELF 83A63D0 (extractAdjacencyFromDebugMesh). The name and colors parameters -// are unused. RendDX9 +E0 (100928A0) returns the D3DX mesh's unsigned face count; +E4 -// (100928C0) takes float epsilon, ushort output[], unsigned count and narrows dword neighbours. +// are unused. The RendDX9 debug X-mesh template's +E0 returns the D3DX mesh's unsigned face count; +// its +E4 takes float epsilon, ushort output[], unsigned count and narrows dword neighbours. void extractCollisionDebugAdjacency(const std::string&, int vertexCount, int faceCount, unsigned char* vertices, unsigned short* indices, std::vector, unsigned short** output) { const std::string name("adjTempTemplate"); IBase* manager = collisionDebugManager(); -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && defined(_M_IX86) IBase* meshTemplate = static_cast(manager)->createTemplate( geom::CID_DebugXMeshTemplate, name); #else @@ -624,7 +613,7 @@ void extractCollisionDebugAdjacency(const std::string&, int vertexCount, int fac Debug(DebugTypeError, "Physics/CollisionMeshTemplate.cpp", 1807, "") << "Failed to generate adjacency"; manager = collisionDebugManager(); // client reloads the global after callbacks -#if !DEDICATED && defined(_M_IX86) && BF2_PLUGIN_ABI_NATIVE +#if !DEDICATED && defined(_M_IX86) static_cast(manager)->removeTemplate(name); #else typedef void (__thiscall* RemoveTemplate)(IBase*, const std::string&); diff --git a/Code/BF2/Physics/SoldierResponse.h b/Code/BF2/Physics/SoldierResponse.h index 043bce772..088535fe3 100644 --- a/Code/BF2/Physics/SoldierResponse.h +++ b/Code/BF2/Physics/SoldierResponse.h @@ -13,6 +13,7 @@ namespace hfe { class SoldierNetworkable; // the wire wrapper - a friend below; see Networkables.h class SoldierSound; // reads the retail ground-contact byte in its movement-sound tick +namespace ai { class AIObjectPhysical; } // isInAir reads the ground-contact byte (+0xFA) namespace ai { class AIObjectPhysical; } // isInAir reads the ground-contact byte (+0xFA) @@ -80,6 +81,12 @@ class SoldierResponsePhysics : public PointResponsePhysics // GenericFireArm::checkAreaToFireZipline samples +0xFA then +0xF9 directly in both ports // (ELF 0x8254940 / PE 0x5847C0). Narrow friend preserves that raw response-physics gate. friend class GenericFireArm; + // SoldierDeviationComp::updateDeviation reads the +0xFA ground-contact byte directly for an + // unparented soldier; the friend keeps that read on the named member. + friend class SoldierDeviationComp; + // ai::AIObjectPhysical::isInAir (bf2 0x841A0C0) answers the negation of the +0xFA byte for a + // soldier. + friend class dice::hfe::ai::AIObjectPhysical; // ai::AIObjectPhysical::isInAir (bf2 0x841A0C0) reads the ground-contact byte. friend class dice::hfe::ai::AIObjectPhysical; diff --git a/Code/BF2/Platform/ExtendedFloat.h b/Code/BF2/Platform/ExtendedFloat.h new file mode 100644 index 000000000..d0c0b0dcb --- /dev/null +++ b/Code/BF2/Platform/ExtendedFloat.h @@ -0,0 +1,244 @@ +// [CHOSEN, not recovered] Arithmetic for the macOS port's retained x87 intermediates. +#ifndef BF2_PLATFORM_EXTENDEDFLOAT_H +#define BF2_PLATFORM_EXTENDEDFLOAT_H + +#include +#include +#include +#include +#include + +namespace bf2x87 { + +class ExtendedFloat; +inline ExtendedFloat abs(ExtendedFloat value); + +// A binary extended value, with a 64-bit significand and x87 exponent range. +// Used only on Apple silicon (and by the Intel differential fixture). This is +// value arithmetic, not an x87 stack/control-word emulator. Operations obey the +// current C rounding direction; precision is always 64 bits. No fused operations. +class ExtendedFloat { + using UInt = unsigned __int128; + std::uint64_t significand_ = 0; + int exponent_ = 0; // exponent of the leading bit, including subnormals + bool negative_ = false; + static constexpr int special = 32768; + + static int width(UInt value) + { + const auto high = static_cast(value >> 64); + return high ? 128 - __builtin_clzll(high) : + value ? 64 - __builtin_clzll(static_cast(value)) : 0; + } + static UInt jam(UInt value, int shift) + { + if (shift <= 0) return value; + if (shift >= 128) return value != 0; + return (value >> shift) | ((value << (128 - shift)) != 0); + } + static bool increment(bool negative, UInt whole, UInt remainder, int shift) + { + if (!remainder) return false; + switch (std::fegetround()) { + case FE_UPWARD: return !negative; + case FE_DOWNWARD: return negative; + case FE_TOWARDZERO: return false; + default: + if (shift > 128) return false; + const UInt half = UInt(1) << (shift - 1); + return remainder > half || (remainder == half && (whole & 1)); + } + } + static UInt rounded(bool negative, UInt value, int shift) + { + if (shift <= 0) return value << -shift; + const UInt whole = shift >= 128 ? 0 : value >> shift; + const UInt remainder = shift >= 128 ? value : value & ((UInt(1) << shift) - 1); + return whole + increment(negative, whole, remainder, shift); + } + static ExtendedFloat raw(bool negative, std::uint64_t sig, int exponent) + { + ExtendedFloat result; + result.negative_ = negative; result.significand_ = sig; result.exponent_ = exponent; + return result; + } + static ExtendedFloat pack(bool negative, UInt value, int unit) + { + if (!value) return raw(negative, 0, 0); + const int shift = (width(value) - 64 > -16445 - unit) ? + width(value) - 64 : -16445 - unit; + UInt sig = rounded(negative, value, shift); + unit += shift; + if (!sig) return raw(negative, 0, 0); + if (width(sig) > 64) { sig >>= 1; ++unit; } + const int bits = width(sig); + const int exponent = unit + bits - 1; + if (exponent > 16383) { + std::feraiseexcept(FE_OVERFLOW | FE_INEXACT); + const int mode = std::fegetround(); + return mode == FE_TOWARDZERO || (mode == FE_DOWNWARD && !negative) || + (mode == FE_UPWARD && negative) ? raw(negative, UINT64_MAX, 16383) : infinity(negative); + } + return raw(negative, static_cast(sig) << (64 - bits), exponent); + } + template T narrow() const + { + constexpr int fraction = Precision - 1; + constexpr int exponentBits = sizeof(Bits) * 8 - Precision; + const Bits sign = Bits(negative_) << (sizeof(Bits) * 8 - 1); + const Bits infinityBits = ((Bits(1) << exponentBits) - 1) << fraction; + Bits result = sign; + if (isNaN()) result |= infinityBits | (Bits(1) << (fraction - 1)) | + (static_cast(significand_ >> (63 - fraction)) & ((Bits(1) << fraction) - 1)); + else if (isInf()) result |= infinityBits; + else if (significand_) { + const int shift = (64 - Precision > (1 - Bias) - exponent_ + 64 - Precision) ? + 64 - Precision : (1 - Bias) - exponent_ + 64 - Precision; + UInt sig = rounded(negative_, significand_, shift); + int exponent = exponent_; + if (sig >= (UInt(1) << Precision)) { sig >>= 1; ++exponent; } + if (exponent > Bias) { + const int mode = std::fegetround(); + result |= mode == FE_TOWARDZERO || (mode == FE_DOWNWARD && !negative_) || + (mode == FE_UPWARD && negative_) ? infinityBits - 1 : infinityBits; + } else if (sig < (UInt(1) << fraction)) result |= static_cast(sig); + else { + if (exponent < 1 - Bias) exponent = 1 - Bias; + result |= (Bits(exponent + Bias) << fraction) | + (static_cast(sig) & ((Bits(1) << fraction) - 1)); + } + } + T output; std::memcpy(&output, &result, sizeof output); return output; + } +public: + ExtendedFloat() = default; + ExtendedFloat(double value) + { + std::uint64_t bits; std::memcpy(&bits, &value, 8); + negative_ = bits >> 63; + const int exponent = (bits >> 52) & 2047; + const std::uint64_t fraction = bits & 0xfffffffffffffULL; + if (exponent == 2047) { + exponent_ = special; significand_ = fraction << 11; + if (fraction && !(fraction & (1ULL << 51))) std::feraiseexcept(FE_INVALID); + } + else *this = pack(negative_, exponent ? fraction | (1ULL << 52) : fraction, + exponent ? exponent - 1023 - 52 : -1074); + } + ExtendedFloat(float value) : ExtendedFloat(static_cast(value)) {} + ExtendedFloat(int value) : ExtendedFloat(static_cast(value)) {} + ExtendedFloat(unsigned value) : ExtendedFloat(static_cast(value)) {} + ExtendedFloat(long value) : ExtendedFloat(static_cast(value)) {} + ExtendedFloat(unsigned long value) : ExtendedFloat(static_cast(value)) {} + ExtendedFloat(long long value) + { + const auto bits = static_cast(value); + *this = pack(value < 0, value < 0 ? 0ULL - bits : bits, 0); + } + ExtendedFloat(unsigned long long value) { *this = pack(false, value, 0); } + ExtendedFloat(long double value) + { +#if defined(__x86_64__) + // The test fixture can load the host's exact extended operands. + unsigned char bytes[sizeof value]; std::memcpy(bytes, &value, sizeof value); + std::uint64_t sig; std::uint16_t se; + std::memcpy(&sig, bytes, 8); std::memcpy(&se, bytes + 8, 2); + const int exp = se & 0x7fff; + if (exp == 0x7fff) *this = raw(se >> 15, sig & 0x7fffffffffffffffULL, special); + else *this = pack(se >> 15, sig, (exp ? exp - 16383 : -16382) - 63); +#else + *this = ExtendedFloat(static_cast(value)); +#endif + } + explicit operator float() const { return narrow(); } + explicit operator double() const { return narrow(); } + bool isNaN() const { return exponent_ == special && significand_ != 0; } + bool isInf() const { return exponent_ == special && significand_ == 0; } + bool isFinite() const { return exponent_ != special; } + static ExtendedFloat infinity(bool negative = false) { return raw(negative, 0, special); } + static ExtendedFloat invalid() + { std::feraiseexcept(FE_INVALID); return raw(true, 1ULL << 62, special); } + ExtendedFloat operator-() const { auto result = *this; result.negative_ = !negative_; return result; } + friend ExtendedFloat abs(ExtendedFloat value) { value.negative_ = false; return value; } + friend bool operator==(ExtendedFloat a, ExtendedFloat b) + { + if (a.isNaN() || b.isNaN()) return false; + if (!a.isInf() && !b.isInf() && !a.significand_ && !b.significand_) return true; + return a.negative_ == b.negative_ && a.exponent_ == b.exponent_ && a.significand_ == b.significand_; + } + friend bool operator!=(ExtendedFloat a, ExtendedFloat b) { return !(a == b); } + friend bool operator<(ExtendedFloat a, ExtendedFloat b) + { + if (a.isNaN() || b.isNaN()) { std::feraiseexcept(FE_INVALID); return false; } + if (a == b) return false; + if (a.negative_ != b.negative_) return a.negative_; + const int ae = !a.significand_ && !a.isInf() ? -32768 : a.exponent_; + const int be = !b.significand_ && !b.isInf() ? -32768 : b.exponent_; + return a.negative_ ? (ae > be || (ae == be && a.significand_ > b.significand_)) : + (ae < be || (ae == be && a.significand_ < b.significand_)); + } + friend bool operator>(ExtendedFloat a, ExtendedFloat b) { return b < a; } + friend bool operator<=(ExtendedFloat a, ExtendedFloat b) { return a < b || a == b; } + friend bool operator>=(ExtendedFloat a, ExtendedFloat b) { return a > b || a == b; } + friend ExtendedFloat operator+(ExtendedFloat a, ExtendedFloat b) + { + if (a.isNaN()) return a; + if (b.isNaN()) return b; + if (a.isInf() || b.isInf()) return a.isInf() && b.isInf() && a.negative_ != b.negative_ ? invalid() : a.isInf() ? a : b; + if (!a.significand_ && !b.significand_) return raw(a.negative_ == b.negative_ ? a.negative_ : std::fegetround() == FE_DOWNWARD, 0, 0); + if (!a.significand_) return b; + if (!b.significand_) return a; + if (abs(a) < abs(b)) { auto t = a; a = b; b = t; } + const UInt first = UInt(a.significand_) << 3; + const UInt second = jam(UInt(b.significand_) << 3, a.exponent_ - b.exponent_); + if (a.negative_ != b.negative_ && first == second) return raw(std::fegetround() == FE_DOWNWARD, 0, 0); + return pack(a.negative_, a.negative_ == b.negative_ ? first + second : first - second, a.exponent_ - 66); + } + friend ExtendedFloat operator-(ExtendedFloat a, ExtendedFloat b) { return a + -b; } + friend ExtendedFloat operator*(ExtendedFloat a, ExtendedFloat b) + { + if (a.isNaN()) return a; + if (b.isNaN()) return b; + if (a.isInf() || b.isInf()) return (!a.isInf() && !a.significand_) || (!b.isInf() && !b.significand_) ? invalid() : infinity(a.negative_ != b.negative_); + return pack(a.negative_ != b.negative_, UInt(a.significand_) * b.significand_, a.exponent_ + b.exponent_ - 126); + } + friend ExtendedFloat operator/(ExtendedFloat a, ExtendedFloat b) + { + if (a.isNaN()) return a; + if (b.isNaN()) return b; + const bool sign = a.negative_ != b.negative_; + if (a.isInf() && b.isInf()) return invalid(); + if (a.isInf()) return infinity(sign); + if (b.isInf()) return raw(sign, 0, 0); + if (!b.significand_) { + if (!a.significand_) return invalid(); + std::feraiseexcept(FE_DIVBYZERO); return infinity(sign); + } + UInt numerator = UInt(a.significand_) << 63; + UInt quotient = numerator / b.significand_, remainder = numerator % b.significand_; + for (int i = 0; i < 3; ++i) { + remainder <<= 1; quotient <<= 1; + if (remainder >= b.significand_) { remainder -= b.significand_; ++quotient; } + } + return pack(sign, quotient | (remainder != 0), a.exponent_ - b.exponent_ - 66); + } + ExtendedFloat& operator+=(ExtendedFloat value) { return *this = *this + value; } + template T integer(bool truncate) const + { + static_assert(std::numeric_limits::is_signed && std::numeric_limits::is_integer, "signed FIST destination required"); + if (!isFinite() || exponent_ >= std::numeric_limits::digits + 1) { + std::feraiseexcept(FE_INVALID); return std::numeric_limits::min(); + } + const int shift = 63 - exponent_; + const UInt magnitude = truncate ? (shift >= 128 ? 0 : shift > 0 ? UInt(significand_) >> shift : UInt(significand_) << -shift) : + rounded(negative_, significand_, shift); + const UInt bound = UInt(1) << std::numeric_limits::digits; + if (magnitude > bound || (magnitude == bound && !negative_)) { + std::feraiseexcept(FE_INVALID); return std::numeric_limits::min(); + } + if (magnitude == bound) return std::numeric_limits::min(); + const T value = static_cast(magnitude); return negative_ ? -value : value; + } +}; +} // namespace bf2x87 +#endif diff --git a/Code/BF2/Platform/InputScript.cpp b/Code/BF2/Platform/InputScript.cpp new file mode 100644 index 000000000..d1f652dd7 --- /dev/null +++ b/Code/BF2/Platform/InputScript.cpp @@ -0,0 +1,638 @@ +// [TEMP] [CHOSEN, not recovered] Client test tool: the platform-independent script engine +// (InputScript.h, docs/macos-c-input-script.md). The hosts and their key tables live in +// Platform/macOS (CocoaHost.mm, MacInputScript.mm) and Platform/Windows (WinInputScript.cpp). +// [RETIRE-WHEN: client-test-automation-replaced] +#include "InputScript.h" +#if !DEDICATED && (defined(__APPLE__) || defined(_WIN32)) +#if defined(_WIN32) +#include // the redirected stdout file (GetFinalPathNameByHandleA) +#else +#include +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dice { +namespace hfe { +namespace inputscript { + +namespace { + +double nowSeconds() +{ + using namespace std::chrono; + return duration(steady_clock::now().time_since_epoch()).count(); +} + +// Key by name: an IDKey_ name (prefix optional, any case) from the host table, or 0xNN. +bool lookupKey(std::string name, unsigned short& code) +{ + for (char& c : name) c = static_cast(std::tolower(static_cast(c))); + if (name.compare(0, 6, "idkey_") == 0) name = name.substr(6); + if (name.size() > 2 && name[0] == '0' && name[1] == 'x') + { + code = static_cast(std::strtoul(name.c_str(), nullptr, 16)); + return true; + } + return keys::lookup(name, code); +} + +std::u16string utf16FromUtf8(const std::string& s) +{ + std::u16string out; + for (std::size_t i = 0; i < s.size();) + { + unsigned char c = static_cast(s[i]); + unsigned int cp = c; std::size_t n = 1; + if (c >= 0xF0 && i + 3 < s.size() + 0) { cp = ((c & 7u) << 18) | ((s[i+1] & 0x3Fu) << 12) | ((s[i+2] & 0x3Fu) << 6) | (s[i+3] & 0x3Fu); n = 4; } + else if (c >= 0xE0 && i + 2 < s.size()) { cp = ((c & 0xFu) << 12) | ((s[i+1] & 0x3Fu) << 6) | (s[i+2] & 0x3Fu); n = 3; } + else if (c >= 0xC0 && i + 1 < s.size()) { cp = ((c & 0x1Fu) << 6) | (s[i+1] & 0x3Fu); n = 2; } + if (cp < 0x10000) out.push_back(static_cast(cp)); + i += n; + } + return out; +} + +std::string trim(const std::string& s) +{ + std::size_t b = 0, e = s.size(); + while (b < e && std::isspace(static_cast(s[b]))) ++b; + while (e > b && std::isspace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +// The rest of a line, without surrounding quotes. +std::string restArgument(const std::string& rest) +{ + std::string t = trim(rest); + if (t.size() >= 2 && t.front() == '"' && t.back() == '"') + t = t.substr(1, t.size() - 2); + return t; +} + +// The file the harness redirects stdout (else stderr) into, or empty. +std::string redirectedOutputPath() +{ +#if defined(_WIN32) + for (DWORD which : {STD_OUTPUT_HANDLE, STD_ERROR_HANDLE}) + { + const HANDLE h = GetStdHandle(which); + char buf[MAX_PATH * 2]; + if (h && h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_DISK) + { + const DWORD n = GetFinalPathNameByHandleA(h, buf, sizeof(buf), FILE_NAME_NORMALIZED); + if (n > 0 && n < sizeof(buf)) + { + std::string path(buf, n); + if (path.compare(0, 4, "\\\\?\\") == 0) // the \\?\ prefix + path = path.substr(4); + return path; + } + } + } +#else + for (int fd : {1, 2}) + { + struct stat st; + char buf[MAXPATHLEN]; + if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && fcntl(fd, F_GETPATH, buf) == 0) + return buf; + } +#endif + return std::string(); +} + +const int kHoldMs = 60; // a key or button held at least this long ... +const int kHoldFrames = 3; // ... and over this many pumps (input samples) + +} // namespace + +namespace { ScriptQueryFn s_scriptQuery = nullptr; } +void setScriptQuery(ScriptQueryFn fn) { s_scriptQuery = fn; } + +InputScript& inputScript() +{ + static InputScript script; + return script; +} + +void InputScript::report(const char* fmt, ...) const +{ + char text[1024]; + va_list args; + va_start(args, fmt); + std::vsnprintf(text, sizeof(text), fmt, args); + va_end(args); + std::fprintf(stderr, "[TEMP] [INPUT-SCRIPT] t=%.2fs frame=%lu %s\n", + nowSeconds() - m_startSeconds, m_frame, text); +} + +void InputScript::finish(const char* why) +{ + m_finished = true; + report("%s", why); +} + +void InputScript::addWaitFrames(int frames, int line) +{ + Step s{}; s.op = OpWaitFrames; s.a = frames; s.line = line; m_steps.push_back(s); +} + +void InputScript::addWaitMs(int ms, int line) +{ + Step s{}; s.op = OpWaitMs; s.a = ms; s.line = line; m_steps.push_back(s); +} + +void InputScript::addKeyPress(unsigned short keyCode, bool shift, const std::u16string& text, int line, int holdMs) +{ + if (shift) + { + Step d{}; d.op = OpKeyDown; d.a = keys::leftShift(); d.line = line; m_steps.push_back(d); + addWaitFrames(1, line); + } + Step d{}; d.op = OpKeyDown; d.a = keyCode; d.chars = text; d.line = line; m_steps.push_back(d); + addWaitFrames(kHoldFrames, line); + addWaitMs(holdMs, line); + Step u{}; u.op = OpKeyUp; u.a = keyCode; u.line = line; m_steps.push_back(u); + if (shift) + { + addWaitFrames(1, line); + Step su{}; su.op = OpKeyUp; su.a = keys::leftShift(); su.line = line; m_steps.push_back(su); + } + addWaitFrames(2, line); +} + +bool InputScript::parseLine(const std::string& raw, int number) +{ + std::string line = trim(raw); + if (line.empty() || line[0] == '#') + return true; + std::istringstream in(line); + std::string cmd; + in >> cmd; + std::string rest; + std::getline(in, rest); + std::istringstream args(rest); + Step s{}; + s.line = number; + auto key = [&](const std::string& name, unsigned short& code) { + if (lookupKey(name, code)) return true; + report("line %d: unknown key '%s'", number, name.c_str()); + return false; + }; + if (cmd == "wait-frames") { args >> s.a; addWaitFrames(s.a, number); } + else if (cmd == "wait-ms") { args >> s.a; addWaitMs(s.a, number); } + else if (cmd == "wait-log") { s.op = OpWaitLog; s.text = restArgument(rest); m_steps.push_back(s); } + else if (cmd == "timeout") { s.op = OpTimeout; args >> s.x; m_steps.push_back(s); } + else if (cmd == "wait-log-else") + { + // wait-log-else SECONDS LABEL TEXT: as wait-log, but after SECONDS jump to `label LABEL`. + args >> s.x >> s.label; + std::string text; + std::getline(args, text); + s.op = OpWaitLogElse; s.text = restArgument(text); m_steps.push_back(s); + } + else if (cmd == "label") { s.op = OpLabel; args >> s.label; m_steps.push_back(s); } + else if (cmd == "key" || cmd == "key-down" || cmd == "key-up") + { + std::string name; int hold = kHoldMs; + args >> name >> hold; + unsigned short code; + if (!key(name, code)) return false; + if (cmd == "key") + { + // The press carries the characters NSEvent would: computed at run time (layout). + Step d{}; d.op = OpKeyDown; d.a = code; d.b = 1; d.line = number; m_steps.push_back(d); + addWaitFrames(kHoldFrames, number); + addWaitMs(hold, number); + Step u{}; u.op = OpKeyUp; u.a = code; u.line = number; m_steps.push_back(u); + addWaitFrames(2, number); + } + else + { + s.op = cmd == "key-down" ? OpKeyDown : OpKeyUp; s.a = code; s.b = 1; m_steps.push_back(s); + } + } + else if (cmd == "type") { s.op = OpText; s.chars = utf16FromUtf8(restArgument(rest)); m_steps.push_back(s); } + else if (cmd == "console") + { + // The shipped console: the key left of 1 toggles it, Enter executes the line. + const std::string text = restArgument(rest); + Step k{}; k.op = OpKeyDown; k.a = keys::grave(); k.b = 1; k.line = number; m_steps.push_back(k); + addWaitFrames(kHoldFrames, number); addWaitMs(kHoldMs, number); + Step ku{}; ku.op = OpKeyUp; ku.a = keys::grave(); ku.line = number; m_steps.push_back(ku); + addWaitFrames(10, number); + Step t{}; t.op = OpText; t.chars = utf16FromUtf8(text); t.line = number; m_steps.push_back(t); + Step e{}; e.op = OpKeyDown; e.a = keys::enter(); e.b = 1; e.line = number; m_steps.push_back(e); + addWaitFrames(kHoldFrames, number); addWaitMs(kHoldMs, number); + Step eu{}; eu.op = OpKeyUp; eu.a = keys::enter(); eu.line = number; m_steps.push_back(eu); + addWaitFrames(10, number); + m_steps.push_back(k); addWaitFrames(kHoldFrames, number); addWaitMs(kHoldMs, number); + m_steps.push_back(ku); addWaitFrames(5, number); + } + else if (cmd == "move") { s.op = OpMoveTo; args >> s.x >> s.y; m_steps.push_back(s); } + else if (cmd == "move-rel") { s.op = OpMoveBy; args >> s.x >> s.y; m_steps.push_back(s); } + else if (cmd == "button-down" || cmd == "button-up") + { + s.op = cmd == "button-down" ? OpButtonDown : OpButtonUp; args >> s.a; m_steps.push_back(s); + } + else if (cmd == "click") + { + // click X Y [button]: move there, settle, press, hold, release. + float x = 0, y = 0; int button = 0; + args >> x >> y >> button; + Step m{}; m.op = OpMoveTo; m.x = x; m.y = y; m.line = number; m_steps.push_back(m); + addWaitFrames(5, number); + Step d{}; d.op = OpButtonDown; d.a = button; d.line = number; m_steps.push_back(d); + addWaitFrames(kHoldFrames, number); addWaitMs(kHoldMs, number); + Step u{}; u.op = OpButtonUp; u.a = button; u.line = number; m_steps.push_back(u); + addWaitFrames(5, number); + } + else if (cmd == "pointer-scale") { args >> m_pointerScale; if (m_pointerScale <= 0) m_pointerScale = 1.2f; } + else if (cmd == "pointer" || cmd == "hud-click") + { + // The in-game HUD pointer (BF2HudManager::handleGameInput) moves by mapped relative mouse + // input and clamps to the 800x600 HUD space, so it is homed to the top-left corner and then + // moved by X/scale, Y/scale counts (pointer-scale: HUD pixels per count, default 1.2 with + // the shipped Controls.con and hudManager.setPointerMouseSensitivity 40). + float x = 0, y = 0; int button = 0; + args >> x >> y >> button; + Step home{}; home.op = OpMoveBy; home.x = -4000; home.y = -4000; home.line = number; m_steps.push_back(home); + addWaitFrames(4, number); + Step to{}; to.op = OpMoveBy; to.x = x / m_pointerScale; to.y = y / m_pointerScale; to.line = number; m_steps.push_back(to); + addWaitFrames(4, number); + if (cmd == "hud-click") + { + Step d{}; d.op = OpButtonDown; d.a = button; d.line = number; m_steps.push_back(d); + addWaitFrames(kHoldFrames, number); addWaitMs(kHoldMs, number); + Step u{}; u.op = OpButtonUp; u.a = button; u.line = number; m_steps.push_back(u); + addWaitFrames(5, number); + } + } + else if (cmd == "aim" || cmd == "face" || cmd == "walk-to") + { + // aim TARGET [tol-deg] [timeout-ms]; face TARGET [tol-deg] [timeout-ms] (yaw only); + // walk-to TARGET RADIUS [timeout-ms] (W held, yaw steered, until within RADIUS metres). + std::string target; float p1 = 0, p2 = 0; + args >> target >> p1 >> p2; + s.op = cmd == "aim" ? OpAim : cmd == "face" ? OpFace : OpWalkTo; + s.text = target; + s.x = p1 > 0 ? p1 : (s.op == OpWalkTo ? 3.0f : 2.0f); + s.y = p2 > 0 ? p2 : (s.op == OpWalkTo ? 30000.0f : 5000.0f); + m_steps.push_back(s); + } + else if (cmd == "wheel") { s.op = OpWheel; args >> s.a; m_steps.push_back(s); } + else if (cmd == "capture") { s.op = OpCapture; s.text = restArgument(rest); m_steps.push_back(s); } + else if (cmd == "log") { s.op = OpLog; s.text = restArgument(rest); m_steps.push_back(s); } + else if (cmd == "quit") { s.op = OpQuit; m_steps.push_back(s); } + else if (cmd == "end") { s.op = OpEnd; m_steps.push_back(s); } + else + { + report("line %d: unknown command '%s'", number, cmd.c_str()); + return false; + } + return true; +} + +bool InputScript::parse(const std::string& path) +{ + std::ifstream in(path.c_str()); + if (!in) + { + report("cannot read %s; script off", path.c_str()); + return false; + } + std::string line; + int number = 0; + while (std::getline(in, line)) + if (!parseLine(line, ++number)) + return false; + return true; +} + +bool InputScript::loadFromEnvironment() +{ + const char* path = std::getenv("BF2_INPUT_SCRIPT"); + if (!path || !*path) + return false; + m_startSeconds = nowSeconds(); + if (!parse(path)) + return false; + if (const char* log = std::getenv("BF2_INPUT_SCRIPT_LOG")) + m_logPath = log; + else + m_logPath = redirectedOutputPath(); + m_active = true; + report("loaded %s: %zu steps; log %s", path, m_steps.size(), + m_logPath.empty() ? "(none: wait-log unavailable)" : m_logPath.c_str()); + return true; +} + +bool InputScript::logContains(const std::string& needle) +{ + if (m_logPath.empty()) + return false; + std::fflush(stdout); + std::fflush(stderr); + std::ifstream log(m_logPath.c_str(), std::ios::binary); + if (!log) + return false; + char buf[65536]; + log.seekg(static_cast(m_logOffset)); + while (log) + { + log.read(buf, sizeof(buf)); + const std::streamsize n = log.gcount(); + if (n <= 0) + break; + m_logOffset += n; + m_logTail.append(buf, static_cast(n)); + } + log.close(); + // The script's own report lines quote the needle; they never match. + for (std::size_t at = m_logTail.find(needle); at != std::string::npos; + at = m_logTail.find(needle, at + 1)) + { + const std::size_t begin = m_logTail.rfind('\n', at); + const std::size_t lineStart = begin == std::string::npos ? 0 : begin + 1; + const std::size_t lineEnd = m_logTail.find('\n', at); + const std::string line = m_logTail.substr(lineStart, lineEnd == std::string::npos + ? std::string::npos : lineEnd - lineStart); + if (line.find("[INPUT-SCRIPT]") != std::string::npos) + continue; + m_logTail.erase(0, at + needle.size()); // the next wait-log matches after this one + return true; + } + // Keep the scan bounded; a needle never spans more than its own length. + if (m_logTail.size() > (1u << 20)) + m_logTail.erase(0, m_logTail.size() - needle.size()); + return false; +} + +bool InputScript::takeCaptureRequest(std::string& label) +{ + if (m_captures.empty()) + return false; + label = m_captures.front(); + m_captures.erase(m_captures.begin()); + return true; +} + +bool InputScript::expandText(const std::u16string& text, int line) +{ + std::vector expanded; + std::vector saved; + saved.swap(m_steps); + for (char16_t c : text) + { + unsigned short found = 0xFFFF; + bool shift = false; + for (unsigned short code = 0; code < 0x80 && found == 0xFFFF; ++code) + { + if (keys::isModifier(code)) + continue; + for (int sh = 0; sh < 2; ++sh) + { + const std::u16string chars = m_sink->scriptKeyCharacter(code, sh != 0); + if (chars.size() == 1 && chars[0] == c) { found = code; shift = sh != 0; break; } + } + } + if (found == 0xFFFF) + { + m_steps.swap(saved); + report("line %d: no key produces U+%04X on this layout", line, static_cast(c)); + return false; + } + addKeyPress(found, shift, std::u16string(1, c), line, 20); + } + expanded.swap(m_steps); + m_steps.swap(saved); + m_steps.insert(m_steps.begin() + static_cast(m_pc) + 1, expanded.begin(), expanded.end()); + return true; +} + +void InputScript::tick(IInputScriptSink& sink) +{ + if (!m_active) + return; + ++m_frame; + if (m_finished) + return; + m_sink = &sink; + while (m_pc < m_steps.size()) + { + Step& s = m_steps[m_pc]; + switch (s.op) + { + case OpWaitFrames: + case OpWaitMs: + case OpWaitLog: + case OpWaitLogElse: + { + if (!m_waiting) + { + m_waiting = true; + m_waitFrame = m_frame; + m_waitStart = nowSeconds(); + if (s.op == OpWaitLog || s.op == OpWaitLogElse) + report("line %d: wait-log \"%s\"", s.line, s.text.c_str()); + } + bool done = false; + if (s.op == OpWaitFrames) done = m_frame - m_waitFrame >= static_cast(s.a); + else if (s.op == OpWaitMs) done = (nowSeconds() - m_waitStart) * 1000.0 >= s.a; + else done = logContains(s.text); + if (!done && s.op == OpWaitLogElse && nowSeconds() - m_waitStart > s.x) + { + size_t target = m_pc + 1; + while (target < m_steps.size() && !(m_steps[target].op == OpLabel && m_steps[target].label == s.label)) + ++target; + report("line %d: no \"%s\" after %.0f s; jumping to label %s", s.line, s.text.c_str(), s.x, s.label.c_str()); + m_waiting = false; + m_pc = target; // the label step itself is a no-op + return; + } + if (!done) + { + if ((s.op == OpWaitLog || s.op == OpWaitLogElse) && nowSeconds() - m_waitStart > m_timeoutSeconds) + { + char why[512]; + std::snprintf(why, sizeof(why), "line %d: TIMEOUT after %.0f s waiting for \"%s\"; script stopped", + s.line, m_timeoutSeconds, s.text.c_str()); + finish(why); + } + return; + } + if (s.op == OpWaitLog || s.op == OpWaitLogElse) + report("line %d: matched \"%s\"", s.line, s.text.c_str()); + m_waiting = false; + break; + } + case OpLabel: + break; + case OpTimeout: + m_timeoutSeconds = s.x > 0 ? s.x : 180.0; + break; + case OpKeyDown: + { + std::u16string text = s.chars; + if (s.b == 1 && text.empty()) + { + text = keys::controlCharacters(static_cast(s.a)); + if (text.empty() && !keys::isModifier(static_cast(s.a))) + text = sink.scriptKeyCharacter(static_cast(s.a), m_shiftHeld); + } + if (keys::isShift(static_cast(s.a))) m_shiftHeld = true; + sink.scriptKey(static_cast(s.a), true, text); + break; + } + case OpKeyUp: + if (keys::isShift(static_cast(s.a))) m_shiftHeld = false; + sink.scriptKey(static_cast(s.a), false, std::u16string()); + break; + case OpText: + if (!expandText(s.chars, s.line)) + { + finish("text expansion failed; script stopped"); + return; + } + break; + case OpMoveTo: sink.scriptMouseTo(s.x, s.y); break; + case OpMoveBy: sink.scriptMouseBy(s.x, s.y); break; + case OpButtonDown: sink.scriptButton(s.a, true); break; + case OpButtonUp: sink.scriptButton(s.a, false); break; + case OpWheel: sink.scriptWheel(s.a * 120); break; + case OpCapture: + m_captures.push_back(s.text.empty() ? std::string("capture") : s.text); + report("line %d: capture %s", s.line, m_captures.back().c_str()); + break; + case OpLog: + report("line %d: %s", s.line, s.text.c_str()); + break; + case OpQuit: + report("line %d: quit", s.line); + ++m_pc; + m_finished = true; + sink.scriptQuit(); + return; + case OpEnd: + m_pc = m_steps.size(); + continue; + case OpAim: + case OpFace: + case OpWalkTo: + if (!m_waiting) + { + m_waiting = true; + m_waitStart = nowSeconds(); + m_haveLast = false; + m_steerFrame = 0; + } + if (!steer(s, sink)) + return; + m_waiting = false; + break; + } + ++m_pc; + } + finish("script complete"); +} + +bool InputScript::steer(Step& s, IInputScriptSink& sink) +{ + const double elapsedMs = (nowSeconds() - m_waitStart) * 1000.0; + auto release = [&]() { + if (m_walkKeyDown) { sink.scriptKey(keys::w(), false, std::u16string()); m_walkKeyDown = false; } + }; + float view[3], fwd[3], target[3]; + bool ok = s_scriptQuery && s_scriptQuery(s.text.c_str(), view, fwd, target); + if (!ok) + { + if (elapsedMs > s.y) + { + release(); + report("line %d: %s %s: no target / no local player; step skipped", s.line, + s.op == OpWalkTo ? "walk-to" : s.op == OpAim ? "aim" : "face", s.text.c_str()); + return true; + } + return false; + } + const float dx = target[0] - view[0], dy = target[1] - view[1], dz = target[2] - view[2]; + const float horizontal = std::sqrt(dx * dx + dz * dz); + const float yaw = std::atan2(fwd[0], fwd[2]); + const float pitch = std::atan2(fwd[1], std::sqrt(fwd[0] * fwd[0] + fwd[2] * fwd[2])); + auto wrap = [](float a) { while (a > 3.14159265f) a -= 6.2831853f; while (a < -3.14159265f) a += 6.2831853f; return a; }; + const float yawErr = wrap(std::atan2(dx, dz) - yaw); + const float pitchErr = s.op == OpAim ? std::atan2(dy, horizontal) - pitch : 0.0f; + const float tol = s.x * 3.14159265f / 180.0f; + const char* name = s.op == OpWalkTo ? "walk-to" : s.op == OpAim ? "aim" : "face"; + // Learn counts per radian from the last correction (sign included). + if (m_haveLast) + { + const float dYaw = wrap(yaw - m_lastYaw), dPitch = pitch - m_lastPitch; + if (std::fabs(m_lastDx) > 5 && std::fabs(dYaw) > 0.003f) m_gainX = 0.5f * m_gainX + 0.5f * (m_lastDx / dYaw); + if (std::fabs(m_lastDy) > 5 && std::fabs(dPitch) > 0.003f) m_gainY = 0.5f * m_gainY + 0.5f * (m_lastDy / dPitch); + } + bool done; + if (s.op == OpWalkTo) + done = horizontal <= s.x; + else + done = std::fabs(yawErr) <= tol && std::fabs(pitchErr) <= tol; + if (done || elapsedMs > s.y) + { + release(); + report("line %d: %s %s: %s; dist %.1f m (horizontal %.1f, dy %.1f), yaw err %.1f deg, pitch err %.1f deg, gain %.0f/%.0f counts/rad", + s.line, name, s.text.c_str(), done ? "reached" : "TIMEOUT", std::sqrt(dx * dx + dy * dy + dz * dz), + horizontal, dy, yawErr * 57.2958f, pitchErr * 57.2958f, m_gainX, m_gainY); + return true; + } + if (s.op == OpWalkTo && !m_walkKeyDown) + { + sink.scriptKey(keys::w(), true, u"w"); + m_walkKeyDown = true; + } + // One correction every 4 pumps (the view follows the input a frame or two later). + if (m_steerFrame && m_frame - m_steerFrame < 4) + return false; + m_steerFrame = m_frame; + auto clampf = [](float v, float lim) { return v > lim ? lim : v < -lim ? -lim : v; }; + float mx = std::fabs(yawErr) > tol * 0.5f ? clampf(yawErr * m_gainX * 0.8f, 250.0f) : 0.0f; + float my = std::fabs(pitchErr) > tol * 0.5f ? clampf(pitchErr * m_gainY * 0.8f, 150.0f) : 0.0f; + if (std::fabs(mx) < 1 && mx != 0) mx = mx > 0 ? 1 : -1; + if (std::fabs(my) < 1 && my != 0) my = my > 0 ? 1 : -1; + m_lastYaw = yaw; m_lastPitch = pitch; m_lastDx = mx; m_lastDy = my; m_haveLast = true; + if (mx != 0 || my != 0) + sink.scriptMouseBy(mx, my); + return false; +} + +} // namespace inputscript +} // namespace hfe +} // namespace dice + +extern "C" bool openbf2InputScriptTakeCapture(char* label, unsigned long size) +{ + std::string text; + if (!dice::hfe::inputscript::inputScript().takeCaptureRequest(text)) + return false; + if (label && size) + { + std::strncpy(label, text.c_str(), size - 1); + label[size - 1] = 0; + for (char* c = label; *c; ++c) // a file-name component + if (!std::isalnum(static_cast(*c)) && *c != '-' && *c != '_') + *c = '_'; + } + return true; +} + +#endif // !DEDICATED && (__APPLE__ || _WIN32) diff --git a/Code/BF2/Platform/InputScript.h b/Code/BF2/Platform/InputScript.h new file mode 100644 index 000000000..b90341898 --- /dev/null +++ b/Code/BF2/Platform/InputScript.h @@ -0,0 +1,147 @@ +// [TEMP] [CHOSEN, not recovered] Client test tool: a scripted input source for unattended client +// runs (docs/macos-c-input-script.md). Off unless BF2_INPUT_SCRIPT= is set. The platform host +// runs one script tick per pump and turns its actions into the input its real devices produce: +// macOS CocoaHost (Platform/macOS) builds HostKeyEvent, HostTextEvent, HostMouse*Event and +// HostRawMouseEvent values for the window-message source and the Mac input devices. +// Win32 WinInputScript (Platform/Windows) sends window messages to the game window (menus, +// Swiff, console, chat) and feeds DirectInput device data to KeyboardDevice and +// MouseDevice (the in-game path). +// While a script is active the host ignores real input, reports focus, and leaves the real cursor +// alone. Key codes are the host's own: kVK_ codes on macOS, DIK_ codes (scan codes) on Win32. +// Client images only (!DEDICATED). [RETIRE-WHEN: client-test-automation-replaced] +#ifndef PLATFORM_INPUTSCRIPT_H +#define PLATFORM_INPUTSCRIPT_H + +#include +#include + +namespace dice { +namespace hfe { +namespace inputscript { + +// What the script needs from the host. Implemented by CocoaHost::Impl (macOS) and the Win32 sink +// in WinInputScript.cpp. +class IInputScriptSink +{ +public: + // A key transition (host key code). text (may be empty) is the characters the press carries + // (NSEvent.characters on macOS, the WM_CHAR sequence on Win32). + virtual void scriptKey(unsigned short keyCode, bool down, const std::u16string& text) = 0; + // Absolute pointer position in back-buffer pixels (origin top left). + virtual void scriptMouseTo(float x, float y) = 0; + // Relative device motion (x right, y down), the in-game mouse-look path. + virtual void scriptMouseBy(float dx, float dy) = 0; + virtual void scriptButton(int button, bool down) = 0; + virtual void scriptWheel(int delta) = 0; // DirectInput units, +120 a notch away + // The character a key produces with the current layout (macOS: UCKeyTranslate; Win32: ToUnicode). + virtual std::u16string scriptKeyCharacter(unsigned short keyCode, bool shift) = 0; + virtual void scriptQuit() = 0; +protected: + ~IInputScriptSink() {} +}; + +// [TEMP] The game side of aim / face / walk-to (BF2Engine.cpp, BF2_INPUT_SCRIPT runs only): +// fills the local player's view (camera position, forward) and, for a named target, its world +// position. Targets: "enemy", "friend", "player" (nearest other alive player, chest height) and +// "x/y/z" (a world position, e.g. a vehicle spawner from GamePlayObjects.con). Returns false when +// there is no local player or no such target. +typedef bool (*ScriptQueryFn)(const char* target, float viewPos[3], float viewFwd[3], float targetPos[3]); +void setScriptQuery(ScriptQueryFn fn); + +class InputScript +{ +public: + // Reads BF2_INPUT_SCRIPT. Returns false (inactive) when unset or unreadable. + bool loadFromEnvironment(); + bool active() const { return m_active; } + // One tick per host pump. Executes steps until one has to wait. + void tick(IInputScriptSink& sink); + + // Capture requests (macOS: MetalBridge's present capture, BF2_PRESENT_PNG; Win32: the sink's + // window capture). Returns true and the label once per request. + bool takeCaptureRequest(std::string& label); + +private: + enum Op + { + OpWaitFrames, OpWaitMs, OpWaitLog, OpKeyDown, OpKeyUp, OpText, OpMoveTo, OpMoveBy, + OpButtonDown, OpButtonUp, OpWheel, OpCapture, OpLog, OpQuit, OpTimeout, OpEnd, + OpAim, OpFace, OpWalkTo, OpWaitLogElse, OpLabel + }; + struct Step + { + Op op; + int line; + int a, b; + float x, y; + std::string text; + std::string label; // wait-log-else: the label to jump to on timeout + std::u16string chars; + }; + + bool parse(const std::string& path); + bool parseLine(const std::string& line, int number); + void addKeyPress(unsigned short keyCode, bool shift, const std::u16string& text, int line, int holdMs); + void addWaitFrames(int frames, int line); + void addWaitMs(int ms, int line); + bool expandText(const std::u16string& text, int line); + bool logContains(const std::string& needle); + void report(const char* fmt, ...) const; + void finish(const char* why); + // aim / face / walk-to: one control step; true when the step is complete. + bool steer(Step& s, IInputScriptSink& sink); + + bool m_active = false; + bool m_finished = false; + std::vector m_steps; + std::size_t m_pc = 0; + unsigned long m_frame = 0; + // Wait state of the current step. + bool m_waiting = false; + unsigned long m_waitFrame = 0; + double m_waitStart = 0.0; + double m_timeoutSeconds = 180.0; + double m_startSeconds = 0.0; + // Log scan: the file stdout/stderr is redirected to (or BF2_INPUT_SCRIPT_LOG). + std::string m_logPath; + std::string m_logTail; // unmatched text since the last wait-log match + long long m_logOffset = 0; + // Pending text expansion: kept as steps after parsing needs the layout, done at first tick. + IInputScriptSink* m_sink = nullptr; + std::vector m_captures; + bool m_shiftHeld = false; + float m_pointerScale = 1.2f; // HUD pixels per mouse count (pointer, hud-click) + // Steering state (aim / face / walk-to): counts per radian, learnt from the view's response. + float m_gainX = 300.0f, m_gainY = -300.0f; // initial guesses; y down looks down + float m_lastYaw = 0.0f, m_lastPitch = 0.0f, m_lastDx = 0.0f, m_lastDy = 0.0f; + bool m_haveLast = false; + bool m_walkKeyDown = false; + unsigned long m_steerFrame = 0; +}; + +InputScript& inputScript(); + +// Host key codes, implemented once per platform (MacInputScript.mm: kVK_; WinInputScript.cpp: +// DIK_). lookup takes a lower-case IDKey_ name without the prefix ("escape", "leftshift"...). +namespace keys { +bool lookup(const std::string& name, unsigned short& code); +// The characters a press carries for keys the layout translation reports as control characters. +std::u16string controlCharacters(unsigned short code); +bool isModifier(unsigned short code); +bool isShift(unsigned short code); +unsigned short leftShift(); +unsigned short grave(); // the console key, left of 1 +unsigned short enter(); +unsigned short w(); // walk-to's forward key +} // namespace keys + +} // namespace inputscript +} // namespace hfe +} // namespace dice + + +// Polled by MetalBridge's present capture (BF2_PRESENT_PNG); a weak default there answers false +// in images without the script. +extern "C" bool openbf2InputScriptTakeCapture(char* label, unsigned long size); + +#endif // PLATFORM_INPUTSCRIPT_H diff --git a/Code/BF2/Platform/MsvcRand.h b/Code/BF2/Platform/MsvcRand.h new file mode 100644 index 000000000..fb72b82ca --- /dev/null +++ b/Code/BF2/Platform/MsvcRand.h @@ -0,0 +1,42 @@ +// [CHOSEN, not recovered] The shipped Windows images (BF2Audio.dll, RendDX9.dll) import rand/srand +// from MSVCR71.DLL, whose generator yields 0..32767 (RAND_MAX 0x7FFF), and the recovered code +// depends on that range: BF2Audio's random envelope rows scale rand() by 1/32767 (the helper at +// 0x10017D90: FILD rand(); FMUL [0x1003B298]), the sample seeds take its low two bytes, and +// RendDX9's Swiff range pick scales by -1/32767. The macOS libc rand() yields 0..0x7FFFFFFF, so +// those products come out ~65536 times too large (pitch pinned at the 2.0 clamp, volume in the +// thousands). This reproduces the MSVCR71 generator: a per-thread state (MSVCR71 keeps _holdrand +// in the per-thread data, initially 1), state = state * 214013 + 2531011, result (state >> 16) & +// 0x7FFF. All client-image rand/srand calls in recovered code go through it, so they share one +// generator per thread as the retail modules share MSVCR71's. The platform reason is the CRT, not a +// behaviour change. Windows keeps std::rand (it is MSVCR71's), and so does the dedicated server +// (DEDICATED=1): its fidelity target, the Linux bf2, imports rand/srand from glibc. +#ifndef BF2_PLATFORM_MSVCRAND_H +#define BF2_PLATFORM_MSVCRAND_H + +#include + +namespace bf2crt { + +#if defined(_WIN32) || (defined(DEDICATED) && DEDICATED) +const int kRandMax = RAND_MAX; +inline int rand() { return std::rand(); } +inline void srand(unsigned int s) { std::srand(s); } +#else +const int kRandMax = 0x7FFF; +inline unsigned int& randState() +{ + static thread_local unsigned int state = 1u; + return state; +} +inline int rand() +{ + unsigned int& s = randState(); + s = s * 214013u + 2531011u; + return (int) ((s >> 16) & 0x7FFFu); +} +inline void srand(unsigned int seed) { randState() = seed; } +#endif + +} // namespace bf2crt + +#endif // BF2_PLATFORM_MSVCRAND_H diff --git a/Code/BF2/Platform/Utf16.h b/Code/BF2/Platform/Utf16.h new file mode 100644 index 000000000..6a755d6fd --- /dev/null +++ b/Code/BF2/Platform/Utf16.h @@ -0,0 +1,40 @@ +// [CHOSEN, not recovered] POSIX UTF-16LE file boundaries (macOSplan.md, S2.10). +#ifndef PLATFORM_UTF16_H +#define PLATFORM_UTF16_H + +#include +#include + +namespace dice { namespace hfe { namespace platform { + +// Reads one little-endian UTF-16 code unit, independent of host width and alignment. +// A short read consumes the available bytes and leaves unit unchanged. +template bool readUtf16LE(Stream& stream, char16_t& unit) +{ + unsigned char bytes[2]; + if (stream.read(bytes, 2) != 2) + return false; + unit = static_cast(bytes[0] | (static_cast(bytes[1]) << 8)); + return true; +} + +// Converts a NUL-terminated UTF-16 buffer to native wide text. Valid surrogate pairs become +// one scalar on 32-bit wchar_t hosts; unpaired surrogates retain their Windows code-unit value. +inline std::wstring utf16ToWide(const char16_t* units) +{ + std::wstring text; + for (std::size_t i = 0; units[i]; ++i) + { + unsigned int value = units[i]; + if (sizeof(wchar_t) > 2 && value >= 0xd800 && value <= 0xdbff + && units[i + 1] >= 0xdc00 && units[i + 1] <= 0xdfff) + { + value = 0x10000 + ((value - 0xd800) << 10) + (units[++i] - 0xdc00); + } + text.push_back(static_cast(value)); + } + return text; +} + +} } } +#endif diff --git a/Code/BF2/Platform/Windows/WinInputScript.cpp b/Code/BF2/Platform/Windows/WinInputScript.cpp new file mode 100644 index 000000000..22957efa2 --- /dev/null +++ b/Code/BF2/Platform/Windows/WinInputScript.cpp @@ -0,0 +1,424 @@ +// [TEMP] [CHOSEN, not recovered] Win32 client test tool: the scripted input host and its DIK_ key +// table (WinInputScript.h, Platform/InputScript.h, docs/macos-c-input-script.md). +// [RETIRE-WHEN: client-test-automation-replaced] +#include "WinInputScript.h" +#if !DEDICATED && defined(_WIN32) +#include "../InputScript.h" +#include +#include +#include +#include +#include +#include +#include + +namespace dice { +namespace hfe { +namespace inputscript { + +namespace keys { +namespace { + +struct KeyName { const char* name; unsigned short code; }; + +// Physical key positions (DIK_ codes: scan codes, 0x80 marks the E0-extended keys). Names follow +// Controls.con's IDKey_ names without the prefix, as in the macOS table. +const KeyName kKeys[] = { + {"a", DIK_A}, {"b", DIK_B}, {"c", DIK_C}, {"d", DIK_D}, {"e", DIK_E}, {"f", DIK_F}, + {"g", DIK_G}, {"h", DIK_H}, {"i", DIK_I}, {"j", DIK_J}, {"k", DIK_K}, {"l", DIK_L}, + {"m", DIK_M}, {"n", DIK_N}, {"o", DIK_O}, {"p", DIK_P}, {"q", DIK_Q}, {"r", DIK_R}, + {"s", DIK_S}, {"t", DIK_T}, {"u", DIK_U}, {"v", DIK_V}, {"w", DIK_W}, {"x", DIK_X}, + {"y", DIK_Y}, {"z", DIK_Z}, + {"0", DIK_0}, {"1", DIK_1}, {"2", DIK_2}, {"3", DIK_3}, {"4", DIK_4}, + {"5", DIK_5}, {"6", DIK_6}, {"7", DIK_7}, {"8", DIK_8}, {"9", DIK_9}, + {"escape", DIK_ESCAPE}, {"esc", DIK_ESCAPE}, {"enter", DIK_RETURN}, {"return", DIK_RETURN}, + {"space", DIK_SPACE}, {"tab", DIK_TAB}, {"backspace", DIK_BACK}, {"grave", DIK_GRAVE}, + {"minus", DIK_MINUS}, {"equals", DIK_EQUALS}, {"leftbracket", DIK_LBRACKET}, + {"rightbracket", DIK_RBRACKET}, {"semicolon", DIK_SEMICOLON}, + {"apostrophe", DIK_APOSTROPHE}, {"backslash", DIK_BACKSLASH}, {"comma", DIK_COMMA}, + {"period", DIK_PERIOD}, {"slash", DIK_SLASH}, + {"f1", DIK_F1}, {"f2", DIK_F2}, {"f3", DIK_F3}, {"f4", DIK_F4}, {"f5", DIK_F5}, {"f6", DIK_F6}, + {"f7", DIK_F7}, {"f8", DIK_F8}, {"f9", DIK_F9}, {"f10", DIK_F10}, {"f11", DIK_F11}, {"f12", DIK_F12}, + {"up", DIK_UP}, {"down", DIK_DOWN}, {"left", DIK_LEFT}, {"right", DIK_RIGHT}, + {"arrowup", DIK_UP}, {"arrowdown", DIK_DOWN}, {"arrowleft", DIK_LEFT}, + {"arrowright", DIK_RIGHT}, + {"home", DIK_HOME}, {"end", DIK_END}, {"pageup", DIK_PRIOR}, {"pagedown", DIK_NEXT}, + {"delete", DIK_DELETE}, {"insert", DIK_INSERT}, {"numpadenter", DIK_NUMPADENTER}, + {"leftshift", DIK_LSHIFT}, {"shift", DIK_LSHIFT}, {"rightshift", DIK_RSHIFT}, + {"leftctrl", DIK_LCONTROL}, {"ctrl", DIK_LCONTROL}, {"rightctrl", DIK_RCONTROL}, + {"leftalt", DIK_LMENU}, {"alt", DIK_LMENU}, {"rightalt", DIK_RMENU}, + {"capital", DIK_CAPITAL}, +}; + +} // namespace + +bool lookup(const std::string& name, unsigned short& code) +{ + for (const KeyName& k : kKeys) + if (name == k.name) { code = k.code; return true; } + return false; +} + +// The WM_CHAR TranslateMessage would produce for keys ToUnicode answers with a control character. +std::u16string controlCharacters(unsigned short code) +{ + switch (code) + { + case DIK_RETURN: + case DIK_NUMPADENTER: return std::u16string(1, u'\r'); + case DIK_TAB: return std::u16string(1, u'\t'); + case DIK_ESCAPE: return std::u16string(1, u'\x1B'); + case DIK_BACK: return std::u16string(1, u'\x08'); + default: return std::u16string(); + } +} + +bool isModifier(unsigned short code) +{ + return code == DIK_LSHIFT || code == DIK_RSHIFT || code == DIK_LCONTROL || code == DIK_RCONTROL || + code == DIK_LMENU || code == DIK_RMENU || code == DIK_LWIN || code == DIK_RWIN || + code == DIK_CAPITAL; +} + +bool isShift(unsigned short code) { return code == DIK_LSHIFT || code == DIK_RSHIFT; } +unsigned short leftShift() { return DIK_LSHIFT; } +unsigned short grave() { return DIK_GRAVE; } +unsigned short enter() { return DIK_RETURN; } +unsigned short w() { return DIK_W; } + +} // namespace keys + +namespace { + +const std::size_t kQueueLimit = 256; // a real buffer would overflow long before this + +// The window-message key code for a DIK_ code, as a real keyboard's WM_KEYDOWN carries it +// (generic VK_SHIFT / VK_CONTROL / VK_MENU for the modifiers). +UINT virtualKey(unsigned short code, bool generic) +{ + const UINT scan = code & 0x7Fu; + const UINT vk = MapVirtualKeyW((code & 0x80u) ? (0xE000u | scan) : scan, MAPVK_VSC_TO_VK_EX); + if (!generic) + return vk; + switch (vk) + { + case VK_LSHIFT: case VK_RSHIFT: return VK_SHIFT; + case VK_LCONTROL: case VK_RCONTROL: return VK_CONTROL; + case VK_LMENU: case VK_RMENU: return VK_MENU; + default: return vk; + } +} + +class WinSink : public IInputScriptSink +{ +public: + HWND window = 0; + bool menuActive = false; + unsigned long pumps = 0; + std::deque keyboard, mouse; + + void scriptKey(unsigned short keyCode, bool down, const std::u16string& text) override + { + push(keyboard, keyCode, down ? 0x80u : 0u); + if (!window) + return; + const UINT vk = virtualKey(keyCode, true); + LPARAM lParam = 1 | (static_cast(keyCode & 0x7Fu) << 16); + if (keyCode & 0x80u) + lParam |= 1 << 24; + if (!down) + lParam |= static_cast(3u << 30); + if (vk) + SendMessageA(window, down ? WM_KEYDOWN : WM_KEYUP, vk, lParam); + if (!down) + return; + for (char16_t c : text) + { + const wchar_t wide = static_cast(c); + char ansi[4] = {}; + if (WideCharToMultiByte(CP_ACP, 0, &wide, 1, ansi, sizeof(ansi), 0, 0) == 1) + SendMessageA(window, WM_CHAR, static_cast(ansi[0]), lParam); + } + } + + void scriptMouseTo(float x, float y) override + { + pointerInit(); + moveDevice(x - m_x, y - m_y); + m_x = x; + m_y = y; + clampPointer(); + if (menuActive) + sendPointer(WM_MOUSEMOVE); + } + + void scriptMouseBy(float dx, float dy) override + { + pointerInit(); + moveDevice(dx, dy); + if (!menuActive) + return; // the exclusive in-game mouse posts no messages + m_x += dx; + m_y += dy; + clampPointer(); + sendPointer(WM_MOUSEMOVE); + } + + void scriptButton(int button, bool down) override + { + pointerInit(); + if (button < 0 || button > 7) + return; + push(mouse, DIMOFS_BUTTON0 + button, down ? 0x80u : 0u); + const unsigned int bit = 1u << button; + if (down) m_buttons |= bit; else m_buttons &= ~bit; + if (!menuActive || button > 2) + return; + static const UINT messages[3][2] = { + {WM_LBUTTONUP, WM_LBUTTONDOWN}, {WM_RBUTTONUP, WM_RBUTTONDOWN}, {WM_MBUTTONUP, WM_MBUTTONDOWN}}; + sendPointer(messages[button][down ? 1 : 0]); + } + + void scriptWheel(int delta) override + { + pointerInit(); + push(mouse, DIMOFS_Z, static_cast(static_cast(delta))); + if (!menuActive || !window) + return; + POINT p = {static_cast(m_x), static_cast(m_y)}; + ClientToScreen(window, &p); + SendMessageA(window, WM_MOUSEWHEEL, MAKEWPARAM(buttonFlags(), static_cast(delta)), + MAKELPARAM(p.x, p.y)); + } + + std::u16string scriptKeyCharacter(unsigned short keyCode, bool shift) override + { + const UINT vk = virtualKey(keyCode, false); + if (!vk) + return std::u16string(); + BYTE state[256] = {}; + if (shift) + state[VK_SHIFT] = state[VK_LSHIFT] = 0x80; + wchar_t chars[8] = {}; + // Flag 4: leave the keyboard (dead-key) state alone. + const int n = ToUnicode(vk, keyCode & 0x7Fu, state, chars, 8, 4); + if (n == 1 && chars[0] >= 0x20 && chars[0] != 0x7F) + return std::u16string(1, static_cast(chars[0])); + return std::u16string(); + } + + void scriptQuit() override + { + if (window) + PostMessageA(window, WM_CLOSE, 0, 0); // as the close button + } + + void push(std::deque& queue, DWORD offset, DWORD data) + { + DIDEVICEOBJECTDATA event; + std::memset(&event, 0, sizeof(event)); + event.dwOfs = offset; + event.dwData = data; + event.dwTimeStamp = GetTickCount(); + event.dwSequence = ++m_sequence; + queue.push_back(event); + if (queue.size() > kQueueLimit) + queue.pop_front(); + } + +private: + void pointerInit() + { + if (m_pointerSet || !window) + return; + RECT r; + if (!GetClientRect(window, &r)) + return; + m_pointerSet = true; + m_x = (r.right - r.left) * 0.5f; + m_y = (r.bottom - r.top) * 0.5f; + } + + void clampPointer() + { + RECT r; + if (!window || !GetClientRect(window, &r)) + return; + const float w = static_cast(r.right - r.left - 1), h = static_cast(r.bottom - r.top - 1); + m_x = m_x < 0 ? 0 : m_x > w ? w : m_x; + m_y = m_y < 0 ? 0 : m_y > h ? h : m_y; + } + + // Relative device motion; fractions carry over to the next move. + void moveDevice(float dx, float dy) + { + m_remX += dx; + m_remY += dy; + const LONG ix = static_cast(m_remX), iy = static_cast(m_remY); + m_remX -= ix; + m_remY -= iy; + if (ix) push(mouse, DIMOFS_X, static_cast(ix)); + if (iy) push(mouse, DIMOFS_Y, static_cast(iy)); + } + + WPARAM buttonFlags() const + { + WPARAM flags = 0; + if (m_buttons & 1) flags |= MK_LBUTTON; + if (m_buttons & 2) flags |= MK_RBUTTON; + if (m_buttons & 4) flags |= MK_MBUTTON; + if (GetKeyState(VK_SHIFT) < 0) flags |= MK_SHIFT; + return flags; + } + + void sendPointer(UINT message) + { + if (!window) + return; + SendMessageA(window, message, buttonFlags(), + MAKELPARAM(static_cast(m_x), static_cast(m_y))); + } + + float m_x = 0.0f, m_y = 0.0f, m_remX = 0.0f, m_remY = 0.0f; + bool m_pointerSet = false; + unsigned int m_buttons = 0; + DWORD m_sequence = 0; +}; + +WinSink& sink() +{ + static WinSink s; + return s; +} + +// "capture LABEL": the game window's client area (a screen copy) as a 24-bit BMP in BF2_PRESENT_PNG (a directory, +// as for the macOS present capture), named present__